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(); }
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(); }
protected override void Initialize() { content = new ContentManager(Services, "Content"); // Load all trees in the Content/Trees folder string[] files = Directory.GetFiles("Content/Trees", "*.xnb", SearchOption.TopDirectoryOnly); foreach (string filename in files) { string assetName = filename.Substring("Content/".Length, filename.Length - "Content/.xnb".Length); Profiles.Add(content.Load <TreeProfile>(assetName)); ProfileNames.Add(Path.GetFileName(assetName)); } profileIndex = 0; // Create the wind animator wind = new WindStrengthSin(); animator = new TreeWindAnimator(wind); // Create the ground plane and an effect for it groundPlane = new Quad(GraphicsDevice, 10000, 10000); groundEffect = new BasicEffect(GraphicsDevice, new EffectPool()); groundEffect.Texture = content.Load <Texture2D>("Textures/Grass"); groundEffect.TextureEnabled = true; // Create a camera Camera = new Camera(); Camera.Position = new Vector3(4000, 4000, 4000); Camera.Target = new Vector3(0, 2000, 0); Camera.AspectRatio = GraphicsDevice.Viewport.Width / (float)GraphicsDevice.Viewport.Height; CameraOrbitAngle = 0.0f; CameraPitchAngle = -10.0f; CameraDistance = 5000.0f; // Enable mipmaps GraphicsDevice.SamplerStates[0].MipFilter = TextureFilter.Linear; // Store the initial renderstate block = new StateBlock(GraphicsDevice); block.Capture(); Initialized = true; UpdateTree(); Application.Idle += new EventHandler(Application_Idle); }
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图形送到图形卡的屏幕显示区中显示 }
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(); }
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图形送到图形卡的屏幕显示区中显示 }
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(); } } }
/// <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(); }
private void pn3D_DeviceReset( object sender, EventArgs e ) { Device dev = pn3D.Device; depthTex1 = new Texture( dev, pn3D.ClientSize.Width, pn3D.ClientSize.Height, 1, Usage.RenderTarget, Format.A32B32G32R32F, Pool.Default ); depthTex2 = new Texture( dev, pn3D.ClientSize.Width, pn3D.ClientSize.Height, 1, Usage.RenderTarget, Format.A32B32G32R32F, Pool.Default ); defState = new StateBlock( dev, StateBlockType.All ); defState.Capture(); }
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(); }
private void pn3D_DeviceReset( object sender, EventArgs e ) { Device dev = pn3D.Device; dev.RenderState.ColorVertex = false; dev.RenderState.SourceBlend = Blend.SourceAlpha; dev.RenderState.DestinationBlend = Blend.InvSourceAlpha; dev.SamplerState[0].MagFilter = TextureFilter.Anisotropic; dev.SamplerState[0].MinFilter = TextureFilter.Linear; dev.SamplerState[0].MipFilter = TextureFilter.Linear; dev.SamplerState[0].MaxAnisotropy = 4; dev.SamplerState[1].MagFilter = TextureFilter.Anisotropic; dev.SamplerState[1].MinFilter = TextureFilter.Linear; dev.SamplerState[1].MipFilter = TextureFilter.Linear; dev.SamplerState[1].MaxAnisotropy = 4; defState = new StateBlock( dev, StateBlockType.All ); defState.Capture(); SelectionChanged(); //force a refresh of anything that depends on this }