public void Apply()
        {
            if (m_stateBlock == null)
            {
                m_device.BeginStateBlock();
                m_device.SetRenderState(RenderState.CcwStencilZFail, CounterClockwiseStencilDepthBufferFail);
                m_device.SetRenderState(RenderState.CcwStencilFail, CounterClockwiseStencilFail);
                m_device.SetRenderState(RenderState.CcwStencilFunc, CounterClockwiseStencilFunction);
                m_device.SetRenderState(RenderState.CcwStencilPass, CounterClockwiseStencilPass);
                m_device.SetRenderState(RenderState.ZEnable, DepthBufferEnable);
                m_device.SetRenderState(RenderState.ZFunc, DepthBufferFunction);
                m_device.SetRenderState(RenderState.ZWriteEnable, DepthBufferWriteEnable);
                m_device.SetRenderState(RenderState.StencilRef, ReferenceStencil);
                m_device.SetRenderState(RenderState.StencilZFail, StencilDepthBufferFail);
                m_device.SetRenderState(RenderState.StencilEnable, StencilEnable);
                m_device.SetRenderState(RenderState.StencilFail, StencilFail);
                m_device.SetRenderState(RenderState.StencilFunc, StencilFunction);
                m_device.SetRenderState(RenderState.StencilMask, StencilMask);
                m_device.SetRenderState(RenderState.StencilPass, StencilPass);
                m_device.SetRenderState(RenderState.StencilWriteMask, StencilWriteMask);
                m_device.SetRenderState(RenderState.TwoSidedStencilMode, TwoSidedStencilMode);
                m_stateBlock = m_device.EndStateBlock();
                m_instances.Add(this);
            }

            m_stateBlock.Apply();

            Current = this;
        }
Пример #2
0
        public void Apply()
        {
            if (m_stateBlock == null)
            {
                m_device.BeginStateBlock();

                m_device.SetRenderState(RenderState.AlphaBlendEnable, true);
                m_device.SetRenderState(RenderState.AlphaFunc, Compare.Always);

                m_device.SetRenderState(RenderState.BlendOperationAlpha, AlphaBlendFunction);
                m_device.SetRenderState(RenderState.DestinationBlendAlpha, AlphaDestinationBlend);
                m_device.SetRenderState(RenderState.SourceBlendAlpha, AlphaSourceBlend);
                m_device.SetRenderState(RenderState.BlendFactor, BlendFactor.ToRgba());
                m_device.SetRenderState(RenderState.BlendOperation, ColorBlendFunction);
                m_device.SetRenderState(RenderState.DestinationBlend, ColorDestinationBlend);
                m_device.SetRenderState(RenderState.SourceBlend, ColorSourceBlend);

                m_device.SetRenderState(RenderState.ColorWriteEnable, ColorWriteChannels);
                m_device.SetRenderState(RenderState.ColorWriteEnable1, ColorWriteChannels1);
                m_device.SetRenderState(RenderState.ColorWriteEnable2, ColorWriteChannels2);
                m_device.SetRenderState(RenderState.ColorWriteEnable3, ColorWriteChannels3);

                m_stateBlock = m_device.EndStateBlock();
                m_instances.Add(this);
            }

            m_stateBlock.Apply();

            Current = this;
        }
Пример #3
0
        public override void EndRender()
        {
            if (!Enabled)
            {
                return;
            }

            try
            {
                stateBlock.Capture();

                Device.SetTransform(TransformState.World, RenderSettings.WorldMatrix);
                Device.SetTransform(TransformState.View, RenderSettings.ViewMatrix);
                Device.SetTransform(TransformState.Projection, RenderSettings.ProjectionMatrix);
                Device.SetRenderState(RenderState.AlphaBlendEnable, true);
                Device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha);
                Device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha);
                Device.SetRenderState(RenderState.ZFunc, Compare.Always);
                Device.SetRenderState(RenderState.ZWriteEnable, false);
                Device.SetTextureStageState(0, TextureStage.ColorArg1, TextureArgument.Diffuse);
                Device.SetTextureStageState(0, TextureStage.ColorArg2, TextureArgument.Current);
                Device.SetTextureStageState(0, TextureStage.ColorOperation, TextureOperation.SelectArg1);
                Device.VertexShader = null;
                Device.PixelShader  = null;
                Device.VertexFormat = VertexFormat.Position | VertexFormat.Diffuse;
                Device.SetStreamSource(0, lineBuffer.UnderlyingBuffer, 0, lineBuffer.ElementSize);
                Device.DrawPrimitives(PrimitiveType.LineList, 0, lineBuffer.Count / 2);
                lineBuffer.Clear();
            }
            finally
            {
                stateBlock.Apply();
            }
        }
 /// <summary>Render the dialog</summary>
 public void OnRender(float elapsedTime)
 {
     state.Capture();
     parent.Device.RenderState.FillMode = FillMode.Solid;
     dialog.OnRender(elapsedTime);
     state.Apply();
 }
Пример #5
0
        public void Render()    //渲染
        {
            if (device == null) //如果device为空则不渲染
            {
                return;
            }
            if (pause) //如果窗口被切换或者最小化则停止渲染,减少CPU压力
            {
                return;
            }

            Matrix viewMatrix = Matrix.LookAtLH(CamPostion, CamTarget, new Vector3(0, 1, 0));

            device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 0.3f, 500f);
            device.Transform.View       = viewMatrix;

            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.DarkSlateBlue, 1.0f, 0);  //清除windows界面为深蓝色
            device.BeginScene();
            //在此添加渲染图形代码
            device.RenderState.CullMode = Cull.None;
            device.RenderState.FillMode = FillMode.Solid;
            device.RenderState.Lighting = false;
            device.SetTexture(0, texture);//设置贴图

            device.VertexFormat = CustomVertex.PositionTextured.Format;
            device.SetStreamSource(0, vertexBuffer, 0);
            device.Indices = indexBuffer;
            device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, (xCount + 1) * (yCount + 1), 0, indices.Length / 3);

            device.Transform.World = Matrix.Translation(0.0f, 0.0f, 0.0f); //底部世界变换
            device.Material        = bottomMaterial;                       //底部使用的材质

            StateBlock sb = new StateBlock(device, StateBlockType.All);

            sb.Capture();//将device以前的设置保存到sb

            device.RenderState.DiffuseMaterialSource = ColorSource.Material;
            device.RenderState.AlphaBlendEnable      = true;
            device.SetTexture(0, bottomTexture);
            device.TextureState[0].ColorOperation = TextureOperation.Modulate;
            device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor;
            device.TextureState[0].ColorArgument2 = TextureArgument.Diffuse;
            device.TextureState[0].AlphaOperation = TextureOperation.Modulate;
            device.TextureState[0].AlphaArgument1 = TextureArgument.TextureColor;
            device.TextureState[0].AlphaArgument2 = TextureArgument.Diffuse;
            device.RenderState.SourceBlend        = Blend.SourceColor;
            device.RenderState.DestinationBlend   = Blend.InvSourceAlpha;
            device.SetStreamSource(0, bottomVertexBuffer, 0);
            device.VertexFormat = CustomVertex.PositionNormalTextured.Format;
            device.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);
            sb.Apply();

            device.EndScene();
            device.Present();
        }
Пример #6
0
        public void Render()            //渲染方法,本方法没有任何渲染代码,可认为是渲染方法的框架
        {
            if (device == null)         //如果未建立设备对象,退出
            {
                return;
            }
            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.WhiteSmoke, 1.0f, 0);
            device.BeginScene();                                                    //开始渲染
            //下句设置上方茶壶的世界变换矩阵
            device.Transform.World = Matrix.RotationYawPitchRoll(angleY, angleY, 0) //茶壶旋转
                                     * Matrix.Translation(0.0f, 1.5f, 5.0f);        //世界变换,y=0平面上方1.5f绘制茶壶
            device.Material = meshMaterials;
            mesh.DrawSubset(0);                                                     //绘制上方的茶壶
            //设置倒影茶壶世界变换矩阵,Matrix.Scaling(1,-1,1)将3D物体的Y轴坐标*(-1)
            //Matrix.Translation(0.0f, -1.5f, 5.0f),表示y=0平面下方1.5f绘制茶壶
            device.Transform.World = Matrix.RotationYawPitchRoll(angleY, angleY, 0) * //茶壶旋转
                                     Matrix.Scaling(1, -1, 1) * Matrix.Translation(0.0f, -1.5f, 5.0f);
            device.Lights[0].Direction  = new Vector3(0, 1, 4);                       //灯光方向从(0,0,0)到(0,1,4)
            device.RenderState.CullMode = Cull.Clockwise;                             //只绘制逆时针三角形
            mesh.DrawSubset(0);                                                       //绘制下边的茶壶
            device.Lights[0].Direction  = new Vector3(0, -1, 4);                      //恢复灯光方向
            device.RenderState.CullMode = Cull.CounterClockwise;                      //恢复背面剔除
            device.Transform.World      = Matrix.Translation(0.0f, 0.0f, 0.0f);       //世界变换
            device.Material             = mtr;                                        //地板使用的材质
            StateBlock sb = new StateBlock(device, StateBlockType.All);

            sb.Capture();//使用sb保存设置会降低运行速度,不建议使用,可采用使用后逐项恢复的方法
            device.RenderState.DiffuseMaterialSource = ColorSource.Material;
            device.RenderState.AlphaBlendEnable      = true;
            device.SetTexture(0, texture);
            device.TextureState[0].ColorOperation = TextureOperation.Modulate;
            device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor;
            device.TextureState[0].ColorArgument2 = TextureArgument.Diffuse;
            device.TextureState[0].AlphaOperation = TextureOperation.Modulate;
            device.TextureState[0].AlphaArgument1 = TextureArgument.TextureColor;
            device.TextureState[0].AlphaArgument2 = TextureArgument.Diffuse;
            device.RenderState.SourceBlend        = Blend.SourceColor;
            device.RenderState.DestinationBlend   = Blend.InvSourceAlpha;
            device.SetStreamSource(0, vertexBuffer, 0);
            device.VertexFormat = CustomVertex.PositionNormalTextured.Format;
            device.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);
            sb.Apply();
            device.EndScene(); //渲染结束
            device.Present();  //更新显示区域,把后备缓存的3D图形送到图形卡的屏幕显示区中显示
        }
Пример #7
0
        public void SaveTreeImage(string filename, ImageFileFormat format)
        {
            if (renderTarget == null)
            {
                renderTarget = new RenderTarget2D(GraphicsDevice, RenderTargetSize, RenderTargetSize, 1, SurfaceFormat.Color);
            }

            Camera.AspectRatio = 1.0f;

            GraphicsDevice.SetRenderTarget(0, renderTarget);
            //GraphicsDevice.Clear(Color.TransparentWhite);
            GraphicsDevice.Clear(BackgroundColor);

            /*
             * block.Apply();
             *
             * // First draw color only so the white background does not bleed onto transparent parts of the tree
             * GraphicsDevice.RenderState.ColorWriteChannels = ColorWriteChannels.Red | ColorWriteChannels.Green | ColorWriteChannels.Blue;
             *
             * GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
             * tree.DrawTrunk(treeWorld, Camera.View, Camera.Projection);
             *
             * tree.LeafEffect.CurrentTechnique = tree.LeafEffect.Techniques["SetNoRenderStates"];
             * GraphicsDevice.RenderState.AlphaTestEnable = true;
             * GraphicsDevice.RenderState.ReferenceAlpha = 127;
             * GraphicsDevice.RenderState.AlphaFunction = CompareFunction.Greater;
             * GraphicsDevice.RenderState.CullMode = CullMode.None;
             * GraphicsDevice.RenderState.DepthBufferEnable = true;
             * GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
             *
             * tree.DrawLeaves(treeWorld, Camera.View, Camera.Projection);
             *
             * tree.LeafEffect.CurrentTechnique = tree.LeafEffect.Techniques["Standard"];
             *
             * GraphicsDevice.RenderState.ColorWriteChannels = ColorWriteChannels.All;*/

            // Now draw the tree again, blending on top of the other tree
            block.Apply();
            tree.DrawTrunk(treeWorld, Camera.View, Camera.Projection);

            block.Apply();
            GraphicsDevice.SamplerStates[0].MipFilter = TextureFilter.Linear;
            tree.DrawLeaves(treeWorld, Camera.View, Camera.Projection);

            GraphicsDevice.SetRenderTarget(0, null);

            Texture2D texture = renderTarget.GetTexture();

            texture.Save(filename, format);

            Camera.AspectRatio = GraphicsDevice.Viewport.Width / (float)GraphicsDevice.Viewport.Height;
        }
Пример #8
0
        public void Apply()
        {
            if (m_stateBlock == null)
            {
                m_device.BeginStateBlock();
                m_device.SetRenderState(RenderState.CullMode, CullMode);
                m_device.SetRenderState(RenderState.DepthBias, DepthBias);
                m_device.SetRenderState(RenderState.FillMode, FillMode);
                m_device.SetRenderState(RenderState.MultisampleAntialias, MultiSampleAntiAlias);
                m_device.SetRenderState(RenderState.ScissorTestEnable, ScissorTestEnable);
                m_device.SetRenderState(RenderState.SlopeScaleDepthBias, SlopeScaleDepthBias);
                m_stateBlock = m_device.EndStateBlock();
                m_instances.Add(this);
            }

            m_stateBlock.Apply();

            Current = this;
        }
Пример #9
0
        public void Apply()
        {
            if (m_stateBlock == null)
            {
                m_device.BeginStateBlock();
                m_device.SetSamplerState(0, SharpDX.Direct3D9.SamplerState.AddressU, AddressU);
                m_device.SetSamplerState(0, SharpDX.Direct3D9.SamplerState.AddressV, AddressV);
                m_device.SetSamplerState(0, SharpDX.Direct3D9.SamplerState.AddressW, AddressW);

                m_device.SetSamplerState(0, SharpDX.Direct3D9.SamplerState.MagFilter, Filter);
                m_device.SetSamplerState(0, SharpDX.Direct3D9.SamplerState.MinFilter, Filter);
                m_device.SetSamplerState(0, SharpDX.Direct3D9.SamplerState.MipFilter, Filter);

                m_device.SetSamplerState(0, SharpDX.Direct3D9.SamplerState.MaxAnisotropy, MaxAnisotropy);
                m_device.SetSamplerState(0, SharpDX.Direct3D9.SamplerState.MaxMipLevel, MaxMipLevel);
                m_device.SetSamplerState(0, SharpDX.Direct3D9.SamplerState.MipMapLodBias, MipMapLevelOfDetailBias);
                m_stateBlock = m_device.EndStateBlock();
                m_instances.Add(this);
            }

            m_stateBlock.Apply();
        }
Пример #10
0
        protected void Render()
        {
            //Clear the backbuffer to a black color
            engine.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, System.Drawing.Color.Black, 1.0f, 0);

            SetupMatrices();
            initState.Capture();

            //Begin the scene
            engine.Device.BeginScene();
            foreach (IRenderable o in objects)
            {
                if (!(o is Object3D) || pov.IsInViewFrustum((Object3D)o))
                {
                    o.Render(engine.Device, engine.DeviceInfo);
                    initState.Apply();
                }
            }

            //End the scene
            engine.Device.EndScene();
        }
Пример #11
0
        public void Render()            //渲染方法,本方法没有任何渲染代码,可认为是渲染方法的框架
        {
            if (device == null)         //如果未建立设备对象,退出
            {
                return;
            }
            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.WhiteSmoke, 1.0f, 0);
            device.BeginScene();                        //开始渲染
            //下句设置上方茶壶的世界变换矩阵

            device.Transform.World = Matrix.Translation(0.0f, 0.0f, 0.0f); //世界变换
            device.Material        = bottomMaterial;                       //地板使用的材质

            StateBlock sb = new StateBlock(device, StateBlockType.All);

            sb.Capture();//使用sb保存设置会降低运行速度,不建议使用,可采用使用后逐项恢复的方法

            device.RenderState.DiffuseMaterialSource = ColorSource.Material;
            device.RenderState.AlphaBlendEnable      = true;
            device.SetTexture(0, bottomTexture);

            device.TextureState[0].ColorOperation = TextureOperation.Modulate;
            device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor;
            device.TextureState[0].ColorArgument2 = TextureArgument.Diffuse;
            device.TextureState[0].AlphaOperation = TextureOperation.Modulate;
            device.TextureState[0].AlphaArgument1 = TextureArgument.TextureColor;
            device.TextureState[0].AlphaArgument2 = TextureArgument.Diffuse;
            device.RenderState.SourceBlend        = Blend.SourceColor;
            device.RenderState.DestinationBlend   = Blend.InvSourceAlpha;

            device.SetStreamSource(0, bottomVertexBuffer, 0);
            device.VertexFormat = CustomVertex.PositionNormalTextured.Format;
            device.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);
            sb.Apply();
            device.EndScene(); //渲染结束
            device.Present();  //更新显示区域,把后备缓存的3D图形送到图形卡的屏幕显示区中显示
        }
Пример #12
0
        private void OnViewportRender(object sender, RenderEventArgs e)
        {
            foreach (IRenderBlock block in this._Model.Blocks)
            {
                using (var stateBlock = new StateBlock(e.Device, StateBlockMask.EnableAll()))
                {
                    stateBlock.Capture();

                    var dssd = new DepthStencilStateDescription();
                    dssd.IsDepthEnabled   = true;
                    dssd.DepthWriteMask   = DepthWriteMask.All;
                    dssd.DepthComparison  = Comparison.Less;
                    dssd.IsStencilEnabled = true;
                    dssd.StencilReadMask  = 0xFF;
                    dssd.StencilWriteMask = 0xFF;

                    var frontFace = new DepthStencilOperationDescription();
                    frontFace.FailOperation      = StencilOperation.Keep;
                    frontFace.DepthFailOperation = StencilOperation.Increment;
                    frontFace.PassOperation      = StencilOperation.Keep;
                    frontFace.Comparison         = Comparison.Always;
                    dssd.FrontFace = frontFace;

                    var backFace = new DepthStencilOperationDescription();
                    backFace.FailOperation      = StencilOperation.Keep;
                    backFace.DepthFailOperation = StencilOperation.Decrement;
                    backFace.PassOperation      = StencilOperation.Keep;
                    backFace.Comparison         = Comparison.Always;
                    dssd.BackFace = backFace;

                    e.Device.OutputMerger.DepthStencilState = DepthStencilState.FromDescription(e.Device, dssd);

                    var oldState = e.Device.Rasterizer.State.Description;
                    var state    = e.Device.Rasterizer.State.Description;
                    state.FillMode = _SelectedBlocks.Contains(block) == true
                                         ? FillMode.Wireframe
                                         : FillMode.Solid;
                    state.CullMode            = CullMode.None;
                    e.Device.Rasterizer.State = RasterizerState.FromDescription(e.Device, state);

                    if (this._BlockRenderers.ContainsKey(block) == false)
                    {
                        var renderer = RendererTypes.Instantiate(block);
                        if (renderer == null)
                        {
                            continue;
                        }

                        renderer.Setup(e.Device,
                                       block,
                                       this._ShaderBundle,
                                       this._ModelPath);
                        this._BlockRenderers.Add(block, renderer);
                        this._BlockRenderers[block].Render(e.Device, e.ViewProjectionMatrix);
                    }
                    else
                    {
                        this._BlockRenderers[block].Render(e.Device, e.ViewProjectionMatrix);
                    }

                    e.Device.Rasterizer.State = RasterizerState.FromDescription(e.Device, oldState);

                    stateBlock.Apply();
                }
            }
        }
Пример #13
0
    /// <summary>
    /// Draw some text on the screen
    /// </summary>
    public void DrawText(float xpos, float ypos, Color color, string text, RenderFlags flags)
    {
        if (text == null)
        {
            return;
        }

        // Setup renderstate
        savedStateBlock.Capture();
        drawTextStateBlock.Apply();
        device.SetTexture(0, fontTexture);
        device.VertexFormat = CustomVertex.TransformedColoredTextured.Format;
        device.PixelShader  = null;
        device.SetStreamSource(0, vertexBuffer, 0);

        // Set filter states
        if ((flags & RenderFlags.Filtered) != 0)
        {
            samplerState0.MinFilter = TextureFilter.Linear;
            samplerState0.MagFilter = TextureFilter.Linear;
        }

        // Adjust for character spacing
        xpos -= spacingPerChar;
        float fStartX = xpos;

        // Fill vertex buffer
        int iv             = 0;
        int dwNumTriangles = 0;

        foreach (char c in text)
        {
            if (c == '\n')
            {
                xpos  = fStartX;
                ypos += (textureCoords[0, 3] - textureCoords[0, 1]) * textureHeight;
            }

            if ((c - 32) < 0 || (c - 32) >= 128 - 32)
            {
                continue;
            }

            float tx1 = textureCoords[c - 32, 0];
            float ty1 = textureCoords[c - 32, 1];
            float tx2 = textureCoords[c - 32, 2];
            float ty2 = textureCoords[c - 32, 3];

            float w = (tx2 - tx1) * textureWidth / textureScale;
            float h = (ty2 - ty1) * textureHeight / textureScale;

            int intColor = color.ToArgb();
            if (c != ' ')
            {
                fontVertices[iv++] = new CustomVertex.TransformedColoredTextured(new Vector4(xpos + 0 - 0.5f, ypos + h - 0.5f, 0.9f, 1.0f), intColor, tx1, ty2);
                fontVertices[iv++] = new CustomVertex.TransformedColoredTextured(new Vector4(xpos + 0 - 0.5f, ypos + 0 - 0.5f, 0.9f, 1.0f), intColor, tx1, ty1);
                fontVertices[iv++] = new CustomVertex.TransformedColoredTextured(new Vector4(xpos + w - 0.5f, ypos + h - 0.5f, 0.9f, 1.0f), intColor, tx2, ty2);
                fontVertices[iv++] = new CustomVertex.TransformedColoredTextured(new Vector4(xpos + w - 0.5f, ypos + 0 - 0.5f, 0.9f, 1.0f), intColor, tx2, ty1);
                fontVertices[iv++] = new CustomVertex.TransformedColoredTextured(new Vector4(xpos + w - 0.5f, ypos + h - 0.5f, 0.9f, 1.0f), intColor, tx2, ty2);
                fontVertices[iv++] = new CustomVertex.TransformedColoredTextured(new Vector4(xpos + 0 - 0.5f, ypos + 0 - 0.5f, 0.9f, 1.0f), intColor, tx1, ty1);
                dwNumTriangles    += 2;

                if (dwNumTriangles * 3 > (MaxNumfontVertices - 6))
                {
                    // Set the data for the vertexbuffer
                    vertexBuffer.SetData(fontVertices, 0, LockFlags.Discard);
                    device.DrawPrimitives(PrimitiveType.TriangleList, 0, dwNumTriangles);
                    dwNumTriangles = 0;
                    iv             = 0;
                }
            }

            xpos += w - (2 * spacingPerChar);
        }

        // Set the data for the vertex buffer
        vertexBuffer.SetData(fontVertices, 0, LockFlags.Discard);
        if (dwNumTriangles > 0)
        {
            device.DrawPrimitives(PrimitiveType.TriangleList, 0, dwNumTriangles);
        }

        // Restore the modified renderstates
        savedStateBlock.Apply();
    }
Пример #14
0
        void DirectX_OnFrame(TimeSpan delta)
        {
            // Attempt to recreate the device if we removed it; WoW does weird device recreating after resetting it on a lost device
            if (Device == null || Device.Disposed)
            {
                DirectX_OnCreateDevice();
                return;
            }

            if (!IsEnabled || !IsReady())
            {
                return;
            }

            // If the device is currently in the lost state don't continue
            var cooplevel = Device.TestCooperativeLevel();

            if (cooplevel.IsFailure)
            {
                return;
            }

            // Store the game's render states
            state_old.Capture();

            var device = Device;

            //device.Clear(ClearFlags.All, Color.Gainsboro, 0, 0);
            // Clean up render states
            device.PixelShader  = null;
            device.VertexShader = null;
            device.SetTexture(0, null);
            device.SetRenderState(RenderState.Lighting, true);
            device.SetRenderState(RenderState.AlphaBlendEnable, false);
            device.SetRenderState(RenderState.AlphaTestEnable, false);
            device.SetRenderState(RenderState.BlendOperation, BlendOperation.Add);

            device.SetRenderState(RenderState.BlendFactor, Color.White.ToArgb());
            device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha);
            device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha);

            device.SetRenderState(RenderState.CullMode, Cull.None);
            device.SetRenderState(RenderState.ColorWriteEnable, ColorWriteEnable.All);
            device.SetRenderState(RenderState.FillMode, FillMode.Wireframe);

            device.SetRenderState(RenderState.ZEnable, false);

            // Force a white ambient material so we can apply the color through the global ambient color
            device.SetRenderState(RenderState.AmbientMaterialSource, ColorSource.Material);
            var mat = new Material();

            mat.Ambient     = new Color4(System.Drawing.Color.White);
            device.Material = mat;

            Matrix mat_view, mat_proj;

            if (GetCameraMatrices(out mat_proj, out mat_view))
            {
                device.SetTransform(TransformState.Projection, mat_proj);
                device.SetTransform(TransformState.View, mat_view);

                device.VertexDeclaration = vert_decl_nocolor;

                // Draw cubes
                device.SetStreamSource(0, vb_cube, 0, 12);
                foreach (var cube in Cubes)
                {
                    device.SetTransform(TransformState.World, Matrix.Scaling(cube.Scale) * Matrix.Translation(cube.Position));
                    device.SetRenderState(RenderState.Ambient, cube.Color);
                    device.DrawPrimitives(PrimitiveType.TriangleList, 0, 12);
                }

                // Draw lines
                device.SetTransform(TransformState.World, Matrix.Identity);
                Vector3[] line_data = new Vector3[2];
                foreach (var line in Lines)
                {
                    line_data[0] = line.Start;
                    line_data[1] = line.End;

                    device.SetRenderState(RenderState.Ambient, line.Color);
                    device.DrawUserPrimitives(PrimitiveType.LineList, 1, line_data);
                }

                // Draw rectangles
                Vector3[] rectangle_data = new Vector3[5];
                foreach (var rect in Rectangles)
                {
                    rectangle_data[0] = rect.Start;
                    rectangle_data[1] = rect.Start + Vector3.UnitX * (rect.End.X - rect.Start.X);
                    rectangle_data[2] = rect.Start + Vector3.UnitX * (rect.End.X - rect.Start.X) + Vector3.UnitY * (rect.End.Y - rect.Start.Y);
                    rectangle_data[3] = rect.Start + Vector3.UnitY * (rect.End.Y - rect.Start.Y);
                    rectangle_data[4] = rect.Start;

                    var world_matrix = Matrix.RotationQuaternion(rect.Rotation) * Matrix.Scaling(rect.Scale) * Matrix.Translation(rect.Position);
                    device.SetTransform(TransformState.World, world_matrix);

                    if (rect.FillColor.HasValue)
                    {
                        device.SetRenderState(RenderState.FillMode, FillMode.Solid);
                        device.SetRenderState(RenderState.Ambient, System.Drawing.Color.White.ToArgb());
                        device.DrawUserPrimitives(PrimitiveType.TriangleFan, 4, rectangle_data);
                        device.SetRenderState(RenderState.FillMode, FillMode.Wireframe);
                    }

                    device.SetRenderState(RenderState.Ambient, rect.Color);
                    device.DrawUserPrimitives(PrimitiveType.LineStrip, 4, rectangle_data);
                }

                // Draw circles

                /*var mat = new Material();
                 * mat.Ambient = new Color4(System.Drawing.Color.White);
                 * device.SetRenderState(RenderState.AmbientMaterialSource, ColorSource.Material);
                 * device.SetRenderState(RenderState.DiffuseMaterialSource, ColorSource.Material);*/

                foreach (var circle in Circles)
                {
                    var circle_points = new Vector3[circle.Steps + 2];
                    // A point in the center of the circle, to use when the triangle is filled
                    circle_points[0] = Vector3.Zero;
                    for (int i = 0; i < circle.Steps; i++)
                    {
                        var angle = ((float)i / circle.Steps) * Math.PI * 2;
                        circle_points[i + 1] = new Vector3((float)Math.Cos(angle), (float)Math.Sin(angle), 0);
                    }
                    circle_points[circle_points.Length - 1] = circle_points[1];

                    var world_matrix = Matrix.RotationQuaternion(circle.Rotation) * Matrix.Scaling(new Vector3(circle.Radius, circle.Radius, 1)) * Matrix.Translation(circle.Position);
                    device.SetTransform(TransformState.World, world_matrix);

                    /*if (circle.FillColor.HasValue) {
                     *  //mat.Diffuse = new Color4(0.5f, 1.0f, 0.0f, 0.0f); //circle.FillColor.Value;
                     *  mat.Ambient = circle.FillColor.Value;
                     *  device.Material = mat;
                     *  device.SetRenderState(RenderState.FillMode, FillMode.Solid);
                     *  device.DrawUserPrimitives(PrimitiveType.TriangleFan, circle.Steps, circle_points);
                     *  device.SetRenderState(RenderState.FillMode, FillMode.Wireframe);
                     * }*/

                    //mat.Ambient = circle.Color;
                    //device.Material = mat;
                    device.SetRenderState(RenderState.Ambient, circle.Color.ToArgb());
                    device.DrawUserPrimitives(PrimitiveType.LineStrip, circle_points.Length - 2, circle_points.Skip(1).ToArray());
                }

                // Draw labels
                var viewport = Device.Viewport;
                var viewproj = Matrix.Multiply(mat_view, mat_proj);
                foreach (var label in Labels)
                {
                    var transformed = Vector3.Project(label.Position, viewport.X, viewport.Y, viewport.Width, viewport.Height, viewport.MinZ, viewport.MaxZ, viewproj);
                    if (transformed.Z <= 1.0f)
                    {
                        GetFont(DefaultFont).DrawString(null, label.Text, (int)transformed.X, (int)transformed.Y, new Color4(label.Color));
                    }
                }

                //device.Material = new Material();
            }

            if (OnRender != null)
            {
                OnRender();
            }

            // Restore render states
            state_old.Apply();
        }
Пример #15
0
        private unsafe void ImGuiRenderDraw(DrawData *drawData)
        {
            if (drawData == null)
            {
                return;
            }
            var io = ImGui.GetIO();

            if (io.DisplaySize.X <= 0.0f || io.DisplaySize.Y <= 0.0f)
            {
                return;
            }
            var st = new StateBlock(device, StateBlockType.All);
            var vp = new Viewport();

            vp.X        = vp.Y = 0;
            vp.Width    = (int)io.DisplaySize.X;
            vp.Height   = (int)io.DisplaySize.Y;
            vp.MinDepth = 0.0f;
            vp.MaxDepth = 1.0f;

            device.Viewport     = vp;
            device.PixelShader  = null;
            device.VertexShader = null;
            device.SetRenderState(RenderState.CullMode, Cull.None);
            device.SetRenderState(RenderState.Lighting, false);
            device.SetRenderState(RenderState.ZEnable, false);
            device.SetRenderState(RenderState.AlphaBlendEnable, true);
            device.SetRenderState(RenderState.AlphaTestEnable, false);
            device.SetRenderState(RenderState.BlendOperation, BlendOperation.Add);
            device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha);
            device.SetRenderState(RenderState.DestinationBlend, Blend.BothInverseSourceAlpha);
            device.SetRenderState(RenderState.ScissorTestEnable, true);
            device.SetTextureStageState(0, TextureStage.ColorOperation, TextureOperation.Modulate);
            device.SetTextureStageState(0, TextureStage.ColorArg1, TextureArgument.Texture);
            device.SetTextureStageState(0, TextureStage.ColorArg2, TextureArgument.Diffuse);
            device.SetTextureStageState(0, TextureStage.AlphaOperation, TextureOperation.Modulate);
            device.SetTextureStageState(0, TextureStage.AlphaArg1, TextureArgument.Texture);
            device.SetTextureStageState(0, TextureStage.AlphaArg2, TextureArgument.Diffuse);
            device.SetSamplerState(0, SamplerState.MinFilter, TextureFilter.Linear);
            device.SetSamplerState(0, SamplerState.MagFilter, TextureFilter.Linear);
            // Setup orthographic projection matrix
            {
                const float L            = 0.5f;
                var         R            = io.DisplaySize.X + 0.5f;
                const float T            = 0.5f;
                var         B            = io.DisplaySize.Y + 0.5f;
                RawMatrix   mat_identity = new Matrix(1.0f, 0.0f, 0.0f, 0.0f,
                                                      0.0f, 1.0f, 0.0f, 0.0f,
                                                      0.0f, 0.0f, 1.0f, 0.0f,
                                                      0.0f, 0.0f, 0.0f, 1.0f);
                RawMatrix mat_projection = new Matrix(
                    2.0f / (R - L), 0.0f, 0.0f, 0.0f,
                    0.0f, 2.0f / (T - B), 0.0f, 0.0f,
                    0.0f, 0.0f, 0.5f, 0.0f,
                    (L + R) / (L - R), (T + B) / (B - T), 0.5f, 1.0f);
                device.SetTransform(TransformState.World, ref mat_identity);
                device.SetTransform(TransformState.View, ref mat_identity);
                device.SetTransform(TransformState.Projection, ref mat_projection);
            }
            using (device.VertexDeclaration = new VertexDeclaration(device, GuiVertex.VertexElements))
            {
                for (var n = 0; n < drawData->CmdListsCount; n++)
                {
                    var cmdList    = drawData->CmdLists[n];
                    var vtx_buffer = (DrawVert *)cmdList->VtxBuffer.Data;
                    var idx_buffer = (ushort *)cmdList->IdxBuffer.Data;

                    var myCustomVertices = new GuiVertex[cmdList->VtxBuffer.Size];

                    for (var i = 0; i < myCustomVertices.Length; i++)
                    {
                        var cl = (vtx_buffer[i].col & 0xFF00FF00) | ((vtx_buffer[i].col & 0xFF0000) >> 16) |
                                 ((vtx_buffer[i].col & 0xFF) << 16);
                        myCustomVertices[i] =
                            new GuiVertex(vtx_buffer[i].pos.X, vtx_buffer[i].pos.Y, vtx_buffer[i].uv.X,
                                          vtx_buffer[i].uv.Y, cl);
                    }

                    for (var i = 0; i < cmdList->CmdBuffer.Size; i++)
                    {
                        var pcmd = &((DrawCmd *)cmdList->CmdBuffer.Data)[i];

                        if (pcmd->UserCallback != IntPtr.Zero)
                        {
                            throw new NotImplementedException();
                        }
                        //Trace.WriteLine(pcmd->TextureId.ToString());
                        device.SetTexture(0, new Texture(pcmd->TextureId));
                        device.ScissorRect = new RectangleF((int)pcmd->ClipRect.X,
                                                            (int)pcmd->ClipRect.Y,
                                                            (int)(pcmd->ClipRect.Z - pcmd->ClipRect.X),
                                                            (int)(pcmd->ClipRect.W - pcmd->ClipRect.Y));
                        var indices = new ushort[pcmd->ElemCount];
                        for (var j = 0; j < indices.Length; j++)
                        {
                            indices[j] = idx_buffer[j];
                        }

                        device.DrawIndexedUserPrimitives(PrimitiveType.TriangleList, 0, myCustomVertices.Length,
                                                         (int)(pcmd->ElemCount / 3), indices, Format.Index16, myCustomVertices);
                        idx_buffer += pcmd->ElemCount;
                    }
                }
            }

            st.Apply();
            st.Dispose();
        }