Starter Classes

A Starter Class defines the entry point (starting point) of a Libgdx application. They are specifically written for a certain platform. Usually, these kinds of classes are very simple and mostly consist of not more than a few lines of code to set certain parameters that apply to the corresponding platform. Think of them as a kind of boot-up sequence for each platform. Once booting has finished, the Libgdx framework hands over control from the Starter Class (for example, the demo-desktop project) to your shared application code (for example, the demo project) by calling the different methods from the ApplicationListener interface that the MyDemo class implements. Remember that the MyDemo class is where the shared application code begins.

We will now take a look at each of the Starter Classes that were generated during the project setup.

Running the demo application on a desktop

The Starter Class for the desktop application is called Main.java.

The following listing is Main.java from demo-desktop:

package com.packtpub.libgdx.demo;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

public class Main {
  public static void main(String[] args) {
 LwjglApplicationConfiguration cfg =
 new LwjglApplicationConfiguration();
 cfg.title = "demo";
 cfg.useGL20 = false;
 cfg.width = 480;
 cfg.height = 320;
 new LwjglApplication(new MyDemo(), cfg);
  }
}

In the preceding code listing, you see the Main class, a plain Java class without the need to implement an interface or inherit from another class. Instead, a new instance of the LwjglApplication class is created. This class provides a couple of overloaded constructors to choose from. Here, we pass a new instance of the MyDemo class as the first argument to the constructor. Optionally, an instance of the LwjglApplicationConfiguration class can be passed as the second argument. The configuration class allows you to set every parameter that is configurable for a Libgdx desktop application. In this case, the window title is set to demo and the window's width and height is set to 480 by 320 pixels.

This is all you need to write and configure a Starter Class for a desktop.

Let us try to run the application now. To do this, right-click on the demo-desktop project in Project Explorer in Eclipse and then navigate to Run As | Java Application. Eclipse may ask you to select the Main class when you do this for the first time. Simply select the Main class and also check that the correct package name (com.packtpub.libgdx.demo) is displayed next to it.

The desktop application should now be up and running on your computer. If you are working on Windows, you should see a window that looks as follows:

Running the demo application on Android

The Starter Class for the Android application is called MainActivity.java.

The following listing is MainActivity.java from demo-android:

package com.packtpub.libgdx.demo;

import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android
  .AndroidApplicationConfiguration;

public class MainActivity extends AndroidApplication {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 AndroidApplicationConfiguration cfg =
 new AndroidApplicationConfiguration();
 cfg.useGL20 = false;
 initialize(new MyDemo(), cfg);
  }
}

In the preceding code listing, you can see the MainActivity class that inherits from the AndroidApplication class. This is how Libgdx encapsulates tasks such as creating a so-called activity that registers handlers to process touch input, read sensor data, and much more. What is left to do for you is to create an instance of a class that implements the ApplicationListener interface. In this case, it is an instance of the MyDemo class. The instances of MyDemo and AndroidApplicationConfiguration are passed as arguments to the initialize() method. The configuration is set to not request OpenGL ES 2.0 support on an Android device.

If you are interested in the latest development of Android hardware statistics, be sure to check out Dashboards on the official Android Developers website: http://developer.android.com/about/dashboards/index.html#OpenGL.

The following screenshot of the OpenGL statistics was taken in February 2013 from the mentioned website:

At the time of writing this book, over 90 percent of today's Android devices support GLES2. So when should GLES2 be used on Android? A better question to ask would be whether you plan to use shaders in your application. If this is the case, opt for GLES2. In any other case, there will be no real benefit except being able to use non-power-of-two textures (also known as NPOT textures); arbitrarily-sized textures that do not equal to widths or heights representable by the formula 2^n, such as 32 x 32, 512 x 512, and 128 x 1024.

Note

NPOT textures are not guaranteed to work on all devices. For example, the Nexus One ignores NPOT textures. Also, they may cause performance penalties on some hardware, so it is best to avoid using this feature at all. In Chapter 4, Gathering Resources, you will learn about a technique called Texture Atlas. This will allow you to use arbitrarily-sized textures even when not using GLES2.

Additionally, on Android, you will have to take care of a manifest file that defines a huge list of parameters to configure the application. If you are not yet familiar with Android's manifest file, you should take some time to read the official documentation at http://developer.android.com/guide/topics/manifest/manifest-intro.html.

The following listing is AndroidManifest.xml from demo-android:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.packtpub.libgdx.demo"
  android:versionCode="1"
  android:versionName="1.0" >
 <uses-sdk android:minSdkVersion="5"
 android:targetSdkVersion="17" />
<application
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name" >
<activity
 android:name=".MainActivity"
 android:label="@string/app_name"
 android:screenOrientation="landscape"
  android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

The following short (and incomplete) list is meant to give you a quick idea of what could be defined in the manifest file:

  • minSdkVersion: This is the minimum API Level required for the application to run. Devices running with lower API Levels will not be able to run this application; or if left undeclared, an API Level of 1 is assumed, which may cause your app to crash at runtime when trying to access unavailable APIs.
  • targetSdkVersion: This is the API Level the application targets. This is used for forward compatibility, where later API Levels may change the behavior of the API that might break old applications. This specification does not prevent the application from running on devices with lower API Levels down to minSdkVersion. If left undeclared, its value is set equal to minSdkVersion.
  • icon: This is the application's icon.
  • name: This is the main class of the application (or the main activity). Note that in terms of Libgdx, this will be the Starter Class for Android.
  • label: This is the application's name shown next to the application icon and in the title bar.
  • screenOrientation: This defines the display orientation of the application. The usual values are portrait (tall) and landscape (wide). See the documentation for more details.

Another crucial part of the manifest file is the correct definition of the permissions that the application should request when a user wants to install it on a device.

Note

Make sure that you will never request unnecessary permissions and put as much information as required into the description text of your application. Users are extremely suspicious, and justifiably so, when it comes to the list of requested permissions. It is not 100 percent clear for which reason an application needs a certain permission.

For an introduction and much more details on the topic of permissions on Android, check out the official documentation at http://developer.android.com/guide/topics/security/permissions.html.

Now, let us try to run the application on a real, physical device. First, make sure that your Android device is connected via a USB cable and is set up for development. To set up your Android device, follow the instructions at http://developer.android.com/tools/device.html.

Now, right-click on the demo-android project in Project Explorer in Eclipse and navigate to Run As | Android Application.

The Android application should now be installed as an application icon and should be happily running on your Android device. The following photograph is of the application running on an HTC Desire HD:

With regards to the Android Emulator that comes with the Android SDK, just a couple of final words, DO NOT USE IT!

At the time of writing this book the emulator appears to have some major issues, such as very slow emulation and unreliable GLES2 support. These issues will hopefully be resolved in future versions. Instead of using the emulator, it is highly recommended to try and test your applications on as many real devices as you can get your hands on.

Running the demo application in a WebGL-capable web browser

The Starter Class for the WebGL application is called GwtLauncher.java.

The following listing is GwtLauncher.java from demo-html:

package com.packtpub.libgdx.demo.client;

import com.packtpub.libgdx.demo.MyDemo;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.gwt.GwtApplication;
import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;
public class GwtLauncher extends GwtApplication {
  @Override
 public GwtApplicationConfiguration getConfig () {
 GwtApplicationConfiguration cfg =
 new GwtApplicationConfiguration(800, 480);
 return cfg;
 }

  @Override
 public ApplicationListener getApplicationListener () {
 return new MyDemo();
 }
}

In the preceding code listing you see the GwtLauncher class that inherits from the GwtApplication class. Libgdx encapsulates GWT and only requires you to implement the two abstract methods, getConfig() and getApplicationListener(). The getConfig() method returns an instance of the GwtApplicationConfiguration class. In this case, the window's width and height are directly passed to its constructor. The g etApplicationListener() method returns an instance of a class that implements the ApplicationListener interface, which is the MyDemo class in the preceding code.

Note

Unlike other target platforms, WebGL always uses OpenGL ES 2.0.

Additionally, GWT is organized in so-called modules that bundle together all the configuration settings. In this case, we only have one module called MyDemo.gwt.xml. It defines the source path where GWT should look for Java source files, in this case com/packtpub/libgdx/demo. These source files will then be cross-compiled by GWT to optimized JavaScript code that is runnable on all major web browsers.

The following listing is MyDemo.gwt.xml from demo:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit trunk//EN" "http://google-web-toolkit.googlecode.com/svn/trunk/distro-source/core/src/gwt-module.dtd">
<module>
 <source path="com/packtpub/libgdx/demo" />
</module>

Let us try to run the application now. To do this, right-click on the demo-html project in Project Explorer in Eclipse and then navigate to Run As | Web Application. A new tab titled Development Mode should open at the bottom. Simply do what the description preceding the URL says and double-click on it. Your default browser should launch shortly after that. Then try to load the website which is hosted on your local machine right now. Hence, the URL points to 127.0.0.1, the infamous IPv4 loopback address that is just another fancy name for this device or computer.

Keep in mind that using the URL suggested by Eclipse will run your WebGL application in debug mode, which is excruciatingly slow for most games. Just remove everything after the question mark in the URL to run your application in normal mode. The resulting URL should look like this: http://127.0.0.1:8888/index.html.

You might be asked to install the Google Web Toolkit Developer Plugin for your web browser to use the Development Mode. You need to install it to develop on your local machine.

After the plugin has been successfully installed, you should see something like this:

If you want to run this application on a real web server and share it with other users on the Internet, you will have to cross-compile the project first. This is a pretty straightforward process. Simply right-click on the demo-html project in Project Explorer in Eclipse and then navigate to Google | GWT Compile.

A window with the title GWT Compile will open. Here you can choose a log level to narrow down on certain messages such as errors only. Keep the default settings for now and click on Compile to begin the cross-compile process.

The compilation process is quite lengthy compared to all the other ones shown in this book. It took over two minutes to finish on an Intel Core i7 (3.4GHz) processor. A good moment to exercise yourself in patience!

Once the compilation has finished, go to the war subfolder in the demo-html project.

You can now upload everything to your web server that is contained in this folder except the WEB-INF folder, which is not needed. Now, you or anyone else can open the URL to your web server and enjoy your Libgdx cross-platform application in a WebGL-capable web browser without having to install any plugin for it to work.