Form Wang Rui, "An initial GLSL shader support of rendering particles. Only the POINT

type is supported at present. The attached osgparticleshader.cpp will
show how it works. It can also be placed in the examples folder. But I
just wonder how this example co-exists with another two (osgparticle
and osgparticleeffect)?

Member variables in Particle, including _alive, _current_size and
_current_alpha, are now merged into one Vec3 variable. Then we can
make use of the set...Pointer() methods to treat them as vertex
attribtues in GLSL. User interfaces are not changed.

Additional methods of ParticleSystem are introduced, including
setDefaultAttributesUsingShaders(), setSortMode() and
setVisibilityDistance(). You can see how they work in
osgparticleshader.cpp.

Additional user-defined particle type is introduced. Set the particle
type to USER and attach a drawable to the template. Be careful because
of possible huge memory consumption. It is highly suggested to use
display lists here.

The ParticleSystemUpdater can accepts ParticleSystem objects as child
drawables now. I myself think it is a little simpler in structure,
than creating a new geode for each particle system. Of course, the
latter is still compatible, and can be used to transform entire
particles in the world.

New particle operators: bounce, sink, damping, orbit and explosion.
The bounce and sink opeartors both use a concept of domains, and can
simulate a very basic collision of particles and objects.

New composite placer. It contains a set of placers and emit particles
from them randomly. The added virtual method size() of each placer
will help determine the probability of generating.

New virtual method operateParticles() for the Operator class. It
actually calls operate() for each particle, but can be overrode to use
speedup techniques like SSE, or even shaders in the future.

Partly fix a floating error of 'delta time' in emitter, program and
updaters. Previously they keep the _t0 variable seperately and compute
different copies of dt by themseleves, which makes some operators,
especially the BounceOperator, work incorrectly (because the dt in
operators and updaters are slightly different). Now a getDeltaTime()
method is maintained in ParticleSystem, and will return the unique dt
value (passing by reference) for use. This makes thing better, but
still very few unexpected behavours at present...

All dotosg and serialzier wrappers for functionalities above are provided.

...

According to some simple tests, the new shader support is slightly
efficient than ordinary glBegin()/end(). That means, I haven't got a
big improvement at present. I think the bottlenack here seems to be
the cull traversal time. Because operators go through the particle
list again and again (for example, the fountain in the shader example
requires 4 operators working all the time).

A really ideal solution here is to implement the particle operators in
shaders, too, and copy the results back to particle attributes. The
concept of GPGPU is good for implementing this. But in my opinion, the
Camera class seems to be too heavy for realizing such functionality in
a particle system. Myabe a light-weight ComputeDrawable class is
enough for receiving data as textures and outputting the results to
the FBO render buffer. What do you think then?

The floating error of emitters
(http://lists.openscenegraph.org/pipermail/osg-users-openscenegraph.org/2009-May/028435.html)
is not solved this time. But what I think is worth testing is that we
could directly compute the node path from the emitter to the particle
system rather than multiplying the worldToLocal and LocalToWorld
matrices. I'll try this idea later.
"
This commit is contained in:
Robert Osfield
2010-09-14 15:47:29 +00:00
parent 551d2b6479
commit b4789863ac
50 changed files with 3001 additions and 130 deletions

View File

@@ -12,10 +12,22 @@
#include <osg/BlendFunc>
#include <osg/TexEnv>
#include <osg/Material>
#include <osg/PointSprite>
#include <osg/Program>
#include <osg/Notify>
#include <osg/io_utils>
#include <osgDB/FileUtils>
#include <osgDB/ReadFile>
#include <osgUtil/CullVisitor>
#define USE_LOCAL_SHADERS
static double distance(const osg::Vec3& coord, const osg::Matrix& matrix)
{
// copied from CullVisitor.cpp
return -(coord[0]*matrix(0,2)+coord[1]*matrix(1,2)+coord[2]*matrix(2,2)+matrix(3,2));
}
osgParticle::ParticleSystem::ParticleSystem()
: osg::Drawable(),
@@ -24,6 +36,9 @@ osgParticle::ParticleSystem::ParticleSystem()
_align_X_axis(1, 0, 0),
_align_Y_axis(0, 1, 0),
_particleScaleReferenceFrame(WORLD_COORDINATES),
_useVertexArray(false),
_useShaders(false),
_dirty_uniforms(false),
_doublepass(false),
_frozen(false),
_bmin(0, 0, 0),
@@ -32,8 +47,13 @@ osgParticle::ParticleSystem::ParticleSystem()
_bounds_computed(false),
_def_ptemp(Particle()),
_last_frame(0),
_dirty_dt(true),
_freeze_on_cull(false),
_t0(0.0),
_dt(0.0),
_detail(1),
_sortMode(NO_SORT),
_visibilityDistance(-1.0),
_draw_count(0)
{
// we don't support display lists because particle systems
@@ -48,6 +68,9 @@ osgParticle::ParticleSystem::ParticleSystem(const ParticleSystem& copy, const os
_align_X_axis(copy._align_X_axis),
_align_Y_axis(copy._align_Y_axis),
_particleScaleReferenceFrame(copy._particleScaleReferenceFrame),
_useVertexArray(copy._useVertexArray),
_useShaders(copy._useShaders),
_dirty_uniforms(copy._dirty_uniforms),
_doublepass(copy._doublepass),
_frozen(copy._frozen),
_bmin(copy._bmin),
@@ -56,8 +79,13 @@ osgParticle::ParticleSystem::ParticleSystem(const ParticleSystem& copy, const os
_bounds_computed(copy._bounds_computed),
_def_ptemp(copy._def_ptemp),
_last_frame(copy._last_frame),
_dirty_dt(copy._dirty_dt),
_freeze_on_cull(copy._freeze_on_cull),
_t0(copy._t0),
_dt(copy._dt),
_detail(copy._detail),
_sortMode(copy._sortMode),
_visibilityDistance(copy._visibilityDistance),
_draw_count(0)
{
}
@@ -66,18 +94,34 @@ osgParticle::ParticleSystem::~ParticleSystem()
{
}
void osgParticle::ParticleSystem::update(double dt)
void osgParticle::ParticleSystem::update(double dt, osg::NodeVisitor& nv)
{
// reset bounds
_reset_bounds_flag = true;
if (_useShaders)
{
// Update shader uniforms
// This slightly reduces the consumption of traversing the particle vector, because we
// don't compute tile and angle attributes that are useleff for shaders.
// At present, our lcoal shader implementation will ignore these particle props:
// _cur_tile, _s_coord, _t_coord, _prev_pos, _prev_angle and _angle
osg::StateSet* stateset = getOrCreateStateSet();
if (_dirty_uniforms)
{
osg::Uniform* u_vd = stateset->getUniform("visibilityDistance");
if (u_vd) u_vd->set((float)_visibilityDistance);
_dirty_uniforms = false;
}
}
for(unsigned int i=0; i<_particles.size(); ++i)
{
Particle& particle = _particles[i];
if (particle.isAlive())
{
if (particle.update(dt))
if (particle.update(dt, _useShaders))
{
update_bounds(particle.getPosition(), particle.getCurrentSize());
}
@@ -87,7 +131,27 @@ void osgParticle::ParticleSystem::update(double dt)
}
}
}
if (_sortMode != NO_SORT)
{
// sort particles
osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(&nv);
if (cv)
{
osg::Matrixd modelview = *(cv->getModelViewMatrix());
float scale = (_sortMode==SORT_FRONT_TO_BACK ? -1.0f : 1.0f);
for (unsigned int i=0; i<_particles.size(); ++i)
{
Particle& particle = _particles[i];
if (particle.isAlive())
particle.setDepth(distance(particle.getPosition(), modelview) * scale);
else
particle.setDepth(0.0f);
}
std::sort<Particle_vector::iterator>(_particles.begin(), _particles.end());
}
}
// force recomputing of bounding box on next frame
dirtyBound();
}
@@ -101,7 +165,11 @@ void osgParticle::ParticleSystem::drawImplementation(osg::RenderInfo& renderInfo
// update the frame count, so other objects can detect when
// this particle system is culled
_last_frame = state.getFrameStamp()->getFrameNumber();
// update the dirty flag of delta time, so next time a new request for delta time
// will automatically cause recomputing
_dirty_dt = true;
// get the current modelview matrix
osg::Matrix modelview = state.getModelViewMatrix();
@@ -113,7 +181,10 @@ void osgParticle::ParticleSystem::drawImplementation(osg::RenderInfo& renderInfo
glDepthMask(GL_FALSE);
// render, first pass
single_pass_render(state, modelview);
if (_useVertexArray)
render_vertex_array(renderInfo);
else
single_pass_render(renderInfo, modelview);
#if !defined(OSG_GLES1_AVAILABLE) && !defined(OSG_GLES2_AVAILABLE) && !defined(OSG_GL3_AVAILABLE)
// restore depth mask settings
@@ -129,7 +200,10 @@ void osgParticle::ParticleSystem::drawImplementation(osg::RenderInfo& renderInfo
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
// render the particles onto the depth buffer
single_pass_render(state, modelview);
if (_useVertexArray)
render_vertex_array(renderInfo);
else
single_pass_render(renderInfo, modelview);
#if !defined(OSG_GLES1_AVAILABLE) && !defined(OSG_GLES2_AVAILABLE) && !defined(OSG_GL3_AVAILABLE)
// restore color mask settings
@@ -179,21 +253,109 @@ void osgParticle::ParticleSystem::setDefaultAttributes(const std::string& textur
stateset->setAttributeAndModes(blend, osg::StateAttribute::ON);
setStateSet(stateset);
setUseVertexArray(false);
setUseShaders(false);
}
void osgParticle::ParticleSystem::single_pass_render(osg::State& state, const osg::Matrix& modelview) const
void osgParticle::ParticleSystem::setDefaultAttributesUsingShaders(const std::string& texturefile, bool emissive_particles, int texture_unit)
{
osg::StateSet *stateset = new osg::StateSet;
stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
osg::PointSprite *sprite = new osg::PointSprite;
stateset->setTextureAttributeAndModes(texture_unit, sprite, osg::StateAttribute::ON);
#if !defined(OSG_GLES1_AVAILABLE) && !defined(OSG_GLES2_AVAILABLE)
stateset->setMode(GL_VERTEX_PROGRAM_POINT_SIZE, osg::StateAttribute::ON);
#else
OSG_NOTICE<<"Warning: ParticleSystem::setDefaultAttributesUsingShaders(..) not fully implemented."<<std::endl;
#endif
if (!texturefile.empty())
{
osg::Texture2D *texture = new osg::Texture2D;
texture->setImage(osgDB::readImageFile(texturefile));
texture->setFilter(osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR);
texture->setFilter(osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR);
texture->setWrap(osg::Texture2D::WRAP_S, osg::Texture2D::MIRROR);
texture->setWrap(osg::Texture2D::WRAP_T, osg::Texture2D::MIRROR);
stateset->setTextureAttributeAndModes(texture_unit, texture, osg::StateAttribute::ON);
}
osg::BlendFunc *blend = new osg::BlendFunc;
if (emissive_particles)
{
blend->setFunction(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE);
}
else
{
blend->setFunction(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA);
}
stateset->setAttributeAndModes(blend, osg::StateAttribute::ON);
osg::Program *program = new osg::Program;
#ifdef USE_LOCAL_SHADERS
char vertexShaderSource[] =
"uniform float visibilityDistance;\n"
"varying vec3 basic_prop;\n"
"\n"
"void main(void)\n"
"{\n"
" basic_prop = gl_MultiTexCoord0.xyz;\n"
" \n"
" vec4 ecPos = gl_ModelViewMatrix * gl_Vertex;\n"
" float ecDepth = -ecPos.z;\n"
" \n"
" if (visibilityDistance > 0.0)\n"
" {\n"
" if (ecDepth <= 0.0 || ecDepth >= visibilityDistance)\n"
" basic_prop.x = -1.0;\n"
" }\n"
" \n"
" gl_Position = ftransform();\n"
" gl_ClipVertex = ecPos;\n"
" \n"
" vec4 color = gl_Color;\n"
" color.a *= basic_prop.z;\n"
" gl_FrontColor = color;\n"
" gl_BackColor = gl_FrontColor;\n"
"}\n";
char fragmentShaderSource[] =
"uniform sampler2D baseTexture;\n"
"varying vec3 basic_prop;\n"
"\n"
"void main(void)\n"
"{\n"
" if (basic_prop.x < 0.0) discard;\n"
" gl_FragColor = gl_Color * texture2D(baseTexture, gl_TexCoord[0].xy);\n"
"}\n";
program->addShader(new osg::Shader(osg::Shader::VERTEX, vertexShaderSource));
program->addShader(new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource));
#else
program->addShader(osg::Shader::readShaderFile(osg::Shader::VERTEX, osgDB::findDataFile("shaders/particle.vert")));
program->addShader(osg::Shader::readShaderFile(osg::Shader::FRAGMENT, osgDB::findDataFile("shaders/particle.frag")));
#endif
stateset->setAttributeAndModes(program, osg::StateAttribute::ON);
stateset->addUniform(new osg::Uniform("visibilityDistance", (float)_visibilityDistance));
stateset->addUniform(new osg::Uniform("baseTexture", texture_unit));
setStateSet(stateset);
setUseVertexArray(true);
setUseShaders(true);
}
void osgParticle::ParticleSystem::single_pass_render(osg::RenderInfo& renderInfo, const osg::Matrix& modelview) const
{
_draw_count = 0;
if (_particles.size() <= 0) return;
osg::GLBeginEndAdapter* gl = &state.getGLBeginEndAdapter();
osg::GLBeginEndAdapter* gl = &(renderInfo.getState()->getGLBeginEndAdapter());
float scale = sqrtf(static_cast<float>(_detail));
const Particle* startParticle = &_particles[0];
startParticle->beginRender(gl);
osg::Vec3 xAxis = _align_X_axis;
osg::Vec3 yAxis = _align_Y_axis;
@@ -229,19 +391,55 @@ void osgParticle::ParticleSystem::single_pass_render(osg::State& state, const o
yAxis *= yScale;
}
bool requiresEndRender = false;
const Particle* startParticle = &_particles[0];
if (startParticle->getShape() != Particle::USER)
{
startParticle->beginRender(gl);
requiresEndRender = true;
}
else
{
// Enable writing depth mask when drawing user-defined particles
glDepthMask(GL_TRUE);
}
for(unsigned int i=0; i<_particles.size(); i+=_detail)
{
const Particle* currentParticle = &_particles[i];
if (currentParticle->isAlive())
bool insideDistance = true;
if (_sortMode != NO_SORT && _visibilityDistance>0.0)
insideDistance = (currentParticle->getDepth()>=0.0 && currentParticle->getDepth()<=_visibilityDistance);
if (currentParticle->isAlive() && insideDistance)
{
if (currentParticle->getShape() != startParticle->getShape())
{
startParticle->endRender(gl);
currentParticle->beginRender(gl);
startParticle = currentParticle;
if (currentParticle->getShape() != Particle::USER)
{
currentParticle->beginRender(gl);
requiresEndRender = true;
glDepthMask(GL_FALSE);
}
else
glDepthMask(GL_TRUE);
}
++_draw_count;
if (currentParticle->getShape() == Particle::USER)
{
if (requiresEndRender)
{
startParticle->endRender(gl);
requiresEndRender = false;
}
currentParticle->render(renderInfo, currentParticle->getPosition(), currentParticle->getAngle());
continue;
}
const osg::Vec3& angle = currentParticle->getAngle();
bool requiresRotation = (angle.x()!=0.0f || angle.y()!=0.0f || angle.z()!=0.0f);
if (requiresRotation)
@@ -277,8 +475,40 @@ void osgParticle::ParticleSystem::single_pass_render(osg::State& state, const o
}
}
startParticle->endRender(gl);
if (requiresEndRender)
startParticle->endRender(gl);
}
void osgParticle::ParticleSystem::render_vertex_array(osg::RenderInfo& renderInfo) const
{
if (_particles.size() <= 0) return;
// Compute the pointer and offsets
Particle_vector::const_iterator itr = _particles.begin();
float* ptr = (float*)(&(*itr));
GLsizei stride = 0;
if (_particles.size() > 1)
{
float* ptr1 = (float*)(&(*(itr+1)));
stride = ptr1 - ptr;
}
GLsizei posOffset = (float*)(&(itr->_position)) - ptr; // Position
GLsizei colorOffset = (float*)(&(itr->_current_color)) - ptr; // Color
GLsizei velOffset = (float*)(&(itr->_velocity)) - ptr; // Velocity
GLsizei propOffset = (float*)(&(itr->_base_prop)) - ptr; // Alive, size & alpha
// Draw particles as arrays
osg::State& state = *renderInfo.getState();
state.lazyDisablingOfVertexAttributes();
state.setColorPointer(4, GL_FLOAT, stride * sizeof(float), ptr + colorOffset);
state.setVertexPointer(3, GL_FLOAT, stride * sizeof(float), ptr + posOffset);
if (_useShaders)
{
state.setNormalPointer(GL_FLOAT, stride * sizeof(float), ptr + velOffset);
state.setTexCoordPointer(0, 3, GL_FLOAT, stride * sizeof(float), ptr + propOffset);
}
state.applyDisablingOfVertexAttributes();
glDrawArrays(GL_POINTS, 0, _particles.size());
}
osg::BoundingBox osgParticle::ParticleSystem::computeBound() const