39,59 €
Android NDK is used for multimedia applications which require direct access to a system's resources. Android NDK is also the key for portability, which in turn provides a reasonably comfortable development and debugging process using familiar tools such as GCC and Clang toolchains. If your wish to build Android games using this amazing framework, then this book is a must-have.This book provides you with a number of clear step-by-step recipes which will help you to start developing mobile games with Android NDK and boost your productivity debugging them on your computer. This book will also provide you with new ways of working as well as some useful tips and tricks that will demonstrably increase your development speed and efficiency.This book will take you through a number of easy-to-follow recipes that will help you to take advantage of the Android NDK as well as some popular C++ libraries. It presents Android application development in C++ and shows you how to create a complete gaming application. You will learn how to write portable multithreaded C++ code, use HTTP networking, play audio files, use OpenGL ES, to render high-quality text, and how to recognize user gestures on multi-touch devices. If you want to leverage your C++ skills in mobile development and add performance to your Android applications, then this is the book for you.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 328
Veröffentlichungsjahr: 2013
Copyright © 2013 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: November 2013
Production Reference: 1191113
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78216-778-5
www.packtpub.com
Cover Image by Aniket Sawant (<[email protected]>)
Authors
Sergey Kosarevsky
Viktor Latypov
Reviewers
Mootez Billeh Chaabani
Guy Cole
Maya Posch
Acquisition Editor
Rebecca Youe
Lead Technical Editor
Azharuddin Sheikh
Technical Editors
Adrian Raposo
Gaurav Thingalaya
Project Coordinator
Apeksha Chitnis
Proofreaders
Simran Bhogal
Ameesha Green
Paul Hindle
Indexer
Priya Subramani
Graphics
Abhinash Sahu
Sheetal Aute
Production Coordinator
Conidon Miranda
Cover Work
Conidon Miranda
Sergey Kosarevsky is a software engineer with experience in C++ and 3D graphics. He has worked for mobile industry companies and was involved in mobile projects at SPB Software and Yandex. He has more than 10 years of software development experience, and more than four years of Android NDK experience. Sergey got his PhD in the field of Mechanical Engineering from the St. Petersburg Institute of Machine Building in Saint Petersburg, Russia. In his spare time Sergey maintains and develops an open source multiplatform 3D gaming engine, Linderdaum Engine (http://www.linderdaum.com). He is online at http://blog.linderdaum.com and can be contacted by email at <[email protected]>.
I would like to thank Alexander Pavlov, a Google engineer, for the time and effort he put into carefully reviewing our initial drafts and helping us to improve this book. Also I would like to thank Igor Demura (Google) for valuable criticism on our chapter 6, as well as Dmitry Ovcharov (Yandex), and other friends and colleagues who helped this book happen.
Viktor Latypov is a software engineer and a mathematician with experience in compiler development, device drivers, robotics, high-performance computing, and a personal interest in 3D graphics and mobile technology. Surrounded by computers for almost 20 years, he enjoys every bit of developing and designing software for anything with a CPU inside. Viktor holds a PhD in Applied Mathematics from Saint Petersburg State University.
I would like to thank my mother, Galina Fedyushina, for all of the support and the innate thirst for knowledge.
Mootez Chaabani works as a software engineer R&D at a French company. He has recently graduated from studies in Graphical Programming, and Virtual and Augmented Reality. He has published two apps: Quiz game in the Windows Market Place, and an Android app in the local app shop. He is currently working on Android/C++ projects based on 3D in SpacEyes.
He is currently working with SpacEyes as a Software Engineer R&D. He has also worked as an Android developer at Orange, Tunisia in 2012. In 2011, he was an intern at Microsoft, Tunisia.
He has also reviewed Unity Android Game Development, Beginner’s Guide, Packt Publishing, by Thomas James Moffitt-Finnegan.
I would like to thank my family, my soul mate, and all my of friends including the Bardo Boys (my neighborhood friends).
Guy Cole is a freelance silicon valley contractor working on mobile devices (Android and iOS), Java/J2EE, relational databases, TCP/IP networks, and UNIX/LINUX hosted enterprise solutions. Guy has designed and fielded applications for B2B, banking, health care, e-commerce, shipping, mass transit, national defense, enterprise/network management, and cable/broadcast industries. His customers include Northrop Grumman, Wells Fargo, Barclay Global Investments, Hewlett Packard, DHL Worldwide Express, Motorola, Cisco Systems, Cray Research, Tandem Computers, NCR, and many smaller (but equally interesting) companies.
Maya Posch has been involved with programming and technology in general from a young age. She has endeavored to expand her programming skills mostly on low-level, embedded, and game-related programming. She currently runs her own company—Nyanko—which is involved in these aforementioned fields, in addition to doing general development work for other companies.
You might want to visit www.PacktPub.com for support files and downloads related to your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt’s online digital book library. Here, you can access, read and search across Packt’s entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
Dedicated to my grandfather Leonid Michailowitsch Sirotkin who passed away during the editing of this book.
--Dedication by Sergey KosarevskyDedicated to my wife Mary who supports my every new initiative.
--Dedication by Viktor LatypovMobility and the demand for high-performance computations are often very tightly coupled. Current mobile applications do many computationally-intense operations such as 3D and stereoscopic rendering, images and audio recognition, and video decoding and encoding, especially the birth of new technologies such as the augmented reality. This include mobile games, 3D user interface software, and social software, which involves media stream processing.
In some sense, mobile game development forces us to travel back in time several years due to the limited hardware capabilities, low memory bandwidth, and precious battery resources, but also makes us reconsider the basic forms of interaction with the user.
A smooth and responsive user interface based on gesture input, Internet access, ambient sound effects, high-quality text, and graphics are the ingredients of a successful mobile application.
All major mobile operating systems give software developers different possibilities to develop close-to-the-hardware. Google provides an Android Native Development Kit (NDK) to ease the porting of existing applications and libraries from other platforms to Android, and exploit the performance of the underlying hardware offered by the modern mobile devices. C, and especially C++, both have a reputation of being a hard language to learn, and a hard language to write user interface code in. This is indeed true, but only when someone attempts to write everything from scratch. In this book we use C and C++ programming languages, and link them to well-established third-party libraries to allow the creation of content-rich applications with a modern touch-based interface and access to the Representational State Transfer (REST) APIs of popular sites such as Facebook, Twitter, Flickr, Picasa, Instagram, and a myriad of others.
Despite the availability of the information on how to use Internet resources in the applications written in Java or .NET languages, not much has been said about doing this in C++ programming language. Modern OpenGL versions require a sufficient amount of effort to create and use the latest extensions. The programming using the OpenGL API is usually described in literature in a platform-specific way. Things get even more complicated with the mobile version, the OpenGL ES, as developers have to adapt existing shader programs to allow them to run on the mobile graphics processing units (GPUs). Sound playback using standard Android facilities in C++ is also not straightforward, for example, things should be done to re-use the existing PC code for the OpenAL library. This book tries to shed some light on these topics and combine a number of useful recipes to simplify the multiplatform-friendly development with Android NDK.
Android is a mobile operating system based on the Linux kernel and designed for smartphones, tablet computers, netbooks, and other portable devices. Initial development of Android was started by Android Inc, which was bought by Google in 2005. In November 2007, the first version was unveiled, however, the first commercially available Android-based smartphone, HTC Dream, was released almost one year later in 2008.
Android versions, besides a numerical denomination, have official code names—each major release is named after a sweet dessert. The following are some significant milestones in Android platform technologies and features related to NDK:
Android Native Development Kit (NDK) is used for multimedia applications that require performance that Dalvik is unable to provide, and direct access to the native system libraries. NDK is also the key for portability, which in turn allows a reasonably comfortable development and debugging process using familiar tools such as GCC and Clang toolchains or alike. The typical usage of NDK determines the scope of this book—integration of some of the most commonly used C/C++ libraries for graphics, sound, networking, and resource storage.
Initially, NDK was based on the Bionic library. It is a derivation of the BSD standard C library (libc) developed by Google for Android. The main goals of Bionic were as follows:
Bionic lacks many important features found in full libc implementations, such as RTTI and C++ exceptions handling support. However, NDK provides several libraries with different C++ helper runtimes which implement these features. These are GAbi++ runtime, STLport runtime, and GNU Standard C++ Library. Besides the basic POSIX features, Bionic has support for Android-specific mechanisms such as logging.
The NDK is a very effective way to reuse a great body of existing C and C++ code.
Chapter 1, Establishing a Build Environment, explains how to install and configure Android SDK and NDK on Microsoft Windows and Ubuntu/Debian Linux flavors, and how to build and run your first application on an Android-based device. You will learn how to use different compilers and toolchains that come with the Android NDK. Debugging and deploying the application using the adb tool is also covered.
Chapter 2, Porting Common Libraries, contains a set of recipes to port well-established C++ projects and APIs to Android NDK, such as FreeType fonts rendering library, FreeImage images loading library, libcurl and OpenSSL (including compilation of libssl and libcrypto), OpenAL API, libmodplug audio library, Box2D physics library, Open Dynamics Engine (ODE), libogg, and libvorbis. Some of them require changes to the source code, which will be explained. Most of these libraries are used later in subsequent chapters.
Chapter 3, Networking, shows you how to use the well-known libcurl library to download files using the HTTP protocol and how to form requests and parse responses from popular Picasa and Flickr online services directly using C++ code. Most applications nowadays use network data transfer in one way or another. HTTP protocol is the foundation of the APIs for all of the popular websites such as Facebook, Twitter, Picasa, Flickr, SoundCloud, and YouTube. The remaining part of the chapter is dedicated to the web server development. Having a mini web server in the application allows a developer to control the software remotely and monitor its runtime without using the OS-specific code. The beginning of the chapter also introduces a task queue for background download processing and simple smartpointers to allow efficient cross-thread data interchange. These threading primitives are used later on in Chapter 4, Organizing a Virtual Filesystem and Chapter 5, Cross-platform Audio Streaming.
Chapter 4, Organizing a Virtual Filesystem, is devoted entirely to the asynchronous file handling, resource proxies, and resource compression. Many programs store their data as a set of files. Loading these files without blocking the whole program is an important issue. Human interface guidelines for all modern operating systems prescript the application developer to avoid any delay, or "freezing", in the program's workflow (known as the Application Not Responding (ANR) error in Android). Android program packages are simply archive files with an .apk extension, compressed with a familiar ZIP algorithm. To allow reading the application's resource files directly from .apk, we have to decompress the .zip format using the zlib library. Another important topic covered is the virtual filesystem concept, which allows us to abstract the underlying OS files and folders structure, and share resources between Android and PC versions of our application.
Chapter 5, Cross-platform Audio Streaming, starts with organizing an audio stream using the OpenAL library. After this, we proceed to the RIFF WAVE file format reading, and OGG Vorbis streams decoding. Finally, we learn how to play some tracker music using libmodplug. Recent Android NDK includes an OpenSL ES API implementation. However, we are looking for a fully portable implementation between the desktop PC and other mobile platforms to allow seamless game debugging capabilities. To do this, we precompile an OpenAL implementation into a static library, and then organize a small multithreaded sound streaming library on top of libogg and libvorbis.
Chapter 6, Unifying OpenGL ES 3 and OpenGL 3, presents the basic rendering loop for the desktop OpenGL 3 and mobile OpenGL ES 3.0. Redeploying the application to a mobile device is a lengthy operation that prevents the developer from quick feature testing and debugging. In order to allow the development and debugging of game logic on the PC, we provide a technique to use desktop GLSL shaders in mobile OpenGL ES.
Chapter 7, Cross-platform UI and Input System, will teach you how to implement multi-touch event handling and gesture recognition in a portable way. A mobile is now almost synonymous with gesture-based touch input. No modern user-oriented application can exist without a graphical user interface (GUI). There are two basic issues to organize the interaction: input and text rendering. To ease the testing and debugging, we also show you how to simulate the multi-touch input on a Windows 7 PC equipped with multiple mouse devices. Since we are aiming at the development of interactive gaming applications, we have to implement user input in a familiar way. We will show you systematically how to create an on-screen gamepad UI. In a global multicultural environment, it is very desirable to have a multi-language text renderer for any application. We will show you how to use the FreeType library to render Latin, Cyrillic, and left-to-right texts. The organization of a multi-language UTF-8 localized interface will be presented as a dictionary-based approach.
Chapter 8, Writing a Match-3 Game, will put all the techniques we have introduced together, and write a simple Match-3 game, including rendering using OpenGL ES, input handling, resources packing, and PC-side debugging. The game is also runnable and debuggable on a Windows desktop PC and can be easily ported to other mobile platforms.
Chapter 9, Writing a Picture Puzzle Game, will provide a more complicated example, integrating all of the things mentioned above. All of the above elements regarding graphics and input will use native network libraries and APIs to download images from the Picasa online service.
This book is centered on a Windows-based PC. An Android smartphone or tablet is advisable due to the limitations of the emulator in 3D graphics and native audio.
The source code in this book is based on open-source Linderdaum Engine and is a hard squeezing of some approaches and techniques used in the engine. You can get at http://www.linderdaum.com.
Basic knowledge of C or C++, including pointer manipulation, multithreading, and basic object-oriented programming concepts is assumed. The reader should be familiar with advanced programming concepts such as threading and synchronization primitives, and have some basic understanding of GCC toolchains. We also hope the reader is not afraid to develop without an IDE (yes, developing without an autocomplete-capable IDE definitely IS a skill) from a terminal/FarManager/Notepad/SublimeText, for example.
Android Java development is not covered in this book. You will have to read something else to get familiar with it.
Some working knowledge of linear algebra and affine transformations in 3D space is useful for the understanding of OpenGL programming and gesture recognition.
Do you want to port your existing C/C++ application to Android? Are you an experienced C++ developer who wants to jump into a modern mobile development? Do you want to increase the performance of your Java-based Android application? Do you want to use great libraries written in C++ in your Android application? Do you want to boost your productivity by debugging your mobile games on a PC?
If you say yes to any of these questions, then this book is for you.
The examples from the code bundle of this book can be compiled using the following commands:
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are show as follows: "JAVA_HOME variable should point to the Java Development Kit folder."
A block of code is typeset as follows:
When we wish to draw your attention to a particular line of code, the relevant lines are emphasized like so:
All command-line input or output is written as follows:
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "install this device software or not, you should click on the Install button".
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title through the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example source code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you. We worked hard to write and debug the source code for this book. The truth is, in real life there are always bugs lurking in the code, which need to be fixed after the release.
We established a GitHub repository, so everyone can download the most recent source code bundle, and open pull requests to submit bugfixes and improvements. The repository can be cloned from: https://github.com/corporateshark/Android-NDK-Game-Development-Cookbook. The latest snapshot of our source code bundle is available at: http://www.linderdaum.com/Android-NDK-Game-Development-Cookbook-SourceCodeBungle.zip.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.
Some LinkedIn profiles say developing with a particular IDE is a skill.
No! Development without any IDE is the skill!
--Sergey KosarevskyIn this chapter, we will cover the following recipes:
This chapter explains how to install and configure Android NDK on Microsoft Windows or Ubuntu/Debian Linux, and how to build and run your first application on an Android-based device. We will learn how to set-up different compilers and toolchains that come with Android NDK. In addition, we show how to setup the GCC toolchain for Windows to build your projects. The rest of the chapter is devoted to cross-platform development using C++.
To start developing games for Android you will need some essential tools to be installed on your system.
Here is the list of all the prerequisites you will need to start developing games for Android:
This book is based on the Android SDK rev. 22.3 and tested with Android API Level 19.
Former versions of SDK/NDK for Windows required a Cygwin environment, a Linux-like environment for Windows, to be installed. Up-to-date versions of these tools can run natively on Windows without any intermediate layer. We will focus on the Cygwin-less environment and will do all of the development without IDE. You heard it right, we will just use the command line. All the examples in this book were written and debugged on a Windows PC.
To compile native Windows applications presented in this book, you will need a decent C++ compiler, such as the MinGW package with a GCC toolchain. Using Microsoft Visual Studio is also possible.
Minimalist GNU for Windows (MinGW) is a minimalist development environment for Windows applications using a port of GNU Compiler Collection (GCC).
This requirement comes from the limitations of scripts in Android SDK. There is a nice discussion on StackOverflow which explains some reasons behind these limitations at http://stackoverflow.com/q/6603194/1065190.
Tools
Path
Android SDK
D:\android-sdk-windows
Android NDK
D:\ndk
Apache Ant
D:\ant
Java Development Kit
C:\Program Files\Java\jdk1.6.0_33
All tools have pretty decent GUI installers (see the following image, that shows the Android SDK Manager from SDK R21) so you don't have to use the command line.
For the Windows environment, you need the MinGW GCC toolchain. The easy to install all-in-one package can be found at http://www.equation.com, in the Programming Tools section, Fortran, C, C++ subsection. Alternatively, you can download the official installer from http://www.mingw.org. We will use the one from www.equation.com
You need to set some environment variables to let the tools know where the files are located. The JAVA_HOME variable should point to the Java Development Kit folder. The NDK_HOME variable should point to the Android NDK installation folder, and ANDROID_HOME should point to the Android SDK folder (note the double backslash). We used the following environment variable values:
JAVA_HOME=D:\Java\jdk1.6.0_23
NDK_HOME=D:\ndk
ANDROID_HOME=D:\\android-sdk-windows
The final configuration looks similar to the one shown in the following screenshot, which shows the Windows Environment Variables dialog box:
After MinGW has been successfully installed, you should also add the bin folder from its installation folder to the PATH environment variable. For example, if MinGW is installed to C:\MinGW, then PATH should contain the C:\MinGW\bin folder.
Installation of the basic tools on Linux is as easy as it was with their Windows counterpart. In this recipe, we will see how to install the basic Android development tools on *nix systems.
We assume you already have an Ubuntu/Debian system with the apt package manager. Refer to http://wiki.debian.org/Apt for details.
Carry out the following steps to install the required basic tools:
Failure to do so will result in an error while trying to use the Ant tool when building any application for the Android.
Get the official Android NDK from http://developer.android.com:It is useful to put this line and the JAVA_HOME definition to /etc/profile or /etc/environment, if these settings are applicable to all the users of the system.
In case you are running a 64-bit system, you must ensure that you have the 32-bit Java runtime installed also.Run the following command to install the libraries. Failure to do so may lead to errors with adb and aapt tools:There is a nice one-liner script that helps you automatically detect the OpenJDK home directory. It essentially resolves the link /usr/bin/javac to the full path and returns the directory part of the path.
First of all, we are going to create a basic template for our applications. Every Android application that is to be built via Android SDK, should contain a predefined directory structure and the configuration .xml files. This can be done using Android SDK tools and IDEs. In this recipe, we will learn how to do it manually. We will use these files later on as the very starting point for all our examples.
Let us set up the directory structure of our project (see the following screenshot):
This is a typical structure for any Android project. We will create all the required files manually rather than using Android tools.
Place the Java Activity code into the App1\src\com\packtpub\ndkcookbook\app1\App1Activity.java file, which should look as follows:
The localizable application name should go to App1\res\values\strings.xml. The string parameter app_name is used in the AndroidManifest.xml file to specify the user-readable name of our application, as seen in the following code:
Now we need to write more scripts for Apache Ant and the Android SDK build system. They are necessary to build the .apk package of your application.