示例#1
0
        public SsaoMapBlur(Effect effect, SpriteBatch spriteBatch, int width, int height, SurfaceFormat format, int radius, float amount)
        {
            if (effect == null) throw new ArgumentNullException("effect");
            if (spriteBatch == null) throw new ArgumentNullException("spriteBatch");
            if (width < 1) throw new ArgumentOutOfRangeException("width");
            if (height < 1) throw new ArgumentOutOfRangeException("height");
            if (radius < MinAmount || MaxRadius < radius) throw new ArgumentOutOfRangeException("value");
            if (amount < MinAmount) throw new ArgumentOutOfRangeException("value");

            this.effect = effect;
            this.spriteBatch = spriteBatch;
            Width = width;
            Height = height;
            Radius = radius;
            Amount = amount;

            graphicsDevice = effect.GraphicsDevice;

            normalDepthMap = effect.Parameters["NormalDepthMap"];
            horizontalBlurTechnique = effect.Techniques["HorizontalBlur"];
            verticalBlurTechnique = effect.Techniques["VerticalBlur"];

            InitializeEffectParameters();

            backingRenderTarget = new RenderTarget2D(graphicsDevice, width, height, false, format,
                DepthFormat.None, 0, RenderTargetUsage.PlatformContents);
        }
示例#2
0
文件: Effect.cs 项目: HaKDMoDz/Zazumo
 internal Effect(GraphicsDevice device)
 {
     graphicsDevice = device;
     Parameters = new EffectParameterCollection();
     Techniques = new EffectTechniqueCollection();
     CurrentTechnique = new EffectTechnique(this);
 }
        public void Draw(EffectTechnique technique)
        {
            if (vertices.Count > 0)
            {
                UniversalEffect effect = RendererAssetPool.UniversalEffect;
                if (technique == null)
                    effect.CurrentTechnique = this.Technique;
                else
                    effect.CurrentTechnique = technique;

                Ready();
                effect.Begin();
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)//TODO1 remove this when shading i
                {
                    pass.Begin();
                    GraphicsDevice device = GraphicOptions.graphics.GraphicsDevice;
                    device.VertexDeclaration = vertDeclaration;
                    device.Vertices[0].SetSource(vertexBuffer, 0, VertexPositionColorTexture.SizeInBytes);
                    device.DrawUserPrimitives<VertexPositionColorTexture>(
                        PrimitiveType.LineList, vertices.ToArray(), 0, 2);
                    pass.End();
                }
                effect.End();
            }
        }
示例#4
0
        private void createBasicEffect()
        {
            var et = new EffectTechnique(this);
            Techniques["Wtf"] = et;
            CurrentTechnique = et;

            et.Passes["Wtf2"] = new EffectPass(et);
        }
示例#5
0
        private void createBasicEffect()
        {
            var et = new EffectTechnique(this);
            Techniques["Wtf"] = et;
            CurrentTechnique = et;
			var pass = new EffectPass(et);
			pass.Name = "Wtf2";
            et.Passes[pass.Name] = pass; 
        }
示例#6
0
    public EffectTechniqueDescription GetDescription(Effect effect, EffectTechnique technique)
    {
      foreach (var pass in technique.Passes)
        foreach (var annotation in pass.Annotations)
          if (annotation.Name == "RepeatParameter")
            return new RepeatTechniqueDescription(effect, technique);

      return null;
    }
示例#7
0
        public ShadowEffect(Effect clone)
            : base(clone)
        {
            SoftShadowEnabled = true;

            RenderShadowmap = Techniques["RenderShadowmap"];
            RenderLightmap = Techniques["RenderLightmap"];
            BlurLightmap = Techniques["BlurLightmap"];
        }
示例#8
0
        internal EffectTechnique(Effect effect, EffectTechnique cloneSource)
        {
            // Share all the immutable types.
            Name = cloneSource.Name;
            Annotations = cloneSource.Annotations;

            // Clone the mutable types.
            Passes = new EffectPassCollection(effect, cloneSource.Passes);
        }
示例#9
0
 public DrawHelper(GraphicsDeviceManager ingraphics, Effect ineffect)
 {
     graphics = ingraphics;
     effect = ineffect;
     techniqueBasicTexturedRender = effect.Techniques["BasicTexturedRender"];
     techniqueBasicColorRender = effect.Techniques["BasicColorRender"];
     paramBoundTexture = effect.Parameters["xBoundTexture"];
     paramViewMatrix = effect.Parameters["xViewMatrix"];
     ortho = Matrix.CreateOrthographicOffCenter(0, 1, 0, 1, -1, 1);
 }
示例#10
0
        public ShapeEffect(Effect clone)
            : base(clone)
        {
            NormalmapEnabled = true;
            HeightmapEnabled = false;
            ShadowEnabled = false;
            SpotlightEnabled = false;

            RenderScene = Techniques["RenderScene"];
        }
        //--------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="EffectTechniqueDescription"/> class.
        /// </summary>
        /// <param name="effect">The effect.</param>
        /// <param name="technique">The effect technique.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="effect"/> or <paramref name="technique"/> is <see langword="null"/>.
        /// </exception>
        public EffectTechniqueDescription(Effect effect, EffectTechnique technique)
        {
            if (effect == null)
            throw new ArgumentNullException("effect");
              if (technique == null)
            throw new ArgumentNullException("technique");

              Technique = technique;
              Index = GetIndex(effect, technique);

            #if !MONOGAME
              // Check if there is an associated technique for hardware instancing.
              var annotation = technique.Annotations["InstancingTechnique"];
              if (annotation != null && annotation.ParameterType == EffectParameterType.String)
              {
            var techniqueName = annotation.GetValueString();
            if (!string.IsNullOrEmpty(techniqueName))
            {
              InstancingTechnique = effect.Techniques[techniqueName];

              if (InstancingTechnique == null)
              {
            string message = string.Format(CultureInfo.InvariantCulture, "Could not find instancing technique \"{0}\" in the effect \"{1}\".", techniqueName, effect.Name);
            throw new GraphicsException(message);
              }
            }
              }
            #else
              // Workaround: MonoGame does not support effect semantics and annotations.
              if (technique.Name.IndexOf("INSTANCING", StringComparison.OrdinalIgnoreCase) == -1)
              {
            if (effect.Techniques.Count == 2
            && effect.Techniques[1].Name.IndexOf("INSTANCING", StringComparison.OrdinalIgnoreCase) >= 0)
            {
              InstancingTechnique = effect.Techniques[1];
            }

            if (InstancingTechnique == null)
            {
              foreach (var otherTechnique in effect.Techniques)
              {
            if (technique == otherTechnique)
              continue;

            if (otherTechnique.Name.IndexOf(technique.Name, StringComparison.OrdinalIgnoreCase) >= 0
                && otherTechnique.Name.IndexOf("INSTANCING", StringComparison.OrdinalIgnoreCase) >= 0)
            {
              InstancingTechnique = otherTechnique;
              break;
            }
              }
            }
              }
            #endif
        }
示例#12
0
 public void init(Effect effect)
 {
     this.effect = effect;
     masterTechnique = effect.Techniques["Master"];
     color = new MasterTechnique(MasterTechnique.Mode.Color, effect, masterTechnique);
     texture = new MasterTechnique(MasterTechnique.Mode.Texture, effect, masterTechnique);
     textureAlpha = new MasterTechnique(MasterTechnique.Mode.TextureAlpha, effect, masterTechnique);
     gradient = new MasterTechnique(MasterTechnique.Mode.Gradient, effect, masterTechnique);
     silhouette = new MasterTechnique(MasterTechnique.Mode.Silhouette, effect, masterTechnique);
     modulate = new MasterTechnique(MasterTechnique.Mode.Modulate, effect, masterTechnique);
     add = new MasterTechnique(MasterTechnique.Mode.Add, effect, masterTechnique);
 }
        public void RenderScreenQuad(Effect effect, EffectTechnique technique, Texture2D texture)
        {
            effect.CurrentTechnique = technique;

            sb.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.None);
            effect.Begin();
            technique.Passes[0].Begin();
            sb.Draw(texture, screen, Color.White);
            technique.Passes[0].End();
            effect.End();
            sb.End();
        }
        /// <inheritdoc/>
        public override EffectTechniqueDescription GetDescription(Effect effect, EffectTechnique technique)
        {
            if (effect is AlphaTestEffect
              || effect is BasicEffect
              || effect is DualTextureEffect
              || effect is EnvironmentMapEffect
              || effect is SkinnedEffect)
              {
            return new EffectTechniqueDescription(effect, technique);
              }

              return null;
        }
示例#15
0
 public StencilStrokeEffect(Effect effect)
 {
     _effect = effect;
     _scalingTechnique = effect.Techniques["StencilStroke_Scaling"];
     _nonscalingTechnique = effect.Techniques["StencilStroke_Nonscaling"];
     _passSolid = _scalingTechnique.Passes["Solid"];
     _passRadial = _scalingTechnique.Passes["Radial"];
     _passSolidNS = _nonscalingTechnique.Passes["Solid"];
     _passRadialNS = _nonscalingTechnique.Passes["Radial"];
     _projection = effect.Parameters["Projection"];
     _transformation = effect.Parameters["Transformation"];
     _offset = effect.Parameters["Offset"];
     _thickness = effect.Parameters["Thickness"];
 }
        public void LoadContent(GraphicsDevice g, ContentManager cm)
        {
            e = cm.Load<Effect>(@"shaders/bloom");
            luminosityExtractTechnique = e.Techniques["LuminosityExtract"];
            gaussianBlurTechnique = e.Techniques["Blur"];
            compositeTechnique = e.Techniques["Composite"];

            PresentationParameters pp = g.PresentationParameters;
            rTarget1 = new RenderTarget2D(g, pp.BackBufferWidth, pp.BackBufferHeight, 1, g.DisplayMode.Format);
            rTarget2 = new RenderTarget2D(g, pp.BackBufferWidth, pp.BackBufferHeight, 1, g.DisplayMode.Format);

            // calculate the blur parameters
            SetBlur(8);
        }
示例#17
0
        protected void DefineTechnique(string techniqueName, string passName, int vertexIndex, int fragmentIndex)
        {
            EffectTechnique tech = new EffectTechnique(this);

            tech.Name = techniqueName;
            EffectPass pass = new EffectPass(tech);

            pass.Name          = passName;
            pass.VertexIndex   = vertexIndex;
            pass.FragmentIndex = fragmentIndex;
            pass.ApplyPass();
            tech.Passes._passes.Add(pass);
            Techniques._techniques.Add(tech);
            LogShaderParameters(String.Format("Technique {0} - Pass {1} :", tech.Name, pass.Name), pass.shaderProgram);
        }
示例#18
0
    protected override bool OnNextPass(EffectTechnique technique, RenderContext context, ref int index, out EffectPass pass)
    {
      int numberOfPasses = technique.Passes.Count;

      // Progress to next pass when the desired number of repetitions were performed.
      // (Note: We use a while statement and not an if statement, because the desired
      // number of repetitions returned by GetPassRepetitionCount() could theoretically
      // be 0.)
      while (_actualPassCount >= _desiredPassCount)
      {
        // Finished with current pass. Progress to next pass.
        _passIndex++;

        if (_passIndex >= numberOfPasses)
        {
          // Finished: All effect passes have been applied.
          context.PassIndex = -1;
          pass = null;
          return false;
        }

        _actualPassCount = 0;
        _desiredPassCount = GetPassRepetitionCount(context, _passIndex);
      }

      pass = technique.Passes[_passIndex];

      // In the parameter index and context.PassIndex, we store the total number
      // of executed passes.
      context.PassIndex = index;
      index++;

      _actualPassCount++;

      if (index == numberOfPasses - 1 && string.Equals(pass.Name, "Restore", StringComparison.OrdinalIgnoreCase))
      {
        // A last effect pass may be used to restore the default render states without 
        // drawing anything. The effect pass needs to be called "Restore".
        pass.Apply();

        // Finished: All effect passes have been applied.
        context.PassIndex = -1;
        pass = null;
        return false;
      }

      return true;
    }
示例#19
0
        public SkySphereEffect(Effect effect)
        {
            if (effect == null) throw new ArgumentNullException("effect");

            this.effect = effect;

            viewProjection = effect.Parameters["ViewProjection"];
            skyColor = effect.Parameters["SkyColor"];
            sunDirection = effect.Parameters["SunDirection"];
            sunDiffuseColor = effect.Parameters["SunDiffuseColor"];
            sunThreshold = effect.Parameters["SunThreshold"];
            sunVisible = effect.Parameters["SunVisible"];
            defaultTechnique = effect.Techniques["Default"];

            currentPass = effect.CurrentTechnique.Passes[0];
        }
        private ScreenQuadEffect( GraphicsDevice device, Effect effect )
            : base(device, effect)
        {
            Parameters["ScreenWidth"].SetValue( device.Viewport.Width );
              Parameters["ScreenHeight"].SetValue( device.Viewport.Height );

              colorTechnique = Techniques["Color"];
              textureTechnique = Techniques["Texture"];
              CurrentTechnique = colorTechnique;

              colorParameter = Parameters["Tint"];
              textureParameter = Parameters["Texture"];

              Color = Color.White;

              colorVertexDeclaration = new VertexDeclaration( device, VertexPositionColor.VertexElements );
              textureVertexDeclaration = new VertexDeclaration( device, VertexPositionTexture.VertexElements );
        }
示例#21
0
 public RepeatTechniqueDescription(Effect effect, EffectTechnique technique)
   : base(effect, technique)
 {
   // Store the repeat parameters for each pass in an array.
   RepeatParameters = new EffectParameter[technique.Passes.Count];
   for (int i = 0; i < technique.Passes.Count; i++)
   {
     var pass = technique.Passes[i];
     foreach (var annotation in pass.Annotations)
     {
       if (annotation.Name == "RepeatParameter")
       {
         var repeatParameter = annotation.GetValueString();
         RepeatParameters[i] = effect.Parameters[repeatParameter];
       }
     }
   }
 }
        //--------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="RebuildZBufferRenderer"/> class.
        /// </summary>
        /// <param name="graphicsService">The graphics service.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="graphicsService"/> is <see langword="null"/>.
        /// </exception>
        public RebuildZBufferRenderer(IGraphicsService graphicsService)
        {
            if (graphicsService == null)
            throw new ArgumentNullException("graphicsService");

              NearBias = 1;
              FarBias = 0.995f;

              _effect = graphicsService.Content.Load<Effect>("DigitalRune/Deferred/RebuildZBuffer");
              _parameterViewportSize = _effect.Parameters["ViewportSize"];
              _parameterProjection = _effect.Parameters["Projection"];
              _parameterCameraFar = _effect.Parameters["CameraFar"];
              _parameterGBuffer0 = _effect.Parameters["GBuffer0"];
              _parameterColor = _effect.Parameters["Color"];
              _parameterSourceTexture = _effect.Parameters["SourceTexture"];
              _techniqueOrthographic = _effect.Techniques["Orthographic"];
              _techniquePerspective = _effect.Techniques["Perspective"];
        }
示例#23
0
        public override void Draw(EffectTechnique technique)
        {
            if (!flag)
                flag = true;
            else
            {
                flag = false;
                return;
            }

            if (ServiceManager.Game.Options.GamePlay.ShowNames)
            {
                /*GraphicsDevice device = GraphicOptions.graphics.GraphicsDevice;
                Vector3 offset = new Vector3(0, 0, 0);
                Vector3 pPosition = Vector3.Zero;// position + offset;
                Matrix projection = GraphicOptions.CurrentCamera.Projection;
                Matrix view = GraphicOptions.CurrentCamera.View;
                Matrix world = Matrix.CreateTranslation(position + offset);//Matrix.Identity;// Matrix.Invert(GraphicOptions.CurrentCamera.View);

                Vector3 projectedPosition = device.Viewport.Project(pPosition, projection, view, world);

                Vector2 newPosition = new Vector2(projectedPosition.X, projectedPosition.Y);
                newPosition.X = newPosition.X - (width / 2.0f);
                newPosition.Y = newPosition.Y - (height / 2.0f);

                ServiceManager.Game.Batch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None);
                ServiceManager.Game.Batch.DrawString(ServiceManager.Game.Font, text, newPosition, Color.Black);
                ServiceManager.Game.Batch.End();*/

                GraphicsDevice device = GraphicOptions.graphics.GraphicsDevice;
                device.RenderState.AlphaBlendEnable = true;
                device.RenderState.SourceBlend = Blend.SourceAlpha;
                device.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
                device.RenderState.AlphaFunction = CompareFunction.Greater;
                device.RenderState.SeparateAlphaBlendEnabled = false;
                device.RenderState.AlphaTestEnable = true;

                base.Draw(technique);

                device.RenderState.AlphaBlendEnable = false;
                device.RenderState.SourceBlend = Blend.One;
                device.RenderState.DestinationBlend = Blend.Zero;
            }
        }
示例#24
0
        /// <summary>
        /// エフェクト (ShadowMap.fx) を指定してインスタンスを生成します。
        /// </summary>
        /// <param name="sourceEffect">エフェクト。</param>
        public ShadowMapEffect(Effect sourceEffect)
        {
            if (sourceEffect == null) throw new ArgumentNullException("sourceEffect");

            this.sourceEffect = sourceEffect;

            worldParameter = sourceEffect.Parameters["World"];
            lightViewProjectionParameter = sourceEffect.Parameters["LightViewProjection"];

            basicTechnique = sourceEffect.Techniques["Basic"];
            varianceTechnique = sourceEffect.Techniques["Variance"];

            world = Matrix.Identity;
            lightViewProjection = Matrix.Identity;

            Form = ShadowMapEffectForm.Basic;

            dirtyFlags = DirtyFlags.World | DirtyFlags.LightViewProjection;
        }
示例#25
0
		public void LoadContent() {
			effect = Puzzle3D.Instance.Content.Load<Effect>( "Shaders/Lighting" );

			noTextureTechnique = effect.Techniques[ "NoTexture" ];
			singleTextureTechnique = effect.Techniques[ "SingleTexture" ];

			effect.CurrentTechnique = singleTextureTechnique;

			world = effect.Parameters[ "World" ];
			worldView = effect.Parameters[ "WorldView" ];
			worldViewProjection = effect.Parameters[ "WorldViewProjection" ];
			lightPos = effect.Parameters[ "LightPos" ];
			cameraPos = effect.Parameters[ "CameraPos" ];
			glowScale = effect.Parameters[ "GlowScale" ];
			colorOverride = effect.Parameters[ "ColorOverride" ];
			texCoordScale = effect.Parameters[ "TexCoordScale" ];
			texCoordTranslation = effect.Parameters[ "TexCoordTranslation" ];
			diffuseTexture = effect.Parameters[ "DiffuseTexture" ];
		}
        //private DepthStencilState _dsOccludedShadow;
        //private DepthStencilState _dsOccludedHull;
        public void Load(PenumbraEngine engine)
        {
            _engine = engine;

            _fxShadow = EffectManager.LoadEffectFromEmbeddedResource(_engine.Device, "Shadow");
            _fxShadowTech = _fxShadow.Techniques["Main"];
            _fxShadowTechDebug = _fxShadow.Techniques["Debug"];
            _fxShadowParamLightPosition = _fxShadow.Parameters["LightPosition"];
            _fxShadowParamLightRadius = _fxShadow.Parameters["LightRadius"];
            _fxShadowParamVp = _fxShadow.Parameters["ViewProjection"];

            _fxShadow.Parameters["Color"].SetValue(DebugColor.ToVector4());

            _fxHull = EffectManager.LoadEffectFromEmbeddedResource(_engine.Device, "Hull");
            _fxHullTech = _fxHull.Techniques["Main"];
            _fxHullParamVp = _fxHull.Parameters["ViewProjection"];
            _fxHullParamColor = _fxHull.Parameters["Color"];

            BuildGraphicsResources();
        }
示例#27
0
文件: Effect.cs 项目: khbecker/FNA
        internal void ReadEffect(BinaryReader reader)
        {
            var effectPass = new EffectPass(this, "Pass", null, null, null, DepthStencilState.Default, RasterizerState.CullNone, EffectAnnotationCollection.Empty);

            effectPass._shaderProgram = new ShaderProgram(reader.ReadBytes((int)reader.BaseStream.Length));
            var shaderProgram = effectPass._shaderProgram;

            EffectParameter[] parametersArray = new EffectParameter[shaderProgram.UniformCount + 4];
            for (int i = 0; i < shaderProgram.UniformCount; i++)
            {
                parametersArray[i] = EffectParameterForUniform(shaderProgram, i);
            }

                        #warning Hacks for BasicEffect as we don't have these parameters yet
            parametersArray[shaderProgram.UniformCount] = new EffectParameter(
                EffectParameterClass.Vector, EffectParameterType.Single, "SpecularColor",
                3, 1, "float3", EffectAnnotationCollection.Empty, EffectParameterCollection.Empty, EffectParameterCollection.Empty, new float[3]);
            parametersArray[shaderProgram.UniformCount + 1] = new EffectParameter(
                EffectParameterClass.Scalar, EffectParameterType.Single, "SpecularPower",
                1, 1, "float", EffectAnnotationCollection.Empty, EffectParameterCollection.Empty, EffectParameterCollection.Empty, 0.0f);
            parametersArray[shaderProgram.UniformCount + 2] = new EffectParameter(
                EffectParameterClass.Vector, EffectParameterType.Single, "FogVector",
                4, 1, "float4", EffectAnnotationCollection.Empty, EffectParameterCollection.Empty, EffectParameterCollection.Empty, new float[4]);
            parametersArray[shaderProgram.UniformCount + 3] = new EffectParameter(
                EffectParameterClass.Vector, EffectParameterType.Single, "DiffuseColor",
                4, 1, "float4", EffectAnnotationCollection.Empty, EffectParameterCollection.Empty, EffectParameterCollection.Empty, new float[4]);

            Parameters = new EffectParameterCollection(parametersArray);

            EffectPass [] effectsPassArray = new EffectPass[1];
            effectsPassArray[0] = effectPass;
            var effectPassCollection = new EffectPassCollection(effectsPassArray);

            EffectTechnique [] effectTechniqueArray = new EffectTechnique[1];
            effectTechniqueArray[0] = new EffectTechnique(this, "Name", effectPassCollection, EffectAnnotationCollection.Empty);
            Techniques = new EffectTechniqueCollection(effectTechniqueArray);

            ConstantBuffers  = new ConstantBuffer[0];
            CurrentTechnique = Techniques[0];
        }
        //private DepthStencilState _dssOccludedLight;
        public void Load(PenumbraEngine engine)
        {
            _engine = engine;

            _fxLight = EffectManager.LoadEffectFromEmbeddedResource(_engine.Device, "Light");
            _fxPointLightTech = _fxLight.Techniques["PointLight"];
            _fxSpotLightTech = _fxLight.Techniques["Spotlight"];
            _fxTexturedLightTech = _fxLight.Techniques["TexturedLight"];
            _fxDebugLightTech = _fxLight.Techniques["DebugLight"];
            _fxLightParamTexture = _fxLight.Parameters["Texture"];
            _fxLightParamTextureTransform = _fxLight.Parameters["TextureTransform"];
            _fxLightParamWvp = _fxLight.Parameters["WorldViewProjection"];
            _fxLightParamColor = _fxLight.Parameters["LightColor"];
            _fxLightParamIntensity = _fxLight.Parameters["LightIntensity"];
            _fxLightParamConeAngle = _fxLight.Parameters["ConeHalfAngle"];
            _fxLightParamConeDecay = _fxLight.Parameters["ConeDecay"];

            // Constant shader param.
            _fxLight.Parameters["Color"].SetValue(DebugColor.ToVector4());

            BuildGraphicsResources();
        }
示例#29
0
        public CollisionManager()
        {
            _allColliders = new List<Collider>();
            _allTriggers = new List<Collider>();
            _allTriggersAndColliders = new List<Collider>();

            var geometryBox = new GeometryData
            {
                Vertices = new[]
                {
                    new VertexPositionNormalTexture(new Vector3(-0.5f, -0.5f, -0.5f), Vector3.Zero, Vector2.Zero),
                    new VertexPositionNormalTexture(new Vector3( 0.5f, -0.5f, -0.5f), Vector3.Zero, Vector2.Zero),
                    new VertexPositionNormalTexture(new Vector3(0.5f, -0.5f,  0.5f), Vector3.Zero, Vector2.Zero),
                    new VertexPositionNormalTexture(new Vector3(-0.5f, -0.5f, 0.5f), Vector3.Zero, Vector2.Zero),

                    new VertexPositionNormalTexture(new Vector3(-0.5f, 0.5f, -0.5f), Vector3.Zero, Vector2.Zero),
                    new VertexPositionNormalTexture(new Vector3( 0.5f, 0.5f, -0.5f), Vector3.Zero, Vector2.Zero),
                    new VertexPositionNormalTexture(new Vector3(0.5f, 0.5f,  0.5f), Vector3.Zero, Vector2.Zero),
                    new VertexPositionNormalTexture(new Vector3(-0.5f, 0.5f, 0.5f), Vector3.Zero, Vector2.Zero),
                },
                Indices = new ushort[]
                {
                    0,1,1,2,2,3,3,0,
                    4,5,5,6,6,7,7,4,
                    0,4,1,5,2,6,3,7
                }
            };

            _boundingBoxMesh = new Mesh(GameInstance.GraphicsDevice, geometryBox, PrimitiveType.LineList, false)
            {
                PreventDrawCallCount = true
            };

            _lineDrawEffect = GameInstance.Content.Load<Effect>(ResourceNames.Effects.DebugShadowMap);
            _worldViewProjection = _lineDrawEffect.Parameters["WorldViewProjection"];
            _modulateColor = _lineDrawEffect.Parameters["Color"];
            _lineTechnique = _lineDrawEffect.Techniques["LineDraw"];
        }
        ///// <summary>
        ///// Dispose(bool disposing) executes in two distinct scenarios.
        ///// If disposing equals true, the method has been called directly
        ///// or indirectly by a user's code. Managed and unmanaged resources
        ///// can be disposed.
        ///// If disposing equals false, the method has been called by the 
        ///// runtime from inside the finalizer and you should not reference 
        ///// other objects. Only unmanaged resources can be disposed.
        ///// </summary>
        //protected override void Dispose(bool disposing)
        //{
        //    if (IsDisposed) 
        //        return;

        //    base.Dispose(disposing);

        //    if (disposing)
        //    {
        //        if (vertexShader != null)
        //        {
        //            vertexShader.Dispose();
        //            vertexShader = null;
        //        }
        //        if (pixelShader != null)
        //        {
        //            pixelShader.Dispose();
        //            pixelShader = null;
        //        }
        //    }
        //}

        #endregion

        #region Creation

        /// <summary>
        /// Creates a new SilverlightEffect with default parameter settings.
        /// </summary>
        internal SilverlightEffect(EffectTechnique[] techniques)
            : base(techniques)
        {
            Dictionary<string, SilverlightEffectParameter> tempParameters = new Dictionary<string, SilverlightEffectParameter>();

            foreach (var technique in techniques)
            {
                foreach (SilverlightEffectPass pass in technique.Passes)
                {
                    pass.ParentEffect = this;

                    foreach (SilverlightEffectInternalParameter parameter in pass.Parameters)
                    {
                        if (!tempParameters.ContainsKey(parameter.Name))
                        {
                            tempParameters.Add(parameter.Name, new SilverlightEffectParameter(parameter.Name));
                        }
                    }
                }
            }

            parameters = new SilverlightEffectParametersCollection(tempParameters.Values);
        }
示例#31
0
        public WindowsSceneEffect(ContentManager content)
        {
            _basicEffect = content.Load<Effect>(ResourceNames.Effects.BasicEffect);
            PostProcessingEffect = content.Load<Effect>(ResourceNames.Effects.PostProcessing);

            _shadowCasterTechnique = _basicEffect.Techniques["ShadowCaster"];
            _shadowCasterTransparentTechnique = _basicEffect.Techniques["ShadowCasterTransparent"];
            ShadowMapDebugEffect = content.Load<Effect>(ResourceNames.Effects.DebugShadowMap);

            _effectsByLightingFlags = new Dictionary<int, EffectTechnique>()
            {
                { LightTechniqueFlag.Lit | LightTechniqueFlag.ReceiveShadows,_basicEffect.Techniques["LitNoTextureShadowReceiver"] },
                { LightTechniqueFlag.Lit | LightTechniqueFlag.ReceiveShadows | LightTechniqueFlag.SoftShadows , _basicEffect.Techniques["LitNoTextureShadowReceiverPCF"] },
                { LightTechniqueFlag.Lit | LightTechniqueFlag.UseTexture, _basicEffect.Techniques["Lit"] },
                { LightTechniqueFlag.Lit | LightTechniqueFlag.UseTexture | LightTechniqueFlag.ReceiveShadows, _basicEffect.Techniques["LitShadowReceiver"] },
                { LightTechniqueFlag.Lit | LightTechniqueFlag.UseTexture | LightTechniqueFlag.ReceiveShadows | LightTechniqueFlag.SoftShadows, _basicEffect.Techniques["LitShadowReceiverPCF"] },
                { 0, _basicEffect.Techniques["UnlitNoTexture"] },
                { LightTechniqueFlag.UseTexture, _basicEffect.Techniques["Unlit"] },
                { LightTechniqueFlag.UseTexture | LightTechniqueFlag.LinearTextureSampling, _basicEffect.Techniques["UnlitLinearSampled"] },
            };

            _lightViewProjection = _basicEffect.Parameters["LightViewProjection"];
            _world = _basicEffect.Parameters["World"];
            _worldLight = _basicEffect.Parameters["WorldLight"];
            _view = _basicEffect.Parameters["View"];
            _projection = _basicEffect.Parameters["Projection"];
            _lightDirection = _basicEffect.Parameters["LightDirection"];
            _shadowMap = _basicEffect.Parameters["ShadowMap"];
            _diffuseTexture = _basicEffect.Parameters["DiffuseTexture"];
            _texcoordOffset = _basicEffect.Parameters["TexcoordOffset"];
            _texcoordScale = _basicEffect.Parameters["TexcoordScale"];
            _ambientLight = _basicEffect.Parameters["AmbientLight"];
            _ambientIntensity = _basicEffect.Parameters["AmbientIntensity"];
            _diffuseIntensity = _basicEffect.Parameters["DiffuseIntensity"];
            _shadowScale = _basicEffect.Parameters["ShadowScale"];
            _materialColor = _basicEffect.Parameters["MaterialColor"];
        }
        /// <summary>
        /// Draws all vertices in the vertex buffer.
        /// </summary>
        /// 
        public override void Draw(EffectTechnique technique)
        {
            UniversalEffect effect = RendererAssetPool.UniversalEffect;

            if (technique == effect.Techniques.UseDefault)
                effect.CurrentTechnique = RendererAssetPool.UniversalEffect.Techniques.Colored;
            else
                effect.CurrentTechnique = technique;

            effect.ColorParameters.TransparencyEnabled = this.TransparencyEnabled && GraphicOptions.TransparentWalls;

               effect.Begin();
               foreach (EffectPass pass in effect.CurrentTechnique.Passes)//TODO1 remove this when shading i
               {
               pass.Begin();
               GraphicsDevice device = GraphicOptions.graphics.GraphicsDevice;
               device.VertexDeclaration = vertDeclaration;
               device.Vertices[0].SetSource(vertexBuffer, 0, VertexPositionColor.SizeInBytes);
               device.DrawUserPrimitives<VertexPositionColor>(
                   PrimitiveType.TriangleStrip, vertices.ToArray(), 0, 2);
               pass.End();
               }
               effect.End();
        }
示例#33
0
        private static EffectTechnique[] CreateTechniques(BinaryReader input)
        {
            int techniquesCount = input.ReadInt32();

            if (techniquesCount < 0 || techniquesCount > 128)
            {
                throw new System.InvalidOperationException(
                          "Invalid silverlight effect. Have you forgot to process the effect using SilverlightEffectProcessor?");
            }

            EffectTechnique[] techniques = new EffectTechnique[techniquesCount];

            for (int techniqueIndex = 0; techniqueIndex < techniquesCount; techniqueIndex++)
            {
                int          passesCount = input.ReadInt32();
                EffectPass[] passes      = new EffectPass[passesCount];

                for (int passIndex = 0; passIndex < passesCount; passIndex++)
                {
                    string passName = input.ReadString();

                    MemoryStream vertexShaderCodeStream       = null;
                    MemoryStream vertexShaderParametersStream = null;

                    MemoryStream pixelShaderCodeStream       = null;
                    MemoryStream pixelShaderParametersStream = null;

                    // Vertex shader
                    int vertexShaderByteCodeLength = input.ReadInt32();
                    if (vertexShaderByteCodeLength > 0)
                    {
                        byte[] vertexShaderByteCode         = input.ReadBytes(vertexShaderByteCodeLength);
                        int    vertexShaderParametersLength = input.ReadInt32();
                        byte[] vertexShaderParameters       = input.ReadBytes(vertexShaderParametersLength);

                        vertexShaderCodeStream       = new MemoryStream(vertexShaderByteCode);
                        vertexShaderParametersStream = new MemoryStream(vertexShaderParameters);
                    }

                    // Pixel shader
                    int pixelShaderByteCodeLength = input.ReadInt32();
                    if (pixelShaderByteCodeLength > 0)
                    {
                        byte[] pixelShaderByteCode         = input.ReadBytes(pixelShaderByteCodeLength);
                        int    pixelShaderParametersLength = input.ReadInt32();
                        byte[] pixelShaderParameters       = input.ReadBytes(pixelShaderParametersLength);

                        pixelShaderCodeStream       = new MemoryStream(pixelShaderByteCode);
                        pixelShaderParametersStream = new MemoryStream(pixelShaderParameters);
                    }


                    // Instanciate pass
                    SilverlightEffectPass currentPass = new SilverlightEffectPass(passName, GraphicsDeviceManager.Current.GraphicsDevice, vertexShaderCodeStream, pixelShaderCodeStream, vertexShaderParametersStream, pixelShaderParametersStream);
                    passes[passIndex] = currentPass;

                    if (vertexShaderCodeStream != null)
                    {
                        vertexShaderCodeStream.Dispose();
                        vertexShaderParametersStream.Dispose();
                    }

                    if (pixelShaderCodeStream != null)
                    {
                        pixelShaderCodeStream.Dispose();
                        pixelShaderParametersStream.Dispose();
                    }

                    // Render states
                    int renderStatesCount = input.ReadInt32();

                    for (int renderStateIndex = 0; renderStateIndex < renderStatesCount; renderStateIndex++)
                    {
                        currentPass.AppendState(input.ReadString(), input.ReadString());
                    }
                }

                // Instanciate technique
                techniques[techniqueIndex] = new EffectTechnique(passes);
            }
            return(techniques);
        }
示例#34
0
        public bool IsDisposed = false; // GG TODO this should be hooked up along with the rest of the Disposable interface

        //GG EDIT
        private void Init(String assetName, String body, GraphicsDevice graphicsDevice)
        {
            _name = assetName;
            if (graphicsDevice == null)
            {
                throw new ArgumentNullException("Graphics Device Cannot Be Null");
            }
            this.graphicsDevice = graphicsDevice;

            program_handle = GL.CreateProgram();

            Parameters = new EffectParameterCollection();
            Techniques = new EffectTechniqueCollection();

            InitVertexShader("DEFAULT_VERTEX", GGShader.DEFAULT_VERTEX);
            InitFragmentShader(assetName, body);

            GL.AttachShader(program_handle, vertex_handle);
            GL.AttachShader(program_handle, fragment_handle);
            GL.LinkProgram(program_handle);

            int actUnis = 0;

            Parameters._parameters.Clear();
            List <int> texes = new List <int>();

            GL.GetProgram(program_handle, ProgramParameter.ActiveUniforms, out actUnis);
            for (int x = 0; x < actUnis; x++)
            {
                int length, size;
                ActiveUniformType type;
                StringBuilder     name = new StringBuilder(100);
                GL.GetActiveUniform(program_handle, x, 100, out length, out size, out type, name);
                String fixedName = name.ToString();

                int location = GL.GetUniformLocation(program_handle, fixedName);
                if (fixedName.EndsWith("[0]"))
                {
                    fixedName = fixedName.Substring(0, fixedName.Length - 3);
                }
                Console.WriteLine("{0}: {1} {2} {3}", location, fixedName, type, size);
                EffectParameter efp = new EffectParameter(this, fixedName, location, type.ToString(), length, size);
                if (type == ActiveUniformType.Sampler2D)
                {
                    texes.Add(location);
                }

                Parameters._parameters.Add(efp.Name, efp);

                List <EffectParameter> _textureMappings = new List <EffectParameter>();

                if (efp.ParameterType == EffectParameterType.Texture2D)
                {
                    _textureMappings.Add(efp);
                }
            }
            texes.Sort();
            texture_locations = texes.ToArray();

            position_index = GL.GetAttribLocation(program_handle, "a_Position");
            color_index    = GL.GetAttribLocation(program_handle, "a_Color");
            texCoord_index = GL.GetAttribLocation(program_handle, "a_TexCoord");

            CurrentTechnique           = new EffectTechnique(this);
            CurrentTechnique.Passes[0] = new EffectPass(CurrentTechnique);
        }
示例#35
0
 public EffectPass(EffectTechnique technique)
 {
     _technique = technique;
 }
示例#36
0
 /// <summary>
 /// Creates a new instance of <see cref="XNAEffectTechnique"/>.
 /// </summary>
 /// <param name="tech">The underlying XNA technique.</param>
 internal XNAEffectTechnique(XFG.EffectTechnique tech)
 {
     _tech           = tech;
     _passCollection = new XNAEffectPassCollection(tech.Passes);
     _annoCollection = new XNAEffectAnnotationCollection(tech.Annotations);
 }
示例#37
0
 public EffectPassCollection(EffectTechnique effectTechnique)
 {
     _effectTechnique = effectTechnique;
 }
示例#38
0
        private void ReadEffect(BinaryReader reader)
        {
            // TODO: Maybe we should be reading in a string
            // table here to save some bytes in the file.

            // Read in all the constant buffers.
            var buffers = (int)reader.ReadByte();

            ConstantBuffers = new ConstantBuffer[buffers];
            for (var c = 0; c < buffers; c++)
            {
                var name = reader.ReadString();

                // Create the backing system memory buffer.
                var sizeInBytes = (int)reader.ReadInt16();

                // Read the parameter index values.
                var parameters = new int[reader.ReadByte()];
                var offsets    = new int[parameters.Length];
                for (var i = 0; i < parameters.Length; i++)
                {
                    parameters[i] = (int)reader.ReadByte();
                    offsets[i]    = (int)reader.ReadUInt16();
                }

                var buffer = new ConstantBuffer(GraphicsDevice,
                                                sizeInBytes,
                                                parameters,
                                                offsets,
                                                name);
                ConstantBuffers[c] = buffer;
            }

            // Read in all the shader objects.
            var shaders = (int)reader.ReadByte();

            _shaders = new Shader[shaders];
            for (var s = 0; s < shaders; s++)
            {
                _shaders[s] = new Shader(GraphicsDevice, reader);
            }

            // Read in the parameters.
            Parameters = ReadParameters(reader);

            // Read the techniques.
            var techniqueCount = (int)reader.ReadByte();
            var techniques     = new EffectTechnique[techniqueCount];

            for (var t = 0; t < techniqueCount; t++)
            {
                var name = reader.ReadString();

                var annotations = ReadAnnotations(reader);

                var passes = ReadPasses(reader, this, _shaders);

                techniques[t] = new EffectTechnique(this, name, passes, annotations);
            }

            Techniques       = new EffectTechniqueCollection(techniques);
            CurrentTechnique = Techniques[0];
        }
示例#39
0
        private void ReadEffect(BinaryReader reader)
        {
            // Check the header to make sure the file and version is correct!
            var header  = new string (reader.ReadChars(MGFXHeader.Length));
            var version = (int)reader.ReadByte();

            if (header != MGFXHeader)
            {
                throw new Exception("The MGFX file is corrupt!");
            }
            if (version != MGFXVersion)
            {
                throw new Exception("Wrong MGFX file version!");
            }

            var profile = reader.ReadByte();

#if DIRECTX
            if (profile != 1)
#else
            if (profile != 0)
#endif
            { throw new Exception("The MGFX effect is the wrong profile for this platform!"); }

            // TODO: Maybe we should be reading in a string
            // table here to save some bytes in the file.

            // Read in all the constant buffers.
            var buffers = (int)reader.ReadByte();
            ConstantBuffers = new ConstantBuffer[buffers];
            for (var c = 0; c < buffers; c++)
            {
#if OPENGL
                string name = reader.ReadString();
#else
                string name = null;
#endif

                // Create the backing system memory buffer.
                var sizeInBytes = (int)reader.ReadInt16();

                // Read the parameter index values.
                var parameters = new int[reader.ReadByte()];
                var offsets    = new int[parameters.Length];
                for (var i = 0; i < parameters.Length; i++)
                {
                    parameters [i] = (int)reader.ReadByte();
                    offsets [i]    = (int)reader.ReadUInt16();
                }

                var buffer = new ConstantBuffer(GraphicsDevice,
                                                sizeInBytes,
                                                parameters,
                                                offsets,
                                                name);
                ConstantBuffers[c] = buffer;
            }

            // Read in all the shader objects.
            var shaders = (int)reader.ReadByte();
            _shaders = new Shader[shaders];
            for (var s = 0; s < shaders; s++)
            {
                _shaders[s] = new Shader(GraphicsDevice, reader);
            }

            // Read in the parameters.
            Parameters = ReadParameters(reader);

            // Read the techniques.
            var techniqueCount = (int)reader.ReadByte();
            var techniques     = new EffectTechnique[techniqueCount];
            for (var t = 0; t < techniqueCount; t++)
            {
                var name = reader.ReadString();

                var annotations = ReadAnnotations(reader);

                var passes = ReadPasses(reader, this, _shaders);

                techniques[t] = new EffectTechnique(this, name, passes, annotations);
            }

            Techniques       = new EffectTechniqueCollection(techniques);
            CurrentTechnique = Techniques[0];
        }