/// <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.Translation); dirtyFlags &= ~EffectDirtyFlags.EyePosition; } return dirtyFlags; }
protected override void OnInit() { base.OnInit(); Texture2D texture = Texture; dtAfterGolUpdate = 0f; golUpdatePeriod = 60f / 140f; needFirstUpdate = true; spriteBatch = new SpriteBatch(Screen.graphicsDevice); eff = TTengineMaster.ActiveGame.Content.Load<Effect>("Effects/GoL"); effTime = eff.Parameters["Time"]; effDeltaPixelX = eff.Parameters["DeltaPixelX"]; effDeltaPixelY = eff.Parameters["DeltaPixelY"]; effDoGolUpdate = eff.Parameters["DoGolUpdate"]; effDeltaPixelX.SetValue(1f/((float)texture.Width)); effDeltaPixelY.SetValue(1f / ((float)texture.Height)); VertexShaderInit(eff); renderBufInput = new RenderTarget2D(spriteBatch.GraphicsDevice, texture.Width, texture.Height); renderBufOutput = new RenderTarget2D(spriteBatch.GraphicsDevice, texture.Width, texture.Height); blendState = new BlendState(); blendState.AlphaDestinationBlend = Blend.Zero; // first time rendering into buffer using BufferInit technique eff.CurrentTechnique = eff.Techniques[0]; spriteBatch.Begin(SpriteSortMode.Deferred,blendState,null,null,null,eff); spriteBatch.GraphicsDevice.SetRenderTarget(renderBufInput); spriteBatch.Draw(texture, renderBufInput.Bounds, Color.White); spriteBatch.End(); }
public PointLight(Vector3 position, Vector3 color, EffectParameter lightParameter) { this.position = position; this.color = color; this.lightParameter = lightParameter; positionParameter = lightParameter.StructureMembers["vPosition"]; rangeParameter = lightParameter.StructureMembers["fRange"]; colorParameter = lightParameter.StructureMembers["vColor"]; lightParameter.StructureMembers["fFalloff"].SetValue(2.0f); positionParameter.SetValue(position); positionParameter.SetValue(position); rangeParameter.SetValue(100); colorParameter.SetValue(color); }
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) { if ((dirtyFlags & EffectDirtyFlags.WorldViewProj) != ~EffectDirtyFlags.All) { Matrix.Multiply(ref world, ref view, out worldView); Matrix result; Matrix.Multiply(ref worldView, ref projection, out result); worldViewProjParam.SetValue(result); dirtyFlags &= ~EffectDirtyFlags.WorldViewProj; } if (fogEnabled) { if ((dirtyFlags & (EffectDirtyFlags.Fog | EffectDirtyFlags.FogEnable)) != ~EffectDirtyFlags.All) { EffectHelpers.SetFogVector(ref worldView, fogStart, fogEnd, fogVectorParam); dirtyFlags &= ~(EffectDirtyFlags.Fog | EffectDirtyFlags.FogEnable); } } else if ((dirtyFlags & EffectDirtyFlags.FogEnable) != ~EffectDirtyFlags.All) { fogVectorParam.SetValue(Vector4.Zero); dirtyFlags &= ~EffectDirtyFlags.FogEnable; } return dirtyFlags; }
public ScanlinesEffect() : base( Core.graphicsDevice, EffectResource.scanlinesBytes ) { _attenuationParam = Parameters["_attenuation"]; _linesFactorParam = Parameters["_linesFactor"]; _attenuationParam.SetValue( _attenuation ); _linesFactorParam.SetValue( _linesFactor ); }
public SpriteLinesEffect() : base( Core.graphicsDevice, EffectResource.spriteLinesEffectBytes ) { _lineColorParam = Parameters["_lineColor"]; _lineSizeParam = Parameters["_lineSize"]; _lineColorParam.SetValue( _lineColor ); _lineSizeParam.SetValue( _lineSize ); }
public DotsEffect() : base( Core.graphicsDevice, EffectResource.dotsBytes ) { _scaleParam = Parameters["scale"]; _angleParam = Parameters["angle"]; _scaleParam.SetValue( _scale ); _angleParam.SetValue( _angle ); }
public override void onAddedToScene() { effect = scene.contentManager.loadEffect<Effect>( "vignette", EffectResource.vignetteBytes ); _powerParam = effect.Parameters["_power"]; _radiusParam = effect.Parameters["_radius"]; _powerParam.SetValue( _power ); _radiusParam.SetValue( _radius ); }
public static void m000001() { f000058 = new SpriteBatch(c000074.m0000d4()); f0000c1 = c000074.f0000b0.Load<Effect>("Blur"); f0000e0 = f0000c1.Parameters["pixelSize"]; f0000e0.SetValue(new Vector2(1f / ((float) c000074.m00000f()), 1f / ((float) c000074.m000010()))); f0000c1.CommitChanges(); f00000a = true; }
private static void SetFogVector(ref Matrix worldView, float fogStart, float fogEnd, EffectParameter fogVectorParam) { if ((double) fogStart == (double) fogEnd) { fogVectorParam.SetValue(new Vector4(0.0f, 0.0f, 0.0f, 1f)); } else { float num = (float) (1.0 / ((double) fogStart - (double) fogEnd)); fogVectorParam.SetValue(new Vector4() { X = worldView.M13 * num, Y = worldView.M23 * num, Z = worldView.M33 * num, W = (worldView.M43 + fogStart) * num }); } }
public override void onAddedToScene() { effect = scene.content.loadEffect<Effect>( "vignette", EffectResource.letterboxBytes ); _colorParam = effect.Parameters["_color"]; _letterboxSizeParam = effect.Parameters["_letterboxSize"]; _colorParam.SetValue( _color.ToVector4() ); _letterboxSizeParam.SetValue( _letterboxSize ); }
public TwistEffect() : base( Core.graphicsDevice, EffectResource.twistBytes ) { _radiusParam = Parameters["radius"]; _angleParam = Parameters["angle"]; _offsetParam = Parameters["offset"]; _radiusParam.SetValue( _radius ); _angleParam.SetValue( _angle ); _offsetParam.SetValue( _offset ); }
public BlurEffect() { if (!GeneralManager.Effects.ContainsKey("Effects/Blur")) { GeneralManager.LoadEffect("Effects/Blur"); } BloomEffect = GeneralManager.Effects["Effects/Blur"]; Value = BloomEffect.Parameters["Param"]; Value.SetValue(0.05f); }
public ReflectionEffect() : base( Core.graphicsDevice, EffectResource.reflectionBytes ) { _reflectionIntensityParam = Parameters["_reflectionIntensity"]; _renderTextureParam = Parameters["_renderTexture"]; _normalMapParam = Parameters["_normalMap"]; _matrixTransformParam = Parameters["_matrixTransform"]; _normalMagnitudeParam = Parameters["_normalMagnitude"]; _reflectionIntensityParam.SetValue( _reflectionIntensity ); _normalMagnitudeParam.SetValue( _normalMagnitude ); }
public override void onAddedToScene() { effect = scene.contentManager.loadEffect<Effect>( "pixelGlitch", EffectResource.pixelGlitchBytes ); _verticalSizeParam = effect.Parameters["_verticalSize"]; _horizontalOffsetParam = effect.Parameters["_horizontalOffset"]; _screenSizeParam = effect.Parameters["_screenSize"]; _verticalSizeParam.SetValue( _verticalSize ); _horizontalOffsetParam.SetValue( _horizontalOffset ); _screenSizeParam.SetValue( new Vector2( Screen.width, Screen.height ) ); }
public DissolveEffect( Texture2D dissolveTexture ) : base( Core.graphicsDevice, EffectResource.dissolveBytes ) { _progressParam = Parameters["_progress"]; _dissolveThresholdParam = Parameters["_dissolveThreshold"]; _dissolveThresholdColorParam = Parameters["_dissolveThresholdColor"]; _dissolveTexParam = Parameters["_dissolveTex"]; _progressParam.SetValue( _progress ); _dissolveThresholdParam.SetValue( _dissolveThreshold ); _dissolveThresholdColorParam.SetValue( _dissolveThresholdColor.ToVector4() ); _dissolveTexParam.SetValue( dissolveTexture ); }
public override void onAddedToScene() { effect = scene.contentManager.loadEffect<Effect>( "heatDistortion", EffectResource.heatDistortionBytes ); _timeParam = effect.Parameters["_time"]; _distortionFactorParam = effect.Parameters["_distortionFactor"]; _riseFactorParam = effect.Parameters["_riseFactor"]; _distortionFactorParam.SetValue( _distortionFactor ); _riseFactorParam.SetValue( _riseFactor ); distortionTexture = scene.contentManager.Load<Texture2D>( "nez/textures/heatDistortionNoise" ); }
/// <summary> /// Set light properties to given effect /// </summary> public void SetEffect( EffectParameter effectLightPosition, EffectParameter effectLightColor, Matrix worldInverse) { Vector4 positionRadius = new Vector4(Vector3.Transform(position,worldInverse),radius); if (effectLightPosition != null) { effectLightPosition.SetValue(positionRadius); } if (effectLightColor != null) { effectLightColor.SetValue(color); } }
/// <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); worldViewProjParam.SetValue(worldViewProj); //System.Console.WriteLine("Helper"); 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; }
internal static EffectDirtyFlags SetLightingMatrices(EffectDirtyFlags dirtyFlags, ref Matrix world, ref Matrix view, EffectParameter worldParam, EffectParameter worldInverseTransposeParam, EffectParameter eyePositionParam) { if ((dirtyFlags & EffectDirtyFlags.World) != ~EffectDirtyFlags.All) { Matrix result1; Matrix.Invert(ref world, out result1); Matrix result2; Matrix.Transpose(ref result1, out result2); worldParam.SetValue(world); worldInverseTransposeParam.SetValue(result2); dirtyFlags &= ~EffectDirtyFlags.World; } if ((dirtyFlags & EffectDirtyFlags.EyePosition) != ~EffectDirtyFlags.All) { Matrix result; Matrix.Invert(ref view, out result); eyePositionParam.SetValue(result.Translation); dirtyFlags &= ~EffectDirtyFlags.EyePosition; } return dirtyFlags; }
public override void Draw(GameTime gameTime) { // Here, we're getting the position of the lantern and passing it into the pixel shader to apply the lighting effect #region Lighting LightSrc = new Vector2((lantern.pos.X + 32) / 1280.0f, ((lantern.pos.Y + 64) / 720.0f)); float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds; lightParam = lighting.Parameters["lightPos"]; lighting.Parameters["intensity"].SetValue(intensity); lightParam.SetValue(LightSrc); ScreenManager.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise, lighting); ScreenManager.SpriteBatch.Draw(black, new Rectangle(0, 0, 1280, 720), Color.White); ScreenManager.SpriteBatch.End(); #endregion Lighting // Just draws useful stuff to the screen #region Debug Drawing ScreenManager.SpriteBatch.Begin(); ScreenManager.SpriteBatch.DrawString(font, "FPS: " + fps + "\nOn Ground: " + player.playerState.onGround + "\nWorld X: " + world.currentX + "\nWorld Y: " + world.currentY, new Vector2(20.0f, 20.0f), Color.White); ScreenManager.SpriteBatch.End(); #endregion Debug Drawing }
public void ApplyFrustumCorners(EffectParameter frustumCorners, Vector2 topLeftVertex, Vector2 bottomRightVertex) { float dx = _currentFrustumCorners[1].X - _currentFrustumCorners[0].X; float dy = _currentFrustumCorners[0].Y - _currentFrustumCorners[2].Y; _localFrustumCorners[0] = _currentFrustumCorners[2]; _localFrustumCorners[0].X += dx * (topLeftVertex.X * 0.5f + 0.5f); _localFrustumCorners[0].Y += dy * (bottomRightVertex.Y * 0.5f + 0.5f); _localFrustumCorners[1] = _currentFrustumCorners[2]; _localFrustumCorners[1].X += dx * (bottomRightVertex.X * 0.5f + 0.5f); _localFrustumCorners[1].Y += dy * (bottomRightVertex.Y * 0.5f + 0.5f); _localFrustumCorners[2] = _currentFrustumCorners[2]; _localFrustumCorners[2].X += dx * (topLeftVertex.X * 0.5f + 0.5f); _localFrustumCorners[2].Y += dy * (topLeftVertex.Y * 0.5f + 0.5f); _localFrustumCorners[3] = _currentFrustumCorners[2]; _localFrustumCorners[3].X += dx * (bottomRightVertex.X * 0.5f + 0.5f); _localFrustumCorners[3].Y += dy * (topLeftVertex.Y * 0.5f + 0.5f); frustumCorners.SetValue(_localFrustumCorners); }
public WaterReflectionEffect() : base() { CurrentTechnique = Techniques["WaterReflectionTechnique"]; _timeParam = Parameters["_time"]; _sparkleIntensityParam = Parameters["_sparkleIntensity"]; _sparkleColorParam = Parameters["_sparkleColor"]; _screenSpaceVerticalOffsetParam = Parameters["_screenSpaceVerticalOffset"]; _perspectiveCorrectionIntensityParam = Parameters["_perspectiveCorrectionIntensity"]; _firstDisplacementSpeedParam = Parameters["_firstDisplacementSpeed"]; _secondDisplacementSpeedParam = Parameters["_secondDisplacementSpeed"]; _secondDisplacementScaleParam = Parameters["_secondDisplacementScale"]; _sparkleIntensityParam.SetValue( _sparkleIntensity ); _sparkleColorParam.SetValue( Vector3.One ); _perspectiveCorrectionIntensityParam.SetValue( _perspectiveCorrectionIntensity ); firstDisplacementSpeed = _firstDisplacementSpeed; secondDisplacementSpeed = _secondDisplacementSpeed; _secondDisplacementScaleParam.SetValue( _secondDisplacementScale ); // override some defaults from the ReflectionEffect reflectionIntensity = _reflectionIntensity; normalMagnitude = _normalMagnitude; }
//EffectParameter PcolorMap; //EffectParameter PlightMap; #endregion #region IDeferredFinalCombination Members public void LoadContent(IContentManager manager, Engine.GraphicInfo ginfo, Engine.GraphicFactory factory, bool useFloatBuffer, bool saveToTexture ) { this.useFloatBuffer = useFloatBuffer; this.ginfo = ginfo; this.saveToTexture = saveToTexture; finalCombineEffect = manager.GetAsset<Effect>("CombineFinal",true); PhalfPixel = finalCombineEffect.Parameters["halfPixel"]; PambientColor = finalCombineEffect.Parameters["ambientColor"]; //PEXTRA1 = finalCombineEffect.Parameters["EXTRA1"]; //PcolorMap = finalCombineEffect.Parameters["colorMap"]; //PlightMap = finalCombineEffect.Parameters["lightMap"]; PhalfPixel.SetValue(ginfo.HalfPixel); if (saveToTexture) { if (useFloatBuffer) target = factory.CreateRenderTarget(ginfo.BackBufferWidth, ginfo.BackBufferHeight, SurfaceFormat.HdrBlendable, ginfo.UseMipMap, DepthFormat.None, ginfo.MultiSample, RenderTargetUsage.DiscardContents); else target = factory.CreateRenderTarget(ginfo.BackBufferWidth, ginfo.BackBufferHeight, SurfaceFormat.Color, ginfo.UseMipMap, DepthFormat.None, ginfo.MultiSample, RenderTargetUsage.DiscardContents); } }
/// <summary> /// Draws the models managed by the batch. /// </summary> public void Draw(Effect effect, EffectParameter worldTransformsParameter, EffectParameter textureIndicesParameter, EffectPass pass) { if (vertices.Length > 0) { graphicsDevice.SetVertexBuffers(bindings); graphicsDevice.Indices = indexBuffer; worldTransformsParameter.SetValue(worldTransforms); textureIndicesParameter.SetValue(textureIndices); pass.Apply(); graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertices.Length, 0, indices.Length / 3); } }
/// <summary> /// Set a shader parameter to some data provided by CBero /// </summary> /// <param name="effectParameter">the shader parameter</param> /// <param name="semantic">the type of data requested</param> public void setBuiltInShaderParameter(EffectParameter effectParameter, Material.ShaderParameterSemantic semantic) { if (effectParameter == null) return; switch (semantic) { case Material.ShaderParameterSemantic.MODEL_MATRIX: { effectParameter.SetValue(RenderState.m_currentWorld.Peek()); break; } case Material.ShaderParameterSemantic.MODEL_INV_MATRIX: { Matrix inv = Matrix.Invert(RenderState.m_currentWorld.Peek()); effectParameter.SetValue(inv); break; } case Material.ShaderParameterSemantic.MODEL_INV_TRANS_MATRIX: { Matrix invTrans = Matrix.Transpose(Matrix.Invert(RenderState.m_currentWorld.Peek())); effectParameter.SetValue(invTrans); break; } case Material.ShaderParameterSemantic.MODEL_TRANS_MATRIX: { Matrix trans = Matrix.Transpose(RenderState.m_currentWorld.Peek()); effectParameter.SetValue(trans); break; } case Material.ShaderParameterSemantic.VIEW_MATRIX: { effectParameter.SetValue(RenderState.m_currentView.Peek()); break; } case Material.ShaderParameterSemantic.VIEW_INV_MATRIX: { Matrix inv = Matrix.Invert(RenderState.m_currentView.Peek()); effectParameter.SetValue(inv); break; } case Material.ShaderParameterSemantic.VIEW_TRANS_MATRIX: { Matrix trans = Matrix.Transpose(RenderState.m_currentView.Peek()); effectParameter.SetValue(trans); break; } case Material.ShaderParameterSemantic.VIEW_INV_TRANS_MATRIX: { Matrix invTrans = Matrix.Transpose(Matrix.Invert(RenderState.m_currentView.Peek())); effectParameter.SetValue(invTrans); break; } case Material.ShaderParameterSemantic.PROJECTION_MATRIX: { effectParameter.SetValue(RenderState.m_currentProj.Peek()); break; } case Material.ShaderParameterSemantic.VIEW_PROJECTION_MATRIX: { Matrix viewProj = Matrix.Multiply(RenderState.m_currentView.Peek(), RenderState.m_currentProj.Peek()); effectParameter.SetValue(viewProj); break; } case Material.ShaderParameterSemantic.MODEL_VIEW_PROJECTION_MATRIX: { Matrix mvp = Matrix.Multiply(Matrix.Multiply(RenderState.m_currentWorld.Peek(), RenderState.m_currentView.Peek()), RenderState.m_currentProj.Peek()); effectParameter.SetValue(mvp); break; } case Material.ShaderParameterSemantic.BONE_TRANSFORMS: { Matrix[] bone; IRenderable3D renderable = RenderState.m_currentRenderable.Peek(); if (renderable is SkinnedRenderable3D) { SkinnedRenderable3D skinned = renderable as SkinnedRenderable3D; bone = skinned.GetSkinTransforms(); } else { bone = new Matrix[1] { Matrix.Identity }; } effectParameter.SetValue(bone); break; } case Material.ShaderParameterSemantic.TEXTURE2D0: { effectParameter.SetValue(RenderState.m_currentTexture[0].Peek()); break; } case Material.ShaderParameterSemantic.TEXTURE2D1: { effectParameter.SetValue(RenderState.m_currentTexture[1].Peek()); break; } case Material.ShaderParameterSemantic.TEXTURE2D2: { effectParameter.SetValue(RenderState.m_currentTexture[2].Peek()); break; } case Material.ShaderParameterSemantic.TEXTURE2D3: { effectParameter.SetValue(RenderState.m_currentTexture[3].Peek()); break; } case Material.ShaderParameterSemantic.AMBIENTLIGHTING: { effectParameter.SetValue(RenderState.GetAmbientLighting().ToVector3()); break; } case Material.ShaderParameterSemantic.BACKGROUNDCOLOR: { effectParameter.SetValue(RenderState.GetClearColor().ToVector3()); break; } case Material.ShaderParameterSemantic.FOGCOLOR: { effectParameter.SetValue(RenderState.GetFogColor().ToVector3()); break; } // TODO implement USER_DEFINED_* } }
/// <summary> /// Lazily computes derived parameter values immediately before applying the effect. /// </summary> protected internal override bool OnApply() { // Recompute the world+view+projection matrix or fog vector? dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam); // Recompute the diffuse/alpha material color parameter? if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0) { diffuseColorParam.SetValue(new Vector4(diffuseColor * alpha, alpha)); dirtyFlags &= ~EffectDirtyFlags.MaterialColor; } // Recompute the alpha test settings? if ((dirtyFlags & EffectDirtyFlags.AlphaTest) != 0) { Vector4 alphaTest = new Vector4(); bool eqNe = false; // Convert reference alpha from 8 bit integer to 0-1 float format. float reference = (float)referenceAlpha / 255f; // Comparison tolerance of half the 8 bit integer precision. const float threshold = 0.5f / 255f; switch (alphaFunction) { case CompareFunction.Less: // Shader will evaluate: clip((a < x) ? z : w) alphaTest.X = reference - threshold; alphaTest.Z = 1; alphaTest.W = -1; break; case CompareFunction.LessEqual: // Shader will evaluate: clip((a < x) ? z : w) alphaTest.X = reference + threshold; alphaTest.Z = 1; alphaTest.W = -1; break; case CompareFunction.GreaterEqual: // Shader will evaluate: clip((a < x) ? z : w) alphaTest.X = reference - threshold; alphaTest.Z = -1; alphaTest.W = 1; break; case CompareFunction.Greater: // Shader will evaluate: clip((a < x) ? z : w) alphaTest.X = reference + threshold; alphaTest.Z = -1; alphaTest.W = 1; break; case CompareFunction.Equal: // Shader will evaluate: clip((abs(a - x) < Y) ? z : w) alphaTest.X = reference; alphaTest.Y = threshold; alphaTest.Z = 1; alphaTest.W = -1; eqNe = true; break; case CompareFunction.NotEqual: // Shader will evaluate: clip((abs(a - x) < Y) ? z : w) alphaTest.X = reference; alphaTest.Y = threshold; alphaTest.Z = -1; alphaTest.W = 1; eqNe = true; break; case CompareFunction.Never: // Shader will evaluate: clip((a < x) ? z : w) alphaTest.Z = -1; alphaTest.W = -1; break; case CompareFunction.Always: default: // Shader will evaluate: clip((a < x) ? z : w) alphaTest.Z = 1; alphaTest.W = 1; break; } alphaTestParam.SetValue(alphaTest); dirtyFlags &= ~EffectDirtyFlags.AlphaTest; // If we changed between less/greater vs. equal/notequal // compare modes, we must also update the shader index. if (isEqNe != eqNe) { isEqNe = eqNe; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } // Recompute the shader index? if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0) { int shaderIndex = 0; if (!fogEnabled) { shaderIndex += 1; } if (vertexColorEnabled) { shaderIndex += 2; } if (isEqNe) { shaderIndex += 4; } dirtyFlags &= ~EffectDirtyFlags.ShaderIndex; if (_shaderIndex != shaderIndex) { _shaderIndex = shaderIndex; CurrentTechnique = Techniques[_shaderIndex]; return(true); } } return(false); }
/// <summary> /// Sets the diffuse/emissive/alpha material color parameters. /// </summary> internal static void SetMaterialColor(bool lightingEnabled, float alpha, ref Vector3 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 futher optimization goodness, we merge material alpha with the diffuse // color parameter, and premultiply all color values by this alpha. if (lightingEnabled) { Vector4 diffuse = new Vector4(); Vector3 emissive = new Vector3(); diffuse.X = diffuseColor.X * alpha; diffuse.Y = diffuseColor.Y * alpha; diffuse.Z = diffuseColor.Z * alpha; diffuse.W = alpha; emissive.X = (emissiveColor.X + ambientLightColor.X * diffuseColor.X) * alpha; emissive.Y = (emissiveColor.Y + ambientLightColor.Y * diffuseColor.Y) * alpha; emissive.Z = (emissiveColor.Z + ambientLightColor.Z * diffuseColor.Z) * alpha; diffuseColorParam.SetValue(diffuse); emissiveColorParam.SetValue(emissive); } else { Vector4 diffuse = new Vector4(); diffuse.X = (diffuseColor.X + emissiveColor.X) * alpha; diffuse.Y = (diffuseColor.Y + emissiveColor.Y) * alpha; diffuse.Z = (diffuseColor.Z + emissiveColor.Z) * alpha; diffuse.W = alpha; diffuseColorParam.SetValue(diffuse); } }
/// <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); Vector4 fogVector = new Vector4(); fogVector.X = worldView.M13 * scale; fogVector.Y = worldView.M23 * scale; fogVector.Z = worldView.M33 * scale; fogVector.W = (worldView.M43 + fogStart) * scale; fogVectorParam.SetValue(fogVector); } }
public static bool TryParse(Stream s, GraphicsDevice g, ContentManager c, out Effect fx, ref List <object> refs, ParsingFlags ps = ParsingFlags.None) { fx = null; StreamReader f = new StreamReader(new BufferedStream(s)); // Get The Arguments From The Material File List <string[]> args = new List <string[]>(); while (!f.EndOfStream) { string line = f.ReadLine(); if (string.IsNullOrWhiteSpace(line)) { continue; } string[] split = line.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries); if (split.Length < 1) { continue; } split[0] = split[0].Trim().ToLower(); switch (split[0]) { case "fx": if (split.Length >= 2) { args.Add(split); } break; case "fxpt": if (split.Length >= 3) { args.Add(split); } break; case "fxptc": if (split.Length >= 3) { args.Add(split); } break; case "fxpf": if (split.Length >= 4) { args.Add(split); } break; } } // Get The Effect For This Material Predicate <string[]> fxMatch = (a) => { return(a[0].Equals("fx")); }; string[] fxArg = args.Find(fxMatch); if (fxArg == null) { return(false); } args.RemoveAll(fxMatch); // Try To Create The Effect if (ps.HasFlag(ParsingFlags.LoadEffectByteCode)) { try { byte[] code = null; using (FileStream fxs = File.OpenRead(fxArg[1].Trim())) { code = new byte[fxs.Length]; fxs.Read(code, 0, code.Length); } fx = new Effect(g, code); } catch (Exception) { fx = null; return(false); } } else { try { fx = c.Load <Effect>(fxArg[1].Trim()); } catch (Exception) { fx = null; return(false); } } // Will Attempt To Set As Many Uniforms As Possible Without Raising Errors foreach (string[] arg in args) { switch (arg[0]) { case "fxpt": EffectParameter fxpt = fx.Parameters[arg[1].Trim()]; if (fxpt == null) { continue; } try { Texture2D t = null; if (ps.HasFlag(ParsingFlags.LoadTextureStream)) { using (FileStream ts = File.OpenRead(arg[2].Trim())) { t = Texture2D.FromStream(g, ts); } } else { t = c.Load <Texture2D>(arg[2].Trim()); } if (t != null) { refs.Add(t); fxpt.SetValue(t); } } catch (Exception) { continue; } break; case "fxptc": // Texture Cube Parameter EffectParameter fxptc = fx.Parameters[arg[1].Trim()]; if (fxptc == null) { continue; } try { TextureCube tc = c.Load <TextureCube>(arg[2].Trim()); if (tc != null) { refs.Add(tc); fxptc.SetValue(tc); } } catch (Exception) { continue; } break; case "fxpf": // Vector Parameter EffectParameter fxptv = fx.Parameters[arg[1].Trim()]; int comps; if (fxptv == null || !int.TryParse(arg[2], out comps)) { continue; } string[] sc = arg[3].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); if (sc.Length != comps) { continue; } switch (comps) { case 1: float v1; if (float.TryParse(sc[0], out v1)) { fxptv.SetValue(v1); } break; case 2: Vector2 v2 = Vector2.Zero; if (float.TryParse(sc[0], out v2.X) && float.TryParse(sc[1], out v2.Y) ) { fxptv.SetValue(v2); } break; case 3: Vector3 v3 = Vector3.Zero; if (float.TryParse(sc[0], out v3.X) && float.TryParse(sc[1], out v3.Y) && float.TryParse(sc[2], out v3.Z) ) { fxptv.SetValue(v3); } break; case 4: Vector4 v4 = Vector4.Zero; if (float.TryParse(sc[0], out v4.X) && float.TryParse(sc[1], out v4.Y) && float.TryParse(sc[2], out v4.Z) && float.TryParse(sc[3], out v4.W) ) { fxptv.SetValue(v4); } break; default: if (comps > 4) { float[] vn = new float[comps]; bool vnc = true; for (int i = 0; i < sc.Length && i < vn.Length && vnc; i++) { if (!float.TryParse(sc[i], out vn[i])) { vnc = false; } } if (vnc) { fxptv.SetValue(vn); } } break; } break; } } return(true); }
/// <summary> /// Sets the value of the parameter. /// </summary> /// <param name="value">Bool value</param> public void SetValue(bool value) { _param.SetValue(value); }
/// <summary> /// Set the effect parameters for this animated sprite /// </summary> public DrawMode SetEffect( EffectParameter effectTexture, EffectParameter effectFrameOffset, EffectParameter effectFrameSize, EffectParameter effectFrameBlend) { // set texture if (effectTexture != null) { effectTexture.SetValue(texture); } // calculate opacity based on squared normalized life time float opacity = Math.Min(1.0f, elapsedTime / totalTime); opacity = 1.0f - opacity*opacity; // calculate the float frame position used for frame blending float floatFrame = elapsedTime * frameRate; // get the two frames to blend int frame = Math.Min(numberFrames - 1, (int)floatFrame); int nextFrame = Math.Min(numberFrames - 1, (frame + 1)); // set frame size if (effectFrameSize != null) { effectFrameSize.SetValue(frameSize); } // set frame offset Vector4 frameOffset = new Vector4( frame % numberFramesX, frame / numberFramesX, nextFrame % numberFramesX, nextFrame / numberFramesX); if (effectFrameOffset != null) { effectFrameOffset.SetValue(frameOffset); } // set blend factor float blendFactor = floatFrame - (float)frame; if (effectFrameBlend != null) { effectFrameBlend.SetValue(new Vector2(blendFactor, 2 * opacity)); } // return true to enable additive blending (if false alpha blending is used) return drawMode; }
/// <summary> /// Lazily computes derived parameter values immediately before applying the effect. /// </summary> protected internal override void OnApply() { // Recompute the shader index? // if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0) { int shaderIndex = 0; if (!fogEnabled) { shaderIndex += 1; } if (vertexColorEnabled) { shaderIndex += 2; } if (textureEnabled) { shaderIndex += 4; } if (lightingEnabled) { if (preferPerPixelLighting) { shaderIndex += 24; } else if (oneLight) { shaderIndex += 16; } else { shaderIndex += 8; } } // // //shaderIndexParam.SetValue (shaderIndex); // // dirtyFlags &= ~EffectDirtyFlags.ShaderIndex; if (oldIndex != shaderIndex) { int vertexShader = VSArray[VSIndices[shaderIndex]]; int fragmentShader = PSArray[PSIndices[shaderIndex]]; UpdateTechnique("BasicEffect", "", vertexShader, fragmentShader); oldIndex = shaderIndex; // Update here } // } // These are the states that work GLStateManager.Projection(Projection); GLStateManager.WorldView(world, view); // Override this for now for testing purposes dirtyFlags |= EffectDirtyFlags.World | EffectDirtyFlags.WorldViewProj; dirtyFlags |= EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.EyePosition; dirtyFlags &= ~EffectDirtyFlags.FogEnable; // turn off fog for now dirtyFlags |= EffectDirtyFlags.MaterialColor; GLStateManager.Textures2D(TextureEnabled); GLStateManager.ColorArray(VertexColorEnabled); // Recompute the world+view+projection matrix or fog vector? dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam); // Recompute the diffuse/emissive/alpha material color parameters? if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0) { EffectHelpers.SetMaterialColor(lightingEnabled, alpha, ref diffuseColor, ref emissiveColor, ref ambientLightColor, diffuseColorParam, emissiveColorParam); dirtyFlags &= ~EffectDirtyFlags.MaterialColor; } if (TextureEnabled) { _texture.Apply(); textureParam.SetValue(_texture); //System.Console.WriteLine("Texture set"); } // // if (lightingEnabled) { // // Recompute the world inverse transpose and eye position? // dirtyFlags = EffectHelpers.SetLightingMatrices (dirtyFlags, ref world, ref view, worldParam, worldInverseTransposeParam, eyePositionParam); // // // Check if we can use the only-bother-with-the-first-light shader optimization. // bool newOneLight = !light1.Enabled && !light2.Enabled; // // if (oneLight != newOneLight) { // oneLight = newOneLight; // dirtyFlags |= EffectDirtyFlags.ShaderIndex; // } // } }
/// <summary> /// Loads all effects and initializes effect variables /// </summary> /// <remarks> /// This method is automatically called when FlatRedBall is Initialized if /// post processing is suppoted in the current build of the engine. /// </remarks> #endregion internal static void InitializeEffects() { #if !MONOGAME // Create the sprite batch mSpriteBatch = new SpriteBatch(FlatRedBallServices.GraphicsDevice); // Shared parameters #region Get and initialize shared parameters // Get the effect // If modifying the shaders uncomment the following file: //mSharedParametersEffect = FlatRedBallServices.Load<Effect>(@"Assets\Shaders\PostProcessing\Blur"); // Otherwise, keep the following line uncommented so the .xnb files in the // resources are used. mSharedParametersEffect = FlatRedBallServices.mResourceContentManager.Load<Effect>(@"Blur"); // Get shared effect parameters mPixelSize = mSharedParametersEffect.Parameters["pixelSize"]; // Initialize shared effect parameters mPixelSize.SetValue(new Vector2( 1f / (float)FlatRedBallServices.ClientWidth, 1f / (float)FlatRedBallServices.ClientHeight)); // Commit #if !XNA4 mSharedParametersEffect.CommitChanges(); #endif #endregion #endif mIsInitialized = true; }