Example #1
0
        public CircleEffect(GameContext context) : base(context)
        {
            _context = context;
            effect   = CGHelper.CreateEffectFx5("Resources\\Shader\\circleShader.fx",
                                                context.RenderContext.DeviceManager.Device);
            beffect = CGHelper.CreateEffectFx5("Resources\\Shader\\convergenceBeam.fx",
                                               context.RenderContext.DeviceManager.Device);
            noiseView = context.LoadTexture("Resources\\Effect\\noise.png");
            beamView  = context.LoadTexture("Resources\\Effect\\lazer.png");
            ShaderResourceView view = context.LoadTexture("Resources\\Effect\\circle.png");

            frontCircle = new DividedPlaneBoard(context.RenderContext, view, 100,
                                                new Vector2(100, 100),
                                                new PlaneBoard.PlaneBoardDescription(BlendStateManager.BlendStates.Add, effect, false, RenderFront));
            frontCircle.Initialize();
            for (int i = 0; i < 3; i++)
            {
                subCircle[i] = new PlaneBoard(context.RenderContext, view, new Vector2(30, 30),
                                              new PlaneBoard.PlaneBoardDescription(BlendStateManager.BlendStates.Add, effect, false, RenderFront));
                subCircle[i].Initialize();
            }
            for (int i = 0; i < 5; i++)
            {
                beamEffects[i] = new DividedPlaneBoard(context.RenderContext, view, 100,
                                                       new Vector2(100, 100),
                                                       new PlaneBoard.PlaneBoardDescription(BlendStateManager.BlendStates.Add, beffect, false, Renderbeam));
                beamEffects[i].Initialize();
            }
        }
Example #2
0
 public CircleEffect(GameContext context)
     : base(context)
 {
     _context = context;
     effect = CGHelper.CreateEffectFx5("Resources\\Shader\\circleShader.fx",
         context.RenderContext.DeviceManager.Device);
     beffect = CGHelper.CreateEffectFx5("Resources\\Shader\\convergenceBeam.fx",
         context.RenderContext.DeviceManager.Device);
     noiseView = context.LoadTexture("Resources\\Effect\\noise.png");
     beamView = context.LoadTexture("Resources\\Effect\\lazer.png");
     ShaderResourceView view = context.LoadTexture("Resources\\Effect\\circle.png");
     frontCircle = new DividedPlaneBoard(context.RenderContext, view,100,
         new Vector2(100, 100),
         new PlaneBoard.PlaneBoardDescription(BlendStateManager.BlendStates.Add, effect, false, RenderFront));
     frontCircle.Initialize();
     for (int i = 0; i < 3; i++)
     {
         subCircle[i] = new PlaneBoard(context.RenderContext, view, new Vector2(30, 30),
             new PlaneBoard.PlaneBoardDescription(BlendStateManager.BlendStates.Add, effect, false, RenderFront));
         subCircle[i].Initialize();
     }
     for (int i = 0; i < 5; i++)
     {
         beamEffects[i]=new DividedPlaneBoard(context.RenderContext, view, 100,
         new Vector2(100, 100),
         new PlaneBoard.PlaneBoardDescription(BlendStateManager.BlendStates.Add, beffect, false, Renderbeam));
         beamEffects[i].Initialize();
     }
 }
        public override void Initialize()
        {
            base.Initialize();

            try
            {
                using (ShaderBytecode effectByteCode = ShaderBytecode.CompileFromFile(
                           "Shaders/transformEffectWireframe.fx",
                           "Render",
                           "fx_5_0",
                           ShaderFlags.EnableStrictness,
                           EffectFlags.None))
                {
                    effect         = new SlimDX.Direct3D11.Effect(DeviceManager.Instance.device, effectByteCode);
                    technique      = effect.GetTechniqueByIndex(0);
                    pass           = technique.GetPassByIndex(0);
                    inputSignature = pass.Description.Signature;
                }

                var elements = new[] {
                    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0),
                };
                layout = new InputLayout(DeviceManager.Instance.device, inputSignature, elements);

                tmat  = effect.GetVariableByName("gWVP").AsMatrix();
                wfCol = effect.GetVariableByName("colorWireframe").AsVector();
                mCol  = effect.GetVariableByName("colorSolid").AsVector();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Example #4
0
        protected Effect(Device device, string filename)
        {
            if (!File.Exists(filename))
            {
                throw new FileNotFoundException(string.Format("Effect file {0} not present", filename));
            }
            ShaderBytecode compiledShader = null;

            try
            {
                compiledShader = new ShaderBytecode(new DataStream(File.ReadAllBytes(filename), false, false));
                FX             = new SlimDX.Direct3D11.Effect(device, compiledShader);
            }
            catch (Exception ex)
            {
                MessageBox.Show
                (
                    "Effect could not be created: " + ex.Message + "\n\nYou may have to reinstall DirectX.",
                    "DirectX Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                );
                throw ex;
            }
            finally
            {
                Util.ReleaseCom(ref compiledShader);
            }
        }
Example #5
0
 /// <summary>
 /// 初期化処理を行う
 /// </summary>
 public void Init(Dx11.Device device, Dx11.Effect effect)
 {
     InitVertexLayout(device, effect);
     InitVertexBuffer(device);
     InitIndexBuffer(device);
     InitTexture(device);
 }
Example #6
0
 protected void SetAsVector(Vector4 vec, SlimDX.Direct3D11.Effect effect, int index, bool isVector3)
 {
     if (!isVector3)
     {
         effect.GetVariableByIndex(index).AsVector().Set(vec);
     }
     else
     {
         effect.GetVariableByIndex(index).AsVector().Set(new Vector3(vec.X, vec.Y, vec.Z));
     }
 }
Example #7
0
 private void InitEffect()
 {
     using (D3DComp.ShaderBytecode shaderBytecode = D3DComp.ShaderBytecode.CompileFromFile(
                "MyEffect.fx", "fx_5_0",
                D3DComp.ShaderFlags.None,
                D3DComp.EffectFlags.None
                ))
     {
         effect = new Dx11.Effect(GraphicsDevice, shaderBytecode);
     }
 }
Example #8
0
        public Texture(Dx11.Device device, Dx11.Effect effect, string parentDir, MmdMaterial[] materials)
        {
            this.device    = device;
            this.effect    = effect;
            this.materials = materials;
            this.parentDir = parentDir;
            normalTex      = new Dx11.ShaderResourceView[materials.Length];
            sphTex         = new Dx11.ShaderResourceView[materials.Length];
            spaTex         = new Dx11.ShaderResourceView[materials.Length];
            toonTex        = new Dx11.ShaderResourceView[materials.Length];

            InitializeTexture();
        }
Example #9
0
 protected Effect(Device device, string filename) {
     //Console.WriteLine("Loading effects from: " + Directory.GetCurrentDirectory());
     if (!File.Exists(filename)) {
         throw new FileNotFoundException(string.Format("Effect file {0} not present", filename));
     }
     ShaderBytecode compiledShader = null;
     try {
         compiledShader = new ShaderBytecode(new DataStream(File.ReadAllBytes(filename), false, false));
         FX = new SlimDX.Direct3D11.Effect(device, compiledShader);
     } catch (Exception ex) {
         MessageBox.Show(ex.Message);
     } finally {
         Util.ReleaseCom(ref compiledShader);
     }
 }
Example #10
0
 /// <summary>
 /// Renderbeams the specified arg1.
 /// </summary>
 /// <param name="arg1">The arg1.</param>
 /// <param name="arg2">The arg2.</param>
 /// <param name="arg3">The arg3.</param>
 private void Renderbeam(PlaneBoard arg1, SlimDX.Direct3D11.Effect arg2, ShaderResourceView arg3)
 {
     arg1.DefaultEffectSubscribe();
     beffect.GetVariableBySemantic("NOISETEX").AsResource().SetResource(beamView);
     beffect.GetVariableBySemantic("TIME").AsScalar().Set(lastTime - 1f);
     beffect.GetVariableBySemantic("STARTPOS").AsVector().Set(_startPosition);
     beffect.GetVariableBySemantic("TARGETPOS").AsVector().Set(-new Vector3(0, 0, 300));
     beffect.GetVariableBySemantic("UP").AsVector().Set(Vector3.TransformNormal(Vector3.UnitY * 100, Matrix.RotationZ((float)(2 * Math.PI / beamEffects.Length * currentBeamIndex))));
     beffect.GetVariableBySemantic("EYE").AsVector().Set(_context.RenderContext.CurrentTargetContext.MatrixManager.ViewMatrixManager.CameraPosition);
     beffect.GetVariableBySemantic("UVOFFSET").AsScalar().Set((float)(0.2 * currentBeamIndex));
     beffect.GetVariableBySemantic("BH").AsScalar().Set(5);
     currentBeamIndex++;
     if (currentBeamIndex == 5)
     {
         currentBeamIndex = 0;
     }
 }
Example #11
0
        public DxDeviceContext(IntPtr formHandle, Control renderAreaObject, bool fullscreen)
        {
            _isFullscreen = fullscreen;

            SwapChainDescription desc = new SwapChainDescription();

            if (fullscreen)
            {
                throw new ApplicationException("Not implemented yet");
            }
            else
            {
                FrameWidth  = renderAreaObject.Width;
                FrameHeight = renderAreaObject.Height;

                desc.BufferCount     = 1;
                desc.ModeDescription = new ModeDescription(FrameWidth,
                                                           FrameHeight,
                                                           new SlimDX.Rational(60, 1),
                                                           Format.R8G8B8A8_UNorm);
                desc.IsWindowed = true;
                desc.SwapEffect = SwapEffect.Discard;
            }

            desc.OutputHandle      = renderAreaObject.Handle;
            desc.SampleDescription = new SampleDescription(1, 0);
            desc.Usage             = Usage.RenderTargetOutput;

            Device    dev;
            SwapChain swapChain;

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out dev, out swapChain);
            Device    = dev;
            SwapChain = swapChain;
            Device.Factory.SetWindowAssociation(renderAreaObject.Handle, WindowAssociationFlags.IgnoreAll);

            _dInput = new DirectInput();
            CooperativeLevel cooLevel = CooperativeLevel.Foreground;

            cooLevel |= CooperativeLevel.Nonexclusive;
            _mouse    = new Mouse(_dInput);
            _mouse.SetCooperativeLevel(formHandle, cooLevel);

            _shaderByteCode = ShaderBytecode.CompileFromFile(GetFxFile(), "fx_5_0", ShaderFlags.None, EffectFlags.None);
            Effect          = new SlimDX.Direct3D11.Effect(Device, _shaderByteCode);
        }
Example #12
0
        /// <summary>
        /// モデルを描画する
        /// </summary>
        public void DrawModel(Dx11.Device device, Dx11.Effect effect)
        {
            int startIdx = 0, indexCount = 0;

            for (int i = 0; i < Cnv.meshSection.matList.PolygonCount; i++)
            {
                //マテリアル名から一致するマテリアルを調べる
                int    matNum  = Cnv.meshSection.matList.materialIndex[i];
                string refName = Cnv.meshSection.matList.materialReferens[matNum];

                Material m = GetMaterialFromReference(refName);
                //Console.WriteLine("mat:" + matNum + "-> ref:" + refName + ",matName:" + m.Name);

                //テクスチャを利用しているかどうか
                if (!m.TextureFileName.Equals(""))
                {
                    effect.GetVariableByName("tex").AsScalar().Set(true);
                    effect.GetVariableByName("normalTexture").AsResource().SetResource(textureManager.GetTexture(m.Name));
                }
                else
                {
                    effect.GetVariableByName("tex").AsScalar().Set(false);
                    effect.GetVariableByName("mat").AsScalar().Set(true);
                    effect.GetVariableByName("matColor").AsVector().Set(m.DiffuseColor);
                }

                //頂点数が4の場合は2つに分割する
                if (Cnv.meshSection.meshList.mesh[i].Length == VTXNUM_SQUARE)
                {
                    indexCount = 6;
                    effect.GetTechniqueByIndex(0).GetPassByIndex(0).Apply(device.ImmediateContext);
                    device.ImmediateContext.DrawIndexed(indexCount, startIdx, 0);
                }
                else
                {
                    indexCount = 3;
                    effect.GetTechniqueByIndex(0).GetPassByIndex(0).Apply(device.ImmediateContext);
                    device.ImmediateContext.DrawIndexed(indexCount, startIdx, 0);
                }
                startIdx += indexCount;
            }

            effect.GetVariableByName("tex").AsScalar().Set(false);
            effect.GetTechniqueByIndex(0).GetPassByIndex(0).Apply(device.ImmediateContext);
            device.ImmediateContext.DrawIndexed(indices.Count, 0, 0);
        }
Example #13
0
        protected Effect(Device device, string filename)
        {
            //Console.WriteLine("Loading effects from: " + Directory.GetCurrentDirectory());
            if (!File.Exists(filename))
            {
                throw new FileNotFoundException(string.Format("Effect file {0} not present", filename));
            }
            ShaderBytecode compiledShader = null;

            try {
                compiledShader = new ShaderBytecode(new DataStream(File.ReadAllBytes(filename), false, false));
                FX             = new SlimDX.Direct3D11.Effect(device, compiledShader);
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
            } finally {
                Util.ReleaseCom(ref compiledShader);
            }
        }
Example #14
0
        public MMEEffectInfo(SlimDX.Direct3D11.Effect effect)
        {
            ScriptOutput         = "color";
            ScriptClass          = ScriptClass.Object;
            ScriptOrder          = ScriptOrder.Standard;
            StandardGlobalScript = "";
            SortedTechnique      = new List <EffectTechnique>();
            for (int i = 0; i < effect.Description.GlobalVariableCount; i++)
            {
                EffectVariable variable = effect.GetVariableByIndex(i);
                if (variable.Description.Semantic.ToUpper().Equals("STANDARDGLOBAL"))
                {
//この時この変数はSTANDARDGLOBAL
                    ParseStandardGlobal(effect, variable);
                    break;
                }
            }
        }
Example #15
0
        private void BuildFX()
        {
            var shaderFlags = ShaderFlags.None;

#if DEBUG
            shaderFlags |= ShaderFlags.Debug;
            shaderFlags |= ShaderFlags.SkipOptimization;
#endif
            string         errors         = null;
            ShaderBytecode compiledShader = null;
            try
            {
                //compiledShader = new ShaderBytecode(new DataStream(File.ReadAllBytes("fx/Lighting.fxo"), false, false));
                //_fx = new Effect(Device, compiledShader);
                Core.FX.IncludeFX includeFX = new Core.FX.IncludeFX();
                compiledShader = ShaderBytecode.CompileFromFile("FX/Lighting.fx", null, "fx_5_0", shaderFlags, EffectFlags.None, null, includeFX, out errors);
                _fx            = new Effect(Device, compiledShader);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            finally
            {
                Util.ReleaseCom(ref compiledShader);
            }

            _tech         = _fx.GetTechniqueByName("LightTech");
            _fxWVP        = _fx.GetVariableByName("gWorldViewProj").AsMatrix();
            _fxWorld      = _fx.GetVariableByName("gWorld").AsMatrix();
            _fxWIT        = _fx.GetVariableByName("gWorldInvTranspose").AsMatrix();
            _fxEyePosW    = _fx.GetVariableByName("gEyePosW").AsVector();
            _fxDirLight   = _fx.GetVariableByName("gDirLight");
            _fxPointLight = _fx.GetVariableByName("gPointLight");
            _fxSpotLight  = _fx.GetVariableByName("gSpotLight");
            _fxMaterial   = _fx.GetVariableByName("gMaterial");
        }
Example #16
0
        protected Effect(Device device, string filename)
        {
            /*if (filename.EndsWith(".fxo"))
             * {
             *  filename = filename.Replace("fxo", "fx");
             * }*/

            //Console.WriteLine("Loading effects from: " + Directory.GetCurrentDirectory());
            if (!File.Exists(filename))
            {
                throw new FileNotFoundException(string.Format("Effect file {0} not present", filename));
            }
            ShaderBytecode compiledShader = null;
            var            shaderFlags    = ShaderFlags.None;

#if DEBUG
            shaderFlags |= ShaderFlags.Debug;
            shaderFlags |= ShaderFlags.SkipOptimization;
#endif
            string errors = null;
            try
            {
                compiledShader = new ShaderBytecode(new DataStream(File.ReadAllBytes(filename), false, false));
                FX             = new SlimDX.Direct3D11.Effect(device, compiledShader);

                /*IncludeFX includeFX = new IncludeFX();
                 * compiledShader = ShaderBytecode.CompileFromFile(filename, null, "fx_5_0", shaderFlags, EffectFlags.None, null, includeFX, out errors);
                 * FX = new SlimDX.Direct3D11.Effect(device, compiledShader);*/
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Util.ReleaseCom(ref compiledShader);
            }
        }
Example #17
0
        public SkullDemo(IntPtr hInstance)
            : base(hInstance)
        {
            _vb = null;
            _ib = null;
            _fx = null;
            _tech = null;
            _fxWVP = null;
            _inputLayout = null;
            _wireframeRS = null;
            _skullIndexCount = 0;
            _theta = 1.5f*MathF.PI;
            _phi = 0.1f*MathF.PI;
            _radius = 20.0f;

            MainWindowCaption = "Skull Demo";

            _lastMousePos = new Point(0,0);

            _view = Matrix.Identity;
            _proj = Matrix.Identity;
            _skullWorld = Matrix.Translation(0.0f, -2.0f, 0.0f);
        }
Example #18
0
        public void TestFullscreenQuad()
        {
            BasicShader    shader = null;
            FullScreenQuad quad   = null;
            var            game   = new DX11Game();

            game.InitDirectX();

            var device = game.Device;

            var bytecode  = ShaderBytecode.CompileFromFile("../../Common.Core/Shaders/FullScreenQuad.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
            var effect    = new Effect(game.Device, bytecode);
            var technique = effect.GetTechniqueByName("TestQuadTextured");
            var pass      = technique.GetPassByIndex(0);

            quad = new FullScreenQuad(game.Device);

            var diffuseShaderVariable = effect.GetVariableByName("txDiffuse").AsResource();

            var texturePath = Wallpaper001_png;

            var diffuseTexture = Texture2D.FromFile(device, texturePath);

            var diffuseTextureRv = new ShaderResourceView(device, diffuseTexture);

            diffuseShaderVariable.SetResource(diffuseTextureRv);

            var inputLayout = FullScreenQuad.CreateInputLayout(device, pass);

            game.GameLoopEvent += delegate
            {
                pass.Apply(game.Device.ImmediateContext);

                quad.Draw(inputLayout);
            };
            game.Run();
        }
Example #19
0
        private void BuildFX()
        {
            ShaderBytecode compiledShader = null;

            try {
                compiledShader = new ShaderBytecode(new DataStream(File.ReadAllBytes("fx/Lighting.fxo"), false, false));
                _fx            = new Effect(Device, compiledShader);
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
                return;
            } finally {
                Util.ReleaseCom(ref compiledShader);
            }

            _tech         = _fx.GetTechniqueByName("LightTech");
            _fxWVP        = _fx.GetVariableByName("gWorldViewProj").AsMatrix();
            _fxWorld      = _fx.GetVariableByName("gWorld").AsMatrix();
            _fxWIT        = _fx.GetVariableByName("gWorldInvTranspose").AsMatrix();
            _fxEyePosW    = _fx.GetVariableByName("gEyePosW").AsVector();
            _fxDirLight   = _fx.GetVariableByName("gDirLight");
            _fxPointLight = _fx.GetVariableByName("gPointLight");
            _fxSpotLight  = _fx.GetVariableByName("gSpotLight");
            _fxMaterial   = _fx.GetVariableByName("gMaterial");
        }
Example #20
0
 private void InitVertexLayout(Dx11.Device device, Dx11.Effect effect)
 {
     vertexLayout = new Dx11.InputLayout(
         device,
         effect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature, VertexPositionTexture.VertexElements);
 }
Example #21
0
        public void TestDirectX11SpecaterCamera()
        {
            var keyboard = new SlimDXTWKeyboard();
            var dev      = new SlimDX.DirectInput.DirectInput();
            var kb       = new SlimDX.DirectInput.Keyboard(dev);

            kb.Acquire();

            var mouse = new TWMouse();
            var m     = new SlimDX.DirectInput.Mouse(dev);

            m.Acquire();



            var game = new DX11Form();

            game.InitDirectX();
            var device    = game.Device;
            var bytecode  = ShaderBytecode.CompileFromFile("../../Common.Core/Shaders/MiniTri.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
            var effect    = new Effect(device, bytecode);
            var technique = effect.GetTechniqueByName("RenderTransform");
            var pass      = technique.GetPassByIndex(0);
            var layout    = new InputLayout(device, pass.Description.Signature,
                                            new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0)
            });

            var vertexStride = (16 + 16 + 8);
            var stream       = new DataStream(3 * vertexStride, true, true);

            stream.WriteRange(new[] {
                new VertexCustom(new Vector4(-1.0f, 0, 0, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector2(0.5f, 0)),
                new VertexCustom(new Vector4(0f, 1f, 0, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector2(0f, 1f)),
                new VertexCustom(new Vector4(1f, 0f, 0, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector2(1f, 1f))
            });
            stream.Position = 0;



            var vertices = new SlimDX.Direct3D11.Buffer(device, stream, new BufferDescription()
            {
                BindFlags      = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,
                SizeInBytes    = 3 * vertexStride,
                Usage          = ResourceUsage.Default
            });

            stream.Dispose();

            //var world = Matrix.Translation(MathHelper.Forward);

            /*var viewProjection = Matrix.LookAtRH(Vector3.UnitZ * 5, -Vector3.UnitZ, MathHelper.Up)
             * Matrix.PerspectiveFovRH(MathHelper.PiOver4, 4f / 3f, 0.1f, 1000f);*/


            var diffuseShaderVariable = effect.GetVariableByName("txDiffuse").AsResource();
            var worldParam            = effect.GetVariableByName("world").AsMatrix();
            //worldParam.AsMatrix().SetMatrix(world);


            var viewProjParam = effect.GetVariableBySemantic("viewprojection").AsMatrix();

            /*viewProjParam.SetMatrix(
             *  viewProjection);*/

            //worldParam.SetMatrix(Matrix.Identity);
            //effect.GetVariableBySemantic("viewprojection").AsMatrix().SetMatrix(Matrix.Identity);

            var texturePath = Wallpaper001_png;

            var diffuseTexture = Texture2D.FromFile(device, texturePath);

            var diffuseTextureRv = new ShaderResourceView(device, diffuseTexture);


            diffuseShaderVariable.SetResource(diffuseTextureRv);


            var rasterizerState = RasterizerState.FromDescription(device, new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid
            });

            device.ImmediateContext.Rasterizer.State = rasterizerState;


            var cam = new SpectaterCamera();

            game.GameLoopEvent += delegate
            {
                mouse.UpdateMouseState(m.GetCurrentState());
                keyboard.UpdateKeyboardState(kb.GetCurrentState());
                cam.Update(0.001f, keyboard, mouse);

                device.ImmediateContext.InputAssembler.InputLayout       = layout;
                device.ImmediateContext.InputAssembler.PrimitiveTopology =
                    PrimitiveTopology.TriangleList;
                device.ImmediateContext.InputAssembler.SetVertexBuffers(0,
                                                                        new VertexBufferBinding
                                                                            (vertices,
                                                                            vertexStride, 0));

                for (int i = 0; i < technique.Description.PassCount; ++i)
                {
                    pass.Apply(device.ImmediateContext);
                    device.ImmediateContext.Draw(3, 0);
                }

                viewProjParam.SetMatrix(cam.ViewProjection);
                worldParam.SetMatrix(Matrix.Identity);
                if (keyboard.IsKeyDown(Key.Escape))
                {
                    game.Exit();
                }
            };

            game.Run();

            bytecode.Dispose();
            effect.Dispose();
            layout.Dispose();
            vertices.Dispose();
            diffuseTexture.Dispose();
            diffuseTextureRv.Dispose();
            rasterizerState.Dispose();
            kb.Dispose();
            m.Dispose();
            dev.Dispose();
        }
Example #22
0
        public void TestDirectX11SimpleShader()
        {
            var game = new DX11Form();

            game.InitDirectX();
            var device    = game.Device;
            var bytecode  = ShaderBytecode.CompileFromFile("../../Common.Core/Shaders/MiniTri.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
            var effect    = new Effect(device, bytecode);
            var technique = effect.GetTechniqueByName("Render");
            var pass      = technique.GetPassByIndex(0);
            var layout    = new InputLayout(device, pass.Description.Signature,
                                            new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0)
            });

            var vertexStride = (16 + 16 + 8);
            var stream       = new DataStream(3 * vertexStride, true, true);

            stream.WriteRange(new[] {
                new VertexCustom(new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector2(0.5f, 0)),
                new VertexCustom(new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector2(0f, 1f)),
                new VertexCustom(new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector2(1f, 1f))
            });
            stream.Position = 0;

            var vertices = new SlimDX.Direct3D11.Buffer(device, stream, new BufferDescription()
            {
                BindFlags      = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,
                SizeInBytes    = 3 * vertexStride,
                Usage          = ResourceUsage.Default
            });

            stream.Dispose();


            var diffuseShaderVariable = effect.GetVariableByName("txDiffuse").AsResource();

            var texturePath = Wallpaper001_png;

            var diffuseTexture = Texture2D.FromFile(device, texturePath);

            var diffuseTextureRv = new ShaderResourceView(device, diffuseTexture);


            diffuseShaderVariable.SetResource(diffuseTextureRv);


            game.GameLoopEvent += delegate
            {
                device.ImmediateContext.InputAssembler.InputLayout       = layout;
                device.ImmediateContext.InputAssembler.PrimitiveTopology =
                    PrimitiveTopology.TriangleList;
                device.ImmediateContext.InputAssembler.SetVertexBuffers(0,
                                                                        new VertexBufferBinding
                                                                            (vertices,
                                                                            vertexStride, 0));

                for (int i = 0; i < technique.Description.PassCount; ++i)
                {
                    pass.Apply(device.ImmediateContext);
                    device.ImmediateContext.Draw(3, 0);
                }
            };

            game.Run();


            bytecode.Dispose();
            effect.Dispose();
            layout.Dispose();
            vertices.Dispose();
            diffuseTexture.Dispose();
            diffuseTextureRv.Dispose();
        }
Example #23
0
 private void InitializeEffect()
 {
     using (var shaderByteCode = ShaderBytecode.CompileFromFile("edge.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None)) {
         effect = new Dx11.Effect(device, shaderByteCode);
     }
 }
Example #24
0
 private void RenderFront(PlaneBoard arg1, SlimDX.Direct3D11.Effect arg2, ShaderResourceView arg3)
 {
     arg1.DefaultEffectSubscribe();
     effect.GetVariableBySemantic("NOISETEX").AsResource().SetResource(noiseView);
     effect.GetVariableBySemantic("TIME").AsScalar().Set(lastTime);
 }
Example #25
0
 protected void SetAsVector(Vector3 vec, SlimDX.Direct3D11.Effect effect, int index)
 {
     effect.GetVariableByIndex(index).AsVector().Set(vec);
 }
Example #26
0
        // Zavedenie zdrojov
        public void LoadResources(DX11.Device device)
        {
            Vertex[] vertices;
            short[]  indices;
            if (telesoObjektu.Equals("Ihlan"))
            {
                //Ihlan - pyramid
                vertices = new Vertex[]
                {
                    new Vertex(new Vector3(-1, -1, 1), Color.Red.ToArgb()),
                    new Vertex(new Vector3(1, -1, 1), Color.LightBlue.ToArgb()),
                    new Vertex(new Vector3(-1, -1, -1), Color.LightCyan.ToArgb()),
                    new Vertex(new Vector3(1, -1, -1), Color.CadetBlue.ToArgb()),
                    new Vertex(new Vector3(0, 2, 0), Color.Yellow.ToArgb()),
                };

                indices = new short[]
                {
                    //Podstava
                    0, 2, 1,
                    1, 2, 3,
                    //Steny
                    0, 1, 4,
                    1, 3, 4,
                    3, 2, 4,
                    2, 0, 4
                };
            }
            else
            {
                //Kocka - box
                vertices = new Vertex[]   //Matica 8 vrcholov
                {
                    new Vertex(new Vector3(-1, -1, -1), Color.Red.ToArgb()),
                    new Vertex(new Vector3(1, -1, -1), Color.LightBlue.ToArgb()),
                    new Vertex(new Vector3(1, -1, 1), Color.LightCyan.ToArgb()),
                    new Vertex(new Vector3(-1, -1, 1), Color.CadetBlue.ToArgb()),
                    new Vertex(new Vector3(-1, 1, -1), Color.Red.ToArgb()),
                    new Vertex(new Vector3(1, 1, -1), Color.Orange.ToArgb()),
                    new Vertex(new Vector3(1, 1, 1), Color.Goldenrod.ToArgb()),
                    new Vertex(new Vector3(-1, 1, 1), Color.Yellow.ToArgb())
                };

                indices = new short[] //Matica 36 indexov
                {
                    4, 1, 0, 4, 5, 1, //Stena 1 ...
                    5, 2, 1, 5, 6, 2,
                    6, 3, 2, 6, 7, 3,
                    7, 0, 3, 7, 4, 0,
                    7, 5, 4, 7, 6, 5,
                    2, 3, 0, 2, 0, 1
                };
            }



            DataStream outStream      = new DataStream(8 * Marshal.SizeOf(typeof(Vertex)), true, true); //Inicializácia objektu typu DataStream pre vertex buffer
            DataStream outStreamIndex = new DataStream(36 * Marshal.SizeOf(typeof(short)), true, true); //Index buffer

            for (int loop = 0; loop < vertices.Length; loop++)                                          //Načítanie hodnôt
            {
                outStream.Write <Vertex>(vertices[loop]);
            }

            for (int loop = 0; loop < indices.Length; loop++)     //Načítanie hodnôt
            {
                outStreamIndex.Write <short>(indices[loop]);
            }

            outStream.Position      = 0;   //Nastavenie polohy
            outStreamIndex.Position = 0;

            DX11.BufferDescription bufferDescription = new DX11.BufferDescription();
            bufferDescription.BindFlags      = DX11.BindFlags.VertexBuffer;
            bufferDescription.CpuAccessFlags = DX11.CpuAccessFlags.None;
            bufferDescription.OptionFlags    = DX11.ResourceOptionFlags.None;
            bufferDescription.SizeInBytes    = 8 * Marshal.SizeOf(typeof(Vertex));
            bufferDescription.Usage          = DX11.ResourceUsage.Default;

            DX11.BufferDescription bufferDescriptionIndex = new DX11.BufferDescription();
            bufferDescriptionIndex.BindFlags      = DX11.BindFlags.IndexBuffer;
            bufferDescriptionIndex.CpuAccessFlags = DX11.CpuAccessFlags.None;
            bufferDescriptionIndex.OptionFlags    = DX11.ResourceOptionFlags.None;
            bufferDescriptionIndex.SizeInBytes    = 36 * Marshal.SizeOf(typeof(short));
            bufferDescriptionIndex.Usage          = DX11.ResourceUsage.Default;

            m_vertexBuffer = new DX11.Buffer(device, outStream, bufferDescription);           //Inicializácia pre vertex buffer
            m_indexBuffer  = new DX11.Buffer(device, outStreamIndex, bufferDescriptionIndex); //Index buffer
            outStream.Close();
            outStreamIndex.Close();

            //Preloženie efektového súboru (HLSL) a priradenie objektu m_ShaderByteCode
            D3DCompiler.ShaderBytecode m_shaderByteCode =
                D3DCompiler.ShaderBytecode.CompileFromFile("Shader1.fx",
                                                           "fx_5_0",
                                                           D3DCompiler.ShaderFlags.None,
                                                           D3DCompiler.EffectFlags.None);

            m_effect            = new DX11.Effect(device, m_shaderByteCode);              //Objekt pre správu množiny stavovývh objektov, zdrojov a šejdrov pre implementáciu D3D renderovacieho efektu
            m_effectTechnique   = m_effect.GetTechniqueByIndex(0);                        //Získať techniku cez index
            m_effectPass        = m_effectTechnique.GetPassByIndex(0);                    //Získať prechod cez index
            m_transformVariable = m_effect.GetVariableByName("WorldViewProj").AsMatrix(); //Získanie premennej cez meno

            DX11.InputElement[] m_inputElements = new DX11.InputElement[]                 //Parameter pre metódu InputLayout
            {
                new DX11.InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32B32_Float, 0, 0),
                new DX11.InputElement("COLOR", 0, SlimDX.DXGI.Format.R8G8B8A8_UNorm, 12, 0)
            };
            m_vertexLayout = new DX11.InputLayout(device, m_effectPass.Description.Signature, m_inputElements); //Vytvorenie objektu pre opis vstupu pre "Input assembler stage"
        }
Example #27
0
 protected void SetAsFloat(float val, SlimDX.Direct3D11.Effect effect, int index)
 {
     effect.GetVariableByIndex(index).AsScalar().Set(val);
 }
Example #28
0
        private void ParseStandardGlobal(SlimDX.Direct3D11.Effect effect, EffectVariable sg)
        {
            if (!sg.Description.Name.ToLower().Equals("script"))
            {
                throw new InvalidMMEEffectShaderException(
                          string.Format("STANDARDGLOBALセマンティクスの指定される変数名は\"Script\"である必要があります、指定された変数名は\"{0}\"でした。",
                                        sg.Description.Name));
            }
            if (!sg.GetVariableType().Description.TypeName.ToLower().Equals("float"))
            {
                throw new InvalidMMEEffectShaderException(
                          string.Format("STANDARDGLOBALセマンティクスの指定される変数型は\"float\"である必要があります、指定された変数名は\"{0}\"でした。",
                                        sg.GetVariableType().Description.TypeName.ToLower()));
            }
            if (sg.AsScalar().GetFloat() != 0.8f)
            {
                throw new InvalidMMEEffectShaderException(
                          string.Format("STANDARDGLOBALセマンティクスの指定される値は\"0.8\"である必要があります、指定された値は\"{0}\"でした。",
                                        sg.AsScalar().GetFloat()));
            }
            //ScriptOutputの解析
            EffectVariable soVal = EffectParseHelper.getAnnotation(sg, "ScriptOutput", "string");

            if (soVal != null)
            {
                if (!soVal.AsString().GetString().Equals("color"))
                {
                    throw new InvalidMMEEffectShaderException(
                              string.Format(
                                  "STANDARDGLOBALセマンティクスの指定される変数のアノテーション「string ScriptOutput」は、\"color\"でなくてはなりません。指定された値は\"{0}\"でした。",
                                  soVal.AsString().GetString().ToLower()));
                }
            }
            EffectVariable scVal = EffectParseHelper.getAnnotation(sg, "ScriptClass", "string");

            if (scVal != null)
            {
                string sc = scVal.AsString().GetString();
                switch (sc.ToLower())
                {
                case "object":
                    ScriptClass = ScriptClass.Object;
                    break;

                case "scene":
                    ScriptClass = ScriptClass.Scene;
                    break;

                case "sceneorobject":
                    ScriptClass = ScriptClass.SceneOrObject;
                    break;

                default:
                    throw new InvalidMMEEffectShaderException(
                              string.Format(
                                  "STANDARDGLOBALセマンティクスの指定される変数のアノテーション「string ScriptClass」は、\"object\",\"scene\",\"sceneorobject\"でなくてはなりません。指定された値は\"{0}\"でした。(スペルミス?)",
                                  sc.ToLower()));
                }
            }
            EffectVariable sorVal = EffectParseHelper.getAnnotation(sg, "ScriptOrder", "string");

            if (sorVal != null)
            {
                string sor = sorVal.AsString().GetString();
                switch (sor.ToLower())
                {
                case "standard":
                    ScriptOrder = ScriptOrder.Standard;
                    break;

                case "preprocess":
                    ScriptOrder = ScriptOrder.Preprocess;
                    break;

                case "postprocess":
                    ScriptOrder = ScriptOrder.Postprocess;
                    break;

                default:
                    throw new InvalidMMEEffectShaderException(
                              string.Format(
                                  "STANDARDGLOBALセマンティクスの指定される変数のアノテーション「string ScriptOrder」は、\"standard\",\"preprocess\",\"postprocess\"でなくてはなりません。指定された値は\"{0}\"でした。(スペルミス?)",
                                  sor.ToLower()));
                }
            }
            EffectVariable scrVal = EffectParseHelper.getAnnotation(sg, "Script", "string");

            if (scrVal != null)
            {
                StandardGlobalScript = scrVal.AsString().GetString();
                if (string.IsNullOrEmpty(StandardGlobalScript))
                {
                    for (int i = 0; i < effect.Description.TechniqueCount; i++)
                    {
                        SortedTechnique.Add(effect.GetTechniqueByIndex(i));
                    }
                }
                else
                {
                    string[] scriptChunks = StandardGlobalScript.Split(';');
                    if (scriptChunks.Length == 1)
                    {
                        throw new InvalidMMEEffectShaderException(
                                  string.Format("STANDARDGLOBALセマンティクスの指定される変数のスクリプト「{0}」は読み込めませんでした。\";\"が足りません。",
                                                StandardGlobalScript));
                    }
                    string targetScript = scriptChunks[scriptChunks.Length - 2]; //最後のセミコロンが付いているスクリプト以外は無視
                    if (StandardGlobalScript.IndexOf("?") == -1)                 //見つからない時
                    {
                        string[] args = targetScript.Split('=');
                        if (args.Length > 2)
                        {
                            throw new InvalidMMEEffectShaderException(
                                      string.Format("STANDARDGLOBALセマンティクスの指定される変数のスクリプト「{0}」は読み込めませんでした。\"=\"の数が多すぎます。",
                                                    targetScript));
                        }
                        if (!args[0].ToLower().Equals("technique"))
                        {
                            throw new InvalidMMEEffectShaderException(
                                      string.Format(
                                          "STANDARDGLOBALセマンティクスの指定される変数のスクリプト「{0}」は読み込めませんでした。\"{1}\"は\"Technique\"であるべきです。(スペルミス?)",
                                          targetScript, args[0]));
                        }
                        EffectTechnique technique = effect.GetTechniqueByName(args[1]);
                        if (technique != null)
                        {
                            SortedTechnique.Add(technique);
                        }
                        else
                        {
                            throw new InvalidMMEEffectShaderException(
                                      string.Format(
                                          "STANDARDGLOBALセマンティクスの指定される変数のスクリプト「{0}」は読み込めませんでした。テクニック\"{1}\"は存在しません。(スペルミス?)",
                                          targetScript, args[1]));
                        }
                    }
                    else //?が見つかるとき
                    {
                        string[] args = targetScript.Split('?');
                        if (args.Length == 2)
                        {
                            string[] techniques = args[1].Split(':');
                            foreach (string technique in techniques)
                            {
                                EffectTechnique effectTechnique = effect.GetTechniqueByName(technique);
                                if (effectTechnique != null)
                                {
                                    SortedTechnique.Add(effectTechnique);
                                }
                                else
                                {
                                    throw new InvalidMMEEffectShaderException(
                                              string.Format(
                                                  "STANDARDGLOBALセマンティクスの指定される変数のスクリプト「{0}」は読み込めませんでした。テクニック\"{1}\"は見つかりません。(スペルミス?)",
                                                  targetScript, technique));
                                }
                            }
                        }
                        else if (args.Length > 2)
                        {
                            throw new InvalidMMEEffectShaderException(
                                      string.Format("STANDARDGLOBALセマンティクスの指定される変数のスクリプト「{0}」は読み込めませんでした。\"?\"の数が多すぎます。",
                                                    targetScript));
                        }
                    }
                    if (scriptChunks.Length > 2)
                    {
                        Debug.WriteLine(
                            string.Format(
                                "STANDARDGLOBALセマンティクスの指定される変数のスクリプト「{0}」では、複数回Techniqueの代入が行われていますが、最後の代入以外は無視されます。",
                                StandardGlobalScript));
                    }
                }
            }
        }
Example #29
0
 private void CompileShader(string effectName)
 {
     using (var shaderByteCode = ShaderBytecode.CompileFromFile(effectName, "fx_5_0", ShaderFlags.None, EffectFlags.None)) {
         effect = new Dx11.Effect(device, shaderByteCode);
     }
 }
Example #30
0
        /// <summary>
        ///     コンストラクタ
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="context"></param>
        /// <param name="effect">解釈対象のエフェクト</param>
        /// <param name="model">使用対象のモデル</param>
        /// <param name="loader"></param>
        private MMEEffectManager(string fileName, RenderContext context, SlimDX.Direct3D11.Effect effect, IDrawable model, ISubresourceLoader loader)
        {
            this.fileName     = fileName;
            SubresourceLoader = loader;
            if (!fileName.Equals(MMFDefaultShaderResourcePath))
            {
                //ファイルパスがデフォルトのシェーダーと等しくない時は、デフォルトのシェーダーも読み込んでおく。
                DefaultShader = LoadFromResource(MMFDefaultShaderResourcePath, model, context, new BasicSubresourceLoader("Shader"));
            }
            else
            {
                DefaultShader = this; //等しい時は自身がデフォルトのシェーダーと等しい。
            }
            Context    = context;
            EffectFile = effect;
            EffectInfo = new MMEEffectInfo(effect);
            ActiveSubscriberByMaterial = new Dictionary <EffectVariable, SubscriberBase>();
            ActiveSubscriberByModel    = new Dictionary <EffectVariable, SubscriberBase>();
            ActivePeculiarSubscriber   = new Dictionary <EffectVariable, PeculiarValueSubscriberBase>();
            Techniques = new List <MMEEffectTechnique>();
            RenderColorTargetViewes   = new Dictionary <string, RenderTargetView>();
            RenderDepthStencilTargets = new Dictionary <string, DepthStencilView>();
            this.model = model;
            //グローバル変数の登録
            int valCount = effect.Description.GlobalVariableCount;

            for (int i = 0; i < valCount; i++)
            {
                string semantic         = Regex.Replace(effect.GetVariableByIndex(i).Description.Semantic, "[0-9]", "");
                string semanticIndexStr = Regex.Replace(effect.GetVariableByIndex(i).Description.Semantic, "[^0-9]", "");
                int    semanticIndex    = string.IsNullOrEmpty(semanticIndexStr)?0:int.Parse(semanticIndexStr);
                string typeName         = effect.GetVariableByIndex(i).GetVariableType().Description.TypeName.ToLower();
                semantic = semantic.ToUpper(); //小文字でもいいようにするため大文字に全て変換
                if (EffectSubscriber.ContainsKey(semantic))
                {                              //通常はセマンティクスに応じて登録
                    SubscriberBase subs     = EffectSubscriber[semantic];
                    EffectVariable variable = effect.GetVariableByIndex(i);
                    subs.CheckType(variable);
                    if (subs.UpdateTiming == UpdateBy.Material)
                    {
                        ActiveSubscriberByMaterial.Add(variable, subs.GetSubscriberInstance(variable, context, this, semanticIndex));
                    }
                    else
                    {
                        ActiveSubscriberByModel.Add(variable, subs.GetSubscriberInstance(variable, context, this, semanticIndex));
                    }
                }
                else if (typeName.Equals("texture") || typeName.Equals("texture2d") || typeName.Equals("texture3d") ||
                         typeName.Equals("texturecube")) //テクスチャのみ例外で、変数型に応じて登録する
                {
                    SubscriberBase subs     = new TextureSubscriber();
                    EffectVariable variable = effect.GetVariableByIndex(i);
                    subs.CheckType(variable);
                    ActiveSubscriberByModel.Add(variable, subs.GetSubscriberInstance(variable, context, this, semanticIndex));
                }
                else//特殊変数は変数名に応じて登録する
                {
                    string name = effect.GetVariableByIndex(i).Description.Name;
                    name = name.ToLower();
                    if (PeculiarEffectSubscriber.ContainsKey(name))
                    {
                        ActivePeculiarSubscriber.Add(effect.GetVariableByIndex(i), PeculiarEffectSubscriber[name]);
                    }
                }
            }
            //定数バッファの登録
            valCount = effect.Description.ConstantBufferCount;
            for (int i = 0; i < valCount; i++)
            {
                string name = effect.GetConstantBufferByIndex(i).Description.Name;
                name = name.ToUpper();
                if (EffectSubscriber.ContainsKey(name))
                {
                    SubscriberBase       subs     = EffectSubscriber[name]; //定数バッファにはセマンティクスが付けられないため、変数名で代用
                    EffectConstantBuffer variable = effect.GetConstantBufferByIndex(i);
                    subs.CheckType(variable);
                    if (subs.UpdateTiming == UpdateBy.Material)
                    {
                        ActiveSubscriberByMaterial.Add(variable, subs.GetSubscriberInstance(variable, context, this, 0));
                    }
                    else
                    {
                        ActiveSubscriberByModel.Add(variable, subs.GetSubscriberInstance(variable, context, this, 0));
                    }
                }
            }

            int subsetCount = model is ISubsetDivided ? ((ISubsetDivided)model).SubsetCount : 1;

            foreach (EffectTechnique t in EffectInfo.SortedTechnique)//MMEEffectTechniqueもソートしておく
            {
                //テクニックをすべて読みだす
                Techniques.Add(new MMEEffectTechnique(this, t, subsetCount, context));
            }
        }
Example #31
0
 /// <summary>
 ///     MMEのエフェクトとして読み込む
 /// </summary>
 /// <param name="str">エフェクトのパス</param>
 /// <param name="model">使用対象のモデル</param>
 /// <param name="context"></param>
 /// <param name="loader"></param>
 /// <param name="device">デバイス</param>
 /// <returns>MME仕様のエフェクト</returns>
 internal static MMEEffectManager LoadFromResource(string str, IDrawable model, RenderContext context, ISubresourceLoader loader)
 {
     SlimDX.Direct3D11.Effect effect = CGHelper.CreateEffectFx5FromResource(str, context.DeviceManager.Device);
     return(new MMEEffectManager(str, context, effect, model, loader));
 }
Example #32
0
        public LightingDemo(IntPtr hInstance) : base(hInstance)
        {
            _landVB       = null;
            _landIB       = null;
            _waveVB       = null;
            _waveIB       = null;
            _fx           = null;
            _tech         = null;
            _fxWorld      = null;
            _fxWIT        = null;
            _fxEyePosW    = null;
            _fxDirLight   = null;
            _fxPointLight = null;
            _fxSpotLight  = null;
            _fxMaterial   = null;
            _fxWVP        = null;
            _inputLayout  = null;
            _eyePosW      = new Vector3();
            _theta        = 1.5f * MathF.PI;
            _phi          = 0.1f * MathF.PI;
            _radius       = 80.0f;

            MainWindowCaption = "Lighting Demo";

            _lastMousePos = new Point();

            _landWorld  = Matrix.Identity;
            _wavesWorld = Matrix.Translation(0, -3.0f, 0);
            _view       = Matrix.Identity;
            _proj       = Matrix.Identity;

            _dirLight = new DirectionalLight {
                Ambient   = new Color4(0.2f, 0.2f, 0.2f),
                Diffuse   = new Color4(0.5f, 0.5f, 0.5f),
                Specular  = new Color4(0.5f, 0.5f, 0.5f),
                Direction = new Vector3(0.57735f, -0.57735f, 0.57735f)
            };

            _pointLight = new PointLight {
                Ambient     = new Color4(0.3f, 0.3f, 0.3f),
                Diffuse     = new Color4(0.7f, 0.7f, 0.7f),
                Specular    = new Color4(0.7f, 0.7f, 0.7f),
                Attenuation = new Vector3(0.0f, 0.1f, 0.0f),
                Range       = 25.0f
            };
            _spotLight = new SpotLight {
                Ambient     = new Color4(0, 0, 0),
                Diffuse     = new Color4(1.0f, 1.0f, 0.0f),
                Specular    = Color.White,
                Attenuation = new Vector3(1.0f, 0.0f, 0.0f),
                Spot        = 96.0f,
                Range       = 10000.0f
            };

            // NOTE: must put alpha (spec power) first, rather than last as in book code
            _landMaterial = new Material {
                Ambient  = new Color4(1.0f, 0.48f, 0.77f, 0.46f),
                Diffuse  = new Color4(1.0f, 0.48f, 0.77f, 0.46f),
                Specular = new Color4(16.0f, 0.2f, 0.2f, 0.2f)
            };
            _wavesMaterial = new Material {
                Ambient  = new Color4(0.137f, 0.42f, 0.556f),
                Diffuse  = new Color4(0.137f, 0.42f, 0.556f),
                Specular = new Color4(96.0f, 0.8f, 0.8f, 0.8f)
            };
        }
Example #33
0
        private void BuildFX() {
            ShaderBytecode compiledShader = null;
            try {
                compiledShader = new ShaderBytecode(new DataStream(File.ReadAllBytes("fx/Lighting.fxo"), false, false));
                _fx = new Effect(Device, compiledShader);
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
                return;
            } finally {
                Util.ReleaseCom(ref compiledShader);
            }

            _tech = _fx.GetTechniqueByName("LightTech");
            _fxWVP = _fx.GetVariableByName("gWorldViewProj").AsMatrix();
            _fxWorld = _fx.GetVariableByName("gWorld").AsMatrix();
            _fxWIT = _fx.GetVariableByName("gWorldInvTranspose").AsMatrix();
            _fxEyePosW = _fx.GetVariableByName("gEyePosW").AsVector();
            _fxDirLight = _fx.GetVariableByName("gDirLight");
            _fxPointLight = _fx.GetVariableByName("gPointLight");
            _fxSpotLight = _fx.GetVariableByName("gSpotLight");
            _fxMaterial = _fx.GetVariableByName("gMaterial");
        }
Example #34
0
        public LightingDemo(IntPtr hInstance) : base(hInstance) {
            _landVB = null;
            _landIB = null;
            _waveVB = null;
            _waveIB = null;
            _fx = null;
            _tech = null;
            _fxWorld = null;
            _fxWIT = null;
            _fxEyePosW = null;
            _fxDirLight = null;
            _fxPointLight = null;
            _fxSpotLight = null;
            _fxMaterial = null;
            _fxWVP = null;
            _inputLayout = null;
            _eyePosW = new Vector3();
            _theta = 1.5f*MathF.PI;
            _phi = 0.1f*MathF.PI;
            _radius = 80.0f;

            MainWindowCaption = "Lighting Demo";

            _lastMousePos = new Point();

            _landWorld = Matrix.Identity;
            _wavesWorld = Matrix.Translation(0, -3.0f, 0);
            _view = Matrix.Identity;
            _proj = Matrix.Identity;

            _dirLight = new DirectionalLight {
                Ambient = new Color4(0.2f, 0.2f, 0.2f),
                Diffuse = new Color4(0.5f, 0.5f, 0.5f),
                Specular = new Color4(0.5f, 0.5f, 0.5f),
                Direction = new Vector3(0.57735f, -0.57735f, 0.57735f)
            };

            _pointLight = new PointLight {
                Ambient = new Color4(0.3f, 0.3f, 0.3f),
                Diffuse = new Color4(0.7f, 0.7f, 0.7f),
                Specular = new Color4(0.7f, 0.7f, 0.7f),
                Attenuation = new Vector3(0.0f, 0.1f, 0.0f),
                Range = 25.0f
            };
            _spotLight = new SpotLight {
                Ambient = new Color4(0,0,0),
                Diffuse = new Color4(1.0f, 1.0f, 0.0f),
                Specular = Color.White,
                Attenuation = new Vector3(1.0f, 0.0f, 0.0f),
                Spot = 96.0f,
                Range = 10000.0f
            };

            // NOTE: must put alpha (spec power) first, rather than last as in book code
            _landMaterial = new Material {
                Ambient = new Color4(1.0f, 0.48f, 0.77f, 0.46f),
                Diffuse = new Color4(1.0f, 0.48f, 0.77f, 0.46f),
                Specular = new Color4(16.0f, 0.2f, 0.2f, 0.2f)
            };
            _wavesMaterial = new Material {
                Ambient =  new Color4(0.137f, 0.42f, 0.556f),
                Diffuse = new Color4(0.137f, 0.42f, 0.556f),
                Specular = new Color4(96.0f, 0.8f, 0.8f, 0.8f)
            };

        }
Example #35
0
        private void BuildFX()
        {
            ShaderBytecode compiledShader = null;
            try {
                compiledShader = new ShaderBytecode(new DataStream(File.ReadAllBytes("fx/color.fxo"), false, false));
                _fx = new Effect(Device, compiledShader);
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
                return;
            } finally {
                Util.ReleaseCom(ref compiledShader);
            }

            _tech = _fx.GetTechniqueByName("ColorTech");
            _fxWVP = _fx.GetVariableByName("gWorldViewProj").AsMatrix();
        }