Skip to content

Upon reading iFanzine’s enticing article about our coming title, Project Spectral, I noticed that a link pointing back at the blog directly (and somewhat logically) hit a one year old article: Appworks 2011.

So I thought it would be a good idea to quickly summarize what we’re up to at Anime 3D SFX.

Antistar 3D: Rising – New chapters in dev?

YES. 90% of game features developed for Project Spectral (see below) will support the long awaited Antistar update.

Please bear with me; Antistar will remain a chatty game; Antistar will remain an adventure game; Antistar will become a physics enabled action game with light RPG elements. The first episode was stir-fried over 8 months. Can’t entirely apologize for stewing up a sequel.

Project Spectral – Why? What? When?

I’d been toying with the idea of creating a dark piece - an interactive journey into a universe filled with nameless fears, with just a tiny light shining at the end of the tunnel.

For the best part of 2011, the Antistar project had been the driving force behind the development of our game platform - around last September I checked what we’d got and I thought, enough for an exciting new game, not enough for the Antistar update.

In the meantime my ideas about gaming and my approach to game design have matured so I thought it would be interesting to put that into practice, giving us a chance to explore and validate some of the goodies I’ve thrown into the game engine (see ‘our game platform is evolving’, below).

So I cooked up a few key features for an action game and started hunting for musicians, telling myself above everything else this game needs bewitching music and ambiances and I’m surely not the person that will create this.

More about Spectral later this month…

Our game platform is evolving

Listing a few exciting features is better than telling the naked truth*

  • NPC AIs – You know how so many game AIs can’t do much other than attacking the player? It’s in part because many games are designed to play this way, but I think we can offer interesting gameplay going way beyond that.
  • AAA Pathfinding – Navmesh oriented pathfinding, including pathfinding between disconnected / moving (!) platforms
  • Bullet Physics – We have integrated Bullet Physics, a popular, open source physics engine also used in Blender and MMD.
  • Level editor – Blender based.
  • Animation software integration – Blender but also MMD and others (via COLLADA).

*Naked truth: At the moment I care about how clean and productive our engine is a lot more than about what it actually does).

Outlook

A recurrent question is whether I’ll port our stuff to Android. The answer is: not very soon (dear Android user, an infuriating article awaits your wrath).

For now I’d say that never mind well “documented” misgivings, I believe Apple are aptly supporting small developers, whether coincidentally or not.

Regarding plans to port to JME, scrap that; while the ‘bright new kids’ ( Apple? Google? Dem new kids? ) didn’t invent anything and trashing decade old industry standards and technology may be a waste, sometimes moving in early appears to be the recipe for failure (remember Ngage?). Either way I vaguely heard that Nokia is migrating to Android so there’s nothing left to say.

This year I’m looking at the Mac App store and feel excited about the NGP; additionally, given intrinsic compatibility at the GPU level, the 3DS is somewhat attractive – assuming the old wizards actually open up to to smaller studios, that is.

And the iPhone 5, yea. I really want an iPhone 5 so don’t 4S-bulls**t me anymore.

This week I deleted around 7,000 spams and it may well be that I accidentally removed comments from friends and genuine readers as well. Sigh

I’m reluctant to setup captchas because I can hardly read them nowadays, nor do I wish to discourage genuine readers from commenting and asking questions.

Your feedback encourages me to improve the quality of my articles.

Along with a few brand names, the following words are now blacklisted:

hosting, awesome, impressive, seo, dramatically, wireless, amateur

Additionally, comments will be closed after a week. It’s not great but still the best compromise for now as it helps reducing spam.

Generally speaking, avoid superlatives (awesome, fantastic, great, etc…) in your comments. Comment to ask for information or clarification or discuss a specific point, not to make noise. As it is superlative comments are spam 99.9% of the time.

Regarding the idiots posting spam comments, I got nothing to say. Regarding the reckless ‘hackers’ providing spamming/injection software, please DIE.

Thanks for reading.

This tutorial is intended for artists with prior animation software experience.

Your Blender Workspace

Blender uses non overlapping areas.

  • To resize an area, drag its edge.
  • To split/join areas, right click on the edge and select split/join in the menu. Experiment.
  • At the bottom left (or top left) of each area, there is a button used to select which editoris showing. The most useful editors (for animation) are:
    • 3D view – shows your model/world at the current frame.
    • Dopesheet – shows your keyframes
    • Timeline – not so useful except to set the beginning / end frame, but you can minimize it until it takes almost no space
    • Outliner – shows a hierarchic view of your
    • Info – it’s also an editor but in your default workspace it’s almost completely minimized showing File/Add/Render/Help menu, please think of it as a “menu bar”
The stuff that looks a bit like ‘areas’

In the 3D view there are little [+] signs on the top left/right and clicking on that or pressing [T] or [N] you can view extra Tools or (Numerical) information. An you can get rid of them by dragging the edge until they disappear.

Menu bars / palettes

Most editors have kinda menu bars or palettes with lots of elements – often too many to fit the area size and scroll bar / arrow to view the missing stuff.

  • With a 3 button mouse, middle button + drag to scroll
  • With some laptops, two finger drag to scroll.

Changing view parameters (3D view)

Use the numerical keypad (1,3,7,9,0,+,-) to change view parameters (experiment).

If you are not comfortable with the way bones / meshes are displayed etc.. please check the eye candy section at the end of this tutorial.

My first keyframe!

I assume you have a rigged model handy.

  • Use [left/right] arrow keys to scrub to frame zero.
  • In 3D view, [right click] on a bone to select the armature.
  • At the bottom of 3D view, select pose mode.
    • You can change between pose mode and object mode using [control+TAB] and you can also toggle to edit mode using [TAB]
    • These are 3D view modes and there is also weight paint and vertex paint mode.
  • Let’s move a bone!
    Right click on a bone to select the bone. Use [G,R,S] to grab/rotate/scale then slide the mouse and press:

    • [return] or [left-click] to confirm
    • [ESC] or [right-click] to cancel.
  • Set a keyframe. I like to keyframe everything at frame 1 (NOT frame zero) to save the rest position when starting a new animation.
    Press [A] to select all the bones and [I] to insert a key frame, after pressing [I], select your option in the menu:

    • Location, Rotation, Scaling to just set the matching parameter
    • LocRot, LocScale etc… shortcuts to set several parameters at once.
    • LocRotScale. Set all 3 at once! Very handy.
      To keyframe everything I use this one.
  • Set another keyframe.
    • Left/Right key to scrub to frame 10.
    • Right click to select the bone and [G,R,S] to grab/rotate/scale like we did before.
    • [I] to insert the keyframe select LocRotScale and [return] to confirm.

A Note

Sorry for introducing so many shortcuts. If you experiment you can do the same with manipulators and of course when selecting in a popup menu there is no need to use [up/down] arrow and return, you can just click instead BUT:

  • [RETURN] instead of left click to confirm after moving a bone avoids making the mouse cursor slip while validating bone position
  • Generally speaking I love using the keyboard to do the technical work (browsing menus etc…), and use the mouse to do the artistic work like moving vertices, moving bones etc…

My first animation

Play your animation using [alt+A], [esc] to stop.

In the timeline editor (at the bottom usually), you can set the Start and End either by holding left mouse button pressed and sliding or by entering a number.

Creating animation libraries (like walk, run, jump etc…)

If you are impatient, please skip to the next section for now.

You noticed the dopesheet is showing keyframes for the currently selected armature/rig.

At the bottom of the dopesheet there is a button that says dopesheet, click on that and select Action Editor instead. The editors are almost the same.

All your animation data is stored inside an action. In action editor you can rename the action. And there are a few annoying buttons on the right and left of action name:

  • A button that reads ’2′ (I’ll explain)
  • Often, the [F] button is showing (I’ll explain)
  • The [+] button to create a new action.
  • The [x] button to unlink the action (I’ll explain)
  • On the left of action name there is a button that you can use to change the current action

We can create action libraries, once you see the benefits the buttons are easier to understand.

  • Your blender file can have lots of actions
  • Even if you delete the model and rig the actions are not deleted.
  • Whatever action is the current action is also the action that you can play when pressing [alt+A] and the action that you are editing now.
  • If you have a rig with the same bone names, you can reuse an action created using another rig/model
  • You can import actions from another *.blend file.

Now let’s explain the weird buttons:

  • The button that reads ’2′ tells us how many rigs are currently using this action. But if nothing uses the action it gets deleted so usually it shows ’2′ instead of ’1′.
    If we press on that button, we make the action single user. In practice it creates a copy of the action and changes the name a little. Suppose I did a jump animation for a tiger and I want to adapt it for a lion, then I will right click on the lion’s armature, select the jump animation and start editing BUT I don’t want to spoil my tiger animation so I press the button (now shows ’3′) and it quietly copies the animation so I can start editing safely.
  • The [F] button can be pressed or depressed. By default, pressed to prevent the action from getting deleted when nothing’s using that action.
    If you really want to delete an action, press this [F] button and after exiting blender, the action will be lost forever (if nothing is using it).
  • The [x] button. It does NOT delete the action, it’s just a way to tell blender that we don’t want to edit/view the action. After pressing [x] you can go to the action list and re-select it like nothing happened.

Timing animations

We can create animations but to get the timing right and for good housekeeping, the action editor is very handy. Like I said it kind of does the same as the dopesheet (but please use the action editor).

I assume your bones are well named otherwise the action editor is useless.

  • In the action editor you can scrub using left click and it moves the green cursor.
  • To select/deselect a keyframe, right click on it; they show as white (not selected) or yellow (selected) dots.
  • Hold shift and right click again to select more keyframes.
  • To move or scale(!) keyframes, press [G] and slide the mouse then click or [return]. Experiment.
  • To delete keyframes, press [delete]
  • To duplicate keyframes, press [shift+D]
    • For example to make the first/last keyframes the same, select the whole column of keyframes and press [shift+D] then drag to the end of the animation and left click or [return] to validate ( [esc] to cancel)

Eye candy

Use [Z] or [sfhit+Z] to switch between views, like solid or wireframe.

While your armature is selected, check the properties editor. There is a tab with a little guy icon. This shows armature properties.

Other than the Display section, messing around with this isn’t good unless you’re rigging the model. But the display section is useful:

  • Check/uncheck to display/hide bone names and other stuff
  • X-Ray mode lets the bones show through the mesh in shaded mode. I love it.
  • At the top, different methods to display the bones. Octahedral is kinda standard but I prefer Stick mode.

Finally, in the Skeleton section, you can hide/display bone layers; if the rig is neatly arranged it may not be necessary but can help understanding the relations between bones and manipulators.

Going further

In Objective C you can easily retrieve a class by name and instantiate it:

Class clss=NSClassFromString(@”Foo”);
id foo=[[clss alloc]init];

The above is perfectly equivalent to:

Foo* f=[[Foo alloc]init];

If your package doesn’t provide a Foo class, clss will be nil.

Sometimes it’s a good idea to make sure that the class you retrieved is a subclass of a base class or complies to a protocol; for example you can use this.

BOOL okay=[clss isSubclassOfClass:FooBase.class]

There are a few uses for this. Notably this kind of technique is useful to serialize runtime graphs.

Sometimes also, you want to break type dependencies at compile time,

For example let’s say you have a ‘game shell’ module. You want to reuse the model to run various games. Each game you have may then have it’s own game class. Your game shell might retrieve the name of the game class from a plist and dynamically instantiate it. There are other tricks you might use to achieve the same goal (e.g link the same header against concurrent .m files) but I think this way of doing it is clean and simple.

Similar tricks can be found on pilky.me, and for somewhat frightening(?) hacks of the ObjC runtime, you can read an article on Phrack Magazine.

After almost a year, my third update to the ObjC beginner caveats blurb. 8 new caveats added today (marked with [NEW])

Language/SDK

1. NSArray/NSMutableArray cannot hold ints or NSInteger
>> although NSInteger is notationally similar to NSNumber, NSNumber is an object while NSInteger is an alias for int or long (depending on whether you’re running a 32/64 bits architecture). NSArray can only hold objects. If you want to add a number to an NSArray, use NSNumber and initialise your number with something like [NSNumber numberWithInt:26].
(Yes, you can use standard C arrays, there are quite a few posts about this around)

2. NSNumber doesn’t auto-unbox
>> If you try to assign NSNumber to an int (or, better, an NSInteger), you’re assigning a pointer, not the actual number. To get the actual number, use something like: [MyNSNumber integerValue]

3. Strings don’t concatenate with [+] or [.]
>>
If something like “Score: “+score is what you’re used to, try making friends with:
[NSString stringWithFormat:@"Score: %i", score];

4. In, (void)applicationDidFinishLaunching:(UIApplication *)application {…}not all IBOutlets depending on your nib file will initialize until your view is added to the main window
after [window makeKeyAndVisible]; it should be safe to access all IBOutlets attached to your viewController.

5. I updated the frame property of a subview, but the coordinates look incorrect.
>> after updating the UIView.frame property on a subview, invoke setNeedsLayout on the parent view.

6. NSTimer fires at the wrong time / fires too many times
>> When you allocate/init NSTimer with the usual code, you don’t need to invoke fire(). NSTimer is setup as soon as it’s initialized and fire() shouldn’t be called directly as it, *doh!* fires the timer.
>> Whatever you name your callback method, it should take a unique NSTimer argument ( the selector argument would typically look like @selector(myCallback:) with the semi-colon at the end).
What happened to me is that my timer kept firing over and over even though repeat:NO was set. Adding the timer argument to the callback fixed the problem.

7. You cannot declare new variables inside a switch statement

switch (foo) {

case BAR:

char foobar=’*'; // compile error

break;

}

Use this instead:

char foobar;

switch (foo) {

case BAR:

foobar=’*'; // OK

break;

}

Memory Management

8. Use NSZombieEnabled to crash and get a call stack when your program attempts accessing a deallocated object [NEW]

Google it…

9. You need a symbolic breakpoint to hit malloc_error_break and get a call stack [NEW]

Google it (I feel lazy).

10. Unless otherwise stated, objects allocated as a side effect of calling methods other than [alloc] are autoreleased.

This is especially applicable to objects created using factory methods. Take the following example:

[NSMutableArray arrayWithCapacity:5]; // will be released automatically

[[NSMutableArray alloc]initWithCapacity:5]; // we just created a zombie!

At first, it would seem that [NSMutableArray arrayWith...] forms are just shorthands for [[NSMutableArray alloc] initWith…]. Hell, not quite.

[NSMutableArray arrayWith...] and other, similar factory methods, ‘emulate stack allocation’ for reference types. This means that we don’t need to worry about releasing them, as the so-called autorelease pool will take care of them for us.

When we check our code for memory issues, knowing which objects are kept in memory (on the heap) is essential. One way to learn about these is to scan for alloc, retain and release statements. The so called ‘shorthand forms’ allow using objects transiently, without worrying about memory issues, so this convention can help reduce the time spent on memory management.

There are downsides to this for unfortunate beginners:

(1) When we start with objective c, the [alloc[init form appears verbose and cumbersome. So we're likely to create our own shortcuts -- generating 'silent allocations' that make memory management harder.
(2) If we use the 'shorthand' forms, we quickly end up with weird, hard to fix bugs, because we might end up assigning auto-releaseable objects to variables, then these objects get deleted implicitly, and finally we end up accessing... ...garbage(!!!).

11. Beware of  abusing autorelease [NEW]

Autorelease is useful and in some cases you cannot avoid using it:

  • Objects returned by factory methods
    A(n essential) convention dictates that objects created using [alloc] have a reference count of 1. In contrast, callers of factory methods are not responsible for releasing returned objects unless they retain them (see #10)
    Since we can’t use [release] before returning an object we just created, we need to use [autorelease]
  • An object on the call stack may get deallocated if [release] is called.
    Now, it may be argued that only bad design can cause this to happen. Nevertheless one way to solve the problem (it can get nasty) is to use [autorelease]

Now that this is out of the way, beware of practices involving using [autorelease] as a ‘default safe way’. Here’s why:

If an object deallocates unexpectedly following a call to [autorelease] the call stack above [dealloc] doesn’t tell you what caused this object to deallocate.

I don’t see how a coding style involving loosing track of deallocation events can be safe.

12. You can crash the leaks tool in Instruments (seen in Instruments 4.0, 4.1) [NEW]

Recently I managed quirky memory management code that didn’t crash on device or in the simulator, yet crashed instruments. Checking the details, I stumbled on something like ‘invalid leaks data’.

I was about to use up one of my support tickets but reflected that sending my code over and waiting for the ticket to process would take a lot longer than reverting my changes and use the weak muscle to figure it out.

On the downside I got lucky before I managed to narrow it down.

Even if you’re not part of a team, consider using versioning (SVN or whatever new-fangled stuff you’d like).

Kind reminder:

No versioning
=> no diff tool
=> no way to accurately revert changes
=> panic
=> loss of money
=> loss of sleep
=> loss of hair(*)

(*)If you are bald I trust this won’t be an issue.

13. WTF my code crashes when ‘unplugged’ [NEW]

Consider the following case:

  • Your code doesn’t crash when debugging on-device.
  • Your code doesn’t crash when debugging in the simulator.
  • Your code crashes when running in the simulator after pressing the app icon.
  • Your code crashes on-device when running after pressing the app icon.

Then try this:

  • Disable NSZombieEnabled. Quite possibly you’ll see a fairly non-descript crash in the debugger when running the same code.
  • Try to isolate the stack that causes the crash (it’s not meant to be fun but using a dichotomy you might get it done in less than an hour)
  • Re-enable NSZombieEnabled. At this point you may see inconsistent variable assignments in the debug window.
  • Set breakpoints on [dealloc]. Quite possibly you’re deallocating an object that’s already ‘somewhere up’ on the call stack. On sunny days this crashes the device/simulator (hey, it’s actually a GOOD thing). On rainy days it drives the debugger crazy.

Build errors & warnings

14. Warning: Multiple Build Commands for output file …

In XCode, the name of a resource (e.g. a picture to include in the build as resource) is different from the path the resource is retrieved from. Several resources can have the same name, linked with different paths. So for example we can have:

  • foo.jpg (/images/foo.jpg)
  • foo.jpg (/mypics/draft/foo.jpg)

In the final bundle, however these resources are in conflict, they both target /foo.jpg. XCode will issue a warning if resources conflict in this way.

Unsurprisingly, this typically happens when reorganizing project resources.

15. Linking C++ libraries [NEW]

If your project depends on C++/ObjC++ libraries, you may need to add -lstdc++ to other linker flags to your build (see here).

Nibbling UIs (Interface Builder)

16. Action mappings are one-to-many

Yesterday I copied a button from my UI and bound an action to it. Then I was rather puzzled to find that, when I clicked on this button, my game started off with an ominous GL error code. I thought binding an action to a button overrides the previously bound action. It doesn’t. The same user action on the same widget can bind several IBAction targets. In my case this caused the game’s start method to be called twice.

Asset management

17. Use the blue folders [NEW]

If you have hundreds of assets, adding them manually will be a pain. However you can link a whole folder; in XCode’s ‘add files wizard’ select your folder and tick create folder references automatically…

XCode is getting better at detecting changed/added assets between builds (but see #18, below)

18. Sometimes you need to remove your app from the simulator/test device [NEW]

If your code relies on a mechanism allowing to retrieve a resource from one of several locations, you need to delete your app from the simulator / device whenever you remove assets from a blue folder.

Let’s say your sound folder is organized like this:

default_sounds/
---- KO_sound.caf
---- goblin_sounds/
-------- KO_sound.caf

Now suppose you deleted KO_sound.caf under goblin_sounds. Well the goblin specific sound recorded from your little sister’s performance will still load and play because it doesn’t get removed automatically.

Between builds, no files are deleted from package contents. I don’t know whether it’s a bug or not. It’s often annoying.

18th of January (hissing wind, desert sand, husky narrator voice).

“I was looking for a title for my next series of articles when I look up Wikipedia, who apparently decided to bully their users into… …what? Challenging the US congress?”

This obviously has nothing to do with me – writing from my favorite coffee shop in Beijing, I am staring doubtfully at a banner offering three equally enticing options:

  • Facebook (blocked)
  • Google+ (crippled)
  • Twitter (blocked)

Imagine a world without Facebook, Google and Twitter. Imagine my world.

Facebook/ the champion of phatic communication (opted out in 2006).

Google+/ from the guys who pitifully stabbed Firefox using Chrome just when we thought the browser wars were over.

Twitter/ a puzzling social platform priming concision over clarity. With a 140 characters limit, may appeal to regex coders.

No regrets. Be assured we got our own trash and the restrictions don’t do much other than promoting local platforms and boosting the economy.

One thing we do have is Wikipedia. Asking why? Hey maybe Wiki is way too very useful to get all their pages banned anywhere in the world (1)

Jimmy Wales, check your encyclopedia. If Washington makes you feel uncomfortable, there are slightly under 196 countries who will be very willing to host your servers.

Maybe less offensive, the decision not to translate their call to arms despite opting for a worldwide ban. I empathize with scores of users anxiously wondering why Wikipedia is banned in their country today.

And what with the dumbass banners begging for money? Since you guys integrated ads in your mix, how about you played the real ones to finance your s**t? You’d even get pocket money to fight the creepy adpedia virus clogging your system.

Notes

(1) Yea, there are a few countries that block wiki or just certain pages – or just in certain places like US schools. I tried to get the list but it’s in Wikipedia, which got banned banned by Jimmy Wales today. Sorry guys.

The focus of this article is how to import models and animations from MikuMikuDance to Blender. MikuMikuDance, (MMD) is animation software popular with talented animators in the anime/manga community.

MMD is freeware – you can find it:

It is distributed with popular models but the models are not free from rights. Read this on wikipedia to get the idea.

Does it work on MacOS-X? probably not.
Of course you can install Windows on your Mac (use BootCamp). But this is off topic.

Importing from MMD to Blender

Importing PMD models

Although I am not aware of a utility that directly imports MMD files, you can import related model files (*.pmd, *.pmx, *.mqo) and animations (*.vmd). This is ideal to integrate with MMD animators.

A nice plugin to do this is MeshIO, created by Ousttrue. MeshIO handles not only meshes and textures but also the whole rig complete with facial manipulators and physics setup, if any. (compatible with Blender 2.5x/2.6x). For installation, see ‘installing MeshIO’, below (or refer to the readme file).

After installation, to import a model just go to the import menu and select PMD/PMX.

There a couple of things that you should know (see FAQ) below.

Importing VMD animations

VMD files contain motion data. It is possible to import this data into Blender using io_import_vmd, created by Yasuhiro Fujii (tested in Blender 2.59, requires MeshIO)

To use this script save it under addons/ like you did with the MeshIO script – but at this point rename the MeshIO scripts folder to just meshio/ (and you need it to re-enable it as explained in installation notes). Enable the script like you do for the MeshIO script.

To import motion data:

  • Right click on the armature first to select it
  • Go to import VMD or such and select your file – Surely the armature used to animate in MMD should be the same as the one your model is using (it’s matching using bone names).

This will import the animation to the currently selected action in the dopesheet. This way you can create several actions for the same model and include all of them in your *.blend file.

Note: this script had an issue with some rotations; the issue is now fixed.

Exporting Blender models to MMD

MeshIO lets you export rigged meshes to the PMD/PMX format – useful to include a blender model in an MMD project, or to share your model with an MMD animator. In the outliner (inside Blender), your model should look like this:

  • empty object (to contain the armature)
    • armature
      • mesh1 (e.g body)
      • mesh2 (e.g a hat)

It’s easier to understand the required structure if you import a PMD model first and figure how it is organized in Blender. This is especially true if you want to include advanced features like physics or facial expressions.

To export, right click on the empty to select your model; then go to the export menu and select PMD or PMX.

Although your PMD model will work directly in MMD, there is an editor (PMDe – try the links suggested here) that can help you tune your model and add MMD specific shaders.

FAQ/Caveats

  • I exported my model back to MMD but the bones look weird? When working with PMD models in blender, remember that the rigs use ‘invisible bones’ – bones that are not on the main layer. If you modify the rest position you should enable secondary bone layers and modify the bones accordingly (it may be that you don’t need these bones if you are only using the rig in blender).
  • I exported my model to MMD but all the materials are white? MeshIO uses blender’s mirror color for ‘ambient’. This is because Blender does not provide ambient RGB. But by default the mirror color is white, so you should set it to a low value, or zero.

Installing MeshIO (tested on Blender 2.59)

Trying too hard can lead to confusion as there are a lot of files in the archive. Don’t try too hard. Copy the folder named:

blender26-meshio

to the following location:

  • MacOS – Blender > Contents > MacOS > 2.59 > scripts > addons
  • Windows – Similar (something like 2.59 > scripts > addons; sorry for being lazy)

Now you need to open Blender and in the menus go to user preferences > add-ons. To locate the add-on easily deselect ‘official’ and select ‘Import-Export’. Check the item reading“Import-Export: meshio. (.pmd)(.pmx)(.mqo)”. (In my case it displays a worrying exclamation mark. Still works)

Click save as default at the bottom left of user prefs. (but don’t do that while you have a scene opened or it will become your default scene)

Where to find sample files?

MMD comes with quite a few interesting models (under UserData/Model or such).

Additionally, some models I liked are available here: http://www10.plala.or.jp/masisi/DL_MMD.html.

There is a page, here, where you might find links to models - it also explains what you can and cannot do (meaning, legally) with some of the models you will find online.

Miscellanii

There is open source, GPL code that can be used to run MMD stuff; to my knowledge it has been used on Windows and Linux. More info here: http://www.frostworx.de/?cat=7

Don’t retain anything unless you must

Regarding reference counting, this is the idea I’d like a developer to at least consider. For several reasons.

  • A dangling pointer / weak reference needn’t be evil. During development hitting a dangling pointer is better than preventing an object to deallocate when it should. An object that exceeds it’s intended lifetime can behave in undesirable, unpredictable ways. All it takes to detect an invalid object is turning NSZombieEnabled on.
  • Everything retained needs to be released. Retain less = less work.
  • If the sums don’t add up (over-released/over-retained object) it’s easier to work out what’s wrong when the number of objects involved is small (e.g. 1, 2 or 3)
  • Potentially any object that retains a target will increase the target’s lifetime; this a priori translates into increased memory usage.
  • Whenever retaining an object we risk creating a cyclic reference. Of course ‘we know what we’re doing’ (and cyclic dependencies can be removed) but isn’t it just easier to avoid getting too many of these.

Unwanted objects that remain inside the runtime after they should have deallocated will harm you. The more your system is dynamic (e.g. game, simulation) the more these objects are likely to generate functional bugs that are hard to figure.

I read a little about automated reference counting (ARC) which we are getting in iOS5. If I understand correctly (reading here) the central idea of this article will translate to ‘don’t abuse strong references’. Now that I more or less get it I look forward to using ARC but I guess I’ll be waiting for another 6 months or so, being a happy laggard.

A quick introduction

Reference counting approaches memory management indirectly, using concurrent ownership:

  • Take ownership of an object by retaining it
  • Relinquish ownership by releasing the object.
  • When all owners of an object have released it, the object is deallocated.

indirect : we don’t explicitly deallocate the object.
concurrent: several objects can simultaneously retain the same target.

The basic rules are covered in many places, like here and here and from the horse’s mouth, here.

Reference counting is efficient, error prone and occasionally awkward.

More efficient than garbage collection: objects get deallocated as soon as their reference count reaches zero, whereas GC is heuristic and may cause your program to slow down unexpectedly while it’s doing its thing.

Error prone – programmers need to pair release/retain statements (either directly or indirectly). Mismatched statements cause a program to leak or crash. Additionally reference counting is hackable; it is easy to traffic the sums (either accidentally or by design) and obtain a valid program that handles memory correctly, while violating reference counting rules.

Awkward, notably when we know beforehand that we would like to deallocate a well defined subset of the runtime graph. A typical example is when you start a kind of ‘session’, allocate any number of objects in the course of the session and wish to deallocate all the objects at the end of the session. In such cases opting out may be somewhat short sighted yet remains attractive.

A design idea

There is a principle which I find rather productive: instead of thinking about whether an object should retain X or not, consider X then try to think about an object ‘up the runtime graph’ that should own X. Often there is an object Y such that, if Y deallocates, X should also deallocate. It could be the parent of X or maybe another object up the chain.

Now, if there is only one such object Y, then you don’t need to retain X anywhere else. You can even assert the retain count to ensure that X is unambiguously managed by Y.

Anti-patterns?

There are little recipes around (e.g. here and here) that you can use to ‘ease the pain of memory management’.  From the point of ownership these recipes work the same way GC does: easy way out of memory management issues, hard into functional bugs with all the enticing prospects of a muddle-through approach.

One point these approaches have in common is ‘if in doubt, retain’. I’m OK with that as long as I know (beyond reasonable doubt) that keeping the target alive won’t generate unwanted behavior. If the target is an observer that receives and processes notifications… …then if in doubt, don’t retain. A clean, happy crash will provide the decision point where you can say:

  • ‘Yea, this object should still be alive at this point’ (in which case maybe something else should have retained it) or…
  • ‘No, this object is dead and well dead, we should have sent a death note’

Additionally these approaches look incomplete. You need to use class extensions if you want to declare everything as a property without exposing all your ivars.

Weak references

An unretained field is a ‘weak reference’. At least in a first approach, the use of weak references is encouraged in a number of situations:

  • Backward references from a child to a parent
  • Listener sets. See a straightforward application here.
  • Same type objects cross-referencing each other.
  • Any situation where you feel unsure whether to claim ownership (retain) or not.

Implementation details

Maybe for historical reasons there are two approaches to enforcing reference counting in objective C:

  • The non intrusive approach revolves around tagging using properties and indirect access using self.x = . Although this approach looks theoretically better and safer there are practical details of how it is done in Objective C which I often find off-putting. For one I like to not declare properties until I want to expose public state, and I’m not used to class extensions, thus find myself unwilling to add class extensions to my .m files.
  • An older approach revolves around the [release] and [retain] statements. The advantage (easier reviewing/debugging) and inconvenience (intrusive approach leading to somewhat cluttered code) are the explicit way in which things are done. This leads to a weird situation because it makes it more likely that bugs are introduced while making the same bugs easier to fix.

Note about [autorelease]

[autorelease] is very convenient and helps avoid errors in many situations. Sadly enough when an error does occur and [autorelease] is the lucky guy that causes a target to deallocate, we get very little debugging information because [autorelease] doesn’t take effect until we exit the frame.

So I try to limit its usage to where it’s unavoidable.

What is covered elsewhere (or should be)

  • Cocoa collections (NSArray, NSSet, NSDictionary) retain all their elements. This can be a hindrance in some cases, but you can configure the underlying, toll-free bridged counterparts, as demonstrated here.
  • There are various approaches to notifying stakeholders when an object gets deallocated. I will try to write a quick article about an approach I find useful when implementing observer schemes.

I started getting my next app ready to release. I’m looking into small things – icons, launch images and the like. This article is mainly about compliance. It is meant as a quick reference if anything and may be little help if you have never released an app before. You can check references at the bottom of this article if you’re looking for comprehensive information.

Finally, keep in mind that this kind of information easily gets out of date. Even if you find this article useful please check every information using reliable sources.

Launch images

XCode 4.2 (for iOS5) will rename images using the following convention:

Default.png, Default@2x, Default-Portrait~iPad, Default-Landscape~iPad

Default-Landscape~iPad won’t work on my iPad running iOS 4.3.

Using these names instead: Default-Portrait, Default-Landscape (without the ~iPad extension) works and the images still appear in XCode.
However using this method, so far I only got Default-Landscape to be recognized (may need to refresh build completely)

Another way to fix the issue is to add keys in the info.plist:

UILaunchImageFile, UILaunchImageFile~ipad

There is a Q&A about that.

App icons summary

iPhone: 57×57 (Icon.png)
iPhone (retina): 114×114 (Icon@2x.png)
iPad: 72×72 (Icon-ipad.png)
iPad (spot): 50×50 (Icon-spot-ipad.png)

Icon-settings.png 29×29

iTunesArtwork.png: 512×512

Note 1: I am not sure whether names are needed depending on the plist configuration; however keeping names is also good to maintain backwards compatibility.

Note 2: In XCode 4.2, if you add icons to the summary view, XCode will duplicate and rename the icon file, even if the icon file is already added to the project and already uses the correct name. If the icon is correctly named and you don’t to keep the duplicates (for example because your project folder is organized in a different way), I think it’s okay to delete the duplicates (icons still appear in the summary view). Additionally XCode adds entries to the info.plist automatically. Apparently older entries may not be overridden so doing a little house keeping may be necessary.

Caveat: in iOS5, it seems that there is a new info.plist entry for icons and this may require adjusting the ‘gloss effect’; check
CFBundleIcons > CFBundlePrimaryIcon>UIPrerenderedIcon, which apparently overrides it’s namesake in the plist root.

Universal apps

In XCode 4.2 some work will be done automatically when you switch to universal app, e.g. copying MainWindow.xib. The UI will look so-so and require corrections. In some situations the same xib file can be used for both (if the UI is simple) – obviously designing a dedicated UI is the best.

Other than MainWindow-iPad.xib (wired from the info.plist), it is the developer’s responsibility to point at the correct xib files.

References

For launch images and icons, check this comprehensive article on the OOPS tech blog

Also check: iPhone Dev 101 – size of UI elements

What a great title. I’m having issues fixing up a physical model for my game character. Since this has been dragging on for a while I decided to review the situation.

The problem given

Game character:

  • Walk, run, jump
  • Can get hit by heavy projectiles (when hit, we want a ‘physical reaction’)
  • Can fall

The terrain:

  • Arbitrary shape including slopes (in the worst case scenario, modeled as a mesh)
  • Walls and other obstructions
  • steps – probably not staircases but a variety of things that look like steps, including non static models (e.g. planks)

Animation system:

  • Traditional animation cycles (no physics in here)

What I’ve done

I tried two distinct physical models

  • Capsule. A single capsule is used to represent the actor
  • Balls. One ball is used to represent the actor’s feet, another represents the head.

I have also written a servo to control walking and running. A ballistic simulation (running in a sandbox) is used to prepare jumps.

What doesn’t work, or doesn’t work well

A ground ball isn’t great

Up to a point, rolling a ball on the ground (aka ‘ground ball’) to represent walking is OK, and I can also add impulses to make it jump. But this isn’t perfect:

  • If we really let the ball roll, we can’t attach anything to it. This means that we need a constraint to maintain the relative position of the feet with another ball representing the head/upper body.
  • If the character is thin, the feet can’t skip stairs or climb over obstacles unless we add a vertical impulse. Or we have to make the ground ball larger.
  • Balls don’t respond very well to friction. This means that the actor tend to drift especially when stopping on inclined surfaces.

Capsules aren’t perfect

Using a capsule brings a different set of problems:

  • In my previous tests I’ve seen a kind of stop and start effect which is probably the result of sliding the capsule on the ground using my servo. This might be because friction plays a very different part when sliding versus rolling.
  • I can’t really lock the capsule’s rotation. locking a body’s rotation is a one liner which makes sense in some cases. Let’s take a simple case where it doesn’t work: I have a heavy block falling on a game actor – then locking the capsule’s rotation is plain wrong.

Common issues

Handling climbing gracefully is a chore. So far I found it difficult to tune my servo to get seamless climbing – in other words, slope transitions generate a kind of noise while the servo is adjusting.

Sudden altitude changes (e.g climbing on top of a plank) are also difficult to handle correctly. If the servo is too loose, velocity tends to get out of control. If the servo is too tight the actor will stop, or even backtrack a little when an obstacle is encountered.

All the above problems are made more visible (a) by the use of a traditional animation system and (b) by the fact that I’m animating a human character. Human (or animals for all that matters) negotiate obstacles with grace and can adjust their motor functions in a smart way.

I’m reluctant to use a rag-doll (actually model limbs and joints). In theory it’s the best solution. In practice it might bring enough problems to keep me busy for a month (or three?)

Then… what?

Here’s my guess:

  1. Use a capsule (or even a box). Using a ground ball doesn’t solve half of my problems and forces a clumsy model for the upper body.
  2. Add a soft constraint to maintain posture (in other words, ‘lock rotation’ ). The constraint should do ‘enough of a decent job’ that the actor won’t tilt more than 5-10 degrees while walking or running. When a heavy object hit the actor the constraint should saturate, and we also want to adjust the same constraint dynamically (e.g, when an actor is KO or badly stunned they can’t stand, so we relax the constraint)
  3. Test the feet’s line of sight (eyes in your toes?) to detect obstacles. We’d rather never do that because it’s expensive but we don’t need to do it at every frame ‘just sometimes’.
  4. Consider using fixed settings instead of a servo (or write a better servo) to handle slopes and other continuous changes.

Alternatively, I could try using a very simple rag-doll (e.g 3 to 5 bodies for the legs and trunk). But most problems will remain integer and even a simple rag-doll may be a lot more work.

[to be continued]