Welcome to my Programming Blog...

I am currently working on a couple of projects: An original game called "Implosion" which I am porting from Flash to the iPad, and a remake of Q*bert in Python (pygame), as part of the class I am teaching. Please feel free to use the "Labels" (at right) to follow a specific project or theme. If you are one of my Python students, I recommend that you check out the Python thread.

Sunday, October 17, 2010

#VTM_iPhone notes on moving to 3d

Here are my notes on Michael Daley's presentation on moving to 3D.

A subject that scares the heck out of everybody.

Can do an awful lot without being a genius.

Http://71squared.com
Book: "learning ios game programming"

http://Particledesigner.71squared.com

Sample code is not optimized, for clarity, but still gets good performance.
Prototype project http://tiny url.com/28jp4pm

A turret game - play around with it!

One of first things you need to do to the opengl template is to ad a depth buffer. Added to createframebuffer method. (remove it in delete frame buffer method, too.)

Next must setup the perspective projection to td3dviewcontroller.mm in initOpenGLES1. Then set up the model view matrix. Setup light, fog, etc. In same method.

The math - don't need to be a math or physics genius. But you do need to have some basics, vectors, points, dot produce, cross product, normal. But the work has been done and coded in classes: SSvectorUtil.h,SSMatrixUtil.h
(found in matrix & vector folder in project, if you're curious.)

--------
State management in OpenGL

It will set a state even if the new value is the same as the old. Perhaps encapsulate the OpenGL state machine, which is what Michael has done with OGLState class.
--------
Creating 3d models

Blender. (free)
Jeff lamarche's blog has a great exporter for blender.

Blender can unwrap the shape (to a UV image) or can let you paint the vertices. Export to a png image. Then export the vertices and normals.

Each model's geometry, normal &texture data is loaded into static Vertex buffer objects.
Each model's text is created as an instance of Texture2D

Reuse models and textures where you can.

Michael has created an AssetManager class that keeps track of all these reusable assets.

(A Mipmap contains several images of the same thing that are prescaled down.)

Collisiiion detection - hard to do fast in 3d. But it has been solved. See bullet3d physics engine. (free) put out by a guy at Sony.

When we create an object, we set up it's physics object. In missile.mm class, for instance, initPhysics() method sets up the model for its physics.

Then in the viewcontroller run its initphysics() method. Also sets up a mo course collision detection shape for things - only checks the "tight" collision mesh if the course one has a collision.

Then in the view controller's game loop (update with delta) calculate the physics. Make sure that the physics update is not directly synched to the screen refresh rate.

------
Setting up the camera

To draw objects, you really are moving the world around to center the objects location and drawing it "here" then moving the world to the next object. Then you move the world to center on where the camera is and set it "here."

Ship class - found Internet code on "autonomous steering."

--------
Moving around

When set up game, set up core motion - reads the gyro 1/60 sec. Then in drawFrame method, get the attitude from the gyro and then applying that matrix to the model view.

Q&A: memory management : recommends caching the model. There is no hard/fast rule. Just kept a pool of allocated objects ahead of time and reused over and over again.

- Posted using BlogPress from my iPad

#VTM_iPhone notes on using cocos2d for game development

Here are my notes on the "Using Cocos2D for Game Development" presentation by Rod Stougo

He has a book coming out soon.

Cocs2dbook.com

Free!

OpenGL es rendering and performance without having to learn OpenGL es to get started.

(you get access to full source code)

Www.cocos2d-iPhone.org/download

Recommends the unstable version


Sudo ./install-templates
This puts templates into Xcode. Box2d is physics engine, so is chipmunk.

Comes with two sample programs, for Mac games and ios games.

Lots of samples. Make sure you select both active target and active executable.

Uses a movie metaphor - scenes, director, layers. (ok, the actors are called sprites.)

Z-layers are compositing order, and there are z-values for the objects within the layers.

Layers can subscribe to touch and accelerometer events

Actions are an easy way to apply transitions, effects and animations to the sprites

Moveto, move by,scale by, scale to, fadein, fadeout, rotate,....
Ccsequence combines actions sequentially, ccspawn combines actions simultaneously

Change gears: Optimization
Starting to get complicated sending info if you send images one at a time - make a sprite sheet. Aka a "texture atlas" zwoptex online sprite sheet creator.

Physics engines box2d and chipmunk(newer) pretty similar. Box is c++, chipmunk is c. Wrapped in objc. If you use c++ code, implementation files must have .mm suffix for complier.

Cocsdenshion sound engine- wrapper for Avaudiiplayer and openAL

Simple, synchronous and asynchronous, background and sound effects

Particle systems!

Cocos2dbook.com

Physics world with a graphics world on top. Calculates where the objects are and then moves the graphics on where they should go. The sprite doesn't have any physics logic.

Event handlers: cctouchesbegan

To make the snowballs, find where the touches start and end and find the delta. Create physics object, and create force or impulse. Add a small rotation

Collisions have masks to indicate which things have detectable collisions.

Can animate the appearance of sprites easily




- Posted using BlogPress from my iPad

#VTM_iPhone notes on game center talk

My notes on the game center talk by Jessica Kahn.

Social gaming functionality, provided by apple

- authentication
-leader boards
Achievements
Friendsinvitations and matchmaking
P2p networking
And one other.

Ios 4.1+

Game center is just catching on.
Why bother? Lots of competition, but game center is a free way to raise visibility. Also, game center advertises what your friends are playing, even if you don't own them. Friends can invite you to games you don't own.

Competing solutions: Plus+, OpenFeint, ScoreLoop, Crystal, and 3rd party

Tapulous network (jessica's company) has some things that apple doesn't, some things it does, but lacks some that apple does.

Bundle identifier, game kit linkage, view controller-based user interface, Ability to code with blocks

BundleID (eg. Com.tapulous.gamecenterdemo)

Best to do a weak link, checking for game kit and ios4.1 or later on user's phone

Leaderboards, achievements, and matchmaking all use view controller subclases for their UI.

GameKit often takes blocks as parameters.

The Basics:

Authentication, leader boards, achievements
Auth... Do it as soon as your app can display ui. One line of code, with a block as error handler, triggers a welcome back overlay at top of screen.
With multitasking, might log out while you are in background. Be observer for GKPlayerAuthenticationDidChange

-----> supporting authentication is enough to get the exposure benefits of game center!

Leaderboards
Configure in iTunes connect
Report using GKscore
Display using GKLeaderboardViewController
Or
get the data from the game sever and display, yourself

Reporting - if it fails, stash the data locally, and try again soon. Don't need to tell user, according to apple interface design.

Leaderboards show up in game center, even if you don't display them in your app.

Achievements are just like leaderboards.
--------
Bonus points

(I had to step out, so much of this is omitted)
Matchmaking - came back in the middle. Looks a bit complicated. But then, romance usually is.

Suggested: doing a lot at boot time - but watch out about interfering with user experience.

Peer-to-peer networking
High-level interface.
Start by making the match (see above)
Decide which data to transmit - as little and as rarely as you can.
You can transfer data reliably or unreliably. Send data to all players or to one specific user.
Data must be "byte (sic) sized" (sic)
Read up on two GKMatch methods
SendDataToAllPlayers...

Voice chat
Use GKVoiceChat & GKMatch
First create and make active a playAndRecord AVAudioSession
Then create one or more voice channels using voiceChatWithName
Start and stop ability to talk with methods on GKVoiceChat.

-------
Gotchas

Fragmentation, due to unsupported os versions.
Complexity, if game is OpenGL based
Beware flaky networks!
Prevent cheaters, you can't reset a leaderboard.
- if you are storing scores, save it in a way so that people can't read it.
Invitation handlers can happen at inopportune times.
Network activity can hamper in-game fps and audio performance.

Great questions, but I was distracted by q/a and did not write them down. Some on age-appropriateness, some on testing, some on handling the modality of authentication requests.

She's vp of engineering Disney mobile and is "hiring like crazy"


- Posted using BlogPress from my iPad

Ow... Sore brain. #VTM_iPhone

So here it is, the morning of the second day of the "Voices that Matter" iPhone conference. (way better than the "Irrelevant Noise" convention.)

My brain is sore. It was a very long - but inspiring - day yesterday, and we just heard a great keynote from a guy dressed as a pirate talking about not sucking. I'm looking forward to a series of great talks about stuff I'm really interested - and I hope that I'll be able to absorb it all. I need time to reflect, to tinker, to play, but I also want to be ready for the next great talk, to cleanse the palette, so to speak.

Oops. The next talk is starting!

- Posted using BlogPress from my iPad

Saturday, October 16, 2010

#VTM_iPhone notes on STAssertTrue

Here are my notes on Graham Lee' unit testing presentation. Note: coming into this, I have heard of unit testing and have a general idea of what it means, but I have never seen it done. I presume it means to do an automated process of running a method with different data sets and checking that the answer is what you wanted each time. Probably, it includes boundary cases, but I don't know.

Software engineering goals: make money (sometimes)... By making something that the user wants. - meets their requirements, without being too expensive.

Testing isn't about finding bugs - it's about validating that your code does what it should., finding bugs is a secondary effect.

The earlier a bug is introduced, the more it costs if you find it late. Unit testing helps with the design and build aspects reducing errors.

Undirected unit testing - checking the minutiae of the program, the opposite side from external testing by somebody who doesn't know the program I.e., the user.

test driven development:
*black-box thinking for the developer.
*YAGNI you ain't gonna need it. Only write the code you need.
*Avoid regression bugs. Keep the tests around, so later code doesn't break earlier code without your knowledge.
*assists accurate planning

Find bugs before....
...your customers do.
Zune didn't know about leap year. Ah, they're incredibly rare.
TDD != [bullet silverColor]
you can't assume the developer understood the problem...or that the requirements didn't change, and it doesn't guarantee successful integration
Takes time to write tests, and you actually run them.

How TDD works: RED - GREEN - REFACTOR
What do I test? Anything within reason - time, environmental conditions (ie DBs, filesystem, network - not repeatable)
Evaluate risk - known buggy code, heavily used code, tricky problems
When do I test? At any change, plus before release.


Testable code: short classes with short methods, each with obvious effects, few & predictable side effects, with helper data passed in - not discovered, low "cyclomatic complexity" - don't need to test thousands of combinations.

This means the end of a @interface GodView:UIViewController


OCUnit and XCode3 or XCode4
GHUnit ... Better than OCUnit? (Does it run on the iPod, itself?-HH)
plug of kaleidoscope app?

Fakes and mocks? Fake is dummy input data, and mock is dummy local data, I think.... - HH

Recommends "refactoring: improving the design of existing code", "test-driven development"(Kent beck), "test-driven development: a practical guide", "xUnit test Patterns", et al

Iamleeg at the usual sites, twitter, etc.


Note: I know more than I did, but I still don't know enough that I am ready to go out and start unit testing. A lot of theory here, but I probably needed a more practical demonstration.

- Posted using BlogPress from my iPad

#VTM_iPhone notes on multitasking presentation

Here are my notes on jeff lamarche's presentation, "multitasking the iPhone sdk way"


One of the biggest complaints from developers about early ios.

Actually, it had multitasking from day one - lots of first party apps running once.

Of course, apple just does this to be mean.

Real reason - battery impact and foreground application responsiveness

The audience at this convention - we're the outliers. Most people see computers as an obstacle.

"Devices for the rest of us."

Myth: with ios 4, we have "true multitasking." but don't use it for its own sake if you don't really need them. Will a push notification work?

Basically, you can maintain state, and can't do much (if any) processing in background.

Legacy apps can be set to opt out of multitasking. In info.plist.

Four types of background tasks - background audio, voip, navigation & location tracking, task completion

Playing nicely: application lifecycle
Before 4.0: not running, inactive, active
application delegate fires when state changes
Active --> inactive: applicationWillResignActive
Active ->not running: applicationWillTerminate
At 4.0:
States
foreground: active, inactive
Background: suspended, active
Not running

If you want to keep running in background, keep your (over)head low.

ApplicationDidEnterBackground
ApplicationWillEnterForeground

Problem: if you are in background, will not get notification if the program is killed. Issues for persistence.
--------
Background
Should not run code that does drawing or leverages the gnu
Should close any network listeners
Stop advertising or looking for bonjour services
But make sure you resume when you return tho the foreground

Generally, should dismiss alerts, action sheets.
If multiple buttons, pick the non-destructive option.

Background - hide sensitive info in UI

Shouldn't access shared data APIs - calendar, address book, music/media library

Hint: instruments works fine with background applications - in fact, a very good idea.

You can still set base SDK to 4.x and still target 3.0. Delegate methods just don't get called.

Don't check hardware or OS version!

Task completion API - general purpose. Can request to keep running - to finish a process. Must finish in given time limit, or will be killed. You do have a chance to clean up and save.

How long? Not documented. Simulator gives 5 minutes. You don't have to wait for app event to request time.

See handout for sample code.

Uses blocks.... Get over it, and they are coming. Suddenly, they will click.

Nb: if it's long enough to require task completion, it needs to be off the main thread.

Background audio

It's opt-in. Must identify that you use them in your info.plist file

Your background app will override foreground audio!
Background apps using radios can drain battery. Be sure to close down the connection.
The background audio can also record sound!
Must implement avaudiosessiondelegate - should implement begin interruption and end interruptooonwithflags

In, must override canBecomeFirstResponder to return YES.

Apple has put a lot of thought about this. Balance between developers and users.

If you can't find a way around this: bugreport.apple.com

Stop drawing? Mostly automatic. You do (seem) to get some time after the notification arrives that the app will go inactive

Jeff_lamarche@Mac.com

- Posted using BlogPress from my iPad

#VTM_iPhone notes on around the block with blocks talk

Here are my notes on Bob Clair's "around the block with blocks" talk

I feel kind of foolish about this - I hadn't heard about blocks until today, so I'm glad I'm here for this presentation.

He says there are some typos in original presentation posted , but new one is forthcoming.

Blocks are not in ios3.2 ( which would explain why I haven't heard of them.)

What problem are we trying to solve. How to package up some functionality (some code to be executed) to pass on to somebody else.

In other languages, called "closures" or "anonymous functions"

Blocks are an apple addition to C, objectiveC, c++

New in snowleopard and ios4

Diversion 1: functions calls are jumps, which you can make dynamic by using a pointer to a function.

(ugly) Example: Void (*myFunctionPtr)(int)

See PowerPoint for code with example. Too much to type!

Main use of a function pointers is for callbacks. (hooks? -hh)

This stuff works, but it's a pain in the butt, particularly when passing lots of data.

You can also do this with selectors SEL objects.

Diversion#2: nsinvocation
Bundles up (freeze dries) receiver, method and arguments. Then the invocation can be interrogated to find the return value.

More ugly code as example in PP...

The issue is that these things are a royal pain to set up.


Blocks:
^(arg list) {body};

No return type declared. This is a block literal.

There is no name for this it is anonymous.
A trivial example.
^(int n) {return n*2;};

How do you call this?

Int j = ^(int n) {return n*2;}(9);

But this is dopey. Send it to a block variable.

Declare a variable that is a pointer to a block

Return type (^myBlock. Afasdhjohfoafhgkj

Int (^doubler)(int);
Doubler = ^(int){return n*2;};

Too fast to keep up. See pp.

Funny syntax when trying to pass a block as a function argument.

So what is the big deal?!?

A block has read only access to automatic variables visible in it's enclosing scope! <-------

When you declare the block, it freezes the value of any extra-scope variables it references in the block. The variable is copied into a structure with all the ?

The block is created on the stack, not the heap. Blocks have same lifetime as an automatic variable (local variable?) when the block literal goes out of scope, it is undefined.

A block variable is declared with type edifier __block

__block int myBlockInt

Can be read/write by a block in the near by scope.

Under the hood.
Blocks are actually objectivec objects

Only example of stack based objectivec
A private subclass of nsobject
The header isn't provided so you can't subclass them or monkey around with them.

Passing a block into a function as an argument is safe, in a single thread.
What if you want to pass the block to another thread or pass it back out of a function to use later?
To do this, you must... Copy the block. He mentioned some c methods, but I'm just listing objc techniques here.
In objc, use the [. Copy] method on the block, since it descends from nsobject. The copied block goes to the heap, and moves any __block variables and fixes any links to those variables. ( mostly works)

Memory management in objc, remember doing copy requires a release or autorelease.

Some uses for blocks: collection classes, animation, threading, completion handlers

Also useful in grand central dispatch - give GCD blocks to run for you.

Gripes: 1) block is a word already in use 2) smashes encapsulation 3) function oriented, not object oriented 4) encourages Design Your Own Language Syndrome

Plug the book "Learning Objective-C 2.0" by Robert Clair. This is chapter 16.


- Posted using BlogPress from my iPad