Skip to content

Archive

Category: Blender
Blender allows associating markers to a given action. This is useful to add logic to animations, for example:
  • Label an ‘effect frame’ for a hit animation
  • Label a ‘takeoff frame’ for a jump
Markers can be added from the action editor in the dope sheet:
  • M to create a marker
  • CTRL+M to rename a marker
After creating markers select ‘Make markers local’ from the Marker menu in the dope sheet; otherwise markers are associated with the timeline instead of the current action.

Python

# get a reference to the 1st marker in action 0
m = bpy.data.actions[0].pose_markers[0]

m.name # marker name
m.frame # frame for this marker 

References

Since we’re already using blender as a level editor, I got a little curious about BGE and decided to check it out.

What is it?

The blender game engine (BGE) is part of Blender, it allows creating games using Blender. Games can run as standalone executables on a PC or Mac. I think there may be a plugin to run this in browsers as well.

I’m not sure whether there is an iOS compatible engine that supports BGE or not. You could look into SiO2 or GameKit.
If you made your own engine (whether 2D or 3D), exporting BGE graphs should be a big piece of cake (somewhat time consuming, but not difficult).

How it works

You can read the comprehensive introduction (see older links, below), I’m not very used to (this approach to) visual programming so this is how I explained it to myself.

The blender game engine uses sensors, controllers and actuators. Soberly, this is an event driven architecture. For each object you define trigger conditions causing events to be generated, then link the conditions to scripts affecting the stage of game objects.

  • sensor: sensors generate events, for example dedicated sensors detect keyboard or collision events.
  • actuator: actuators change the state of the world, for example make an object move or play an animation.
  • controller: read on.
In Blender’s logic editor, each object has a tab for sensors, actuators and controllers, so BGE is also object oriented. In practice we attach behavior to a game object by creating a graph, so a basic linked graph will look like this in the blender UI:
.
[sensor] => [controller] => [actuator]
example:
[right arrow key] => [AND] => [motion actuator]  
.
So we could make a game actor move to the right by linking a keyboard sensor (right arrow key) to a motion actuator, right? So what’s this AND controller in the middle?
Controllers provide a way to integrate inputs from several sensors. For example if we have sensors A and B and we want actuator X to apply only when both A and B are firing, we can use a simple AND controller. Yes, basic controllers are ‘logic gates’. Naturally this scales up – you can write your own logic expressions, or use scripts if you need more elbow room.

Links

2.5x/2.6x

  • Tutorials (Blender Noob To Pro on wikibooks – search ‘Game engine’)
  • Where to start BGE Python (blenderArtists.org)
  • 2.6x API docs
  • 2.6x GameObjectSettings  - These APIs aren’t used to access game objects while a BGE game is running, instead they can be used to inspect/modify game properties (including actuators/sensors/controllers).
    Blender 2.5x and later stores this under an object’s game property; 2.6x added APIs to inspect linkages between sensors, controllers and actuators.
    Situations where this gets useful:
    • You want to setup game objects programmatically
    • You want to export logic bricks using a py script.

Older links (but still useful to understand how stuff works)

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

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

I just did a test using blender 2.49′s radiosity feature. I wanted to bake self illumination to vertex color.

However, this opens more questions than it solves.

Radiosity in 2.49 doesn’t support double sided faces. This seems to cause artifacts when baking clothes and hair (clothes don’t have thickness, and I doubt I would go this far – the model is heavy enough as it is).

Additionally, the rendering is not very clean with the original, mid poly model (~5k faces). I can increase the definition to render lighting (using radio buttons), but then I need to transfer the result back to the original model.

So the plan (assuming I persist) would be to modify the model, add thickness to clothes, bake illumination, then write a script that can transfer color data back to the original model.

I think it’s a bit over the top but radio bakes play an important part in our pipeline already, and I feel vertex paint, however old fashioned, offers distinctive possibilities. For example I already have a script that can extract dark areas from the radio bake, which gives access to ‘shadow geometry’ – so we can take this into account when programming gameplay.

I’m also working on a method to simplify geometry while losing as little color information as possible – ultimately this should help me improve rendering quality without losing much performance.

Blender 2.49 has a ‘radioactive’ button opening up a hard to figure bunch of buttons related to radiosity. However these buttons can be pretty useful if you’re looking to add realistic illumination to a scene and like to work with vertex paint. This option isn’t available in later versions of Blender, so it’s a bit of a vintage approach – however you can import the output in a later version of blender.

Radiosity – unlike classic computer light that cannot ‘turn around walls’ radiosity methods let light bounce over and over; it generates soft shadows and is good at indirect illumination.

Baking – The 2.49 radiosity method works with faces, not pixels; it outputs the result as a vertex painted mesh. This is original and defines the unique strengths and weaknesses of the illumination model. The input is the currently selected meshes; the output is a mesh. As part of baking the mesh may be subdivided according to your parameters (see below)

Workflow:

  1. Add meshes to represent light sources. Yes, with radiosity only meshes can emit and receive light. Standard light sources do not illuminate your scene/selection.
  2. Adjust ambient and emit material properties. Every mesh that has emit>0 becomes a light emitter; every  mesh that has ambient>0 can be a secondary source.
  3. Select a few meshes, including some meshes you want to render light on, and some meshes to be used as light sources (a typical case consists in selecting all meshes in your scene).
  4. Press ‘Collect meshes‘ to enter ‘radiosity baking mode’
  5. Press Go, then wait for the process to complete or press ESC if the result already looks good (rendering/baking is interactive). You can also limit the number of iterations automatically by selecting Max Iterations > 0. (At each iteration, the biggest ‘light patch’ transmits energy to the scene, so don’t be afraid of a large number of iterations).
  6. Press either Replace Meshes or Add new meshes. The first will delete the original meshes and replace with just one mesh containing the resulting vertex paint; the second will keep the original mesh data in case you still need it.
  7. Press ‘Free Radio Data‘ to exit baking.
  8. Press SHIFT + Z to activate lighting preview (or render the scene). By default the new mesh uses vertex paint as vcol_light, meaning the result can be rendered without a light source present.

Problems and solutions

  • Shadows are not detailed enough
    • reduce ‘ElMin’ – an element is a face that receives light, smaller means smaller faces
    • try reducing PaMin – a patch is a face that emits/bounces light, smaller means more precise sourcing of the light.
    • increase MaxEl – the number of elements is limited by MaxEl regardless of ElMin/ElMax
  • Too slow - increase ElMax and PaMax, decrease MaxEl, decrease Hemires.
  • Too dark/bright, too much/too little contrast - change Mult and Gamma; this is interactive, after you pressed Go and completed the bake. The advantage is that at this stage the color model still contains a lot more information than just RGB values, so there is no quality loss.
  • Don’t want the algorithm to modify your mesh geometry? Change MaxEl: to 1. If you do so you and still want a good result, prepare subdivided geometry yourself.
    • It can be useful to do a pre-render with MaxEl set high, then you subdivide your meshes knowing ‘light transition areas’ in advance. If your scene isn’t too complex or keeping the face count low is important, this may be a good compromise.
  • I see a kind of rash/noise.
    • Select ‘Gour’(aud) shading to find out. Wire/Solid/Gour are just visualization modes for radiosity baking.
    • Increase ElMin. But this will reduce precision
    • Decrease MaxEl (again, reduces precision)
    • Decrease PaMax and PaMin (increases rendering time and precision)
    • Increase Hemires to something high (e.g. maximum) This reduces artefacts without reducing precision. (When each patch of light is rendered an image of the scene is rendered to decide how the patch illuminates your scene, HemiRes is the resolution of that image). Of course higher Hemires renders a little slower.
    • Use FaceFilter and ElementFilter after rendering. This tends to blur shadows and you can apply it over and over (FaceFilter causes more blurring. Hitting ElementFilter once feels like a good thing to do).
    • Clear artifacts selectively later, using vertex paint (blur mode)

When/Why use it?

There are several alternatives (e.g. Yafaray and Blender Cycles) so maybe this is a bit out of date, however there are cases where this might be just what you need:

  • On current hardware it runs fast, and benefits post-render intensity and gamma tuning
  • I haven’t seen any other method that lets you look at and rotate around a nearly WYSIWYG presentation of your scene’s illumination in real time.
  • The resulting, pre-rendered meshes will render super fast, which may help completing a complex animation (minimally, you might want to add mirror reflections and specular components).
  • The result can be edited using vertex paint (and vertex paint can be converted to texture paint afaik).

So even though it’s a bit quirky it generates data that’s forward compatible and is really good at what it does, being at once interactive, fast and flexible.

Find detailed docs here (official B2.49 manual), including an introduction to radiosity and a detailed explanation of every available knob and button.

Today’s link: 25 useful Blender tricks (from blenderguru.com)

These days I’m working on urban environments in Blender. Urban environments can be easily broken down into modules and series – cloning the same objects over and over to create roads, floor tilings, buildings and so forth…

Duplicating modules by hand is tedious even if you don’t care about millimeter accuracy. So I thought I’d write a little script to do simple tilings.

The script duplicates the active object several times and merges the result into a single object. The original module or ’tile’ is preserved. This script will run with Blender 2.49 and can be easily modified (for example, if you want to add padding between copies or don’t want to merge the result)

What we need to know

To retrieve the active object:

scene=Scene.GetCurrent()
active=scene.objects.active

Initially I thought about duplicating vertex data directly as I want the tiles to be part of the same object. But duplicating the object first may be safer and offers more flexibility.

We can use the following command to duplicate active objects:

Object.Duplicate() # duplicate, link mesh data
Object.Duplicate(mesh=1) # duplicate, clone mesh data

To tile clones edge to edge, we’ll need to know the extent of the object:

dimX=obj.getBoundBox()[6][0]-obj.getBoundBox()[0][0]
dimY=obj.getBoundBox()[6][1]-obj.getBoundBox()[0][1]
dimZ=obj.getBoundBox()[6][2]-obj.getBoundBox()[0][2]

Once we have duplicated and moved our objects we can merge them together using join(). This function is a member of the object class and will join the target with all objects in a given array:

arr=[]
arr.append(anObject)
obj.join(arr)

join() doesn’t delete merged objects; usually we want to delete all clones after merging. To remove an object from the scene, we can use the following command:

scene.unlink(anObj)

Reminder… to iterate in python:

for x in range(N) # e.g range 10 iterates from zero to 9

If you’re in a hurry, a modal UI provides the quick and dirty way to input data from the user:

numX = Blender.Draw.PupMenu(“X dupli%t|1|2″)

This gets the user to input either ’1′ or ’2′.

Complete Source Code

#!BPY

“”" Registration info for Blender menus:

Name: ‘Tile v0.0′

Blender: 249

Group: ‘Object’

Tip: ‘Tile an object along x,y,z axis and merge’

“”"

import Blender

import bpy

from Blender import *

# TILE V0.0 – A SIMPLE SCRIPT FOR TILING AND MERGING THE RESULT

# LICENSE: LGPL

def copy_and_merge(nx,ny,nz):

scene=Blender.Scene.GetCurrent()

target=scene.objects.active

dimX=target.getBoundBox()[6][0]-target.getBoundBox()[0][0]

dimY=target.getBoundBox()[6][1]-target.getBoundBox()[0][1]

dimZ=target.getBoundBox()[6][2]-target.getBoundBox()[0][2]

clones=[]

for x in range(nx):

for y in range(ny):

for z in range(nz):

Object.Duplicate(mesh=1)

clone=scene.objects.active

clone.LocX+=dimX*x

clone.LocY+=dimY*y

clone.LocZ+=dimZ*z

clones.append(clone)

clone.select(0)

target.select(1)

first=clones.pop()

first.join(clones)

for k in clones: scene.unlink(k)

# ————————————–
# Get the number of copies from the user and run the script

numX = Blender.Draw.PupMenu(“X dupli%t|1|2|3|4|5|5|6|7|8|9|10″)

numY = Blender.Draw.PupMenu(“Y dupli%t|1|2|3|4|5|5|6|7|8|9|10″)

numZ = Blender.Draw.PupMenu(“Z dupli%t|1|2|3|4|5|5|6|7|8|9|10″)

copy_and_merge(numX,numY,numZ)

# END ————————————

This is it. Modifying the script just a little can help you make staircases, fences and all kind of stuff, so I think it’s a nice introduction to how scripting can help generating scenes quickly and easily.

Aging

Remember one problem with cloth simulation is that the cloth / garment (or whatever else) is originally assuming a rather stiff, unnatural shape. One solution may be to add lead frames to ensure there is enough time for cloth material to assume it’s rest position.

A much easier solution in practice is to bake a few frames, then apply the cloth modifier in the modifier stack. This will save the current vertex coordinates (so if you go to frame 10 and apply the modifier, you have a ’10 frames old’ version of your mesh).

This method isn’t absolutely accurate for a cyclic animation. Our ‘aged mesh’ doesn’t record initial velocities, so it’s probably more accurate to run/duplicate (sigh) 2 or 3 animation cycles. Still useful…

The Marilyn Effect

I continued experimenting with the dress (I know I should post a pic, just think of it as a light summer dress or night dress).

And I continued getting this funny/bizarre/undesirable effect where the dress is steadily rolling over itself and upwards, and this isn’t exactly what I’m looking for.

I tried pushing a fair bunch of parameters that should logically rid me of this effect, but I can just about mitigate it. Shall we start from the beginning then?

  • Expected behavior: the dress settles down under the influence of gravity, covering the character’s body.
  • Actual behavior: the dress rolls up while the character is walking (12 centimetres up after a complete walk cycle)

Proposed solutions:

Increase the definition of the mesh

I don’t know for sure how the simulation works. So I guess this is worth trying since my mesh is pretty low def, just to get a rough idea of how the definition of the mesh affects the simulation.

=> At subsurf level 1, I gain 2 cm although it’s difficult to evaluate because the ‘bottom sleeve’ isn’t straight if anything.
=> At level 2 I strictly get the same as without subsurf enabled.

I guess this is good news if anything. Means I should be able to work at low def and save time on testing.

Increase gravity

The dress doesn’t roll up by itself. This happens because the character is walking, so their legs are pushing the dress forward and up. I thought that, if I increased gravity, it may be more difficult for the dress to bounce up.

=> Increasing to 10 G (100), the collision detection fails and the dress simply slips down. Interesting.
=> At 2G, the result is much more interesting. In fact I didn’t see the ‘dress rolls up’ effect in this case. But the result looked pretty rough so I increased collision quality (2>3>4) …and after doing this I fall back in the initial situation.

Increase Cloth Friction (Cloth tab group > Collision > Friction)

Increased friction is meant to ‘kill motion’ when a collision occurs. So I increase friction (5 > 80 – the maximum).

This pretty much does the trick, but just using it in isolation may not be enough; note that there are similar parameters in the collider’s collision tab (). However tuning this doesn’t seem to affect the outcome.

But just increasing friction doesn’t help much with a silk preset. It only really worked after I replaced the silk preset by leather.

Increase the mass?

I restored the silk preset and replaced the default 0.150 (Kg?) by a staggering 10 kg. The effect is spectacular. The top  sleeves stretched a good 20 cm down, revealing most of the character’s upper body. The bottom sleeve also dropped down. This uses about 10 frames. During the walk cycle per se there is no ‘rolling up’.

Changing the mass of the cloth demonstrates limitations when trying to pre-calculate a ‘rest position’. Say we burn 10 frames. Now the dress top sleeves are stretched 20 cm down as I explained. Let’s apply the cloth modifier and restart the simulation. What happens then? You guessed, the top sleeves stretch another 20 cm down.

Back to leather

I wasn’t fully convinced with my experiment with leather and friction. So I thought I’d try leather alone first, then add friction (80 – still maximum) and think things through.

In short, friction helped a little, not all that much. Without friction the dress seemed to be bouncing up and down, pretty much like very hard leather. With a lot of friction the overall effect would be better, filling more like wearing a clothe and less like wearing a piece of armory.

Some thoughts

There’s a couple of things I didn’t do, which may actually solve the problem independently from everything else:

  1. Make the dress longer (well… I’ve actually done that)
  2. Duplicate my walk cycle 2 to 4 times and run the simulation through.

Given the tests I carried out, it feels like we need to plan ahead, taking into account a dynamic relaxing process rather than trying to rely on pre-calculated aging. In plain english, I think if I made the dress longer, and let the animation run, a little more, it would stabilize and the dress would appear shorter, with more or less jiggling depending on selected material properties.

Since it’s a walk animation the feet of the actor are somehow linked to ‘ground dummies’. That shouldn’t make duplicating the walk cycle difficult, but somehow it does (at least for me). It’s a pity because Blender has unified views to deal with key frames involving concurrent objects (e.g. NLA editor) but these seem to fall just a little short of letting me ‘just copy everything’.

Cloth properties are unit-less. That doesn’t make individual properties terribly easy to understand.

I think it would be nice if we could specify in advance which parts of the clothe are stretched before running the simulation. Pinning feels like a kind of substitute, not necessarily a great one. Pinning makes it difficult / impossible to avoid combining the cloth with an armature, but then the kinematics of the armature tend to conflict with cloth behavior. Instead, I’d like to specify (e.g weight paint) that the top of the dress is stretched, while the bottom isn’t.

That’s it for now. Next time I’ll discuss exporting cloth animations.

Today I decided to experiment with the Blender clothes module (see here and here). So I took the hairlock/antistar PC model (the red haired girl) who happen to be wearing a pretty dress, and off we go.
It took me an evening to get something decent up and running. First I’ll describe the minimal setup, then reasons why the initial setup didn’t work out and how I fixed it.

The minimal setup involves three essential steps:

First we enable ‘cloth mode’ on the target (a mesh we’d like to behave as clothe, e.g. a table cloth, a pair of jeans etc…). This means that we tell Blender to compute cloths physics based on gravity and collisions on this object.

Secondly we setup one or several ‘colliders’ – Blender will only evaluate collisions with designated objects.
Finally we ‘bake’ (precalculate) the cloth simulation. While this step is in theory optional (Blender will calculate frames while scrubbing through the timeline), you’ll need a really fast box to avoid it.

I just outline the procedure, if you’re getting lost please refer to the links provided or dig up a YouTube video (no, really!). The caveats section is more interesting.


Minimal setup
  • Setup clothe:
    • select the mesh that you want to use as cloth.
    • select object > physics > cloth > enable clothe
    • enable clothe.
  • Enable clothe collision
    • In cloth tab group, select collision tab
    • enable collisions
    • enable self collisions (recommended)
  • Setup collider
    • select object to collide with
    • select object > physics > enable collisions.
  • Bake and playback
    • Again, select the clothe object, then object > physics > cloth
    • Select the start and end frame. The 250 frames default will have you wait a couple of hours or more. Just pick the frame range you need, or less to experiment with parameters.
    • Press ALT+A to preview the animation for baking is complete.
    • Select Free bake to get rid of the current simulation.

Caveats

  1. The first time I run this simulation I had the character’s skin clipping (showing through) the clothe. Not just a bit, really showing through.
    => If we have a character animated with an armature, and we want to ‘let physics take care of clothing’ we probably don’t want the armature to be enabled for the cloth object. However, with a posed character, that typically means that, in the first frame, the clothe object won’t be fitting, it will overlap the character. The simulation starts with the posed character as is (not the rest position).
    I shifted all keyframes 10 frames forward, then key-framed the character back to rest position (at frame zero) and fitted the clothe correctly. That got rid of clipping (no need to worry about collision quality just yet).
  2. To prepare my models for Open GL rendering I usually split meshes by color (otherwise color bleeding occurs). Unfortunately this also means that each colored piece of clothe becomes a separate object in it’s own right.
    => A cloth object must be ‘in one piece’ for the simulation to work correctly. separating color groups should be done later (e.g. when exporting the animation)
  3. Initially my character didn’t have a trunk (anymore). Why include faces and vertices that won’t ever be displayed? Unfortunately this doesn’t work any good with clothes, because there’s nothing to collide with(!). The solution, obviously, is to have a complete body with a decent shape! In fact we don’t need to use the same object for simulating the clothe and rendering (let alone animation playback in a game).
  4. Physics ‘takes time to boot’. The piece of clothe we’re animating won’t look right at frame 1, it needs to ‘shape up’ following the rules of the simulation.
    If we’re already adding lead frames at the beginning of the simulation to match the shape of the cloth with a ‘rest position’ then this may leave enough lead time for the clothe to start fitting naturally before our animation really begins, otherwise there is a technique (see links above) which allows baking a pre-calculated deformation for the cloth, so we could replace the original mesh by a fitted version.
  5. Why does it look all rounded?
    If we’re using something like 1 blender unit = 1 metre (I do) then the default minimum distance for collision is really set too high. if we’re trying to fit a cloth nicely, it will look good in places, bad in others. In my case I had a sleeveless dress with just a couple of ribbons to fit at the top, so the ribbons looked all round and even bounced unrealistically against… …nothing. Reduce the collision distance as much as possible (there are two settings for this, one in the collision tab for the cloth, one in the collision tab for the character’s body.
  6. Clothe simulation per se isn’t overly time consuming (or the Blender routines are deadly optimized), collisions are. Animating just about 20 frames takes minutes, and my model isn’t really high poly. This isn’t a problem except tuning parameters is time consuming.

Simple experiments

While trying to get around the ’rounded sleeves bouncing in thin air’ issue, I tried a few things…

  • Combining with the sub-surface modifier. It may be fairly obvious that, if we want smooth wrinkles and other clothe-like appearance, we might want to refine the definition of the source mesh. Adding a subsurface modifier does the trick (without the need to generate hard to edit vertex data). The subsurface modifier should be at the top, keep the cloth modifier (gets generated automatically when we check the cloth setting) at the bottom.
    Make sure the resulting subsurface doesn’t overlap the character
  • Pinning. With most garments, not all parts are meant to flow freely. In fact, some parts are stretched. The cloth simulator gives a light ‘free flow effect’ that looks nice in parts and rather terrible in others. So Blender includes a ‘pinning feature’. The idea of pinning is that a selected group of vertices will be very ‘stiff’ compared to other, keeping the default shape of the mesh throughout the simulation (can save a lot of time trying to tune cloth parameters).
    With a posed character, we really can’t use pinning without  adding the armature modifier to the clothe. While this hurts my logic a little (I want the body to the move the clothe, not the armature…) it can be fairly easy to limit the armature’s influence (e.g. use envelopes or vertex groups) to avoid unwanted effects.1

I’m seeing weird glitches when I combine sub-surface, pinning and armature together (sometimes). Aside, my character’s dress seems to bounce up all too willingly. It’s almost amusing but not always desirable; but I’m really just learning how to tune this up and there’s quite a bunch of parameters to go through.

Conclusion

Animating clothes with bones is a total pain (I tried). In contrast, using the Blender cloth functionality definitely has a learning curve, but the results look very promising. I can see many useful applications, even with fairly stiff, low poly clothe models. With a reasonably high poly count it can get really pretty.

I’m expecting the baked cloth animations to go through when I export the animation (because the exporter collapses the modifier stack, and cloth is a modifier) so I may be able to get this working in my game. Frames may need to be offset to allow time for ‘shaping up’ the garment, then I would need to adapt my exporter.

Finally, many animations cycle through. The physics simulation doesn’t take this into account, so beginning and ending frames must be interpolated, either while exporting or later.

A quick solution for equipment

The story so far

A few months back I wrote a simple export plugin for Blender. Unlike most export scripts, the plugin interprets blender files as asset libraries. The plugin supports basic material properties and animation.

When I wrote the export script, I didn’t want to spend time writing a bone animation module for the engine. Instead I decided to bake animation frames – bone deformations are applied from within blender, resulting in ‘mesh frames’.

While mesh frames are pretty heavy, there are advantages too:

  • Interpolating between frames is much faster than applying bone deformations.
  • Since the exporter generates frames by collapsing an object’s modifier stack, it is possible to export all kind of animations, not just bone animations.

Equipment

At that point, my setup didn’t provide a solution for equipment. So if I wanted an actor to hold an axe, or a sword, I had to clone the model and bake a separate animation. Needless to say such a system is hardly usable.

Equipping items consists in making them visible as part of a PC or NPC visual presentation, so an actor could hold a sword, a shield, or change dress (this requires more care).

The new setup is fairly simple:

  1. Bones are added to the actor’s armature – so we can add a bone to represent a sword, a gun, a hat… anything.
  2. The item we want to equip is placed at the correct location – so if it’s a sword, we just place it in the character’s hand.
  3. The item is renamed accordingly, e.g. sword@elven, indicates that the sword should animate along with an actor named ‘elven’.
  4. Parent the item to the armature (in the item’s modifier tab, I check ‘make real’ for the armature modifier, to ensure that this gets applied when the exporter collapses the modifier stack)

The notation item@actor is an arbitrary convention. Since actions are not bound to any particular actor, if we have…

  • an action named elven.strike
  • a piece of equipment named sword@elven

…then the exporter knows that elven.strike should be applied to sword@elven.

Animations are exported separately for various pieces of equipment. It’s a huge step forward compared to the previous system I used. When we want an actor to equip an item, all we have to do is load the matching ‘animated version’ of this item and synchronize animation playback.

This solution is still wasteful – but it wouldn’t be too hard to extend it to define equipment slots (so instead of exporting all animations over again for each item, we’d just have ‘dummies’ used to define transform matrices)

One Animation per File, really?

When I investigated Blender animation to create my exporter, I found about Blender actions. Blender actions provide a simple, easy way to define ‘several animations per actor’. More specifically, an action is a named sequence of key frames associated with an object (typically an armature, but also works with other object types). So at the moment I have ‘run’,'walk’,'hit’ actions etc… While actions are normally used in NLA (non linear animation – aka mixing part animations together, e.g. smile + run), they originally seemed well suited to building ‘animation libraries’ - All the exporter has to do is retrieve each action, bind it to the armature and export it.

Unfortunately, this approach breaks down when we combine several animated objects. For example, suppose you want to apply a floor constraint (e.g., as part of a walk animation), then…

  1. Consider the armature for the actor we’re animating.
  2. Define a ‘floor’ object
  3. Define 2 empties (used to move the actor’s feet)
  4. Apply the floor constraint to the empties using the ‘floor’ object as target
  5. Add IK solver constraints to the feet of the actor’s armature, so the feet now follow the empties.
  6. To animate, we move the empties, not just the bones.

How many objects are being animated here? Well, 3 really. We have the armature and the empties. To setup this animation correctly, then, we need to bind the following actions (assuming we associated the empties animations to actions) …

  • The armature action (e.g. elven.walk)
  • LeftFootEmpty action (elven.walk.leftFoot?)
  • RightFootEmpty action (elven.walk.rightFoot?)

At this point, I drop the towel altogether. Although there are disadvantages to keeping one file per animation, we have to choose: unless an animation is simple (1 action <=> 1 animation <=> 1 object), it should be kept in a separate file.

I guess if it was to do all over again, I’d simply try to avoid complex rigs. In the meantime I changed my export script (never mind some of my engine code) so that animations are always kept in separate files. I now have, for each object:

  • A model file. All models, whether animated or not, use the same format
  • For each model, zero, one or several animation files.