Friday, June 22, 2012

SPH Fluid Simulation

Recalled from the previous post, there are 2 major approaches used to describe the fluid motion, Eulerian and Lagrangian. Eulerian is grid-based, measuring properties at fixed points in space. Physical values are stored on grids. Lagrangian is particle-based, measuring properties as particles drift through the flow. Physical values are stored on each particle. Both methods have pros and cons. The prevalent methods used nowadays are mostly the hybrids. (e.g. FLIP is the hybrid between particle-based and volume-based).

Let's start from the particle-based approach and take SPH (Smoothed Particle Hydrodynamics) for example. Via discrete particles located arbitrary in space , SPH utilizes weighted summation from adjacent particles to interpolate values and derivative of continuous field.

SPH uses smoothing kernel (W) to determine which adjacent particles have how much contribution of values on one particular point in space. The selected smoothing kernel should be normalized, positive, even and last but not least, no kernel interaction outside the range of the radius "h". The derivatives of the field could be approximated with analytical differentiation:


Since the physical value at point j doesn't directly depend on other components in space, thus, the gradient of the field only has effect on the smoothing kernel. Same for Laplacian.


With above SPH equations, we can start to approximate each term in Navier-Stokes's Equation. Since the main idea of Lagrangian method is the particle itself moves with the fluid, thus the advection term can be ignored, which simplify the equation a lot. For other terms (e.g. density, pressure, viscosity, external forces, etc), they all can be approximated with SPH approach. I won't paste the equation for each term here since they all can be found from lots of material online, and the main purpose of this article is just for getting myself familiar with the big picture and techniques behind the scene. However, there is a thing worth mentioning,  if just using SPH equation above to directly approximate something like pressure and viscosity force, we will confront an asymmertric problem. Think about a situation, if there are only 2 particles with contact in space, the pressure of one particle only uses the pressure force of another, and since the pressure for each partilce may be different, the result pressure will not be symmetrical. These can be fixed with few ways to rewrite the equation.

OK. With the above knowledge, let's talk about the advantages and disadvantages of SPH. There are several benefits of using particle-based approach over pure grid-based method. First of all, the equation is more intuitive and easier to implement. Second, since SPH stores mass on particles, it guarantees the conservation of mass w/o extra calculation. Third, SPH doesn't have to track fluid boundaries; it supports free surface effect. But there still has to be a way for mesh generation for rendering since SPH doesn't contain topology info.

The obvious drawback of using particle methods is the need of large numbers of particles to get more accurate result, which enhances computational cost. The other thing is the density summation would cause problems when neighboring particles have different rest densities (i.e. different masses). This would lead to incorrect pressure and have weird gaps (break into pieces?). Some solutions have been introduced which involves alternative density computation, formulas rewriting and new surface tension model.

What if we need the boundary to limit the movement of particles? One way could be adding boundary particles to prevent penetration and inverse the velocity. Another way is to use Ghost Particles. There is a technical paper about Ghost SPH in the upcoming Siggraph 2012: http://www.cs.ubc.ca/~rbridson/docs/schechter-siggraph2012-ghostsph.pdf


Monday, June 4, 2012

Navier-Stokes Equation

Here is a summarized note I took after reading some material relevant to fluid effect.



This is the compact version of Navier-Stokes Equation excerpted from Jos Stam's paper. For simulation in Computer Graphics, physical accuracy isn't the primary but the appearance and performance is. In order to get a faster simulation and realistic at the same time, here it assumes constant density, which means the fluid is incompressible. Basically, fluid effect in CG is mostly based on this assumption.

The first equation is the condition of incompressibility. With constant density, the net flow in and out of a region should sum to zero, which means the divergence of velocity should be zero, no sinks or sources.

The second equation is based on Newton's second law F=ma. Before going further, I spent some time trying to understand 2 different descriptions for fluid mechanics, Eulerian and Lagrangian respectively. I recommend the following video on YouTube, which does a great job on explaining these 2 ideas. It also provides a clear demonstration about how to deduce material derivative, which is quite important to help understand the second equation here.

http://www.youtube.com/watch?v=mdN8OOkx2ko&feature=related

It's obvious to see that the left hand side of the assignment, combining with the first term on the right hand side is the material derivative. It says that the change of a point moving within a velocity field is the sum of the change at the fixed position and the one due to the movement.  The first term on the right hand side is what we call "Advection" (imaging if we drip a pigment drop into a moving liquid, how the pigment will move within it).
OK. Back to F=ma. 


Here we represent the mass as density since unit size is used; then expand the material derivative to get the following:


Well... divide each side by density, we get equation 2 :)
It's apparent that the sum of (F)orces corresponds to the rest 3 terms in equation 2:  pressure, viscosity and other external forces.

Pressure is used for enforcing incompressibility. Since the gradient points to the greatest rate of increase and fluid should flow from high pressure to low, negative sign is used for reversing.
Viscosity is used for simulating viscous fluid. Laplace operator is used here for getting smoothing result. External forces are something like gravity, buoyancy, etc.

So lots of research are around solving this equation, leading to various algorithms, such as SPH (Smoothed Particle Hydrodynamics), PIC/FLIP (Particles in Cell / Fluid Implicit Particle). It's kind of complicated and better has separate articles for these.


Monday, May 21, 2012

SIGGRAPH 2012 Technical Papers Preview

SIGGRAPH just uploaded the Technical Papers Preview Trailer for 2012. Fluid effect seems the primary topic this year, with totally 8 related papers accepted.

All technical papers:



Wednesday, May 9, 2012

Thursday, April 26, 2012

[RenderMan] Ri Filters

The following is a snippet of code I wrote to test with Ri Filters. The goal is to simply replace any polygonal geometry with RiSphere, then replace any RiSphere with RiCone before the final RIB being passed to the renderer.

First filter plugin:
RifPlugin *RifPluginManufacture(int argc, char **argv)
{  
    return new myRifPlugin();
}
myRifPlugin::myRifPlugin()
{
    myRifFilter.PointsGeneralPolygonsV = pointsGeneralPolygons_to_RiSphere;
    myRifFilter.Filtering = RifFilter::k_Continue;
}
RifFilter &myRifPlugin::GetFilter()
{  
    return myRifFilter;
}
The second filter plugin is almost like the first one, except the registered callback needs to be changed to "myRifFilter.SphereV = riSphere_to_RiCone". With riSphere_to_RiCone defined as follow:
RtVoid myRifPlugin2::riSphere_to_RiCone(RtFloat radius, RtFloat zmin, 
      RtFloat zmax, RtFloat tmax, RtInt, RtToken[], RtPointer[])
{
    RiCone(0.5, 0.5, 360, RI_NULL);
}
Now it's about to render! If rendering with RMS (RenderMan Studio), it's better to check the Full Paths box in the Render Settings. Besides, set all the necessary Ri Filters (just new 2 Rif in this case ) and provide the paths toward 2 Plugins. Within command prompt,
render -r rman xxx.ma [ render the image with RMS]
render -r rib xxx.ma [export the rib after replacing]

If using RPS (RenderMan Pro Server),
prman -rif myRifPlugin -rif myRifPlugin2 xxx.rib [ render the image with PRMan]
catrib -o filtered.rib -rif myRifPlugin -rif myRifPlugin2 xxx.rib [export the rib after replacing]
Right, if using RPS, you need to generate rib first for filter processing. RMS accepts .ma for filtering but RPS only accepts .rib.

If everything runs correctly, all the polygonal geometries (lets say if we create 3 cubes in Maya) should be rendered as 3 cones in the final image. Cheers!!

Friday, April 13, 2012

The Walking Dead S1&S2: Behind the Scene

The Walking Dead S2 just ended. It's one of my favorite US TV series. Initially I thought it's another version of "Dawn of the Dead" or "Resident Evil", another cliche or something. I was wrong. It completely held my attention from the very first episode. Well...of course it couldn't avoid having some cliche material from those plot we've been familiar with. It still have lots of fresh stuff that the preceding didn't explore that much. The story is more on the humanity side. The visual effects, compositing, and zombie makeup are best of all. AND it's also the first zombie-related TV series. Here embedded 2 Vimeo videos from Stargate Studios which handled the visual effects of it. They really did an amazing job!!




The following link are 2 articles from fxguide, giving a quick look over what's going on behind the scene. Worthing reading!! 
http://www.fxguide.com/featured/stargate_studios_walking_the_dead/
http://www.fxguide.com/featured/the-walking-dead-season-2-walk-harder/ 


Saturday, March 31, 2012

[Maya] Custom Shape Nodes

I've worked on building system with custom shape nodes in Maya for a while and truly learnt a lot from it.

Maya indeed provides great proxies for developers to make custom shape nodes with different level of complexity. Using MPxSurfaceShape (or MPxComponentShape), combined with  MPxSurfaceShapeUI & MPxGeometryIterator &MPxData, you can implement a "very complicated" shape node in Maya. This node can have developer-defined data structure. The data itself can be an attribute which is able to connect to other nodes. You can also define the shape node's behavior under Maya's tools, such as move, rotate, scale, even deformer (lattice, cluster, etc)!!!! And with context command, interacting with custom shape nodes with defined context tool outside becomes possible. This work flow and mechanism is really awesome!!! well... just a flash into my mind, can it support dynamic stuff? Or should I do it outside and write the result back to the shape nodes? hmmm I will figure that out. 

Because they are just proxies, which means you have to do the coding for the actual content. Maya gives you lots of flexibility, but meanwhile, you also have to follow its rules. It would take a while to realize those provided virtual functions of each proxy, like when they will be called and how to make Maya recognize your shape node (Oh Ya, this is the main point!! You have to make Maya recognize your shape node and be able to interact with it!!)

Looking at my system growing bigger and bigger is excited. The custom shape nodes and context tools are almost done. It's time for the official greeting to Renderman API!! Hello Renderman!! :)

Thursday, March 22, 2012

[QT] Signal & Slot

Recently because of the need at work for developing Maya plugin, I got a chance to dabble in Qt. Always excited about new things to learn!! :)

As the central feature of Qt, the first thing I started experimenting is the Signal & Slot mechanism. I found that there are some similarity  between Qt's Signal & Slot and Maya's Push & Pull model. Probably this is the reason why Maya chose Qt to rewrite the entire GUI from 2011 (just guessing :p)

Instead of using traditional callback functions, Qt adopts an alternative approach: Signal & Slot. When an event occurs (or object's internal state changed), it emit signals, objects interested in this event would use slot to respond to the signal. It doesn't know if anything receives the signals it emits; and the slot itself doesn't know if any signals connected to it. Loose Coupling!! Oh... and the signature of signal should match the signature of slot.

QObject::connect(&a, SIGNAL(valueChanged(int)), &b, SLOT(setValue(int)));

Don't you think the usage of Signal & Slot is kind of like the following in Maya when trying to build dependent relationship between attributes?

attributeAffects(width, area);
attributeAffects(height, area);

In Maya, each node just knows about itself, it doesn't know anything about node connection, not knowing which node connects to it and which node it connects to. It only knows which input attribute affects which output attribute of itself. It's just like a black box with a compute function inside to do the necessay calculation. With commands, we can connect nodes together. With Maya's Push & Pull model, we can get the most updated state of a particular node.

That's why I think that there are some common ideas between these two architectures. They all maintain truly independent components and provide ways to bind objects(nodes) together for communication.

Saturday, March 17, 2012

[Maya] Handle MouseMove Event

Maya doesn't have MouseMove event, only provide doPress, doDrag and doRelease. One way to deal with MouseHover would be using Qt which is available since Maya 2011.

We can get QWidget from Maya's M3dView, then use it to instantiate a QWidget object with EventFilter installed and MouseTracking enabled. With eventFilter method, MouseMove event can be detected.

Quite straightforward and good so far. However, here is the thing.
For some reasons, if I just passed my M3dView to QWidget, that M3dView would only be valid at that moment. When it gets into the eventFilter method, it wouldn't be valid anymore. But I need that view to handle the scene in Maya.

There is an alternative. Within eventFilter method, I can get the name of the model panel I'm working on in Maya (via watchedObject->objectName()). Given the name of the model panel, M3dView::getM3dViewFromModelPanel should return the valid M3dView. Then I can do what I want to do with Maya scene under MouseMove event captured in Qt.

Interesting huh...

Tuesday, March 13, 2012

Enthusiasm!!


I happened to watch this quite inspiring speech, given by Mike Jutan, R&D Engineer at ILM. He decided his career goal right after watching Terminator 2 with amazing special effects. It's that very moment that keeps driving his enthusiasm all the way from studying Computer Science, working at Alias, Pixar and now ILM. He is awesome!

Dare to be different!
Luck favors the prepared.
Strive to be happy!
Overnight Success is many years in making.