/// <summary> /// Performs rendering of particles. /// </summary> /// <param name="iterator">The particle iterator object.</param> /// <param name="context">The render context containing rendering information.</param> protected override void Render(ref RenderContext context, ref ParticleIterator iterator) { Vector2 origin = new Vector2(context.Texture.Width / 2f, context.Texture.Height / 2f); this.SpriteBatch.Begin(SpriteSortMode.Deferred, context.BlendState, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullNone, null, this.Transformation); { #if UNSAFE unsafe { Particle* particle = iterator.First; #else Particle particle = iterator.First; #endif do { #if UNSAFE Single scale = particle->Scale / context.Texture.Width; Vector2 position = new Vector2 { X = particle->Position.X, Y = particle->Position.Y }; this.SpriteBatch.Draw(context.Texture, position, null, new Color(particle->Colour), particle->Rotation.Z, origin, scale, SpriteEffects.None, 0f); #else Single scale = particle.Scale / context.Texture.Width; Vector2 position = new Vector2 { X = particle.Position.X, Y = particle.Position.Y }; this.SpriteBatch.Draw(context.Texture, position, null, new Color(particle.Colour), particle.Rotation.Z, origin, scale, SpriteEffects.None, 0f); #endif } #if UNSAFE while (iterator.MoveNext(&particle)); #else while (iterator.MoveNext(ref particle)); #endif #if UNSAFE } #endif this.SpriteBatch.End(); } }
public void RenderEffect(ParticleEffect effect, ref Matrix world, ref Matrix view, ref Matrix projection, ref Vector3 camera) { Guard.ArgumentNull("effect", effect); RenderContext context = new RenderContext { CameraPosition = camera, Projection = projection, View = view, World = world }; unsafe { this.PreRender(); for (int i = 0; i < effect.Count; i++) { Emitter emitter = effect[i]; // Skip if the emitter does not have a texture... if (emitter.ParticleTexture == null) continue; // Skip if the emitter blend mode is 'None'... if (emitter.BlendMode == EmitterBlendMode.None) continue; if (emitter.ActiveParticlesCount > 0) { fixed (Particle* particleArray = emitter.Particles) { context.BlendState = BlendStateFactory.GetBlendState(emitter.BlendMode); context.Count = emitter.ActiveParticlesCount; context.ParticleArray = particleArray; context.Texture = emitter.ParticleTexture; this.Render(ref context); } } } } }
/// <summary> /// Renders the specified particle effect. /// </summary> /// <param name="effect">The particle effect to render.</param> /// <param name="worldMatrix">The world transformation matrix.</param> /// <param name="viewMatrix">The view matrix.</param> /// <param name="projectionMatrix">The projection matrix.</param> /// <param name="cameraPosition">The camera matrix.</param> public void RenderEffect(ParticleEffect effect, ref Matrix worldMatrix, ref Matrix viewMatrix, ref Matrix projectionMatrix, ref Vector3 cameraPosition) { #if UNSAFE unsafe #endif { this.PreRender(ref worldMatrix, ref viewMatrix, ref projectionMatrix); //Pre-multiply any proxies world matrices with the passed in world matrix if (effect.Proxies != null && worldMatrix != Matrix.Identity) { effect.SetFinalWorld(ref worldMatrix); } for (Int32 i = 0; i < effect.Emitters.Count; i++) { AbstractEmitter emitter = effect.Emitters[i]; // Skip if the emitter does not have a texture... if (emitter.ParticleTexture == null) continue; // Skip if the emitter blend mode is set to 'None'... if (emitter.BlendMode == EmitterBlendMode.None) continue; // Skip if the emitter has no active particles... if (emitter.ActiveParticlesCount == 0) continue; BlendState blendState = BlendStateFactory.GetBlendState(emitter.BlendMode); RenderContext context = new RenderContext(emitter.BillboardStyle, emitter.BillboardRotationalAxis, blendState, emitter.ParticleTexture, ref worldMatrix, ref viewMatrix, ref projectionMatrix, ref cameraPosition, emitter.ActiveParticlesCount, emitter.UseVelocityAsBillboardAxis); Counters.ParticlesDrawn += emitter.ActiveParticlesCount; #if UNSAFE fixed (Particle* buffer = emitter.Particles) #else Particle[] buffer = emitter.Particles; #endif { ParticleIterator iterator = new ParticleIterator(buffer, emitter.Budget, emitter.ActiveIndex, emitter.ActiveParticlesCount); this.Render(ref context, ref iterator); } } } }
/// <summary> /// Performs rendering of particles. /// </summary> /// <param name="context">The render context containing rendering information.</param> /// <param name="iterator">The particle iterator object.</param> protected abstract void Render(ref RenderContext context, ref ParticleIterator iterator);
protected override unsafe void Render(ref RenderContext context) { Guard.IsTrue(this._basicEffect == null, "BillboardRenderer is not ready! Did you forget to LoadContent?"); Particle* particle = context.ParticleArray; Vector3 cameraPosition = context.CameraPosition; SetDataOptions setDataOptions = SetDataOptions.NoOverwrite; //TODO - cyclics buffers not quite working, though no sign of a perf increase for it anyway //if (_vertexBufferPosition + context.Count * VerticesPerParticle > MaxVertices) //{ //Too much to fit in the remaining space - start at the beginning and discard _vertexBufferPosition = 0; setDataOptions = SetDataOptions.Discard; //} fixed (VertexPositionVectorColorTexture* vertexArray = _vertices) { //Where to start writing vertices into the array VertexPositionVectorColorTexture* verts = vertexArray + _vertexBufferPosition; for (int i = 0; i < context.Count; i++) { Guard.ArgumentGreaterThan("context.Count", context.Count, MaxParticles); //TODO: If/when we move to a custom vertex shader use this to billboard http://forums.create.msdn.com/forums/t/16106.aspx - or copy the 3d sample //TODO - take rotation into account //TODO - take texture size into account - partially done Need a overall scale factor //TODO - any way to merge particles that share a texture/blend - we can avoid a draw call in that case. I think it will need sorting outside the renderer //TODO - needs a 'Use world transform' flag to optimize var position = context.World != Matrix.Identity ? Vector3.Transform(particle->Position, context.World) : particle->Position; //Calculate the corner offsets 2 and 4 are reflections of 0 and 1 var sizeX = particle->Scale*context.Texture.Width; var sizeY = particle->Scale*context.Texture.Height; _cornerOffsets[0].X = -sizeX; _cornerOffsets[0].Y = -sizeY; _cornerOffsets[1].X = sizeX; _cornerOffsets[1].Y = -sizeY; _cornerOffsets[2].X = sizeX; _cornerOffsets[2].Y = sizeY; _cornerOffsets[3].X = -sizeX; _cornerOffsets[3].Y = sizeY; //Work out the billboard transformation Matrix billboard; Matrix.CreateBillboard(ref position, ref cameraPosition, ref _up, -context.CameraPosition, out billboard); //Create the 4 vertices //Transform the corner offsets by billboard to make them camera facing for (int j = 0; j < VerticesPerParticle; j++) { Vector3.Transform(ref _cornerOffsets[j], ref billboard, out verts->Position); verts->Color = particle->Colour; verts->TextureCoordinate = _cornerUvs[j]; verts++; } particle++; } } int vertexCount = context.Count * VerticesPerParticle; base.GraphicsDeviceService.GraphicsDevice.BlendState = context.BlendState; //Xbox need the vertex buffer to be set to null before SetData is called //Windows does not //TODO: Is this a bug? see http://forums.create.msdn.com/forums/p/61885/399495.aspx#399495 base.GraphicsDeviceService.GraphicsDevice.SetVertexBuffer(null); _vertexBuffer.SetData(_vertices, _vertexBufferPosition, vertexCount, setDataOptions); Debug.WriteLine("{0} vertex pos, {2} count {1} options", _vertexBufferPosition, setDataOptions, vertexCount/4); base.GraphicsDeviceService.GraphicsDevice.SetVertexBuffer(_vertexBuffer); _basicEffect.View = context.View; _basicEffect.Projection = context.Projection; _basicEffect.Texture = context.Texture; foreach (EffectPass effectPass in _basicEffect.CurrentTechnique.Passes) { effectPass.Apply(); base.GraphicsDeviceService.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, _vertexBufferPosition, vertexCount, //TODO - index buffer not quite right when cyclic buffer enabled _vertexBufferPosition /4 * 6 , vertexCount / 3); } //Move to the next free part of the array _vertexBufferPosition += vertexCount; }
protected abstract unsafe void Render(ref RenderContext context);
/// <summary> /// Performs rendering of particles. /// </summary> /// <param name="iterator">The particle iterator object.</param> /// <param name="context">The render context containing rendering information.</param> protected override void Render(ref RenderContext context, ref ParticleIterator iterator) { Int32 vertexCount = 0; Vector3 cameraPos = context.CameraPosition; Vector3 rotationAxis = context.BillboardRotationalAxis; bool squareTexture = (context.Texture.Height == context.Texture.Width); float aspectRatio = context.Texture.Height / (float)context.Texture.Width ; SetDataOptions setDataOptions = SetDataOptions.NoOverwrite; //Use the SpriteBatch style of filling buffers //http://blogs.msdn.com/b/shawnhar/archive/2010/07/07/setdataoptions-nooverwrite-versus-discard.aspx if (_vertexBufferPosition + context.Count * VerticesPerParticle > NumVertices) { //Too much to fit in the remaining space - start at the beginning and discard _vertexBufferPosition = 0; setDataOptions = SetDataOptions.Discard; } #if UNSAFE unsafe { fixed (ParticleVertex* vertexArray = Vertices) { ParticleVertex* verts = vertexArray +_vertexBufferPosition; #else int vertexIndex = _vertexBufferPosition; #endif var particle = iterator.First; do { #if UNSAFE Single scale = particle->Scale; Vector3 position = particle->Position; Vector3 rotation = particle->Rotation; Vector4 colour = particle->Colour; //Work out our world transform - and set a flag to avoid some multiplies if world ends up as zero bool worldIsNotIdentity = true; Matrix effectWorld; if (context.WorldIsIdentity) { if (particle->EffectProxyIndex > 0) { effectWorld = ParticleEffectProxy.Proxies[particle->EffectProxyIndex].World; } else { worldIsNotIdentity = false; effectWorld = Matrix.Identity; //Makes the compiler happy though we will never actually use it. } } else { effectWorld = particle->EffectProxyIndex > 0 ? ParticleEffectProxy.Proxies[particle->EffectProxyIndex].FinalWorld : context.World; } #else Single scale = particle.Scale; Vector3 position = particle.Position; Vector3 rotation = particle.Rotation; Vector4 colour = particle.Colour; //If we have a proxy then multiply in the proxy world matrix bool worldIsNotIdentity = true; Matrix effectWorld; if (context.WorldIsIdentity) { if (particle.EffectProxyIndex > 0) { effectWorld = ParticleEffectProxy.Proxies[particle.EffectProxyIndex].World; } else { worldIsNotIdentity = false; effectWorld = Matrix.Identity; //Makes the compiler happy though we will never actually use it. } } else { effectWorld = particle.EffectProxyIndex > 0 ? ParticleEffectProxy.Proxies[particle.EffectProxyIndex].FinalWorld : context.World; } #endif //Individual particle transformations - scale and rotation //The Rotation setup will fill in the top 3x3 so we just need to initialise 44 var transform = new Matrix {M44 = 1}; float scaleX = scale; float scaleY = squareTexture ? scale : scale * aspectRatio; //ScaleZ is always 1 so no need multiple into M_3 //Inline the rotation and scale calculations and do each element in one go //Fast rotation matrix - see http://en.wikipedia.org/wiki/Rotation_matrix#General_rotations //This set matches //Matrix temp2 = Matrix.CreateRotationX(rotation.X) * Matrix.CreateRotationY(rotation.Y) * Matrix.CreateRotationZ(rotation.Z); //Matches math od Rotx*RotY*RotZ //var cosX = (float) Math.Cos(rotation.X); //var cosY = (float) Math.Cos(rotation.Y); //var cosZ = (float) Math.Cos(rotation.Z); //var sinX = (float) Math.Sin(rotation.X); //var sinY = (float) Math.Sin(rotation.Y); //var sinZ = (float) Math.Sin(rotation.Z); //transform.M11 = cosY*cosZ; //transform.M12 = cosY * sinZ; //transform.M13 = -sinY; //transform.M21 = sinX*sinY*cosZ - cosX * sinZ; //transform.M22 = sinX*sinY*sinZ + cosX*cosZ; //transform.M23 = sinX*cosY; //transform.M31 = cosX*sinY*cosZ + sinX * sinZ; //transform.M32 = cosX*sinY*sinZ - sinX * cosZ; //transform.M33 = cosX * cosY; //This set matches //Matrix temp2 = Matrix.CreateScale(new VEctor3(scaleX, scaleY,1) * Matrix.CreateRotationZ(rotation.Z) * Matrix.CreateRotationX(rotation.Y) * Matrix.CreateRotationY(rotation.X) ; //Matches YawPitchRoll order //Matrix temp = Matrix.CreateScale(new VEctor3(scaleX, scaleY,1) * Matrix.CreateFromYawPitchRoll(rotation.X, rotation.Y, rotation.Z); //TODO - can we optimise out a rotation e.g.fast path if rotation.Y=0 etc //TODO - can we optimise out rotation(s) if we know its a billboard? That overwrites much of the transform var cosX = (float)Math.Cos(rotation.Y); var cosY = (float)Math.Cos(rotation.X); var cosZ = (float)Math.Cos(rotation.Z); var sinX = (float)Math.Sin(rotation.Y); var sinY = (float)Math.Sin(rotation.X); var sinZ = (float)Math.Sin(rotation.Z); var cosYcosZ = cosY*cosZ; var cosYsinZ = cosY*sinZ; var sinXsinY = sinX*sinY; transform.M11 = (cosYcosZ + sinXsinY * sinZ) * scaleX; transform.M12 = (cosX * sinZ) * scaleX; transform.M13 = (sinX * cosYsinZ - sinY * cosZ) * scaleX; transform.M21 = (sinXsinY * cosZ - cosYsinZ) * scaleY; transform.M22 = (cosX * cosZ) *scaleY; transform.M23 = (sinY * sinZ + sinX * cosYcosZ) * scaleY; transform.M31 = cosX * sinY; transform.M32 = -sinX; transform.M33 = cosX * cosY; switch (context.BillboardStyle) { case BillboardStyle.None: //Position the particle without a multiplication! transform.M41 = position.X; transform.M42 = position.Y; transform.M43 = position.Z; //Just apply the world //TODO - we can just do this in Basic effect instead of per vertex - only if there is no proxy, sort of a fast path! if (worldIsNotIdentity) { Matrix.Multiply(ref transform, ref effectWorld, out transform); } break; default: //Its billboarded Vector3 worldPos; if (worldIsNotIdentity) { Vector3.Transform(ref position, ref effectWorld, out worldPos); } else { worldPos = position; } //Apply the billboard (which includes the world translation) Matrix billboardMatrix; if (context.BillboardStyle == BillboardStyle.Spherical) { //Spherical billboards (always face the camera) Matrix.CreateBillboard(ref worldPos, ref cameraPos, ref Up, Forward, out billboardMatrix); } else { //HACK: For progenitor DBP use the velocity as the axis for a per particle axis if (context.UseVelocityAsBillboardAxis) { #if UNSAFE Matrix.CreateConstrainedBillboard(ref worldPos, ref cameraPos, ref particle->Velocity, Forward, null, out billboardMatrix); #else Matrix.CreateConstrainedBillboard(ref worldPos, ref cameraPos, ref particle.Velocity, Forward, null, out billboardMatrix); #endif } else { //Cylindrical billboards have a vector they are allowed to rotate around Matrix.CreateConstrainedBillboard(ref worldPos, ref cameraPos, ref rotationAxis, Forward, null, out billboardMatrix); } } Matrix.Multiply(ref transform, ref billboardMatrix, out transform); break; } Vector3 v1; Vector3 v2; Vector3 v3; Vector3 v4; Vector3.Transform(ref inv1, ref transform, out v1); Vector3.Transform(ref inv2, ref transform, out v2); Vector3.Transform(ref inv3, ref transform, out v3); Vector3.Transform(ref inv4, ref transform, out v4); #if UNSAFE //inline particle value assignments - removes 4 calls with their parameters and its a struct anyway verts->Position.X = v1.X; verts->Position.Y = v1.Y; verts->Position.Z = v1.Z; verts->Colour.X = colour.X; verts->Colour.Y = colour.Y; verts->Colour.Z = colour.Z; verts->Colour.W = colour.W; verts++; verts->Position.X = v2.X; verts->Position.Y = v2.Y; verts->Position.Z = v2.Z; verts->Colour.X = colour.X; verts->Colour.Y = colour.Y; verts->Colour.Z = colour.Z; verts->Colour.W = colour.W; verts++; verts->Position.X = v3.X; verts->Position.Y = v3.Y; verts->Position.Z = v3.Z; verts->Colour.X = colour.X; verts->Colour.Y = colour.Y; verts->Colour.Z = colour.Z; verts->Colour.W = colour.W; verts++; verts->Position.X = v4.X; verts->Position.Y = v4.Y; verts->Position.Z = v4.Z; verts->Colour.X = colour.X; verts->Colour.Y = colour.Y; verts->Colour.Z = colour.Z; verts->Colour.W = colour.W; verts++; #else //inline particle value assignments - removes 4 calls with their parameters and its a struct anyway this.Vertices[vertexIndex].Position = v1; this.Vertices[vertexIndex].Colour = colour; this.Vertices[vertexIndex++].TextureCoordinate = uv1; this.Vertices[vertexIndex].Position = v2; this.Vertices[vertexIndex].Colour = colour; this.Vertices[vertexIndex++].TextureCoordinate = uv2; this.Vertices[vertexIndex].Position = v3; this.Vertices[vertexIndex].Colour = colour; this.Vertices[vertexIndex++].TextureCoordinate = uv3; this.Vertices[vertexIndex].Position = v4; this.Vertices[vertexIndex].Colour = colour; this.Vertices[vertexIndex++].TextureCoordinate = uv4; #endif vertexCount += 4; } #if UNSAFE while (iterator.MoveNext(&particle)); #else while (iterator.MoveNext(ref particle)); #endif base.GraphicsDeviceService.GraphicsDevice.BlendState = context.BlendState; this.BasicEffect.Texture = context.Texture; //Xbox need the vertex buffer to be set to null before SetData is called //Windows does not //TODO: Is this a bug? see http://forums.create.msdn.com/forums/p/61885/399495.aspx#399495 #if XBOX if (setDataOptions == SetDataOptions.Discard) { base.GraphicsDeviceService.GraphicsDevice.SetVertexBuffer(null); } #endif _vertexBuffer.SetData(_vertexBufferPosition * ParticleVertex.Size, Vertices, _vertexBufferPosition, vertexCount, ParticleVertex.Size, setDataOptions); Debug.WriteLine(String.Format("position: {0} Count: {1} Hint: {2}", _vertexBufferPosition, vertexCount, setDataOptions)); base.GraphicsDeviceService.GraphicsDevice.SetVertexBuffer(_vertexBuffer); foreach (EffectPass pass in this.BasicEffect.CurrentTechnique.Passes) { pass.Apply(); base.GraphicsDeviceService.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, _vertexBufferPosition, vertexCount, _vertexBufferPosition/4*6, vertexCount/2); } //Move to the next free part of the array _vertexBufferPosition += vertexCount; #if UNSAFE } } #endif }