Thursday, December 16, 2010

Ohh... Now i get it

So this morning at 4:30 am it finally dawned on me how developing video games really should be thought of as "creating simulations".  (I guess it's just me and my crazy reliance on metaphors that finally makes me see the light).  Having spent years developing "business logic" and Java (J2EE) applications, moving into game development has been a large paradigm shift.  Anyways, trying to make heads and tails over all of these new things (APIs, etc.) required me to take some source code examples from android game projects, and decompose them/modify them/rewrite them/rebuild them (You can't get that kinda experience just reading about developing, you gotta get your hands dirty and grind out some code).

Anyways, one of the things I've had drilled into my psychi over the years is not to mix business logic with presentation logic, and the first thing I do is start tearing into some code where its (frankly) just a hodgepodge.
You got one class that does all of these things:
  • main game loop
  • handle input events from user
  • maintain graphics (draw itself every frame)
  • run game rules (i.e business logic)
  • handle state change (it's stateful)
 I started modifying things (in this "uber" class) just to see if I could add functionality, and (as expected) things started to crack very early on.  In one regard it was easy for me to turn around simple changes because (almost) all of the code was just a few lines away.  However you start fiddling a little here and there and the code is just as ugly as hell and hard to keep straight (and buggy).

Really, I think the problem here is that when developing a video game, the first thing you want to do is figure out how you can get something rendered and viewable on the screen.  So you hack something together and slam it into a prototype that will show some sprite or animation show up... then from there you try to figure out how this thing is going to move around and exist in this game world.  Moving further into development with this paradigm causes all of the logic to be placed on how these simulated objects will appear in the simulated world.  We should really think of it like this "The Simulated World should be simulated whether it's viewable or not is a different concern"... so in that regard, the should be "runnable" without any view.

So I took the original code and I would try to refactor it in a way that made things a little more manageable.
After a few passes the following things (abstractions) started to emerge:
1) State - "GameObjects" - the state of anything that is being simulated in the game root object is WorldState, contains the states of other objects (MapState, MarbleState,...)
2) Loop - Metaphor (Time) a Simulation that occurs over time and has/contains rules/constraints that are enforced WorldLoop
3) Rule(s) - What happens for each iteration of the gameLoop (Collision Detection, AI, and other simulated world when things "happen"
4) Input - Entity that can handle the users input to the simulation
5) *Feedback - view, sound, vibration and other game feedback should be under this umbrella contains  *Renderer(s) - given a "GameObject" render it's contents for each simulated object that has a visual representation we have a *Renderer (i.e. TileRenderer, MarbleRenderer, etc.)

At minimum, you should be able to run the simulation with the State, the Loop and the Rules... (assuming the simulation doesnt require user input) this makes it much easier to port the game to multiple platforms (because they all have rules for rendering that are heavily console specific)

I think it was when I started to see that the UI thread (I'm using a SurfaceView) was relatively decoupled from the GameLoop that I realized that the "simulation" metaphor made so much sense... Lemme elaborate:

Lets say you were given a "simple" physics problem  the usual car A leaves Boston travelling at 40 mph and car B leaves New York travelling at 60 mph (where will their paths cross?)
You can "solve" this problem using a simulation with the following gamestate
GameStateObject
name : Car A
location : Boston
location Lat /Long:
422171512:00 noon
speed: 40Mph

GameStateObject
name: Car B
location: New York
location Lat/Long:

4047735812:00 noon

speed:  60mph

Then you have a GameLoop that basically simulates elapsed time and asks the GameRules to update the GameObjects (A and B) location based on their speed and the time that has elapsed since the last update (the GameRules also determines when to "stop" given the latitude and longitude of both cars (Car A and Car B).

Anyways doing this in practice requires a great deal of discipline, (and much more code) but adds a ton of flexibility... the renders can render things completely differently if they are decoupled from the state of something (3rd person, first person, etc.)  But in a generic sense, time passes and things happen in this simulated world how the user manipulates and perceives this is becomes a different issue.




Wednesday, August 18, 2010

Development & Release Aware Android Apps/Builds

What am I talking about and why would I need this?

Use Case
An Android application that collects data from the client, and then ships this data (via an HTTP POST) to be processed on a server.  This have 2 server locations/endpoints that will process this request:

  • "development" environment ("http://www.processme-test.com/development")
  • "production" environment ("http://www.processme.com/release")

So the crux of the problem lies in a property (or set of properties) that contain the server url for the post must be different between the development and release version of the android application.


in pseudo code terms:
if (inTestMode()) {
     serverUrl ="http://www.processme-test.com/test";
} else {
     serverUrl ="http://www.processme.com/release";
}
When I first looked into it I wanted a mechanism to find out (programatically) if the APK file was signed with a Development Certificate or not to accomplish this :(.  After looking and searching, I found no mechanism for accessing information about the certificate.  Other folks had recommended doing things like customizing ANT scripts to replace text in some of the source Java files, but I thought that was kind of a hack (and certainly doesn't scale well).  Also the problem with doing this is I would like to avoid having ANY of my non-prod properties classes etc. appear in the release version of the application. (using scripts for replacement  seems error prone) Another property I ran into is Config.DEBUG and I thought I might be able to use this, however in practice it seemed th value for this parameter was always false (even when deploying a development debug build to my Htc incredible). :(

Ideally the solution would be:
1) optimized for development (i.e. make the common case fast) specifically since our team is using eclipse and the majority of my builds (90+%) will be development where the build is signed with a Development certificate
2) simple to script (in ANT or MAVEN) so either the development or release versions can be built with different build targets
3) no development code and properties files should find their way into Prod/Release build
4) scalable to allow multiple properties and strategies for overriding (you always start out having one property (like a server url) but realistically there may be many properties that you want overrides for.

...Long post will be continued next round

 

Sunday, August 15, 2010

Android clocks...(SystemClock, AlarmManager, etc.)

So as it turns out, the Android Dalvik VM has better built in mechanisms for dealing with time and scheduling.

Core timekeeping facilities. Since I am developing a Poker Timer (where an alarm, rings every 10/15 minutes or so) I wanted to highlight some important things that need to be accounted for in these APIs in order to use them with PokerTimer.

from SystemClock Javadocs:

Three different clocks are available, and they should not be confused:
  • System.currentTimeMillis() is the standard "wall" clock (time and date) expressing milliseconds since the epoch. The wall clock can be set by the user or the phone network (see setCurrentTimeMillis(long)), so the time may jump backwards or forwards unpredictably. This clock should only be used when correspondence with real-world dates and times is important, such as in a calendar or alarm clock application. Interval or elapsed time measurements should use a different clock. If you are using System.currentTimeMillis(), consider listening to the ACTION_TIME_TICK, ACTION_TIME_CHANGED and ACTION_TIMEZONE_CHANGED Intent broadcasts to find out when the time changes.
  • uptimeMillis() is counted in milliseconds since the system was booted. This clock stops when the system enters deep sleep (CPU off, display dark, device waiting for external input), but is not affected by clock scaling, idle, or other power saving mechanisms. This is the basis for most interval timing such as Thread.sleep(millls), Object.wait(millis), and System.nanoTime(). This clock is guaranteed to be monotonic, and is the recommended basis for the general purpose interval timing of user interface events, performance measurements, and anything else that does not need to measure elapsed time during device sleep. Most methods that accept a timestamp value expect the uptimeMillis() clock.
  • elapsedRealtime() is counted in milliseconds since the system was booted, including deep sleep. This clock should be used when measuring time intervals that may span periods of system sleep.
There are several mechanisms for controlling the timing of events:
  • Standard functions like Thread.sleep(millis) and Object.wait(millis) are always available. These functions use the uptimeMillis() clock; if the device enters sleep, the remainder of the time will be postponed until the device wakes up. These synchronous functions may be interrupted with Thread.interrupt(), and you must handle InterruptedException.
  • SystemClock.sleep(millis) is a utility function very similar to Thread.sleep(millis), but it ignores InterruptedException. Use this function for delays if you do not use Thread.interrupt(), as it will preserve the interrupted state of the thread.
  • The Handler class can schedule asynchronous callbacks at an absolute or relative time. Handler objects also use the uptimeMillis() clock, and require an event loop (normally present in any GUI application).


    The AlarmManager can trigger one-time or recurring events which occur even when the device is in deep sleep or your application is not running. Events may be scheduled with your choice of currentTimeMillis() (RTC) or elapsedRealtime()

The Poker timer I'm writing will have to use the AlarmManager and elapsedRealtime to account for the device being run over long periods... the only caveat here is that I need a mechanism for pausing, so the alarmmanager needs to be able to dynamically change it's schedule if the user pauses the timer.

Monday, August 9, 2010

Learned so far

In a short amount of time, i have been able to get up to speed very quickly with developing Android Apps.  Gotta hand it to the folks at Google, first with App Engine (develop server side applications using Servlets) and now with the Android being Java-based, they certainly do cater to the millions of folks who know Java.
Anyways I've probably spent 50 hours total (installing Android, getting things configured, looking over examples, and developing) And here's a bulleted list of things I've done and am now comfortable working on/with in Android:

The Basics

  • Activities
  • Intents
  • ADT (eclipse plugin for Android)
  • Layout Managers
  • Integrating Resources (using R.)

Integrating with Platform/Tools

  • Using Temporary Storage
  • Integrating HTTP (Posting Data from the Phone to a Web Location)
  • Multithreading (spawning and running threads)
  • Integrating with the Camera
  • Integrating TTS (Text To Speech)
  • Querying and using users Contact Information (Querying Phones information)
  • Using SQLLite (Database)
  • Integrating Sounds (Button Clicks)


  • Drawing Api
  • Dynamic UI (showing and hiding view elements)
  • Sprite integration and manipulation
  • Image Manipulation (handling different Image formats, scaling/resizing images)
  • NinePatch (using Draw-9 tool)
  • ImageButtons (buttons that change when focus, selected, etc.)
  • Page Transitions (Fade, Slide)

Not bad considering it's been only about 2 weeks of casually looking at it... I have lots more to learn, but so far, the platform and tools (ADT, Emulator, Draw-9, SqlLite)  have been excellent

Thursday, August 5, 2010

...Need a new Language

Italians, we are an expressive people... sometimes, when I have big ideas, (and those creative juices start flowing) I use my hands and start making (embarrassing) sound effects and somehow, you can present an idea (and amazingly some people understand my "vision").

It's often difficult or frustrating  to try write or visually represent ideas, it almost always limits them... there is something lost in the transition from the idea in your head to the description on paper...

...Then along comes mobile technologies and this divide is even more evident. Having spent time designing websites (from the UI all the way to the mainframe) things we mostly straight forward... HTML is fairly limiting on what it allows, (simple form elements, layouts, static images, it's "boxy" layout) and rarely do you deviate from the simple label form element submit button approach.

In mobile, however, things are changing...  I took a look at some old requirements documents for a mobile application that we did recently, (it seemed kinda boring based on the document), then I saw the application demoed and it certainly seemed more "alive".  In a former life, I worked with the creative team who gave me screenshots for how they wanted a ui to look, I would break things down then slap them into Html in a way that would appease all of the browsers and also look good reguardless of screen resolution or window size. Sometimes you have to make tradeoffs, but (for the most part) you can get things to look pretty spot on. (And for my client at th time, that was good enough)

In mobile, things are different because the "interaction is core to the device"... I say this because you have much less space (on the UI) to deal with, However you have access to all of these tools (compass, accelerometer, GPS, camera...).  You don't have a "sedentary person in front of a keyboard and screen" anymore, you have people on the move, and IMHO you need to take advantage of the platform to make an application successful.

Anyways I think we need a new "language" or way of communicating ideas (i.e. customer requirements) so that less is lost between an idea and its implementation in the mobile space, 'cause screenshots and flowcharts leave much to interpretation. (especially with all of the  features in these mobile apps (i.e. sounds, vibration, more robust animations, accelerometers, compasses, cameras...)

Into the Droid...

Learning a lot of Android... blogging to can keep track of my "learning" progress.  BTW "Into the Droid" is a reference to the 1971 Black Sabbath classic "Into the Void". (it's also been remade many times, and even by artists like Nine Inch Nails

So this is going to be kindof an ugly post, So here are a few things I'm going to be looking into:
  • QR Codes - 2d barcodes for applications (use the camera and perform some action)
  • Patch-9 - the image stretching stuff for android (need to understand for work project)
  • Widgets - Im creating one for my "Poker timer application"
  • Services - Creating one for the poker timer widget/application
Also I'm in the process of getting a domain, so I can upload stuff to market.

More relevant content to follow...