public override void Apply()
        {
            // TODO: We should check whether the matrices are not null
            mViewMatrixParameter.SetValue(mViewMatrix);
            mProjectionMatrixParameter.SetValue(mProjectionMatrix);

            mGlobalLightDirectionParameter.SetValue(mGlobalLightDirection);
            mGlobalLightColorParameter.SetValue(mGlobalLightColor);
            mGlobalLightAmbientParameter.SetValue(mGlobalLightAmbient);

            mLightSpaceMatrixParameter.SetValue(mLightSpaceMatrix);
            mShadowMapParameter.SetValue(mShadowMap);
            mShadowBiasParameter.SetValue(mShadowBias);
            mShadowNumSamplesParameter.SetValue(mShadowNumSamples);
            mShadowSampleRangeParameter.SetValue(mShadowSampleRange);
            mShadowDistanceParameter.SetValue(mShadowDistance);
            mShadowResolutionParameter.SetValue(mShadowResolution);

            mUpVectorParameter?.SetValue(mUp);

            mFarPlaneParameter.SetValue(mFarPlane);
            mFogColorParameter.SetValue(mFogColor);
            mFogDistanceParameter.SetValue(mFogDistance);

            base.Apply();
        }
        /// <summary>
        /// Lazily recomputes the world inverse transpose matrix and
        /// eye position based on the current effect parameter settings.
        /// </summary>
        internal static EffectDirtyFlags SetLightingMatrices(EffectDirtyFlags dirtyFlags, ref Matrix world, ref Matrix view,
                                                             EffectParameter worldParam, EffectParameter worldInverseTransposeParam, EffectParameter eyePositionParam)
        {
            // Set the world and world inverse transpose matrices.
            if ((dirtyFlags & EffectDirtyFlags.World) != 0)
            {
                Matrix worldTranspose;
                Matrix worldInverseTranspose;

                Matrix.Invert(ref world, out worldTranspose);
                Matrix.Transpose(ref worldTranspose, out worldInverseTranspose);

                worldParam.SetValue(world);
                worldInverseTransposeParam.SetValue(worldInverseTranspose);

                dirtyFlags &= ~EffectDirtyFlags.World;
            }

            // Set the eye position.
            if ((dirtyFlags & EffectDirtyFlags.EyePosition) != 0)
            {
                Matrix viewInverse;

                Matrix.Invert(ref view, out viewInverse);

                eyePositionParam.SetValue(viewInverse.TranslationVector);

                dirtyFlags &= ~EffectDirtyFlags.EyePosition;
            }

            return dirtyFlags;
        }
 public void play(Vector2 strongPoint, float totalTimeInMs)
 {
     StrongPoint   = strongPoint;
     TotalTimeInMs = totalTimeInMs;
     timerMs       = 0f;
     frequencyParam?.SetValue(frequency);
     amplitudeParam?.SetValue(amplitude);
     this.enabled = true;
 }
        public void ApplyMaterial(Material material)
        {
            mDiffuseMapParameter?.SetValue(material.mDiffuseMap);

            mHasDiffuseMapParameter?.SetValue(material.mDiffuseMap != null);
            mDiffuseColorParameter.SetValue(material.mDiffuseColor);

            mSpecularIntensityParameter?.SetValue(material.mSpecularIntensitiy);
            mSpecularHardnessParameter?.SetValue(material.mSpecularHardness);

            base.Apply();
        }
        /// <summary>
        /// Lazily recomputes the world+view+projection matrix and
        /// fog vector based on the current effect parameter settings.
        /// </summary>
        internal static EffectDirtyFlags SetWorldViewProjAndFog(EffectDirtyFlags dirtyFlags,
                                                                ref Matrix world, ref Matrix view, ref Matrix projection, ref Matrix worldView,
                                                                bool fogEnabled, float fogStart, float fogEnd,
                                                                EffectParameter worldViewProjParam, EffectParameter fogVectorParam)
        {
            // Recompute the world+view+projection matrix?
            if ((dirtyFlags & EffectDirtyFlags.WorldViewProj) != 0)
            {
                Matrix worldViewProj;
                
                Matrix.Multiply(ref world, ref view, out worldView);
                Matrix.Multiply(ref worldView, ref projection, out worldViewProj);
                
                worldViewProjParam.SetValue(worldViewProj);
                
                dirtyFlags &= ~EffectDirtyFlags.WorldViewProj;
            }

            if (fogEnabled)
            {
                // Recompute the fog vector?
                if ((dirtyFlags & (EffectDirtyFlags.Fog | EffectDirtyFlags.FogEnable)) != 0)
                {
                    SetFogVector(ref worldView, fogStart, fogEnd, fogVectorParam);

                    dirtyFlags &= ~(EffectDirtyFlags.Fog | EffectDirtyFlags.FogEnable);
                }
            }
            else
            {
                // When fog is disabled, make sure the fog vector is reset to zero.
                if ((dirtyFlags & EffectDirtyFlags.FogEnable) != 0)
                {
                    fogVectorParam.SetValue(Vector4.Zero);

                    dirtyFlags &= ~EffectDirtyFlags.FogEnable;
                }
            }

            return dirtyFlags;
        }
Exemple #6
0
        protected override void OnApply()
        {
            if (_paletteDirty)
            {
                _paletteParam.SetValue(Palette);

                _paletteDirty = false;
            }

            if (!ManualLightMatrix && _lightMatrixDirty)
            {
                var mat = LightDirection.GetViewProjectionMatrix(new BoundingFrustum(_view * _projection));
                _dirLightMatrixParam?.SetValue(mat);
                _lightMatrixDirty = false;
            }

            if (_cameraDirty)
            {
                _positionParam?.SetValue(ChunkPosition);
                _viewParam?.SetValue(View);
                _projectionParam?.SetValue(Projection);

                _cameraDirty = false;
            }

            if (_lightDirty)
            {
                _lightDirParam?.SetValue(LightDirection);
                _diffuseLightParam?.SetValue(DiffuseLight);
                _ambientLightParam?.SetValue(AmbientLight.ToVector3());

                _lightDirty = false;
            }

            if (_shadowMapDirty)
            {
                _shadowMapParam?.SetValue(_shadowMap);
                _shadowMapDirty = false;
            }
        }
        public VisionEffect(Effect effect, SamplerState samplerState = null)
        {
            GraphicsDevice = effect.GraphicsDevice;
            Effect = effect;
            Name = effect.Name;

            _epTextureSampler = effect.Parameters["TextureSampler"];
            if(_epTextureSampler!=null)
                Sampler = samplerState ?? GraphicsDevice.SamplerStates.LinearWrap;

            _epWorld = effect.Parameters["World"];
            _epWorldInverseTranspose = effect.Parameters["WorldInverseTranspose"];
            _epView = effect.Parameters["View"];
            _epProjection = effect.Parameters["Projection"];
            _epCameraPosition = effect.Parameters["CameraPosition"];
            _epClipPlane = effect.Parameters["ClipPlane"];
            _epSunlightDirection = effect.Parameters["SunlightDirection"];
            _epTexture = effect.Parameters["Texture"];
            _epDiffuseColor = effect.Parameters["DiffuseColor"];

            _epDoShadowMapping = effect.Parameters["DoShadowMapping"];
            _epShadowMap = effect.Parameters["ShadowMap"];
            _epShadowViewProjection = effect.Parameters["ShadowViewProjection"];
            _epShadowFarPlane = effect.Parameters["ShadowFarPlane"];
            _epShadowMult = effect.Parameters["ShadowMult"];

            _techStandard = effect.Techniques["TechStandard"];
            _techClipPlane = effect.Techniques["TechClipPlane"];
            _techDepthMap = effect.Techniques["TechDepthMap"];

            //Debug.Assert( _epView != null );
            //Debug.Assert(_techDepthMap != null);

            if ( _epSunlightDirection != null)
                _epSunlightDirection.SetValue(VisionContent.SunlightDirection);
        }
Exemple #8
0
 public void SetSpecularIntensity(float specIntensity)
 {
     _specularIntensityParam.SetValue(specIntensity);
 }
 /// <summary>
 /// Sets the diffuse/emissive/alpha material color parameters.
 /// </summary>
 internal static void SetMaterialColor(bool lightingEnabled, float alpha,
                                       ref Vector4 diffuseColor, ref Vector3 emissiveColor, ref Vector3 ambientLightColor,
                                       EffectParameter diffuseColorParam, EffectParameter emissiveColorParam)
 {
     // Desired lighting model:
     //
     //     ((AmbientLightColor + sum(diffuse directional light)) * DiffuseColor) + EmissiveColor
     //
     // When lighting is disabled, ambient and directional lights are ignored, leaving:
     //
     //     DiffuseColor + EmissiveColor
     //
     // For the lighting disabled case, we can save one shader instruction by precomputing
     // diffuse+emissive on the CPU, after which the shader can use DiffuseColor directly,
     // ignoring its emissive parameter.
     //
     // When lighting is enabled, we can merge the ambient and emissive settings. If we
     // set our emissive parameter to emissive+(ambient*diffuse), the shader no longer
     // needs to bother adding the ambient contribution, simplifying its computation to:
     //
     //     (sum(diffuse directional light) * DiffuseColor) + EmissiveColor
     //
     // For further optimization goodness, we merge material alpha with the diffuse
     // color parameter, and premultiply all color values by this alpha.
     
     if (lightingEnabled)
     {
         var diffuse = new Vector4(diffuseColor.X * alpha, diffuseColor.Y * alpha, diffuseColor.Z * alpha, alpha);
         var emissive = new Vector3(
                                (emissiveColor.X + ambientLightColor.X * diffuseColor.X) * alpha,
                                (emissiveColor.Y + ambientLightColor.Y * diffuseColor.Y) * alpha,
                                (emissiveColor.Z + ambientLightColor.Z * diffuseColor.Z) * alpha
                            );
         diffuseColorParam.SetValue(diffuse);
         emissiveColorParam.SetValue(emissive);
     }
     else
     {
         var diffuse = new Vector4((diffuseColor.X + emissiveColor.X) * alpha, (diffuseColor.Y + emissiveColor.Y) * alpha, (diffuseColor.Z + emissiveColor.Z) * alpha, alpha);
         diffuseColorParam.SetValue(diffuse);
     }
 }
Exemple #10
0
 public void SetColor(Color color)
 {
     _colorParam.SetValue(color.ToVector3());
 }
Exemple #11
0
 public void Set(float value)
 {
                 #if SILVERLIGHT
     if (vsRegisterIndex != -1)
     {
         video.Device.SetVertexShaderConstantFloat4 <float>(vsRegisterIndex, ref value);
     }
     if (psRegisterIndex != -1)
     {
         video.Device.SetPixelShaderConstantFloat4 <float>(psRegisterIndex, ref value);
     }
                 #else
     parameter.SetValue(value);
                 #endif
 }
Exemple #12
0
 public void EnableLight(bool value)
 {
     _drawLightingEffect.SetValue(value);
 }
        protected override void OnProcess(RenderContext context)
        {
            var graphicsDevice = GraphicsService.GraphicsDevice;

            // Set the render target - but only if no kind of alpha blending is currently set.
            // If alpha-blending is set, then we have to assume that the render target is already
            // set - everything else does not make sense.
            if (graphicsDevice.BlendState.ColorDestinationBlend == Blend.Zero &&
                graphicsDevice.BlendState.AlphaDestinationBlend == Blend.Zero)
            {
                graphicsDevice.SetRenderTarget(context.RenderTarget);
                graphicsDevice.Viewport = context.Viewport;
            }

            Projection projection = null;

            if (RebuildZBuffer || Mode == UpsamplingMode.NearestDepth)
            {
                context.ThrowIfCameraMissing();
                projection = context.CameraNode.Camera.Projection;
            }

            var sourceTexture = context.SourceTexture;

            _parameterSourceTexture.SetValue(sourceTexture);
            _parameterSourceSize.SetValue(new Vector2(sourceTexture.Width, sourceTexture.Height));

            var viewport = context.Viewport;

            _parameterTargetSize.SetValue(new Vector2(viewport.Width, viewport.Height));

            if (Mode == UpsamplingMode.Bilateral)
            {
                _parameterDepthSensitivity.SetValue(DepthSensitivity);
            }
            else if (Mode == UpsamplingMode.NearestDepth)
            {
                _parameterDepthThreshold.SetValue(DepthThreshold / projection.Far);
            }

            int techniqueIndex = (int)Mode;
            int passIndex      = 0;

            if (context.SceneTexture != null)
            {
                _parameterSceneTexture.SetValue(context.SceneTexture);
                passIndex |= 1;
            }

            if (RebuildZBuffer)
            {
                passIndex |= 2;

                float  nearBias = 1;
                float  farBias  = 0.995f;
                object obj;
                context.Data.TryGetValue(RenderContextKeys.RebuildZBufferRenderer, out obj);
                var rebuildZBufferRenderer = obj as RebuildZBufferRenderer;
                if (rebuildZBufferRenderer != null)
                {
                    nearBias = rebuildZBufferRenderer.NearBias;
                    farBias  = rebuildZBufferRenderer.FarBias;
                }

                // Compute biased projection for restoring the z-buffer.
                var biasedProjection = Matrix.CreatePerspectiveOffCenter(
                    projection.Left,
                    projection.Right,
                    projection.Bottom,
                    projection.Top,
                    projection.Near * nearBias,
                    projection.Far * farBias);
                _parameterProjection.SetValue((Matrix)biasedProjection);
                _parameterCameraFar.SetValue(projection.Far);

                // PostProcessor.ProcessInternal sets the DepthStencilState to None.
                // --> Enable depth writes.
                graphicsDevice.DepthStencilState = GraphicsHelper.DepthStencilStateAlways;
            }

            if (RebuildZBuffer || Mode >= UpsamplingMode.Bilateral)
            {
                context.ThrowIfGBuffer0Missing();
                _parameterDepthBuffer.SetValue(context.GBuffer0);
            }

            if (Mode >= UpsamplingMode.Bilateral)
            {
                // Render at half resolution into off-screen buffer.
                object dummy;
                context.Data.TryGetValue(RenderContextKeys.DepthBufferHalf, out dummy);
                var depthBufferHalf = dummy as Texture2D;
                if (depthBufferHalf == null)
                {
                    string message = "Downsampled depth buffer is not set in render context. (The downsampled "
                                     + "depth buffer (half width and height) is required by the UpsampleFilter."
                                     + "It needs to be stored in RenderContext.Data[RenderContextKeys.DepthBufferHalf].)";
                    throw new GraphicsException(message);
                }

                _parameterDepthBufferLow.SetValue(depthBufferHalf);
            }

            _effect.CurrentTechnique = _effect.Techniques[techniqueIndex];
            _effect.CurrentTechnique.Passes[passIndex].Apply();

            graphicsDevice.DrawFullScreenQuad();

            _parameterSourceTexture.SetValue((Texture2D)null);
            _parameterSceneTexture.SetValue((Texture2D)null);
            _parameterDepthBuffer.SetValue((Texture2D)null);
            _parameterDepthBufferLow.SetValue((Texture2D)null);
        }
 public void SetMatrix(Matrix world, ref Matrix view, ref Matrix projection)
 {
     worldViewProjection.SetValue(world * view * projection);
     invView.SetValue(Matrix.Invert(view));
 }
Exemple #15
0
 /// <summary>
 /// directly sets the light direction
 /// </summary>
 /// <param name="lightDirection">Light direction.</param>
 public void SetSpotLightDirection(Vector2 lightDirection)
 {
     _lightDirectionParam.SetValue(lightDirection);
 }
Exemple #16
0
        // Perform FFTs.
        // 4 complex input images: source0.xy, source0.zw, source1.xy, source1.zw
        // 2 targets: target0 = displacement map, target1 = normal map using Color format.
        public void Process(RenderContext context, bool forward, Texture2D source0, Texture2D source1, RenderTarget2D target0, RenderTarget2D target1, float choppiness)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (source0 == null)
            {
                throw new ArgumentNullException("source0");
            }
            if (source1 == null)
            {
                throw new ArgumentNullException("source1");
            }

            if (forward)
            {
                // For forward FFT, uncomment the LastPassScale stuff!
                throw new NotImplementedException("Forward FFT not implemented.");
            }

            var graphicsService  = context.GraphicsService;
            var graphicsDevice   = graphicsService.GraphicsDevice;
            var renderTargetPool = graphicsService.RenderTargetPool;

            var savedRenderState = new RenderStateSnapshot(graphicsDevice);

            graphicsDevice.BlendState        = BlendState.Opaque;
            graphicsDevice.RasterizerState   = RasterizerState.CullNone;
            graphicsDevice.DepthStencilState = DepthStencilState.None;

            int size = source0.Width;

            _parameterSize.SetValue((float)size);

            _parameterChoppiness.SetValue(choppiness);

            int numberOfButterflyPasses = (int)MathHelper.Log2GreaterOrEqual((uint)source0.Width);

            // ReSharper disable once ConditionIsAlwaysTrueOrFalse
            _parameterButterflyTexture.SetValue(GetButterflyTexture(forward, numberOfButterflyPasses));

            var format    = new RenderTargetFormat(size, size, false, source0.Format, DepthFormat.None);
            var tempPing0 = renderTargetPool.Obtain2D(format);
            var tempPing1 = renderTargetPool.Obtain2D(format);
            var tempPong0 = renderTargetPool.Obtain2D(format);
            var tempPong1 = renderTargetPool.Obtain2D(format);

            //_parameterIsLastPass.SetValue(false);

            // Perform horizontal and vertical FFT pass.
            for (int i = 0; i < 2; i++)
            {
                //_parameterLastPassScale.SetValue(1);

                // Perform butterfly passes. We ping-pong between two temp targets.
                for (int pass = 0; pass < numberOfButterflyPasses; pass++)
                {
                    _parameterButterflyIndex.SetValue(0.5f / numberOfButterflyPasses + (float)pass / numberOfButterflyPasses);

                    if (i == 0 && pass == 0)
                    {
                        // First pass.
                        _renderTargetBindings[0] = new RenderTargetBinding(tempPing0);
                        _renderTargetBindings[1] = new RenderTargetBinding(tempPing1);
                        graphicsDevice.SetRenderTargets(_renderTargetBindings);
                        _parameterSourceTexture0.SetValue(source0);
                        _parameterSourceTexture1.SetValue(source1);
                    }
                    else if (i == 1 && pass == numberOfButterflyPasses - 1)
                    {
                        // Last pass.
                        // We have explicit shader passes for the last FFT pass.
                        break;

                        //_parameterIsLastPass.SetValue(true);
                        //if (forward)
                        //  _parameterLastPassScale.SetValue(1.0f / size / size);

                        //if (_renderTargetBindings[0].RenderTarget == tempPing0)
                        //{
                        //  _renderTargetBindings[0] = new RenderTargetBinding(target0);
                        //  _renderTargetBindings[1] = new RenderTargetBinding(target1);
                        //  graphicsDevice.SetRenderTargets(_renderTargetBindings);
                        //  _parameterSourceTexture0.SetValue(tempPing0);
                        //  _parameterSourceTexture1.SetValue(tempPing1);
                        //}
                        //else
                        //{
                        //  _renderTargetBindings[0] = new RenderTargetBinding(target0);
                        //  _renderTargetBindings[1] = new RenderTargetBinding(target1);
                        //  graphicsDevice.SetRenderTargets(_renderTargetBindings);
                        //  _parameterSourceTexture0.SetValue(tempPong0);
                        //  _parameterSourceTexture1.SetValue(tempPong1);
                        //}
                    }
                    else
                    {
                        // Intermediate pass.
                        if (_renderTargetBindings[0].RenderTarget == tempPing0)
                        {
                            _renderTargetBindings[0] = new RenderTargetBinding(tempPong0);
                            _renderTargetBindings[1] = new RenderTargetBinding(tempPong1);
                            graphicsDevice.SetRenderTargets(_renderTargetBindings);
                            _parameterSourceTexture0.SetValue(tempPing0);
                            _parameterSourceTexture1.SetValue(tempPing1);
                        }
                        else
                        {
                            _renderTargetBindings[0] = new RenderTargetBinding(tempPing0);
                            _renderTargetBindings[1] = new RenderTargetBinding(tempPing1);
                            graphicsDevice.SetRenderTargets(_renderTargetBindings);
                            _parameterSourceTexture0.SetValue(tempPong0);
                            _parameterSourceTexture1.SetValue(tempPong1);
                        }
                    }

                    if (i == 0)
                    {
                        _passFftHorizontal.Apply();
                    }
                    else
                    {
                        _passFftVertical.Apply();
                    }

                    graphicsDevice.DrawFullScreenQuad();
                }
            }

            // Perform final vertical FFT passes. We have to perform them separately
            // because displacement map and normal map usually have different bit depth.
            // Final pass for displacement.
            graphicsDevice.SetRenderTarget(target0);
            if (_renderTargetBindings[1].RenderTarget == tempPing1)
            {
                _parameterSourceTexture0.SetValue(tempPing0);
            }
            else
            {
                _parameterSourceTexture0.SetValue(tempPong0);
            }

            _passFftDisplacement.Apply();
            graphicsDevice.DrawFullScreenQuad();

            // Final pass for normals.
            graphicsDevice.SetRenderTarget(target1);
            if (_renderTargetBindings[1].RenderTarget == tempPing1)
            {
                _parameterSourceTexture0.SetValue(tempPing1);
            }
            else
            {
                _parameterSourceTexture0.SetValue(tempPong1);
            }

            _passFftNormal.Apply();
            graphicsDevice.DrawFullScreenQuad();

            // Clean up.
            _renderTargetBindings[0] = default(RenderTargetBinding);
            _renderTargetBindings[1] = default(RenderTargetBinding);
            _parameterButterflyTexture.SetValue((Texture2D)null);
            _parameterSourceTexture0.SetValue((Texture2D)null);
            _parameterSourceTexture1.SetValue((Texture2D)null);

            renderTargetPool.Recycle(tempPing0);
            renderTargetPool.Recycle(tempPing1);
            renderTargetPool.Recycle(tempPong0);
            renderTargetPool.Recycle(tempPong1);

            savedRenderState.Restore();

            // Reset the texture stages. If a floating point texture is set, we get exceptions
            // when a sampler with bilinear filtering is set.

            graphicsDevice.ResetTextures();
        }
Exemple #17
0
 public void SetMatrixTransform(ref Matrix matrixTransform)
 {
     _matrixTransformParam.SetValue(matrixTransform);
 }
Exemple #18
0
 public void SetAmbientColor(Color color)
 {
     _ambientColorParam.SetValue(color.ToVector3());
 }
Exemple #19
0
 public void SetAreaDirectionalLightDirection(Vector3 lightDir)
 {
     _dirAreaLightDirectionParam.SetValue(lightDir);
 }
Exemple #20
0
 public void SetSpecularPower(float specPower)
 {
     _specularPowerParam.SetValue(specPower);
 }
Exemple #21
0
        public void LoadContent(ContentManager Content, GraphicsDevice GraphicsDevice, Matrix Projection)
        {
            // Allocate the particle array, and fill in the corner fields (which never change).
            particles = new ParticleVertex[settings.MaxParticles * 4];

            for (int i = 0; i < settings.MaxParticles; i++)
            {
                particles[i * 4 + 0].UV = new Vector2(0, 0);
                particles[i * 4 + 1].UV = new Vector2(1, 0);
                particles[i * 4 + 2].UV = new Vector2(1, 1);
                particles[i * 4 + 3].UV = new Vector2(0, 1);
            }

            Effect effect = Content.Load <Effect>("Shaders/Particle shader");

            // If we have several particle systems, the content manager will return
            // a single shared effect instance to them all. But we want to preconfigure
            // the effect with parameters that are specific to this particular
            // particle system. By cloning the effect, we prevent one particle system
            // from stomping over the parameter settings of another.

            particleEffect = effect.Clone();

            parameters = particleEffect.Parameters;

            // Look up shortcuts for parameters that change every frame.
            effectViewProjectionParameter = parameters["ViewProjection"];
            effectTimeParameter           = parameters["CurrentTime"];
            effectViewProjectionParameter.SetValue(Projection);

            // Set the values of parameters that do not change.
            parameters["Gravity"].SetValue(settings.Gravity);
            parameters["Duration"].SetValue((float)settings.DurationInSeconds);
            parameters["SpeedMultiplier"].SetValue(60f);
            parameters["NumberOfImages"].SetValue(settings.NumberOfImages);
            parameters["StartingAlpha"].SetValue(settings.StartingAlpha);
            parameters["EndAlpha"].SetValue(settings.EndAlpha);

            // Load the particle texture, and set it onto the effect.
            Texture2D texture = Content.Load <Texture2D>(settings.TextureName);

            parameters["Size"].SetValue(new Vector2((texture.Width / settings.NumberOfImages) * 0.5f, texture.Height * 0.5f));
            parameters["t0"].SetValue(texture);

            // Create a dynamic vertex buffer.
            vertexBuffer = new DynamicVertexBuffer(GraphicsDevice, ParticleVertex.VertexDeclaration,
                                                   settings.MaxParticles * 4, BufferUsage.WriteOnly);

            // Create and populate the index buffer.
            ushort[] indices = new ushort[settings.MaxParticles * 6];

            for (int i = 0; i < settings.MaxParticles; i++)
            {
                indices[i * 6 + 0] = (ushort)(i * 4 + 0);
                indices[i * 6 + 1] = (ushort)(i * 4 + 1);
                indices[i * 6 + 2] = (ushort)(i * 4 + 2);

                indices[i * 6 + 3] = (ushort)(i * 4 + 0);
                indices[i * 6 + 4] = (ushort)(i * 4 + 2);
                indices[i * 6 + 5] = (ushort)(i * 4 + 3);
            }

            indexBuffer = new IndexBuffer(GraphicsDevice, typeof(ushort), indices.Length, BufferUsage.WriteOnly);

            indexBuffer.SetData(indices);
        }
Exemple #22
0
        public void Draw(GraphicsDevice GraphicsDevice, Vector2 Camera)
        {
            parameters["Camera"].SetValue(Camera);

            GraphicsDevice device = GraphicsDevice;

            // Restore the vertex buffer contents if the graphics device was lost.
            if (vertexBuffer.IsContentLost)
            {
                vertexBuffer.SetData(particles);
            }

            // If there are any particles waiting in the newly added queue,
            // we'd better upload them to the GPU ready for drawing.
            if (firstNewParticle != firstFreeParticle)
            {
                AddNewParticlesToVertexBuffer();
            }

            // If there are any active particles, draw them now!
            if (firstActiveParticle != firstFreeParticle)
            {
                device.BlendState        = settings.BlendState;
                device.DepthStencilState = DepthStencilState.DepthRead;

                // Set an effect parameter describing the current time. All the vertex
                // shader particle animation is keyed off this value.
                effectTimeParameter.SetValue(currentTime);

                // Set the particle vertex and index buffer.
                device.SetVertexBuffer(vertexBuffer);
                device.Indices = indexBuffer;

                // Activate the particle effect.
                foreach (EffectPass pass in particleEffect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    if (firstActiveParticle < firstFreeParticle)
                    {
                        // If the active particles are all in one consecutive range,
                        // we can draw them all in a single call.
                        device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0,
                                                     firstActiveParticle * 4, (firstFreeParticle - firstActiveParticle) * 4,
                                                     firstActiveParticle * 6, (firstFreeParticle - firstActiveParticle) * 2);
                    }
                    else
                    {
                        // If the active particle range wraps past the end of the queue
                        // back to the start, we must split them over two draw calls.
                        device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0,
                                                     firstActiveParticle * 4, (settings.MaxParticles - firstActiveParticle) * 4,
                                                     firstActiveParticle * 6, (settings.MaxParticles - firstActiveParticle) * 2);

                        if (firstFreeParticle > 0)
                        {
                            device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0,
                                                         0, firstFreeParticle * 4,
                                                         0, firstFreeParticle * 2);
                        }
                    }
                }

                // Reset some of the renderstates that we changed,
                // so as not to mess up any other subsequent drawing.
                device.DepthStencilState = DepthStencilState.Default;
            }

            drawCounter++;
        }
 public void ApplyActor(Matrix modelMatrix, Vector3 color)
 {
     mModelMatrixParameter?.SetValue(modelMatrix);
     mActorColorParameter?.SetValue(color);
     base.Apply();
 }
 public override void UpdateEffect(GameTime GameTime)
 {
     Value.SetValue(Time / MaxTime);
     base.UpdateEffect(GameTime);
 }
Exemple #25
0
 public void SetLightIntensity(float intensity)
 {
     _lightIntensityParam.SetValue(intensity);
 }
Exemple #26
0
        protected override void Update(GameTime gameTime)
        {
            if (gamestate == gameState.menu)
            {
                if (Keyboard.GetState().IsKeyDown(Keys.Enter) == true)
                {
                    gamestate = gameState.play;
                }
            }
            else if (gamestate == gameState.play)
            {
                effectParameter1.SetValue(count);
                foreach (Runner mRunner in runnersToDelete)
                {
                    runnerList.Remove(mRunner);
                }

                // Allows the game to exit
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                {
                    this.Exit();
                }

                //Runners
                timeElapsed += gameTime.ElapsedGameTime.Milliseconds;
                if (runnersRunning < runnerLimit)
                {
                    if (timeElapsed > 500)
                    {
                        Runner newRunner = new Runner();
                        newRunner.Initialize();
                        newRunner.position = new Vector2(1300, GetRandomNumber(newRunner.srcHorizon, newRunner.srcForeground));
                        newRunner.LoadContent(Content, "run_cycle");
                        LinkedListNode <Runner> newNode = new LinkedListNode <Runner>(newRunner);
                        runnerList.AddLast(newRunner);
                        runnersRunning += 1;
                        timeElapsed     = 0;
                    }
                }

                timeSince += gameTime.ElapsedGameTime.Milliseconds;
                if (timeSince >= 1000)
                {
                    totalTime -= 1;
                    timeSince  = 0;
                }
                if (totalTime == -1 || runnersRunning == 0)
                {
                    gamestate = gameState.end;
                }

                if ((runnersRunning == 1 && gameTime.TotalGameTime.Seconds > 40) || totalTime <= 5)
                {
                    if (count < 4f && increasing)
                    {
                        count += .1f;
                    }
                    else
                    {
                        increasing = false;
                    }

                    if (count > 1 && !increasing)
                    {
                        count -= .1f;
                    }
                    else
                    {
                        increasing = true;
                    }
                }
                if (totalTime == 0)
                {
                    count = 10;
                }
                effectParameter1.SetValue(count);


                foreach (Runner mRunner in runnerList)
                {
                    mRunner.m_bIsRunning = true;

                    if (mRunner.velocity.X < -maxRunnerVelocity.X)
                    {
                        mRunner.velocity.X -= 0.2f;
                    }

                    //Dubug - Make the runner stand still for hit detection testing
                    //runners[i].velocity = new Vector2(0, 0);

                    mRunner.m_eDestSprEff = SpriteEffects.FlipHorizontally;
                    mRunner.m_bIsRunning  = true;
                    mRunner.velocity.X   -= 15f;

                    //Udpate
                    mRunner.Update(gameTime);
                }

                //Heli Movement
                if (Keyboard.GetState().IsKeyDown(Keys.Up))
                {
                    heli.velocity.Y -= 10f;
                }
                else if (Keyboard.GetState().IsKeyDown(Keys.Down))
                {
                    heli.velocity.Y += 10f;
                }
                if (Keyboard.GetState().IsKeyDown(Keys.Left))
                {
                    heli.m_eDestSprEff  = SpriteEffects.None;
                    heli.velocity.X    -= 10f;
                    heli.emitterXOffset = 19;
                    particleEngine.velocityDirection = .3f;
                }
                else if (Keyboard.GetState().IsKeyDown(Keys.Right))
                {
                    heli.m_eDestSprEff  = SpriteEffects.FlipHorizontally;
                    heli.velocity.X    += 10f;
                    heli.emitterXOffset = 18;
                    particleEngine.velocityDirection = -.3f;
                }

                if (Keyboard.GetState().IsKeyDown(Keys.Space))
                {
                    heli.dropCrate();
                }

                heli.position.Y = MathHelper.Clamp(heli.position.Y, heli.srcHorizon, 720);
                heli.Update(gameTime);

                //Particle Engine
                particleEngine.EmitterLocation = heli.emitterLocation;
                particleEngine.Update(gameTime);

                //
                debugInfo.Update(gameTime);
            }
            else
            {
                //game over
                if (Keyboard.GetState().IsKeyDown(Keys.Enter) == true)
                {
                    this.Exit();
                }
            }
            base.Update(gameTime);
        }
Exemple #27
0
 protected override void OnApply()
 {
     _timeParam.SetValue(Time.TotalTime);
 }
Exemple #28
0
 public SpriteBlinkEffect() : base(Core.graphicsDevice, EffectResource.spriteBlinkEffectBytes)
 {
     _blinkColorParam = Parameters["blinkColor"];
     _blinkColorParam.SetValue(_blinkColor);
 }
Exemple #29
0
 /// <summary>
 /// Sets the camera view and projection matrices
 /// that will be used to draw this particle system.
 /// </summary>
 public void SetCamera(Matrix view, Matrix projection)
 {
     effectViewParameter.SetValue(view);
     effectProjectionParameter.SetValue(projection);
 }
Exemple #30
0
 public void SetLightRadius(float radius)
 {
     _lightRadiusParam.SetValue(radius);
 }
Exemple #31
0
 public void SetViewProjection(Matrix View, Matrix Projection)
 {
     effectViewParameter.SetValue(View);
     effectProjectionParameter.SetValue(Projection);
 }
        /// <summary>
        /// Sets a vector which can be dotted with the object space vertex position to compute fog amount.
        /// </summary>
        static void SetFogVector(ref Matrix worldView, float fogStart, float fogEnd, EffectParameter fogVectorParam)
        {
            if (fogStart == fogEnd)
            {
                // Degenerate case: force everything to 100% fogged if start and end are the same.
                fogVectorParam.SetValue(new Vector4(0, 0, 0, 1));
            }
            else
            {
                // We want to transform vertex positions into view space, take the resulting
                // Z value, then scale and offset according to the fog start/end distances.
                // Because we only care about the Z component, the shader can do all this
                // with a single dot product, using only the Z row of the world+view matrix.
                
                float scale = 1f / (fogStart - fogEnd);

                var fogVector = new Vector4(worldView.M13 * scale, worldView.M23 * scale, worldView.M33 * scale, (worldView.M43 + fogStart) * scale);

                fogVectorParam.SetValue(fogVector);
            }
        }
Exemple #33
0
        public void Draw(GraphicsDevice GraphicsDevice)
        {
            GraphicsDevice device = GraphicsDevice;

            // Restore the vertex buffer contents if the graphics device was lost.
            if (vertexBuffer.IsContentLost)
            {
                vertexBuffer.SetData(ArrayParticles);
            }

            // If there are any particles waiting in the newly added queue,
            // we'd better upload them to the GPU ready for drawing.
            if (FirstNewParticle != FirstFreeParticle)
            {
                AddNewParticlesToVertexBuffer();
            }

            // If there are any active particles, draw them now!
            if (FirstActiveParticle != FirstFreeParticle)
            {
                device.BlendState = BlendState;
                if (_UseAlphaBlend)
                {
                    device.DepthStencilState = DepthStencilState.DepthRead;
                }
                else
                {
                    device.DepthStencilState = DepthStencilState.Default;
                }

                // Set an effect parameter describing the viewport size. This is
                // needed to convert particle sizes into screen space point sizes.
                effectViewportScaleParameter.SetValue(new Vector2(0.5f / device.Viewport.AspectRatio, -0.5f));

                // Set an effect parameter describing the current time. All the vertex
                // shader particle animation is keyed off this value.
                effectTimeParameter.SetValue(CurrentTime);

                // Set the particle vertex and index buffer.
                device.SetVertexBuffer(vertexBuffer);
                device.Indices = indexBuffer;

                // Activate the particle effect.
                foreach (EffectPass pass in particleEffect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    if (FirstActiveParticle < FirstFreeParticle)
                    {
                        // If the active particles are all in one consecutive range,
                        // we can draw them all in a single call.
                        device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0,
                                                     FirstActiveParticle * 4, (FirstFreeParticle - FirstActiveParticle) * 4,
                                                     FirstActiveParticle * 6, (FirstFreeParticle - FirstActiveParticle) * 2);
                    }
                    else
                    {
                        // If the active particle range wraps past the end of the queue
                        // back to the start, we must split them over two draw calls.
                        device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0,
                                                     FirstActiveParticle * 4, (MaxParticles - FirstActiveParticle) * 4,
                                                     FirstActiveParticle * 6, (MaxParticles - FirstActiveParticle) * 2);

                        if (FirstFreeParticle > 0)
                        {
                            device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0,
                                                         0, FirstFreeParticle * 4,
                                                         0, FirstFreeParticle * 2);
                        }
                    }
                }

                // Reset some of the renderstates that we changed,
                // so as not to mess up any other subsequent drawing.
                device.DepthStencilState = DepthStencilState.Default;
            }

            drawCounter++;
        }
Exemple #34
0
        /// <summary>
        /// Draws the particle system.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            GraphicsDevice device = GraphicsDevice;

            // Restore the vertex buffer contents if the graphics device was lost.
            if (vertexBuffer.IsContentLost)
            {
                vertexBuffer.SetData(particles);
            }

            // If there are any particles waiting in the newly added queue,
            // we'd better upload them to the GPU ready for drawing.
            if (firstNewParticle != firstFreeParticle)
            {
                AddNewParticlesToVertexBuffer();
            }

            // If there are any active particles, draw them now!
            if (firstActiveParticle != firstFreeParticle)
            {
                SetParticleRenderStates(device.RenderState);

                // Set an effect parameter describing the viewport size. This is needed
                // to convert particle sizes into screen space point sprite sizes.
                effectViewportHeightParameter.SetValue(device.Viewport.Height);

                // Set an effect parameter describing the current time. All the vertex
                // shader particle animation is keyed off this value.
                effectTimeParameter.SetValue(currentTime);

                // Set the particle vertex buffer and vertex declaration.
                device.Vertices[0].SetSource(vertexBuffer, 0,
                                             ParticleVertex.SizeInBytes);

                device.VertexDeclaration = vertexDeclaration;

                // Activate the particle effect.
                particleEffect.Begin();

                foreach (EffectPass pass in particleEffect.CurrentTechnique.Passes)
                {
                    pass.Begin();

                    if (firstActiveParticle < firstFreeParticle)
                    {
                        // If the active particles are all in one consecutive range,
                        // we can draw them all in a single call.
                        device.DrawPrimitives(PrimitiveType.PointList,
                                              firstActiveParticle,
                                              firstFreeParticle - firstActiveParticle);
                    }
                    else
                    {
                        // If the active particle range wraps past the end of the queue
                        // back to the start, we must split them over two draw calls.
                        device.DrawPrimitives(PrimitiveType.PointList,
                                              firstActiveParticle,
                                              particles.Length - firstActiveParticle);

                        if (firstFreeParticle > 0)
                        {
                            device.DrawPrimitives(PrimitiveType.PointList,
                                                  0,
                                                  firstFreeParticle);
                        }
                    }

                    pass.End();
                }

                particleEffect.End();

                // Reset a couple of the more unusual renderstates that we changed,
                // so as not to mess up any other subsequent drawing.
                device.RenderState.PointSpriteEnable      = false;
                device.RenderState.DepthBufferWriteEnable = true;
            }

            drawCounter++;
        }
Exemple #35
0
 public void SetSpotConeAngle(float coneAngle)
 {
     _coneAngleParam.SetValue(coneAngle);
 }