static RasterizerState () { CullNone = Create( CullMode.CullNone ); CullCW = Create( CullMode.CullCW ); CullCCW = Create( CullMode.CullCCW ); Wireframe = Create( CullMode.CullNone, FillMode.Wireframe ); }
public RasterizerStateChangeCommand(RasterizerStateDescription rStateDesc) : base(CommandType.RasterizerStateChange) { CommandAttributes |= CommandAttributes.MonoRendering; Description = rStateDesc; rasterizerState = RasterizerState.FromDescription(Game.Context.Device, Description); }
public void Affect(GraphicsDevice device, RasterizerState currentState) { RasterizerState internalState = new RasterizerState(); // CullMode internalState.CullMode = CullMode.HasValue ? CullMode.Value : currentState.CullMode; // FillMode internalState.FillMode = FillMode.HasValue ? FillMode.Value : currentState.FillMode; // ScissorTestEnable internalState.ScissorTestEnable = ScissorTestEnable.HasValue ? ScissorTestEnable.Value : currentState.ScissorTestEnable; // MultiSampleAntiAlias internalState.MultiSampleAntiAlias = MultiSampleAntiAlias.HasValue ? MultiSampleAntiAlias.Value : currentState.MultiSampleAntiAlias; // DepthBias internalState.DepthBias = DepthBias.HasValue ? DepthBias.Value : currentState.DepthBias; // SlopeScaleDepthBias internalState.SlopeScaleDepthBias = SlopeScaleDepthBias.HasValue ? SlopeScaleDepthBias.Value : currentState.SlopeScaleDepthBias; // Finally apply the state device.RasterizerState = internalState; }
protected override async Task LoadContent() { await base.LoadContent(); wireframeState = RasterizerState.New(GraphicsDevice, new RasterizerStateDescription(CullMode.Back) { FillMode = FillMode.Wireframe }); simpleEffect = new Effect(GraphicsDevice, SpriteEffect.Bytecode); parameterCollection = new ParameterCollection(); parameterCollectionGroup = new EffectParameterCollectionGroup(GraphicsDevice, simpleEffect, new [] { parameterCollection }); parameterCollection.Set(TexturingKeys.Texture0, UVTexture); primitives = new List<GeometricPrimitive>(); // Creates all primitives primitives = new List<GeometricPrimitive> { GeometricPrimitive.Plane.New(GraphicsDevice), GeometricPrimitive.Cube.New(GraphicsDevice), GeometricPrimitive.Sphere.New(GraphicsDevice), GeometricPrimitive.GeoSphere.New(GraphicsDevice), GeometricPrimitive.Cylinder.New(GraphicsDevice), GeometricPrimitive.Torus.New(GraphicsDevice), GeometricPrimitive.Teapot.New(GraphicsDevice), GeometricPrimitive.Capsule.New(GraphicsDevice, 0.5f, 0.3f), GeometricPrimitive.Cone.New(GraphicsDevice) }; view = Matrix.LookAtRH(new Vector3(0, 0, 5), new Vector3(0, 0, 0), Vector3.UnitY); Window.AllowUserResizing = true; }
public ShapesDemo(IntPtr hInstance) : base(hInstance) { _vb = null; _ib = null; _fx = null; _tech = null; _fxWVP = null; _inputLayout = null; _wireframeRS = null; _theta = 1.5f * MathF.PI; _phi = 0.1f * MathF.PI; _radius = 15.0f; MainWindowCaption = "Shapes Demo"; _lastMousePos = new Point(0, 0); _gridWorld = Matrix.Identity; _view = Matrix.Identity; _proj = Matrix.Identity; _boxWorld = Matrix.Scaling(2.0f, 1.0f, 2.0f) * Matrix.Translation(0, 0.5f, 0); _centerSphere = Matrix.Scaling(2.0f, 2.0f, 2.0f) * Matrix.Translation(0, 2, 0); for (int i = 0; i < 5; ++i) { _cylWorld[i * 2] = Matrix.Translation(-5.0f, 1.5f, -10.0f + i * 5.0f); _cylWorld[i * 2 + 1] = Matrix.Translation(5.0f, 1.5f, -10.0f + i * 5.0f); _sphereWorld[i * 2] = Matrix.Translation(-5.0f, 3.5f, -10.0f + i * 5.0f); _sphereWorld[i * 2 + 1] = Matrix.Translation(5.0f, 3.5f, -10.0f + i * 5.0f); } }
protected override async Task LoadContent() { await base.LoadContent(); batch = new Sprite3DBatch(GraphicsDevice); sphere = Asset.Load<Texture>("Sphere"); rotatedImages = Asset.Load<SpriteSheet>("RotatedImages"); rasterizerState = RasterizerState.New(GraphicsDevice, new RasterizerStateDescription(CullMode.None)); }
public void Initialize(DeviceContextHolder contextHolder) { _effect = contextHolder.GetEffect<EffectDeferredGSky>(); _rasterizerState = RasterizerState.FromDescription(contextHolder.Device, new RasterizerStateDescription { FillMode = FillMode.Solid, CullMode = CullMode.Front, IsAntialiasedLineEnabled = false, IsFrontCounterclockwise = false, IsDepthClipEnabled = true }); }
/// <summary> /// Initializes a new instance of the <see cref="SpriteBatchState"/> structure. /// </summary> /// <param name="sortMode">The sprite batch's sort mode.</param> /// <param name="blendState">The sprite batch's blend state.</param> /// <param name="samplerState">The sprite batch's sampler state.</param> /// <param name="rasterizerState">The sprite batch's rasterizer state.</param> /// <param name="depthStencilState">The sprite batch's depth/stencil state.</param> /// <param name="effect">The sprite batch's custom effect.</param> /// <param name="transformMatrix">The sprite batch's transformation matrix.</param> public SpriteBatchState(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, RasterizerState rasterizerState, DepthStencilState depthStencilState, Effect effect, Matrix transformMatrix) { this.sortMode = sortMode; this.blendState = blendState; this.samplerState = samplerState; this.rasterizerState = rasterizerState; this.depthStencilState = depthStencilState; this.customEffect = effect; this.transformMatrix = transformMatrix; }
internal EffectPass(Effect effect, EffectPass cloneSource) { this._effect = effect; this.Name = cloneSource.Name; this._blendState = cloneSource._blendState; this._depthStencilState = cloneSource._depthStencilState; this._rasterizerState = cloneSource._rasterizerState; this.Annotations = cloneSource.Annotations; this._vertexShader = cloneSource._vertexShader; this._pixelShader = cloneSource._pixelShader; }
internal EffectPass(Effect effect, string name, Shader vertexShader, Shader pixelShader, BlendState blendState, DepthStencilState depthStencilState, RasterizerState rasterizerState, EffectAnnotationCollection annotations) { this._effect = effect; this.Name = name; this._vertexShader = vertexShader; this._pixelShader = pixelShader; this._blendState = blendState; this._depthStencilState = depthStencilState; this._rasterizerState = rasterizerState; this.Annotations = annotations; this.Initialize(); }
/// <summary> /// Initializes a new instance of the StateFactory /// </summary> /// <param name="device"></param> /// <param name="ubershader"></param> private StateFactory ( Ubershader ubershader, Type enumType, Primitive primitive, VertexInputElement[] vertexInputElements, BlendState blendState, RasterizerState rasterizerState ) : base(ubershader.GraphicsDevice) { this.ubershader = ubershader; Enumerate( enumType, ubershader, (ps,i) => { ps.Primitive = primitive; ps.VertexInputElements = vertexInputElements; ps.BlendState = blendState; ps.RasterizerState = rasterizerState; } ); }
/// <summary> /// Creates a new instance of the rasterizer state. /// </summary> /// <param name="cullMode"></param> /// <param name="fillMode"></param> /// <param name="depthBias"></param> /// <param name="slopeDepthBias"></param> /// <returns></returns> public static RasterizerState Create ( CullMode cullMode, FillMode fillMode = FillMode.Solid, int depthBias = 0, float slopeDepthBias = 0 ) { var rs = new RasterizerState(); rs.CullMode = cullMode; rs.DepthBias = depthBias; rs.SlopeDepthBias = slopeDepthBias; rs.MsaaEnabled = true; rs.FillMode = fillMode; rs.DepthClipEnabled = true; rs.ScissorEnabled = false; return rs; }
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); }
public new void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect, Matrix transformMatrix) { base.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, transformMatrix); }
public void SetRasterizerState(RasterizerState state) { DXDeviceContext.Rasterizer.State = state.NativeRasterizerState; }
private void StartSpritebatch( FloatRect view, GameBlendModes mode = GameBlendModes.None, GameShader shader = null, GameRenderTexture target = null, bool forced = false, RasterizerState rs = null, bool drawImmediate = false ) { var viewsDiff = view.X != mCurrentSpriteView.X || view.Y != mCurrentSpriteView.Y || view.Width != mCurrentSpriteView.Width || view.Height != mCurrentSpriteView.Height; if (mode != mCurrentBlendmode || shader != mCurrentShader || shader != null && shader.ValuesChanged() || target != mCurrentTarget || viewsDiff || forced || drawImmediate || !mSpriteBatchBegan) { if (mSpriteBatchBegan) { mSpriteBatch.End(); } if (target != null) { mGraphicsDevice?.SetRenderTarget((RenderTarget2D)target.GetTexture()); } else { mGraphicsDevice?.SetRenderTarget(mScreenshotRenderTarget); } var blend = mNormalState; Effect useEffect = null; switch (mode) { case GameBlendModes.None: blend = mNormalState; break; case GameBlendModes.Alpha: blend = BlendState.AlphaBlend; break; case GameBlendModes.Multiply: blend = mMultiplyState; break; case GameBlendModes.Add: blend = BlendState.Additive; break; case GameBlendModes.Opaque: blend = BlendState.Opaque; break; case GameBlendModes.Cutout: blend = mCutoutState; break; } if (shader != null) { useEffect = (Effect)shader.GetShader(); shader.ResetChanged(); } mSpriteBatch.Begin( drawImmediate ? SpriteSortMode.Immediate : SpriteSortMode.Deferred, blend, SamplerState.PointClamp, null, rs, useEffect, Matrix.CreateRotationZ(0f) * Matrix.CreateScale(new Vector3(1, 1, 1)) * Matrix.CreateTranslation(-view.X, -view.Y, 0) ); mCurrentSpriteView = view; mCurrentBlendmode = mode; mCurrentShader = shader; mCurrentTarget = target; mSpriteBatchBegan = true; } }
public override void Attach(IRenderHost host) { /// --- attach this.renderTechnique = Techniques.RenderCubeMap; base.Attach(host); /// --- get variables this.vertexLayout = EffectsManager.Instance.GetLayout(this.renderTechnique); this.effectTechnique = effect.GetTechniqueByName(this.renderTechnique.Name); this.effectTransforms = new EffectTransformVariables(this.effect); /// -- attach cube map if (this.Filename != null) { /// -- attach texture using (var texture = Texture2D.FromFile<Texture2D>(this.Device, this.Filename)) { this.texCubeMapView = new ShaderResourceView(this.Device, texture); } this.texCubeMap = effect.GetVariableByName("texCubeMap").AsShaderResource(); this.texCubeMap.SetResource(this.texCubeMapView); this.bHasCubeMap = effect.GetVariableByName("bHasCubeMap").AsScalar(); this.bHasCubeMap.Set(true); /// --- set up geometry var sphere = new MeshBuilder(false,true,false); sphere.AddSphere(new Vector3(0, 0, 0)); this.geometry = sphere.ToMeshGeometry3D(); /// --- set up vertex buffer this.vertexBuffer = Device.CreateBuffer(BindFlags.VertexBuffer, CubeVertex.SizeInBytes, this.geometry.Positions.Select((x, ii) => new CubeVertex() { Position = new Vector4(x, 1f) }).ToArray()); /// --- set up index buffer this.indexBuffer = Device.CreateBuffer(BindFlags.IndexBuffer, sizeof(int), geometry.Indices.Array); /// --- set up rasterizer states var rasterStateDesc = new RasterizerStateDescription() { FillMode = FillMode.Solid, CullMode = CullMode.Back, IsMultisampleEnabled = true, IsAntialiasedLineEnabled = true, IsFrontCounterClockwise = false, }; this.rasterState = new RasterizerState(this.Device, rasterStateDesc); /// --- set up depth stencil state var depthStencilDesc = new DepthStencilStateDescription() { DepthComparison = Comparison.LessEqual, DepthWriteMask = global::SharpDX.Direct3D11.DepthWriteMask.All, IsDepthEnabled = true, }; this.depthStencilState = new DepthStencilState(this.Device, depthStencilDesc); } /// --- flush this.Device.ImmediateContext.Flush(); }
public new void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState) { base.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState); }
/// <summary>This is called when the game should draw itself.</summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); RasterizerState rs = new RasterizerState(); clipMap.Draw(View, Projection); #region old testing //rs.CullMode = CullMode.CullClockwiseFace; //rs.FillMode = FillMode.WireFrame; //rs.CullMode = CullMode.None; //GraphicsDevice.SetVertexBuffer(vb); //GraphicsDevice.Indices = ib; //graphics.GraphicsDevice.RasterizerState = rs; //effect.Parameters["MaxHeight"].SetValue(100); //effect.Parameters["World"].SetValue(World); //effect.Parameters["View"].SetValue(View); //effect.Parameters["Projection"].SetValue(Projection); //effect.Parameters["LightDirection"].SetValue(Vector3.Normalize(Vector3.One)); //effect.Parameters["CloudRotation"].SetValue(MathHelper.ToRadians(rotation) * 2.4f); //effect.Parameters["CloudHeight"].SetValue(0.03f); //effect.Parameters["GlowColor"].SetValue(Color.DodgerBlue.ToVector4()); //effect.Parameters["heightMap"].SetValue(heightMap); //effect.Parameters["ColorMap"].SetValue(colorMap); //effect.Parameters["GlowMap"].SetValue(nightMap); //effect.Parameters["ReflectionMap"].SetValue(reflectionMap); //effect.Parameters["CloudMap"].SetValue(cloudMap); //effect.Parameters["GlowMap"].SetValue(nightMap); //effect.CurrentTechnique = effect.Techniques["t1"]; //foreach (EffectPass pass in effect.CurrentTechnique.Passes) //{ // pass.Apply(); // GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 0, _indices.Count); //} //be.View = View;// Matrix.CreateLookAt(camera.Position, (camera.Position + new Vector3(0, 0, -1)), new Vector3(0, 1, 0)); //be.Projection = Projection; //be.World = Matrix.Identity;// R * T * S; //be.VertexColorEnabled = true; //be.CurrentTechnique.Passes[0].Apply(); //GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList, vertices, 0, 2); //base.Draw(gameTime); spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive); spriteBatch.DrawString(sf, string.Format("Cam:{0},{1},{2}", Math.Round((decimal)camera.Position.X, 2), Math.Round((decimal)camera.Position.Y, 2), Math.Round((decimal)camera.Position.Z, 2)), Vector2.Zero, Color.White); //spriteBatch.DrawString(sf, // string.Format("v1:{0},{1},{2}", // Math.Round((decimal)vertices[0].Position.X, 2), // Math.Round((decimal)vertices[0].Position.Y, 2), // Math.Round((decimal)vertices[0].Position.Z, 2)), // Vector2.Zero, // Color.White); //spriteBatch.DrawString(sf, // string.Format("v2:{0},{1},{2}", // Math.Round((decimal)vertices[1].Position.X, 2), // Math.Round((decimal)vertices[1].Position.Y, 2), // Math.Round((decimal)vertices[1].Position.Z, 2)), // new Vector2 { X = 0, Y = sf.MeasureString("HI").Y }, // Color.White); //Vector3 dir = Vector3.Transform(camera.Position, Matrix.CreateFromQuaternion(camera.Rotation)); //dir.Normalize(); //spriteBatch.DrawString(sf, // string.Format("d:{0}", Vector3.Distance(vertices[0].Position, vertices[1].Position)), // //string.Format("dir:{0},{1},{2}", // // dir.X, // // dir.Y, // // dir.Z), // new Vector2 { X = 0, Y = sf.MeasureString("HI").Y * 2 }, // Color.White); spriteBatch.End(); #endregion }
public void Draw() { Game1.BscEffect.World = Game1.World; Game1.BscEffect.View = Game1.View; Game1.BscEffect.Projection = Game1.projection; Game1.BscEffect.Alpha = Transparency; Game1.BscEffect.Texture = _tex; Game1.GraphicsGlobal.GraphicsDevice.SamplerStates[0] = SamplerState.PointWrap; float a = 4; for (int i = 0; i < Nodes.Count - 1; i++) { rotated = new Vector3(Nodes[i].Position.X, 0 + Nodes[i].Position.Y - Width / 2, 0); rotated = Vector3.Transform(rotated, Matrix.CreateRotationZ(rotation)); vertices[i * 4 + 0] = new VertexPositionTexture(rotated + new Vector3(Start.Position, 0), new Vector2((i / a) + (Game1.Time * _scroll), 0)); rotated = new Vector3(Nodes[i + 1].Position.X, 0 + Nodes[i + 1].Position.Y - Width / 2, 0); rotated = Vector3.Transform(rotated, Matrix.CreateRotationZ(rotation)); vertices[i * 4 + 1] = new VertexPositionTexture(rotated + new Vector3(Start.Position, 0), new Vector2(((i + 1) / a) + (Game1.Time * _scroll), 0)); rotated = new Vector3(Nodes[i + 1].Position.X, Nodes[i + 1].Position.Y + Width / 2, 0); rotated = Vector3.Transform(rotated, Matrix.CreateRotationZ(rotation)); vertices[i * 4 + 2] = new VertexPositionTexture(rotated + new Vector3(Start.Position, 0), new Vector2(((i + 1) / a) + (Game1.Time * _scroll), 1)); rotated = new Vector3(Nodes[i].Position.X, Nodes[i].Position.Y + Width / 2, 0); rotated = Vector3.Transform(rotated, Matrix.CreateRotationZ(rotation)); vertices[i * 4 + 3] = new VertexPositionTexture(rotated + new Vector3(Start.Position, 0), new Vector2((i / a) + (Game1.Time * _scroll), 1)); } for (int i = 0; i < (indices.GetLength(0) / 6); i++) { indices[i * 6 + 0] = (short)(0 + i * 4); indices[i * 6 + 1] = (short)(1 + i * 4); indices[i * 6 + 2] = (short)(2 + i * 4); indices[i * 6 + 3] = (short)(0 + i * 4); indices[i * 6 + 4] = (short)(2 + i * 4); indices[i * 6 + 5] = (short)(3 + i * 4); } IndexBuffer.SetData(indices, 0, (Nodes.Count * 4) + (Nodes.Count) * 4); Game1.GraphicsGlobal.GraphicsDevice.Indices = IndexBuffer; VertexBuffer.SetData(vertices, 0, Nodes.Count * 4); Game1.GraphicsGlobal.GraphicsDevice.SetVertexBuffer(VertexBuffer); rasterizerState = new RasterizerState(); rasterizerState.CullMode = CullMode.CullCounterClockwiseFace; Game1.GraphicsGlobal.GraphicsDevice.RasterizerState = rasterizerState; foreach (EffectPass pass in Game1.BscEffect.CurrentTechnique.Passes) { pass.Apply(); Game1.GraphicsGlobal.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, Nodes.Count * 4, 0, Nodes.Count * 2); } Effects.ResetEffect3D(); }
public void begin(BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect, Matrix transformationMatrix, bool disableBatching) { Assert.isFalse(_beginCalled, "Begin has been called before calling End after the last call to Begin. Begin cannot be called again until End has been successfully called."); _beginCalled = true; _blendState = blendState ?? BlendState.AlphaBlend; _samplerState = samplerState ?? Core.defaultSamplerState; _depthStencilState = depthStencilState ?? DepthStencilState.None; _rasterizerState = rasterizerState ?? RasterizerState.CullCounterClockwise; _customEffect = effect; _transformMatrix = transformationMatrix; _disableBatching = disableBatching; if (_disableBatching) { prepRenderState(); } }
public void begin(BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect, Matrix transformationMatrix) { begin( blendState, samplerState, depthStencilState, rasterizerState, effect, transformationMatrix, false ); }
public void begin(BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect) { begin( blendState, samplerState, depthStencilState, rasterizerState, effect, Matrix.Identity, false ); }
public Dx11RenderingDevice() { logger.Info("Dx11 rendering device creating."); #if DEBUG const DeviceCreationFlags DebugFlags = DeviceCreationFlags.Debug; #else const DeviceCreationFlags DebugFlags = DeviceCreationFlags.None; #endif try { Factory = new Factory(); if (Factory.Adapters.Count() == 0) { MessageBox.Show("Your system have no video adapters. Try to install video adapter.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error); throw new Exception("There are no valid video adapters in system."); } var adapter = Factory.GetAdapter(0); if (adapter == null) { MessageBox.Show("DirectX wasn't able to acquire video adapter. Try to restart your system.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error); throw new Exception("DirectX wasn't able to acquire video adapter."); } if (adapter.Outputs == null || adapter.Outputs.Count() == 0) { MessageBox.Show("There are no video displays connected to your system. Try to connect a display.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error); throw new Exception("No connected displays found."); } Device = new Device(adapter, DebugFlags | DeviceCreationFlags.SingleThreaded, FeatureLevel.Level_10_0); } catch (Exception exc) { switch ((uint)exc.HResult) { case 0x887A0004: MessageBox.Show("Your DirectX version, videocard or drivers are out of date.\nDirectX 11 installation and videocard with DirectX 10 support is required.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error); break; case 0x887A002D: MessageBox.Show("Warning: provided build is a debug build.\nPlease install DirectX SDK or request release build from QA team.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error); break; case 0x887A0005: case 0x887A0020: MessageBox.Show("There was a serious video system error while initializing Direct3D device.\nTry to restart your system.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error); break; default: MessageBox.Show("Unknown error while creating Direct3D device!\nShutting down now.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error); break; } throw new Exception("Can't create Direct3D 11 device! Exception: " + exc); } #if DEBUG using (InfoQueue DeviceInfoQueue = Device.QueryInterface <InfoQueue>()) { DeviceInfoQueue.SetBreakOnSeverity(MessageSeverity.Warning, true); } #endif try { Context = Device.ImmediateContext; /*TestShader = new Dx11PipelineState(this, "TestShader", new InputElement[] * { * new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), * new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 0, 1, InputClassification.PerVertexData, 0) * });*/ TextShader = new Dx11PipelineState(this, "TextShader", new InputElement[] { new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("UVW", 0, Format.R32G32_UInt, 0, 1, InputClassification.PerVertexData, 0) }); SpriteShader = new Dx11PipelineState(this, "SpriteShader", new InputElement[] { new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("UVW", 0, Format.R32G32_UInt, 0, 1, InputClassification.PerVertexData, 0) }); RoomShader = new Dx11PipelineState(this, "RoomShader", new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 0, 1, InputClassification.PerVertexData, 0), new InputElement("OVERLAY", 0, Format.R8G8B8A8_UNorm, 0, 2, InputClassification.PerVertexData, 0), new InputElement("UVWANDBLENDMODE", 0, Format.R32G32_UInt, 0, 3, InputClassification.PerVertexData, 0), new InputElement("EDITORUVANDSECTORTEXTURE", 0, Format.R32_UInt, 0, 4, InputClassification.PerVertexData, 0) }); RasterizerBackCulling = new RasterizerState(Device, new RasterizerStateDescription { CullMode = CullMode.Back, FillMode = FillMode.Solid, }); SamplerDefault = new SamplerState(Device, new SamplerStateDescription { AddressU = TextureAddressMode.Mirror, AddressV = TextureAddressMode.Mirror, AddressW = TextureAddressMode.Wrap, Filter = Filter.Anisotropic, MaximumAnisotropy = 4, }); SamplerRoundToNearest = new SamplerState(Device, new SamplerStateDescription { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, Filter = Filter.MinMagMipPoint, MaximumAnisotropy = 4, }); { DepthStencilStateDescription desc = DepthStencilStateDescription.Default(); desc.DepthComparison = Comparison.LessEqual; desc.DepthWriteMask = DepthWriteMask.All; desc.IsDepthEnabled = true; desc.IsStencilEnabled = false; DepthStencilDefault = new DepthStencilState(Device, desc); } { DepthStencilStateDescription desc = DepthStencilStateDescription.Default(); desc.DepthComparison = Comparison.Always; desc.DepthWriteMask = DepthWriteMask.Zero; desc.IsDepthEnabled = false; desc.IsStencilEnabled = false; DepthStencilNoZBuffer = new DepthStencilState(Device, desc); } BlendingDisabled = new BlendState(Device, BlendStateDescription.Default()); { BlendStateDescription desc = BlendStateDescription.Default(); desc.RenderTarget[0].IsBlendEnabled = true; desc.RenderTarget[0].SourceBlend = desc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; desc.RenderTarget[0].DestinationBlend = desc.RenderTarget[0].DestinationAlphaBlend = BlendOption.InverseSourceAlpha; desc.RenderTarget[0].BlendOperation = desc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; desc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; BlendingPremultipliedAlpha = new BlendState(Device, desc); } } catch (Exception exc) { throw new Exception("Can't assign needed Direct3D parameters! Exception: " + exc); } // Sector textures bool support16BitTexture = Device.CheckFormatSupport(Format.B5G5R5A1_UNorm).HasFlag(FormatSupport.Texture2D); // For some reason not all DirectX devices support 16 bit textures. string[] sectorTextureNames = Enum.GetNames(typeof(SectorTexture)).Skip(1).ToArray(); GCHandle[] handles = new GCHandle[sectorTextureNames.Length]; try { DataBox[] dataBoxes = new DataBox[sectorTextureNames.Length]; for (int i = 0; i < sectorTextureNames.Length; ++i) { string name = nameof(TombLib) + "." + nameof(Rendering) + ".SectorTextures." + sectorTextureNames[i] + ".png"; using (Stream stream = ThisAssembly.GetManifestResourceStream(name)) { ImageC image = ImageC.FromStream(stream); if ((image.Width != SectorTextureSize) || (image.Height != SectorTextureSize)) { throw new ArgumentOutOfRangeException("The embedded resource '" + name + "' is not of a valid size."); } if (support16BitTexture) { // Compress image data into B5G5R5A1 format to save a bit of GPU memory. (3 MB saved with currently 23 images) ushort[] sectorTextureData = new ushort[SectorTextureSize * SectorTextureSize]; for (int j = 0; j < (SectorTextureSize * SectorTextureSize); ++j) { ColorC Color = image.Get(j); sectorTextureData[j] = (ushort)( ((Color.B >> 3) << 0) | ((Color.G >> 3) << 5) | ((Color.R >> 3) << 10) | ((Color.A >> 7) << 15)); } handles[i] = GCHandle.Alloc(sectorTextureData, GCHandleType.Pinned); dataBoxes[i] = new DataBox(handles[i].AddrOfPinnedObject(), sizeof(ushort) * SectorTextureSize, 0); } else { handles[i] = GCHandle.Alloc(image.ToByteArray(), GCHandleType.Pinned); dataBoxes[i] = new DataBox(handles[i].AddrOfPinnedObject(), sizeof(uint) * SectorTextureSize, 0); } } } SectorTextureArray = new Texture2D(Device, new Texture2DDescription { Width = SectorTextureSize, Height = SectorTextureSize, MipLevels = 1, ArraySize = sectorTextureNames.Length, Format = support16BitTexture ? Format.B5G5R5A1_UNorm : Format.B8G8R8A8_UNorm, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Immutable, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }, dataBoxes); } finally { foreach (GCHandle handle in handles) { handle.Free(); } } SectorTextureArrayView = new ShaderResourceView(Device, SectorTextureArray); // Set omni present state ResetState(); logger.Info("Dx11 rendering device created."); }
public bool Begin(ref SpriteBatch __instance, ref SpriteSortMode sortMode, ref BlendState blendState, ref SamplerState samplerState, ref DepthStencilState depthStencilState, ref RasterizerState rasterizerState, ref Effect effect, ref Matrix?transformMatrix) { if (VisualizeMod.shader is Effect e) { effect = e; } return(true); }
protected void InitOnce() { var shaderdeffile = Manager.Files.Get(@"Shaders\DeferredRendering.hlsl", false); var bbuffer = new byte[shaderdeffile.Length]; shaderdeffile.Read(bbuffer,0, bbuffer.Length); shaderdeffile.Dispose(); var bytecode = ShaderBytecode.Compile(bbuffer, "fx_5_0"); bbuffer = null; _effect = new Effect(D3DDevice, bytecode); bytecode.Dispose(); _composeTechnique = _effect.GetTechniqueByName("Compose"); _composePass = _composeTechnique.GetPassByIndex(0); var vertices = new DataStream(20 * 4, true, true); vertices.Write(new Vector3(-1f, -1f, -1f)); vertices.Write(new Vector2(0f,1f)); vertices.Write(new Vector3(-1f, 1f, -1f)); vertices.Write(new Vector2(0f, 0f)); vertices.Write(new Vector3(1f, -1f, -1f)); vertices.Write(new Vector2(1f, 1f)); vertices.Write(new Vector3(1f, 1f, -1f)); vertices.Write(new Vector2(1f, 0f)); vertices.Position = 0; _composeVertices = new Buffer(D3DDevice, vertices, 20 * 4, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); _composeVerticesBB = new VertexBufferBinding(_composeVertices, 20, 0); vertices.Dispose(); _composeLayout = new InputLayout(D3DDevice, _composePass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 0) }); var sampleMode = SamplerState.FromDescription(D3DDevice, new SamplerDescription() { AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, BorderColor = new Color4(0, 0, 0, 0), Filter = Filter.MinLinearMagMipPoint, ComparisonFunction = Comparison.Always, MipLodBias = 0f, MaximumAnisotropy = 8, MinimumLod = 0f, MaximumLod = float.MaxValue }); _effect.GetVariableByName("composeSampler").AsSampler().SetSamplerState(0, sampleMode); sampleMode.Dispose(); _effect.GetVariableByName("composeFlags").AsScalar().Set( Manager.Opts.Get<bool>("rndr_rawGBufferView")?0x1:0 ); NotifyHandlers.Add(Manager.Opts.RegisterChangeNotification("rndr_rawGBufferView", delegate(string key, object value) { Output.BeginInvoke((Action)delegate { if ((bool)value) _effect.GetVariableByName("composeFlags").AsScalar().Set(_effect.GetVariableByName("composeFlags").AsScalar().GetInt() | 0x1); else _effect.GetVariableByName("composeFlags").AsScalar().Set(_effect.GetVariableByName("composeFlags").AsScalar().GetInt() & (int.MaxValue - 0x1)); }); })); NotifyHandlers.Add(Manager.Opts.RegisterChangeNotification("rndr_nearPlane", delegate { Output.BeginInvoke((Action)ResetDevice); })); NotifyHandlers.Add(Manager.Opts.RegisterChangeNotification("rndr_farPlane", delegate { Output.BeginInvoke((Action)ResetDevice); })); SceneRasterizer = RasterizerState.FromDescription(D3DDevice, new RasterizerStateDescription() { FillMode = (Manager.Opts.Get<bool>("rndr_wireframe") ? FillMode.Wireframe : FillMode.Solid), CullMode = (Manager.Opts.Get<bool>("rndr_cull") ? CullMode.Back : CullMode.None) }); _composeRasterizer = RasterizerState.FromDescription(D3DDevice, new RasterizerStateDescription() { FillMode = FillMode.Solid, CullMode = CullMode.Back }); var bsd = new BlendStateDescription(); bsd.RenderTargets[0].BlendEnable = true; bsd.RenderTargets[0].SourceBlend = BlendOption.SourceAlpha; bsd.RenderTargets[0].DestinationBlend = BlendOption.InverseSourceAlpha; bsd.RenderTargets[0].BlendOperation = BlendOperation.Add; bsd.RenderTargets[0].SourceBlendAlpha = BlendOption.One; bsd.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero; bsd.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add; bsd.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; Context.OutputMerger.BlendState = BlendState.FromDescription(D3DDevice, bsd); NotifyHandlers.Add(Manager.Opts.RegisterChangeNotification("rndr_wireframe", delegate(string key, object value) { Output.BeginInvoke((Action)delegate { var oldcullmode = CullMode.Back; if (SceneRasterizer != null) { oldcullmode = SceneRasterizer.Description.CullMode; SceneRasterizer.Dispose(); } SceneRasterizer = RasterizerState.FromDescription(D3DDevice, new RasterizerStateDescription() { FillMode = (((bool)value) ? FillMode.Wireframe : FillMode.Solid), CullMode = oldcullmode }); }); })); NotifyHandlers.Add(Manager.Opts.RegisterChangeNotification("rndr_cull", delegate(string key, object value) { Output.BeginInvoke((Action)delegate { var oldfillmode = FillMode.Solid; if (SceneRasterizer != null) { oldfillmode = SceneRasterizer.Description.FillMode; SceneRasterizer.Dispose(); } SceneRasterizer = RasterizerState.FromDescription(D3DDevice, new RasterizerStateDescription() { FillMode = oldfillmode, CullMode = (((bool)value) ? CullMode.Back : CullMode.None) }); }); })); Context.OutputMerger.DepthStencilState = DepthStencilState.FromDescription(D3DDevice, new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = false, }); _camIncorporeal = Manager.Opts.Get<bool>("rndr_incorporeal"); NotifyHandlers.Add(Manager.Opts.RegisterChangeNotification("rndr_incorporeal", delegate(string key, object value) { _camIncorporeal = (bool)value; })); ViewerLocation = new Vector3(-1, 1, -1); ViewerLookAt = new Vector3(0, 0, 0); ViewerUpVector = Vector3.UnitY; _camLocationIncorporeal = new Vector3(-1, 1, -1); _camLookAtIncorporeal = new Vector3(0, 0, 0); _camUpVectorIncorporeal = Vector3.UnitY; ViewerFrustum = new Frustum(); _fpsTimer = new HTimer(); _fpsRingbuffer = new double[60]; _fpsRingbufferIndex = 0; }
internal override ShaderResourceView UpdateRasterizerStateForPart(Part part) { RasterizerState state = showOneTexture && !partEmphasis.Contains(part) ? wireframeRasterizerState : solidRasterizerState; if (state != currentRasterizerState) { this.manager.device.RS.State = currentRasterizerState = state; } ShaderResourceView textureOverride; if (!alternateTextures.TryGetValue(part.name, out textureOverride)) { textureOverride = null; } return textureOverride; }
private void InitializeInternal(Device device) { Debug.Assert(device != null); var wfDesc = new RasterizerStateDescription { FillMode = FillMode.Wireframe, CullMode = CullMode.Back, IsFrontCounterClockwise = false, IsDepthClipEnabled = true }; _wireframeRs = new RasterizerState(device, wfDesc); var noCullDesc = new RasterizerStateDescription { FillMode = FillMode.Solid, CullMode = CullMode.None, IsFrontCounterClockwise = false, IsDepthClipEnabled = true }; _noCullRs = new RasterizerState(device, noCullDesc); var cullClockwiseDesc = new RasterizerStateDescription { FillMode = FillMode.Solid, CullMode = CullMode.Back, IsFrontCounterClockwise = true, IsDepthClipEnabled = true }; _cullClockwiseRs = new RasterizerState(device, cullClockwiseDesc); var atcDesc = new BlendStateDescription { AlphaToCoverageEnable = true, IndependentBlendEnable = false, }; atcDesc.RenderTarget[0].IsBlendEnabled = false; atcDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _alphaToCoverageBs = new BlendState(device, atcDesc); var transDesc = new BlendStateDescription { AlphaToCoverageEnable = false, IndependentBlendEnable = false }; transDesc.RenderTarget[0].IsBlendEnabled = true; transDesc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; transDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; transDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; transDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; transDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; transDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; transDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _transparentBs = new BlendState(device, transDesc); var noRenderTargetWritesDesc = new BlendStateDescription { AlphaToCoverageEnable = false, IndependentBlendEnable = false }; noRenderTargetWritesDesc.RenderTarget[0].IsBlendEnabled = false; noRenderTargetWritesDesc.RenderTarget[0].SourceBlend = BlendOption.One; noRenderTargetWritesDesc.RenderTarget[0].DestinationBlend = BlendOption.Zero; noRenderTargetWritesDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; noRenderTargetWritesDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; noRenderTargetWritesDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; noRenderTargetWritesDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; noRenderTargetWritesDesc.RenderTarget[0].RenderTargetWriteMask = 0; _noRenderTargetWritesBs = new BlendState(device, noRenderTargetWritesDesc); var mirrorDesc = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.Zero, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xff, StencilWriteMask = 0xff, FrontFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Replace, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Replace, Comparison = Comparison.Always } }; _markMirrorDss = new DepthStencilState(device, mirrorDesc); var drawReflectionDesc = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xff, StencilWriteMask = 0xff, FrontFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep, Comparison = Comparison.Equal }, BackFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep, Comparison = Comparison.Equal } }; _drawReflectionDss = new DepthStencilState(device, drawReflectionDesc); var noDoubleBlendDesc = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xff, StencilWriteMask = 0xff, FrontFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Increment, Comparison = Comparison.Equal }, BackFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Increment, Comparison = Comparison.Equal } }; _noDoubleBlendDss = new DepthStencilState(device, noDoubleBlendDesc); var lessEqualDesc = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.LessEqual, IsStencilEnabled = false }; _lessEqualDss = new DepthStencilState(device, lessEqualDesc); var equalsDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.Zero, DepthComparison = Comparison.LessEqual, }; _equalsDss = new DepthStencilState(device, equalsDesc); var noDepthDesc = new DepthStencilStateDescription() { IsDepthEnabled = false, DepthComparison = Comparison.Always, DepthWriteMask = DepthWriteMask.Zero }; _noDepthDss = new DepthStencilState(device, noDepthDesc); }
private void InitalizeGraphics() { if (Window.RenderCanvasHandle == IntPtr.Zero) throw new InvalidOperationException(); SwapChainDescription swapChainDesc = new SwapChainDescription() { BufferCount = 1, Flags = SwapChainFlags.None, IsWindowed = true, OutputHandle = Window.RenderCanvasHandle, SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, ModeDescription = new ModeDescription() { Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm, //Format = SlimDX.DXGI.Format.B8G8R8A8_UNorm, Width = (int)Window.RenderCanvasSize.Width, Height = (int)Window.RenderCanvasSize.Height, RefreshRate = new Rational(60, 1), Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrdering.Unspecified }, SampleDescription = new SampleDescription(1, 0) }; var giFactory = new SlimDX.DXGI.Factory(); var adapter = giFactory.GetAdapter(0); Device device; SwapChain swapChain; Device.CreateWithSwapChain(adapter, DriverType.Hardware, DeviceCreationFlags.Debug, swapChainDesc, out device, out swapChain); _swapChain = swapChain; GraphicsDevice = device; // create a view of our render target, which is the backbuffer of the swap chain we just created using (var resource = SlimDX.Direct3D10.Resource.FromSwapChain<Texture2D>(swapChain, 0)) { _backBuffer = new RenderTargetView(device, resource); } // setting a viewport is required if you want to actually see anything var viewport = new Viewport(0, 0, (int)Window.RenderCanvasSize.Width, (int)Window.RenderCanvasSize.Height); device.OutputMerger.SetTargets(_backBuffer); device.Rasterizer.SetViewports(viewport); CreateDepthStencil(); LoadVisualizationEffect(); // Allocate a large buffer to write the PhysX visualization vertices into // There's more optimized ways of doing this, but for this sample a large buffer will do _userPrimitivesBuffer = new SlimDX.Direct3D10.Buffer(GraphicsDevice, VertexPositionColor.SizeInBytes * 50000, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None); var elements = new[] { new InputElement("Position", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("Color", 0, Format.R32G32B32A32_Float, 16, 0) }; _inputLayout = new InputLayout(GraphicsDevice, _visualizationEffect.RenderScenePass0.Description.Signature, elements); // States var blendDesc = new BlendStateDescription() { SourceBlend = BlendOption.One, DestinationBlend = BlendOption.Zero, BlendOperation = BlendOperation.Add, SourceAlphaBlend = BlendOption.One, DestinationAlphaBlend = BlendOption.Zero, AlphaBlendOperation = BlendOperation.Add }; blendDesc.SetBlendEnable(0, true); _blendState = BlendState.FromDescription(device, blendDesc); var rasterDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, IsMultisampleEnabled = false, FillMode = FillMode.Solid, CullMode = CullMode.None }; _rasterizerState = RasterizerState.FromDescription(device, rasterDesc); }
public void GenerateShadowMaps(Device device, DeviceContext deviceContext, CRenderScene renderScene) { // Store current render targets. Accourding to the function description we need to release these temporary interfaces DepthStencilView depthStencilRestore; RenderTargetView[] renderTargetRestore = deviceContext.OutputMerger.GetRenderTargets(1, out depthStencilRestore); RawViewportF[] viewPortsRestore = deviceContext.Rasterizer.GetViewports <RawViewportF>(); DepthStencilState depthStenctilStateRestore = deviceContext.OutputMerger.DepthStencilState; RasterizerState rasterizerRestore = deviceContext.Rasterizer.State; int shadowMapSlotOffset = 0; int cubeShadowMapSlotOffset = 0; // Unbind texture resources for (int i = CubeShadowMapBaseSlot; i < CubeShadowMapBaseSlot + MaxCubeShadowMaps; i++) { deviceContext.PixelShader.SetShaderResource(i, null); } for (int i = ShadowMapBaseSlot; i < ShadowMapBaseSlot + MaxShadowMaps; i++) { deviceContext.PixelShader.SetShaderResource(i, null); } // Generate shadow maps for all active lights foreach (CDirectionalLight directionalLight in m_directionalLights) { if (directionalLight.IsCastingShadow() && !directionalLight.NeedsShadowMapInit()) { // Init Shadow Map } } foreach (CPositionalLight positionalLight in m_positionalLights) { if (positionalLight.IsCastingShadow() && !positionalLight.NeedsShadowMapInit()) { if (positionalLight.IsShadowMapCube()) { if (cubeShadowMapSlotOffset < MaxCubeShadowMaps) { positionalLight.GenerateShadowMaps(device, deviceContext, renderScene); positionalLight.ShadowMapRegister = CubeShadowMapBaseSlot + cubeShadowMapSlotOffset; deviceContext.PixelShader.SetShaderResource(CubeShadowMapBaseSlot + cubeShadowMapSlotOffset, positionalLight.GetShadowMapView()); cubeShadowMapSlotOffset++; } } else { if (shadowMapSlotOffset < MaxShadowMaps) { positionalLight.GenerateShadowMaps(device, deviceContext, renderScene); positionalLight.ShadowMapRegister = ShadowMapBaseSlot + shadowMapSlotOffset; deviceContext.PixelShader.SetShaderResource(ShadowMapBaseSlot + shadowMapSlotOffset, positionalLight.GetShadowMapView()); shadowMapSlotOffset++; } } } } m_shadowMapSamplers.SetSamplers(deviceContext); // Restore previous render targets deviceContext.OutputMerger.SetRenderTargets(depthStencilRestore, renderTargetRestore); deviceContext.Rasterizer.SetViewports(viewPortsRestore); deviceContext.Rasterizer.State = rasterizerRestore; deviceContext.OutputMerger.DepthStencilState = depthStenctilStateRestore; //Dispose temporary interfaces depthStencilRestore?.Dispose(); depthStenctilStateRestore?.Dispose(); rasterizerRestore?.Dispose(); foreach (RenderTargetView renderTargetView in renderTargetRestore) { renderTargetView?.Dispose(); } }
public override bool Init() { if (!base.Init()) { return false; } BuildGeometryBuffers(); BuildFX(); BuildVertexLayout(); var wireFrameDesc = new RasterizerStateDescription { FillMode = FillMode.Wireframe, CullMode = CullMode.Back, IsFrontCounterclockwise = false, IsDepthClipEnabled = true }; _wireframeRS = RasterizerState.FromDescription(Device, wireFrameDesc); return true; }
public bool Initialize(int screenWidth, int screenHeight, bool vSync, IntPtr hwnd, bool fullScreen, float screenDepth, float screenNear) { try { vSyncEnabled = vSync; Rational refreshRate = new Rational(0, 0); var factory = new Factory1(); var adapter = factory.Adapters[0]; var adapterOutput = adapter.Outputs[0]; var modes = adapterOutput.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); for (int i = 0; i < modes.Length; i++) { if (modes[i].Width == screenWidth) { if (modes[i].Height == screenHeight) { refreshRate = modes[i].RefreshRate; } } } VideoCardMemory = adapter.Description.DedicatedVideoMemory / 1024 / 1024; VideoCardDescription = adapter.Description.Description; adapterOutput.Dispose(); adapter.Dispose(); factory.Dispose(); var swapChainDescription = new SwapChainDescription { BufferCount = 1, ModeDescription = { Width = screenWidth, Height = screenHeight, Format = Format.R8G8B8A8_UNorm, RefreshRate = vSyncEnabled ? refreshRate : new Rational(0, 0), ScanlineOrdering = DisplayModeScanlineOrder.Unspecified, Scaling = DisplayModeScaling.Unspecified }, Usage = Usage.RenderTargetOutput, OutputHandle = hwnd, SampleDescription = { Count = 1, Quality = 0 }, IsWindowed = !fullScreen, SwapEffect = SwapEffect.Discard, Flags = SwapChainFlags.None }; var featureLevel = FeatureLevel.Level_11_0; Device device; Device.CreateWithSwapChain( DriverType.Hardware, DeviceCreationFlags.Debug, new[] { featureLevel }, swapChainDescription, out device, out swapChain ); Device = device; DeviceContext = device.ImmediateContext; using (var backBuffer = swapChain.GetBackBuffer <Texture2D>(0)) { renderTargetView = new RenderTargetView(device, backBuffer); } var depthBufferDescription = new Texture2DDescription { Width = screenWidth, Height = screenHeight, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; depthStencilBuffer = new Texture2D(device, depthBufferDescription); var depthStencilStateDescription = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; depthStencilState = new DepthStencilState(device, depthStencilStateDescription); var depthStencilViewDescription = new DepthStencilViewDescription { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = { MipSlice = 0 } }; DepthStencilView = new DepthStencilView(device, depthStencilBuffer, depthStencilViewDescription); DeviceContext.OutputMerger.SetRenderTargets(DepthStencilView, renderTargetView); var rasterizerStateDescription = new RasterizerStateDescription { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }; rasterizerState = new RasterizerState(device, rasterizerStateDescription); DeviceContext.Rasterizer.State = rasterizerState; var viewport = new Viewport { Width = screenWidth, Height = screenHeight, MinDepth = 0.0f, MaxDepth = 1.0f, X = 0, Y = 0 }; DeviceContext.Rasterizer.SetViewport(viewport); var fieldOfView = MathUtil.Pi / 4.0f; var screenAspect = (float)screenWidth / screenHeight; Projection = Matrix.PerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth); World = Matrix.Identity; Orthogonal = Matrix.OrthoLH(screenWidth, screenHeight, screenNear, screenDepth); var depthDisabledStencilStateDescription = new DepthStencilStateDescription { IsDepthEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; depthDisabledStencilState = new DepthStencilState(device, depthDisabledStencilStateDescription); } catch { return(false); } return(true); }
public VoroniRenderer2d(String title) { m_scenes = new List <Scene>(); cameras_ = new List <Camera>(); samplerStates_ = new Dictionary <string, SamplerState>(); lastTime_ = DateTime.Now; form_ = new RenderForm(title); form_.Width = 1024; form_.Height = 768; var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form_.ClientSize.Width, form_.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form_.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device_, out swapChain_); Factory factory = swapChain_.GetParent <Factory>(); factory.SetWindowAssociation(form_.Handle, WindowAssociationFlags.IgnoreAll); backBuffer_ = Texture2D.FromSwapChain <Texture2D>(swapChain_, 0); renderView_ = new RenderTargetView(device_, backBuffer_); var depthDesc = new Texture2DDescription() { Width = form_.Width, Height = form_.Height, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription() { Count = 1, Quality = 0 }, Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = 0, OptionFlags = 0 }; m_depthBuffer = new Texture2D(device_, depthDesc); device_.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, form_.ClientSize.Width, form_.ClientSize.Height, 0.1f, 1.0f)); RasterizerStateDescription descRast = new RasterizerStateDescription() { FillMode = FillMode.Solid, CullMode = CullMode.None, IsDepthClipEnabled = true }; m_rasterizerState = RasterizerState.FromDescription(device_, descRast); DepthStencilStateDescription dsStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { Comparison = Comparison.Always, DepthFailOperation = StencilOperation.Increment, FailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep }, BackFace = new DepthStencilOperationDescription() { Comparison = Comparison.Always, DepthFailOperation = StencilOperation.Increment, FailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep }, }; DepthStencilState dsState = DepthStencilState.FromDescription(device_, dsStateDesc); device_.ImmediateContext.OutputMerger.DepthStencilState = dsState; device_.ImmediateContext.Rasterizer.State = m_rasterizerState; DepthStencilViewDescription DSVDesc = new DepthStencilViewDescription() { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, MipSlice = 0 }; m_depthView = new DepthStencilView(device_, m_depthBuffer, DSVDesc); dsState.Dispose(); device_.ImmediateContext.OutputMerger.SetTargets(m_depthView, renderView_); CreateSamplers(); }
public bool Initialize(DSystemConfiguration configuration, IntPtr windowHandle) { try { #region Environment Configuration // Store the vsync setting. VerticalSyncEnabled = DSystemConfiguration.VerticalSyncEnabled; // Create a DirectX graphics interface factory. var factory = new Factory1(); // Use the factory to create an adapter for the primary graphics interface (video card). var adapter = factory.GetAdapter1(0); // Get the primary adapter output (monitor). var monitor = adapter.GetOutput(0); // Get modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor). var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); // Now go through all the display modes and find the one that matches the screen width and height. // When a match is found store the the refresh rate for that monitor, if vertical sync is enabled. // Otherwise we use maximum refresh rate. var rational = new Rational(0, 1); if (VerticalSyncEnabled) { foreach (var mode in modes) { if (mode.Width == configuration.Width && mode.Height == configuration.Height) { rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator); break; } } } // Get the adapter (video card) description. var adapterDescription = adapter.Description; // Store the dedicated video card memory in megabytes. VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; // Convert the name of the video card to a character array and store it. VideoCardDescription = adapterDescription.Description.Trim('\0'); // Release the adapter output. monitor.Dispose(); // Release the adapter. adapter.Dispose(); // Release the factory. factory.Dispose(); #endregion #region Initialize swap chain and d3d device // Initialize the swap chain description. var swapChainDesc = new SwapChainDescription() { // Set to a single back buffer. BufferCount = 1, // Set the width and height of the back buffer. ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm), // Set the usage of the back buffer. Usage = Usage.RenderTargetOutput, // Set the handle for the window to render to. OutputHandle = windowHandle, // Turn multisampling off. SampleDescription = new SampleDescription(1, 0), // Set to full screen or windowed mode. IsWindowed = !DSystemConfiguration.FullScreen, // Don't set the advanced flags. Flags = SwapChainFlags.None, // Discard the back buffer content after presenting. SwapEffect = SwapEffect.Discard }; // Create the swap chain, Direct3D device, and Direct3D device context. SharpDX.Direct3D11.Device device; SwapChain swapChain; SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); Device = device; SwapChain = swapChain; DeviceContext = device.ImmediateContext; #endregion #region Initialize buffers // Get the pointer to the back buffer. var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0); // Create the render target view with the back buffer pointer. RenderTargetView = new RenderTargetView(device, backBuffer); // Release pointer to the back buffer as we no longer need it. backBuffer.Dispose(); // Initialize and set up the description of the depth buffer. var depthBufferDesc = new Texture2DDescription() { Width = configuration.Width, Height = configuration.Height, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; // Create the texture for the depth buffer using the filled out description. DepthStencilBuffer = new Texture2D(device, depthBufferDesc); #endregion #region Initialize Depth Enabled Stencil #endregion #region Initialize Output Merger // Initialize and set up the depth stencil view. var depthStencilViewDesc = new DepthStencilViewDescription() { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; // Create the depth stencil view. DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc); // Bind the render target view and depth stencil buffer to the output render pipeline. DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView); #endregion #region Initialize Raster State // Setup the raster description which will determine how and what polygon will be drawn. var rasterDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = .0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }; // Create the rasterizer state from the description we just filled out. RasterState = new RasterizerState(Device, rasterDesc); #endregion #region Initialize Rasterizer // Now set the rasterizer state. DeviceContext.Rasterizer.State = RasterState; // Setup and create the viewport for rendering. DeviceContext.Rasterizer.SetViewport(0, 0, configuration.Width, configuration.Height, 0, 1); #endregion #region Initialize matrices // Setup and create the projection matrix. ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4), ((float)configuration.Width / (float)configuration.Height), DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth); // Initialize the world matrix to the identity matrix. WorldMatrix = Matrix.Identity; #endregion #region Initialize Depth Disabled Stencil #endregion #region Initialize Blend States #endregion return(true); } catch (Exception) { return(false); } }
/// <summary> /// Creates pipeline state factory /// </summary> public StateFactory CreateFactory ( Type type, Primitive primitive, VertexInputElement[] vertexInputElements, BlendState blendState, RasterizerState rasterizerState, DepthStencilState depthStencilState ) { return CreateFactory( type, (ps,i) => { ps.Primitive = primitive; ps.VertexInputElements = vertexInputElements; ps.BlendState = blendState; ps.RasterizerState = rasterizerState; ps.DepthStencilState = depthStencilState; }); }
internal void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect, Matrix transformMatrix) { return; }
public void setup(GraphicsDeviceManager graphicsDeviceManager) { scissorTestRasterizerState = new RasterizerState { ScissorTestEnable = true, CullMode = CullMode.None }; //Resolução virtual displayWidth = Config.displayWidth;; displayHeight = Config.displayHeight; displayWidthOver2 = displayWidth / 2; displayHeightOver2 = displayHeight / 2; graphicsDeviceManager.IsFullScreen = Config.IsFullScreen; if (graphicsDeviceManager.IsFullScreen) { if (graphicsDeviceManager.GraphicsDevice.DisplayMode.Width > graphicsDeviceManager.GraphicsDevice.DisplayMode.Height) { graphicsDeviceManager.PreferredBackBufferWidth = graphicsDeviceManager.GraphicsDevice.DisplayMode.Width; graphicsDeviceManager.PreferredBackBufferHeight = graphicsDeviceManager.GraphicsDevice.DisplayMode.Height; } else { graphicsDeviceManager.PreferredBackBufferWidth = graphicsDeviceManager.GraphicsDevice.DisplayMode.Height; graphicsDeviceManager.PreferredBackBufferHeight = graphicsDeviceManager.GraphicsDevice.DisplayMode.Width; } } else { graphicsDeviceManager.PreferredBackBufferWidth = displayWidth; graphicsDeviceManager.PreferredBackBufferHeight = displayHeight; } graphicsDeviceManager.ApplyChanges(); screenViewport = graphicsDeviceManager.GraphicsDevice.Viewport; centerViewport = screenViewport; float scaleX = (float)graphicsDeviceManager.GraphicsDevice.PresentationParameters.BackBufferWidth / displayWidth; float scaleY = (float)graphicsDeviceManager.GraphicsDevice.PresentationParameters.BackBufferHeight / displayHeight; scale = Math.Min(scaleX, scaleY); translateX = ((float)graphicsDeviceManager.GraphicsDevice.PresentationParameters.BackBufferWidth - (displayWidth * scale)) / 2f; translateY = ((float)graphicsDeviceManager.GraphicsDevice.PresentationParameters.BackBufferHeight - (displayHeight * scale)) / 2f; camera = Matrix.CreateScale(scale, scale, 1); centerViewport.X = (int)translateX; centerViewport.Width = (int)(centerViewport.Width - translateX - translateX); centerViewport.Y = (int)translateY; centerViewport.Height = (int)(centerViewport.Height - translateY - translateY); graphicsDeviceManager.GraphicsDevice.ScissorRectangle = centerViewport.Bounds; graphicsDeviceManager.GraphicsDevice.Viewport = centerViewport; translateX = -translateX / scale; translateY = -translateY / scale; }
internal void Begin(SpriteSortMode sortMode = SpriteSortMode.Deferred, BlendState blendState = null, SamplerState samplerState = null, DepthStencilState depthStencilState = null, RasterizerState rasterizerState = null, Effect effect = null, Matrix?transformMatrix = null) { return; }
private void MakeBothSidesRendered() { RasterizerDescription rsDesc = new RasterizerDescription(); rsDesc.AntiAliasedLineEnable = false; rsDesc.CullMode = CullMode.None; rsDesc.DepthBias = 0; rsDesc.DepthBiasClamp = 0; rsDesc.DepthClipEnable = true; rsDesc.FillMode = Microsoft.WindowsAPICodePack.DirectX.Direct3D10.FillMode.Solid; rsDesc.FrontCounterclockwise = false; // Must be FALSE for 10on9 rsDesc.MultisampleEnable = false; rsDesc.ScissorEnable = false; rsDesc.SlopeScaledDepthBias = 0; rasterizerState = device.CreateRasterizerState(rsDesc); device.RS.State = rasterizerState; }
/// <summary> /// Sets the input layout and primitive topology, then starts a new 3D drawing pass using custom state settings. /// </summary> /// <param name="inputLayout">The input layout indicating how vertices are stored.</param> /// <param name="topology">The primitive topology indicating how indices are stored.</param> /// <param name="blend">The alpha blend state.</param> /// <param name="depthStencil">The depth-stencil comparer state.</param> /// <param name="rasterizer">The rasterizer state.</param> public void Begin3D(InputLayout inputLayout, PrimitiveTopology topology, BlendState blend, DepthStencilState depthStencil, RasterizerState rasterizer) { var ctx = Direct3DDevice.ImmediateContext; ctx.InputAssembler.InputLayout = inputLayout; ctx.InputAssembler.PrimitiveTopology = topology; ctx.Rasterizer.State = rasterizer; ctx.OutputMerger.BlendState = blend; ctx.OutputMerger.DepthStencilState = depthStencil; }
private void createRasterizerState() { RasterizerStateDescription rsd = new RasterizerStateDescription() { //CullMode = CullMode.None, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = 0.0f, //FillMode = FillMode.Wireframe, FillMode = FillMode.Solid, IsAntialiasedLineEnabled = false, IsDepthClipEnabled = false, IsFrontCounterclockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }; rasterState = RasterizerState.FromDescription(D3DDevice, rsd); D3DDevice.ImmediateContext.Rasterizer.State = rasterState; }
/// The draw order is determined by layer depth public override void draw(GameTime gameTime) { RasterizerState rState = new RasterizerState(); rState.CullMode = CullMode.None; rState.ScissorTestEnable = true; //graphicsDeviceManagerReference.GraphicsDevice.Clear(screenColor); sbReference.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, SamplerState.LinearWrap, DepthStencilState.None, rState); gdmReference.GraphicsDevice.ScissorRectangle = playerOneCamera.getScreenBoundingBox; //playerOne map.draw(playerOneCamera); foreach (ParallaxBackground pBackground in parallaxBackgrounds) { pBackground.drawAltPosition(map.getWorldToScreenCoord(new Vector2(pBackground.worldPosition.X, pBackground.worldPosition.Y), playerOneCamera)); } //Sloped Platforms foreach (SlopedPlatform sp in slopedPlatforms) { sp.drawAltPosition(map.getWorldToScreenCoord(new Vector2(sp.platformSlope.pt1.X, sp.platformSlope.pt1.Y), playerOneCamera), map.getWorldToScreenCoord(new Vector2(sp.platformSlope.pt2.X, sp.platformSlope.pt2.Y), playerOneCamera));; } foreach (GrindRail gr in grindRails) { if (playerOneCamera.getWorldBoundingBox.Intersects(gr.platformSlope.getBoundingRectangle)) { gr.drawAltPosition(map.getWorldToScreenCoord(new Vector2(gr.platformSlope.pt1.X, gr.platformSlope.pt1.Y), playerOneCamera), map.getWorldToScreenCoord(new Vector2(gr.platformSlope.pt2.X, gr.platformSlope.pt2.Y), playerOneCamera));; } } //Platforms foreach (Platform tp in platforms) { if (playerOneCamera.getWorldBoundingBox.Intersects(tp.boundingRectangle)) { tp.DrawAltPosition(map.getWorldToScreenCoord(tp.position, playerOneCamera)); } } //Springs foreach (Spring sp in springs) { if (playerOneCamera.getWorldBoundingBox.Intersects(sp.getBoundingBox)) { sp.drawAltPosition(map.getWorldToScreenCoord(sp.worldPosition, playerOneCamera)); } } //Treasure foreach (Treasure treasure in worldTreasure) { if (playerOneCamera.getWorldBoundingBox.Intersects(treasure.getBoundingBox)) { treasure.drawAltPosition(map.getWorldToScreenCoord(treasure.centerPosition, playerOneCamera)); //treasure.checkToActivateSpring(playerOne); } } playerOne.DrawAltPosition(map.getWorldToScreenCoord(playerOne.currentWorldPosition, playerOneCamera)); //playerOne.drawBoundingBox(map.getWorldToScreenCoord(playerOne.currentWorldPosition, playerOneCamera)); sbReference.End(); //playerOne 2 draw section //sbReference.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearWrap, DepthStencilState.None, rState); //graphicsDeviceManagerReference.GraphicsDevice.ScissorRectangle = playerTwoCamera.getScreenBoundingBox; //playerTwo //map.draw(playerTwoCamera); //playerTwo.DrawAltPosition(map.getWorldToScreenCoord(playerTwo.currentWorldPosition, playerTwoCamera)); //platformOne.DrawAltPosition(map.getWorldToScreenCoord(platformOne.position, playerTwoCamera)); //sbReference.End(); }
/// <summary> /// Set the <strong>rasterizer state</strong> for the rasterizer stage of the pipeline. See <see cref="Render+states"/> to learn how to use it. /// </summary> /// <param name="rasterizerState">The rasterizser state to set on this device.</param> private void SetRasterizerStateImpl(RasterizerState rasterizerState) { NativeDeviceContext.Rasterizer.State = rasterizerState != null ? (SharpDX.Direct3D11.RasterizerState)rasterizerState.NativeDeviceChild : null; }
public static void Render(GraphicsDevice device, Effect effect, bool delete) { BlendState origBlen = device.BlendState; device.BlendState = BlendState.NonPremultiplied; RasterizerState newState = RasterizerState.CullNone; RasterizerState oldState = device.RasterizerState; device.RasterizerState = newState; effect.CurrentTechnique = effect.Techniques["Untextured"]; effect.Parameters["xWorld"].SetValue(Matrix.Identity); DrawCommand3D.LineStrip strips = new DrawCommand3D.LineStrip() { Vertices = new List <VertexPositionColor>() }; foreach (DrawCommand3D command in Commands) { if (command.DrawAccumlatedStrips) { command.AccumulateStrips(strips); } } if (strips.Vertices.Count > 0 && strips.NumTriangles > 0) { foreach (EffectPass pass in effect.CurrentTechnique.Passes) { pass.Apply(); device.DrawUserPrimitives(PrimitiveType.TriangleStrip, strips.Vertices.ToArray(), 0, Math.Min(strips.Vertices.Count - 2, short.MaxValue)); } } effect.CurrentTechnique = effect.Techniques["Textured"]; foreach (DrawCommand3D command in Commands) { if (!command.DrawAccumlatedStrips) { command.Render(device, effect); } } if (oldState != null) { device.RasterizerState = oldState; } if (origBlen != null) { device.BlendState = origBlen; } if (!delete) { return; } while (Commands.Count > 0) { DrawCommand3D result = null; Commands.TryTake(out result); } }
/// <summary> /// Renders the mesh with the specified transformation. This alternate render method /// supplements the base class rendering to provide part-by-part texturing support. /// </summary> /// <param name="modelTransform"></param> public void Render(Matrix3D modelTransform) { // setup rasterization RasterizerDescription rasterizerDescription = new RasterizerDescription() { FillMode = FillMode.Solid, CullMode = CullMode.Back, FrontCounterclockwise = false, DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, DepthClipEnable = true, ScissorEnable = false, MultisampleEnable = true, AntiAliasedLineEnable = true }; try { solidRasterizerState = this.manager.device.CreateRasterizerState(rasterizerDescription); rasterizerDescription.FillMode = FillMode.Wireframe; wireframeRasterizerState = this.manager.device.CreateRasterizerState(rasterizerDescription); base.Render(modelTransform.ToMatrix4x4F()); } finally { if (solidRasterizerState != null) { solidRasterizerState.Dispose(); solidRasterizerState = null; } if (wireframeRasterizerState != null) { wireframeRasterizerState.Dispose(); wireframeRasterizerState = null; } currentRasterizerState = null; } }
public bool Initialize(DSystemConfiguration configuration, IntPtr windowHandle) { try { #region Environment Configuration VerticalSyncEnabled = DSystemConfiguration.VerticalSyncEnabled; var factory = new Factory1(); var adapter = factory.GetAdapter1(0); var monitor = adapter.GetOutput(0); var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); var rational = new Rational(0, 1); if (VerticalSyncEnabled) { foreach (var mode in modes) { if (mode.Width == configuration.Width && mode.Height == configuration.Height) { rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator); break; } } } var adapterDescription = adapter.Description; VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; VideoCardDescription = string.Format("VideoCard: {0}", adapterDescription.Description.Trim('\0')); monitor.Dispose(); adapter.Dispose(); factory.Dispose(); #endregion #region Initialize swap chain and d3d device var swapChainDesc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm) { Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrder.Unspecified }, Usage = Usage.RenderTargetOutput, OutputHandle = windowHandle, SampleDescription = new SampleDescription(1, 0), IsWindowed = !DSystemConfiguration.FullScreen, Flags = SwapChainFlags.None, SwapEffect = SwapEffect.Discard }; SharpDX.Direct3D11.Device device; SwapChain swapChain; SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); Device = device; SwapChain = swapChain; DeviceContext = device.ImmediateContext; #endregion #region Initialize buffers var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0); RenderTargetView = new RenderTargetView(device, backBuffer); backBuffer.Dispose(); var depthBufferDesc = new Texture2DDescription() { Width = configuration.Width, Height = configuration.Height, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; DepthStencilBuffer = new Texture2D(device, depthBufferDesc); #endregion #region Initialize Depth Enabled Stencil var depthStencilDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; DepthStencilState = new DepthStencilState(Device, depthStencilDesc); #endregion #region Initialize Output Merger DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1); var depthStencilViewDesc = new DepthStencilViewDescription() { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc); DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView); #endregion #region Initialize Raster State var rasterDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }; RasterState = new RasterizerState(Device, rasterDesc); var rasterDescWireFrame = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = true, FillMode = FillMode.Wireframe, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }; RasterStateWirefram = new RasterizerState(Device, rasterDescWireFrame); // Setup a raster description which turns off back face culling. var rasterNoCullDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = CullMode.None, DepthBias = 0, DepthBiasClamp = .0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }; // Create the no culling rasterizer state. RasterStateNoCulling = new RasterizerState(Device, rasterNoCullDesc); #endregion #region Initialize Rasterizer DeviceContext.Rasterizer.State = RasterState; ViewPort = new ViewportF(0.0f, 0.0f, (float)configuration.Width, (float)configuration.Height, 0.0f, 1.0f); DeviceContext.Rasterizer.SetViewport(ViewPort); #endregion #region Initialize matrices ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4), ((float)configuration.Width / (float)configuration.Height), DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth); WorldMatrix = Matrix.Identity; OrthoMatrix = Matrix.OrthoLH(configuration.Width, configuration.Height, DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth); #endregion #region Initialize Depth Disabled Stencil var depthDisabledStencilDesc = new DepthStencilStateDescription() { IsDepthEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; DepthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc); #endregion #region Initialize Blend States var blendStateDesc = new BlendStateDescription(); blendStateDesc.AlphaToCoverageEnable = false; blendStateDesc.IndependentBlendEnable = false; blendStateDesc.RenderTarget[0].IsBlendEnabled = true; blendStateDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; blendStateDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; blendStateDesc.RenderTarget[0].SourceBlend = BlendOption.One; blendStateDesc.RenderTarget[0].DestinationBlend = BlendOption.One; blendStateDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; blendStateDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; blendStateDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; AlphaEnableBlendingState = new BlendState(device, blendStateDesc); blendStateDesc.RenderTarget[0].IsBlendEnabled = false; blendStateDesc.AlphaToCoverageEnable = false; AlphaDisableBlendingState = new BlendState(device, blendStateDesc); #endregion return(true); } catch (Exception) { return(false); } }
private PropertyCollection PrepareProperties(Logger logger, CommonData.PropertyCollection properties) { var passProperties = new PropertyCollection(); foreach (var property in properties) { switch (property.Key) { case EffectData.PropertyKeys.Blending: BlendState = graphicsDevice.BlendStates[(string)property.Value]; if (BlendState == null) logger.Error("Unable to find registered BlendState [{0}]", (string)property.Value); break; case EffectData.PropertyKeys.BlendingColor: BlendStateColor = (Color4)(Vector4)property.Value; break; case EffectData.PropertyKeys.BlendingSampleMask: BlendStateSampleMask = (uint)property.Value; break; case EffectData.PropertyKeys.DepthStencil: DepthStencilState = graphicsDevice.DepthStencilStates[(string)property.Value]; if (DepthStencilState == null) logger.Error("Unable to find registered DepthStencilState [{0}]", (string)property.Value); break; case EffectData.PropertyKeys.DepthStencilReference: DepthStencilReference = (int)property.Value; break; case EffectData.PropertyKeys.Rasterizer: RasterizerState = graphicsDevice.RasterizerStates[(string)property.Value]; if (RasterizerState == null) logger.Error("Unable to find registered RasterizerState [{0}]", (string)property.Value); break; default: passProperties[new PropertyKey(property.Key)] = property.Value; break; } } return passProperties; }
public override void Initialize() { base.Initialize(); plStruct = new PointLightStruct[maxLights]; pLightBuffer = new StructuredBuffer<PointLightStruct>(maxLights, false, true); cBuffer = new ConstantBufferWrapper(Renderer, sizeof(float) * 32, ShaderType.PixelShader, 0); cBuffer.Semantics.Add(Semantic.Projection); cBuffer.Semantics.Add(Semantic.CameraNearFar); GBuffer = new GBuffer(Renderer); BlendStateDescription disabledBlendDesc = States.BlendDefault(); BlendStateDescription additiveDesc = States.BlendDefault(); additiveDesc.RenderTargets[0] = new RenderTargetBlendDescription() { BlendEnable = true, SourceBlend = BlendOption.One, DestinationBlend = BlendOption.One, BlendOperation = BlendOperation.Add, SourceBlendAlpha = BlendOption.One, DestinationBlendAlpha = BlendOption.One, BlendOperationAlpha = BlendOperation.Add, RenderTargetWriteMask = ColorWriteMaskFlags.All, }; DepthStencilStateDescription defaultDepthDesc = States.DepthDefault(); defaultDepthDesc.DepthComparison = Comparison.GreaterEqual; DepthStencilStateDescription equalDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.Zero, DepthComparison = Comparison.GreaterEqual, IsStencilEnabled = true, StencilWriteMask = 0xFF, StencilReadMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep, Comparison = Comparison.Equal, }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep, Comparison = Comparison.Equal, } }; DepthStencilStateDescription writeDesc = new DepthStencilStateDescription() { IsDepthEnabled = false, DepthWriteMask = DepthWriteMask.Zero, DepthComparison = Comparison.GreaterEqual, IsStencilEnabled = true, StencilWriteMask = 0xFF, StencilReadMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Replace, DepthFailOperation = StencilOperation.Replace, PassOperation = StencilOperation.Replace, Comparison = Comparison.Always, }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Replace, DepthFailOperation = StencilOperation.Replace, PassOperation = StencilOperation.Replace, Comparison = Comparison.Always, } }; RasterizerStateDescription rsDesc = States.RasterizerDefault(); mGeometryBlendState = BlendState.FromDescription(Renderer.Device, disabledBlendDesc); mLightingBlendState = BlendState.FromDescription(Renderer.Device, additiveDesc); mDepthState = DepthStencilState.FromDescription(Renderer.Device, defaultDepthDesc); mEqualStencilState = DepthStencilState.FromDescription(Renderer.Device, equalDesc); mWriteStencilState = DepthStencilState.FromDescription(Renderer.Device, writeDesc); mRasterizerState = RasterizerState.FromDescription(Renderer.Device, rsDesc); InitializeBuffers(); InitializeShaders(); }
private void InitializeGraphics() { // Creating device (we accept dx10 cards or greater) FeatureLevel[] levels = { FeatureLevel.Level_11_0, FeatureLevel.Level_10_1, FeatureLevel.Level_10_0 }; // Defining our swap chain SwapChainDescription desc = new SwapChainDescription(); desc.BufferCount = 1; desc.Usage = Usage.RenderTargetOutput; desc.ModeDescription = new ModeDescription(0, 0, new Rational(0, 0), Format.R8G8B8A8_UNorm); desc.SampleDescription = new SampleDescription(1, 0); desc.OutputHandle = form.Handle; desc.IsWindowed = true; desc.SwapEffect = SwapEffect.Discard; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, levels, desc, out device11, out swapChain); Format depthFormat = Format.D24_UNorm_S8_UInt; Texture2DDescription depthBufferDesc = new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, Format = depthFormat, Height = form.Height, Width = form.Width, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }; depthBuffer = new Texture2D(device11, depthBufferDesc); DepthStencilViewDescription dsViewDesc = new DepthStencilViewDescription { Format = depthFormat, Dimension = DepthStencilViewDimension.Texture2D, MipSlice = 0, }; depthView = new DepthStencilView(device11, depthBuffer, dsViewDesc); DepthStencilStateDescription dsStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, }; depthState = DepthStencilState.FromDescription(device11, dsStateDesc); // Getting back buffer backBuffer = Resource.FromSwapChain<Texture2D>(swapChain, 0); // Defining render view renderTargetView = new RenderTargetView(device11, backBuffer); device11.ImmediateContext.OutputMerger.DepthStencilState = depthState; device11.ImmediateContext.OutputMerger.SetTargets(depthView, renderTargetView); // Setup the raster description which will determine how and what polygons will be drawn. RasterizerStateDescription rasterDesc = new RasterizerStateDescription(){ IsAntialiasedLineEnabled = false, CullMode = CullMode.None, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterclockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f, }; // Create the rasterizer state from the description we just filled out. rasterState = RasterizerState.FromDescription(device11, rasterDesc); // Now set the rasterizer state. device11.ImmediateContext.Rasterizer.State = rasterState; device11.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); }
protected virtual void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { // Dispose loaded game components for (int i = 0; i < _components.Count; i++) { var disposable = _components[i] as IDisposable; if (disposable != null) { disposable.Dispose(); } } _components = null; if (Content != null) { Content.Dispose(); Content = null; } if (_graphicsDeviceManager != null) { (_graphicsDeviceManager as GraphicsDeviceManager).Dispose(); _graphicsDeviceManager = null; } if (Platform != null) { Platform.Activated -= OnActivated; Platform.Deactivated -= OnDeactivated; _services.RemoveService(typeof(GamePlatform)); #if WINDOWS_STOREAPP Platform.ViewStateChanged -= Platform_ApplicationViewChanged; #endif Platform.Dispose(); Platform = null; } Effect.FlushCache(); ContentTypeReaderManager.ClearTypeCreators(); #if WINDOWS_PHONE TouchPanel.ResetState(); #endif #if WINDOWS_MEDIA_SESSION Media.MediaManagerState.CheckShutdown(); #endif #if DIRECTX SoundEffect.Shutdown(); BlendState.ResetStates(); DepthStencilState.ResetStates(); RasterizerState.ResetStates(); SamplerState.ResetStates(); #endif } #if ANDROID Activity = null; #endif _isDisposed = true; _instance = null; } }
public override void Run() { #region Create renderers // Note: the renderers take care of creating their own // device resources and listen for DeviceManager.OnInitialize #region Initialize MeshRenderer instances // Create and initialize the mesh renderer var loadedMesh = Common.Mesh.LoadFromFile("Scene.cmo"); List <MeshRenderer> meshes = new List <MeshRenderer>(); meshes.AddRange((from mesh in loadedMesh select ToDispose(new MeshRenderer(mesh)))); // We will support a envmap for each mesh that contains "reflector" in its name List <DualParaboloidMap> envMaps = new List <DualParaboloidMap>(); // We will rotate any meshes that contains "rotate" in its name List <MeshRenderer> rotateMeshes = new List <MeshRenderer>(); // We will generate meshRows * meshColumns of any mesh that contains "replicate" in its name int meshRows = 10; int meshColumns = 10; // Define an action to initialize our meshes so that we can // dynamically change the number of reflective surfaces and // replicated meshes Action createMeshes = () => { // Clear context states, ensures we don't have // any of the resources we are going to release // assigned to the pipeline. DeviceManager.Direct3DContext.ClearState(); if (contextList != null) { foreach (var context in contextList) { context.ClearState(); } } // Remove meshes foreach (var mesh in meshes) { mesh.Dispose(); } meshes.Clear(); // Remove environment maps foreach (var envMap in envMaps) { envMap.Dispose(); } envMaps.Clear(); // Create non-replicated MeshRenderer instances meshes.AddRange(from mesh in loadedMesh where !((mesh.Name ?? "").ToLower().Contains("replicate")) select ToDispose(new MeshRenderer(mesh))); #region Create replicated meshes // Add the same mesh multiple times, separate by the combined extent var replicatedMeshes = (from mesh in loadedMesh where (mesh.Name ?? "").ToLower().Contains("replicate") select mesh).ToArray(); if (replicatedMeshes.Length > 0) { var minExtent = (from mesh in replicatedMeshes orderby new { mesh.Extent.Min.X, mesh.Extent.Min.Z } select mesh.Extent).First(); var maxExtent = (from mesh in replicatedMeshes orderby new { mesh.Extent.Max.X, mesh.Extent.Max.Z } descending select mesh.Extent).First(); var extentDiff = (maxExtent.Max - minExtent.Min); for (int x = -(meshColumns / 2); x < (meshColumns / 2); x++) { for (int z = -(meshRows / 2); z < (meshRows / 2); z++) { var meshGroup = (from mesh in replicatedMeshes where (mesh.Name ?? "").ToLower().Contains("replicate") select ToDispose(new MeshRenderer(mesh))).ToList(); // Reposition based on width/depth of combined extent foreach (var m in meshGroup) { m.World.TranslationVector = new Vector3(m.Mesh.Extent.Center.X + extentDiff.X * x, m.Mesh.Extent.Min.Y, m.Mesh.Extent.Center.Z + extentDiff.Z * z); } meshes.AddRange(meshGroup); } } } #endregion #region Create reflective meshes // Create reflections where necessary and add rotation meshes int reflectorCount = 0; meshes.ForEach(m => { var name = (m.Mesh.Name ?? "").ToLower(); if (name.Contains("reflector") && reflectorCount < maxReflectors) { reflectorCount++; var envMap = ToDispose(new DualParaboloidMap(512)); envMap.Reflector = m; envMap.Initialize(this); m.EnvironmentMap = envMap; envMaps.Add(envMap); } if (name.Contains("rotate")) { rotateMeshes.Add(m); } m.Initialize(this); }); #endregion // Initialize each mesh meshes.ForEach(m => m.Initialize(this)); }; createMeshes(); // Set the first animation as the current animation and start clock meshes.ForEach(m => { if (m.Mesh.Animations != null && m.Mesh.Animations.Any()) { m.CurrentAnimation = m.Mesh.Animations.First().Value; } m.Clock.Start(); }); // Create the overall mesh World matrix var meshWorld = Matrix.Identity; #endregion // Create and initialize a Direct2D FPS text renderer var fps = ToDispose(new Common.FpsRenderer("Calibri", Color.CornflowerBlue, new Point(8, 8), 16)); fps.Initialize(this); // Create and initialize a general purpose Direct2D text renderer // This will display some instructions and the current view and rotation offsets var textRenderer = ToDispose(new Common.TextRenderer("Calibri", Color.CornflowerBlue, new Point(8, 40), 12)); textRenderer.Initialize(this); #endregion // Initialize the world matrix var worldMatrix = Matrix.Identity; // Set the camera position slightly behind (z) var cameraPosition = new Vector3(0, 1, 2); var cameraTarget = Vector3.Zero; // Looking at the origin 0,0,0 var cameraUp = Vector3.UnitY; // Y+ is Up // Prepare matrices // Create the view matrix from our camera position, look target and up direction var viewMatrix = Matrix.LookAtRH(cameraPosition, cameraTarget, cameraUp); viewMatrix.TranslationVector += new Vector3(0, -0.98f, 0); // Create the projection matrix /* FoV 60degrees = Pi/3 radians */ // Aspect ratio (based on window size), Near clip, Far clip var projectionMatrix = Matrix.PerspectiveFovRH((float)Math.PI / 3f, Width / (float)Height, 0.1f, 100f); // Maintain the correct aspect ratio on resize Window.Resize += (s, e) => { projectionMatrix = Matrix.PerspectiveFovRH((float)Math.PI / 3f, Width / (float)Height, 0.1f, 100f); }; #region Rotation and window event handlers // Create a rotation vector to keep track of the rotation // around each of the axes var rotation = new Vector3(0.0f, 0.0f, 0.0f); // We will call this action to update text // for the text renderer Action updateText = () => { textRenderer.Text = String.Format( "\nPause rotation: P" + "\nThreads: {0} (+/-)" + "\nReflectors: {1} (Shift-Up/Down)" + "\nCPU load: {2} matrix ops (Shift +/-)" + "\nRotating meshes: {3} (Up/Down, Left/Right)" , threadCount, maxReflectors, additionalCPULoad, meshRows * meshColumns); }; Dictionary <Keys, bool> keyToggles = new Dictionary <Keys, bool>(); keyToggles[Keys.Z] = false; keyToggles[Keys.F] = false; // Support keyboard/mouse input to rotate or move camera view var moveFactor = 0.02f; // how much to change on each keypress var shiftKey = false; var ctrlKey = false; var background = Color.White; Window.KeyDown += (s, e) => { var context = DeviceManager.Direct3DContext; shiftKey = e.Shift; ctrlKey = e.Control; switch (e.KeyCode) { // WASD -> pans view case Keys.A: viewMatrix.TranslationVector += new Vector3(moveFactor * 2, 0f, 0f); break; case Keys.D: viewMatrix.TranslationVector -= new Vector3(moveFactor * 2, 0f, 0f); break; case Keys.S: if (shiftKey) { viewMatrix.TranslationVector += new Vector3(0f, moveFactor * 2, 0f); } else { viewMatrix.TranslationVector -= new Vector3(0f, 0f, 1) * moveFactor * 2; } break; case Keys.W: if (shiftKey) { viewMatrix.TranslationVector -= new Vector3(0f, moveFactor * 2, 0f); } else { viewMatrix.TranslationVector += new Vector3(0f, 0f, 1) * moveFactor * 2; } break; // Up/Down and Left/Right - rotates around X / Y respectively // (Mouse wheel rotates around Z) //case Keys.Down: // worldMatrix *= Matrix.RotationX(moveFactor); // rotation += new Vector3(moveFactor, 0f, 0f); // break; //case Keys.Up: // worldMatrix *= Matrix.RotationX(-moveFactor); // rotation -= new Vector3(moveFactor, 0f, 0f); // break; //case Keys.Left: // worldMatrix *= Matrix.RotationY(moveFactor); // rotation += new Vector3(0f, moveFactor, 0f); // break; //case Keys.Right: // worldMatrix *= Matrix.RotationY(-moveFactor); // rotation -= new Vector3(0f, moveFactor, 0f); // break; case Keys.T: fps.Show = !fps.Show; textRenderer.Show = !textRenderer.Show; break; case Keys.B: if (background == Color.White) { background = new Color(30, 30, 34); } else { background = Color.White; } break; case Keys.P: // Pause or resume mesh animation meshes.ForEach(m => { if (m.Clock.IsRunning) { m.Clock.Stop(); } else { m.Clock.Start(); } }); break; case Keys.X: // To test for correct resource recreation // Simulate device reset or lost. System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects()); DeviceManager.Initialize(DeviceManager.Dpi); System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects()); break; //case Keys.Z: // keyToggles[Keys.Z] = !keyToggles[Keys.Z]; // if (keyToggles[Keys.Z]) // { // context.PixelShader.Set(depthPixelShader); // } // else // { // context.PixelShader.Set(pixelShader); // } // break; case Keys.F: keyToggles[Keys.F] = !keyToggles[Keys.F]; RasterizerStateDescription rasterDesc; if (context.Rasterizer.State != null) { rasterDesc = context.Rasterizer.State.Description; } else { rasterDesc = new RasterizerStateDescription() { CullMode = CullMode.Back, FillMode = FillMode.Solid } }; if (keyToggles[Keys.F]) { rasterDesc.FillMode = FillMode.Wireframe; rasterizerState = ToDispose(new RasterizerState(context.Device, rasterDesc)); } else { rasterDesc.FillMode = FillMode.Solid; rasterizerState = ToDispose(new RasterizerState(context.Device, rasterDesc)); } break; //case Keys.D1: // context.PixelShader.Set(pixelShader); // break; //case Keys.D2: // context.PixelShader.Set(lambertShader); // break; //case Keys.D3: // context.PixelShader.Set(phongShader); // break; //case Keys.D4: // context.PixelShader.Set(blinnPhongShader); // break; //case Keys.D5: // context.PixelShader.Set(simpleUVShader); // break; //case Keys.D6: // context.PixelShader.Set(lambertUVShader); // break; //case Keys.D7: // context.PixelShader.Set(phongUVShader); // break; //case Keys.D8: // context.PixelShader.Set(blinnPhongUVShader); // break; } updateText(); }; Window.KeyUp += (s, e) => { // Clear the shift/ctrl keys so they aren't sticky if (e.KeyCode == Keys.ShiftKey) { shiftKey = false; } if (e.KeyCode == Keys.ControlKey) { ctrlKey = false; } }; Window.MouseWheel += (s, e) => { if (shiftKey) { // Zoom in/out viewMatrix.TranslationVector += new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor * 2); } else { // rotate around Z-axis viewMatrix *= Matrix.RotationZ((e.Delta / 120f) * moveFactor); rotation += new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor); } updateText(); }; var lastX = 0; var lastY = 0; Window.MouseDown += (s, e) => { if (e.Button == MouseButtons.Left) { lastX = e.X; lastY = e.Y; } }; Window.MouseMove += (s, e) => { if (e.Button == MouseButtons.Left) { var yRotate = lastX - e.X; var xRotate = lastY - e.Y; lastY = e.Y; lastX = e.X; // Mouse move changes // Rotate view (i.e. camera) //viewMatrix *= Matrix.RotationX(-xRotate * moveFactor); //viewMatrix *= Matrix.RotationY(-yRotate * moveFactor); // Rotate around origin var backup = viewMatrix.TranslationVector; viewMatrix.TranslationVector = Vector3.Zero; viewMatrix *= Matrix.RotationX(-xRotate * moveFactor); viewMatrix.TranslationVector = backup; worldMatrix *= Matrix.RotationY(-yRotate * moveFactor); updateText(); } }; // Display instructions with initial values updateText(); #endregion var clock = new System.Diagnostics.Stopwatch(); clock.Start(); // Setup the deferred contexts SetupContextList(); #region Render loop // Whether or not to reinitialize meshes bool initializeMesh = false; // Define additional key handlers for controlling the // number of threads, reflectors, and replicated meshes #region Dynamic Cube map and threading KeyDown handlers Window.KeyDown += (s, e) => { switch (e.KeyCode) { case Keys.Up: if (shiftKey) { maxReflectors++; } else { meshRows += 2; } initializeMesh = true; break; case Keys.Down: if (shiftKey) { maxReflectors = Math.Max(0, maxReflectors - 1); } else { meshRows = Math.Max(2, meshRows - 2); } initializeMesh = true; break; case Keys.Right: meshColumns += 2; initializeMesh = true; break; case Keys.Left: meshColumns = Math.Max(2, meshColumns - 2); initializeMesh = true; break; case Keys.Add: if (shiftKey) { additionalCPULoad += 100; } else { threadCount++; } break; case Keys.Subtract: if (shiftKey) { additionalCPULoad = Math.Max(0, additionalCPULoad - 100); } else { threadCount = Math.Max(1, threadCount - 1); } break; case Keys.Enter: if (keyToggles.ContainsKey(Keys.Enter)) { keyToggles[Keys.Enter] = !keyToggles[Keys.Enter]; } else { keyToggles[Keys.Enter] = true; } break; default: break; } updateText(); }; #endregion #region Render mesh group // Action for rendering a group of meshes for a // context (based on number of available contexts) Action <int, DeviceContext, Matrix, Matrix> renderMeshGroup = (contextIndex, renderContext, view, projection) => { var viewProjection = view * projection; // Determine the meshes to render for this context int batchSize = (int)Math.Floor((double)meshes.Count / contextList.Length); int startIndex = batchSize * contextIndex; int endIndex = Math.Min(startIndex + batchSize, meshes.Count - 1); // If this is the last context include whatever remains to be // rendered due to the rounding above. if (contextIndex == contextList.Length - 1) { endIndex = meshes.Count - 1; } // Loop over the meshes for this context and render them var perObject = new ConstantBuffers.PerObject(); for (var i = startIndex; i <= endIndex; i++) { // Simulate additional CPU load for (var j = 0; j < additionalCPULoad; j++) { viewProjection = Matrix.Multiply(view, projection); } // Retrieve current mesh var m = meshes[i]; // Check if this is a rotating mesh if (rotateMeshes.Contains(m)) { var rotate = Matrix.RotationAxis(Vector3.UnitY, m.Clock.ElapsedMilliseconds / 1000.0f); perObject.World = m.World * rotate * worldMatrix; } else { perObject.World = m.World * worldMatrix; } // Update perObject constant buffer perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World)); perObject.WorldViewProjection = perObject.World * viewProjection; perObject.Transpose(); renderContext.UpdateSubresource(ref perObject, perObjectBuffer); // Provide the material and armature constant buffer to the mesh renderer m.PerArmatureBuffer = perArmatureBuffer; m.PerMaterialBuffer = perMaterialBuffer; // Render the mesh using the provided DeviceContext m.Render(renderContext); } }; #endregion #region Render scene // Action for rendering the entire scene Action <DeviceContext, Matrix, Matrix, RenderTargetView, DepthStencilView, DualParaboloidMap> renderScene = (context, view, projection, rtv, dsv, envMap) => { // We must initialize the context every time we render // the scene as we are changing the state depending on // whether we are rendering the envmaps or final scene InitializeContext(context, false); // We always need the immediate context // Note: the passed in context will normally be the immediate context // however it is possible to run this method threaded also. var immediateContext = this.DeviceManager.Direct3DDevice.ImmediateContext; // Clear depth stencil view context.ClearDepthStencilView(dsv, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0); // Clear render target view context.ClearRenderTargetView(rtv, background); // Create viewProjection matrix var viewProjection = Matrix.Multiply(view, projection); // Extract camera position from view var camPosition = Matrix.Transpose(Matrix.Invert(view)).Column4; cameraPosition = new Vector3(camPosition.X, camPosition.Y, camPosition.Z); // Setup the per frame constant buffer var perFrame = new ConstantBuffers.PerFrame(); perFrame.Light.Color = new Color(0.9f, 0.9f, 0.9f, 1.0f); var lightDir = Vector3.Transform(new Vector3(-1f, -1f, -1f), worldMatrix); perFrame.Light.Direction = new Vector3(lightDir.X, lightDir.Y, lightDir.Z); perFrame.CameraPosition = cameraPosition; context.UpdateSubresource(ref perFrame, perFrameBuffer); // Render each object // Prepare the default per material constant buffer var perMaterial = new ConstantBuffers.PerMaterial(); perMaterial.Ambient = new Color4(0.2f); perMaterial.Diffuse = Color.White; perMaterial.Emissive = new Color4(0); perMaterial.Specular = Color.White; perMaterial.SpecularPower = 20f; context.UpdateSubresource(ref perMaterial, perMaterialBuffer); // ----------Render meshes------------ if (contextList.Length == 1) { // If there is only one context available there is no need to // generate command lists and execute them so just render the // mesh directly on the current context (which may or may // not be an immediate context depending on the caller). renderMeshGroup(0, context, view, projection); } else { // There are multiple contexts therefore // we are using deferred contexts. Prepare a // separate thread for each available context // and render a group of meshes on each. Task[] renderTasks = new Task[contextList.Length]; CommandList[] commands = new CommandList[contextList.Length]; var viewports = context.Rasterizer.GetViewports(); for (var i = 0; i < contextList.Length; i++) { // Must store the iteration value in another variable // or each task action will use the last iteration value. var contextIndex = i; // Create task to run on new thread from ThreadPool renderTasks[i] = Task.Run(() => { // Retrieve context for this thread var renderContext = contextList[contextIndex]; // Initialize the context state InitializeContext(renderContext, false); // Set the render targets and viewport renderContext.OutputMerger.SetRenderTargets(dsv, rtv); renderContext.Rasterizer.SetViewports(viewports); // If we are rendering for an env map we must set the // per environment map buffer. if (envMap != null) { renderContext.VertexShader.SetConstantBuffer(4, envMap.PerEnvMapBuffer); renderContext.PixelShader.SetConstantBuffer(4, envMap.PerEnvMapBuffer); } // Render logic renderMeshGroup(contextIndex, renderContext, view, projection); // Create the command list if (renderContext.TypeInfo == DeviceContextType.Deferred) { commands[contextIndex] = renderContext.FinishCommandList(false); } }); } // Wait for all the tasks to complete Task.WaitAll(renderTasks); // Replay the command lists on the immediate context for (var i = 0; i < contextList.Length; i++) { if (contextList[i].TypeInfo == DeviceContextType.Deferred && commands[i] != null) { immediateContext.ExecuteCommandList(commands[i], false); // Clean up command list commands[i].Dispose(); commands[i] = null; } } } }; #endregion long frameCount = 0; int lastThreadCount = threadCount; keyToggles[Keys.Enter] = false; // Create and run the render loop RenderLoop.Run(Window, () => { // Allow dynamic changes to number of reflectors and replications if (initializeMesh) { initializeMesh = false; createMeshes(); } if (keyToggles[Keys.Enter]) { // Export the paraboloid maps var i = 0; foreach (var item in envMaps) { using (var tex = item.EnvMapSRV.ResourceAs <Texture2D>()) { for (var j = 0; j < tex.Description.ArraySize; j++) { CopyTexture.SaveToFile(DeviceManager, tex, String.Format("DualMap{0}_{1}.png", i, j), null, tex.Description.MipLevels * j); } i++; } } keyToggles[Keys.Enter] = false; } // Allow dynamic chnages to the number of threads to use if (lastThreadCount != threadCount) { SetupContextList(); lastThreadCount = threadCount; } // Start of frame: frameCount++; // Retrieve immediate context var context = DeviceManager.Direct3DContext; //if (frameCount % 3 == 1) // to update envmap once every third frame //{ #region Update environment maps // Update each of the environment maps activeVertexShader = envMapVSShader; activeGeometryShader = envMapGSShader; activePixelShader = envMapPSShader; // Render the scene from the perspective of each of the environment maps foreach (var envMap in envMaps) { var mesh = envMap.Reflector as MeshRenderer; if (mesh != null) { // Calculate view point for reflector var meshCenter = Vector3.Transform(mesh.Mesh.Extent.Center, mesh.World * worldMatrix); envMap.SetViewPoint(new Vector3(meshCenter.X, meshCenter.Y, meshCenter.Z)); // Render envmap in single full render pass using // geometry shader instancing. envMap.UpdateSinglePass(context, renderScene); } } #endregion //} #region Render final scene // Reset the vertex, geometry and pixel shader activeVertexShader = vertexShader; activeGeometryShader = null; activePixelShader = blinnPhongShader; // Initialize context (also resetting the render targets) InitializeContext(context, true); // Render the final scene renderScene(context, viewMatrix, projectionMatrix, RenderTargetView, DepthStencilView, null); #endregion // Render FPS fps.Render(); // Render instructions + position changes textRenderer.Render(); // Present the frame Present(); }); #endregion } }
public void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect) { g.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, Scale); }
void CreateDeviceResources() { uint width = (uint) host.ActualWidth; uint height = (uint) host.ActualHeight; // If we don't have a device, need to create one now and all // accompanying D3D resources. CreateDevice(); DXGIFactory dxgiFactory = DXGIFactory.CreateFactory(); SwapChainDescription swapDesc = new SwapChainDescription(); swapDesc.BufferDescription.Width = width; swapDesc.BufferDescription.Height = height; swapDesc.BufferDescription.Format = Format.R8G8B8A8_UNORM; swapDesc.BufferDescription.RefreshRate.Numerator = 60; swapDesc.BufferDescription.RefreshRate.Denominator = 1; swapDesc.SampleDescription.Count = 1; swapDesc.SampleDescription.Quality = 0; swapDesc.BufferUsage = UsageOption.RenderTargetOutput; swapDesc.BufferCount = 1; swapDesc.OutputWindowHandle = host.Handle; swapDesc.Windowed = true; swapChain = dxgiFactory.CreateSwapChain( device, swapDesc); // Create rasterizer state object RasterizerDescription rsDesc = new RasterizerDescription(); rsDesc.AntialiasedLineEnable = false; rsDesc.CullMode = CullMode.None; rsDesc.DepthBias = 0; rsDesc.DepthBiasClamp = 0; rsDesc.DepthClipEnable = true; rsDesc.FillMode = D3D10.FillMode.Solid; rsDesc.FrontCounterClockwise = false; // Must be FALSE for 10on9 rsDesc.MultisampleEnable = false; rsDesc.ScissorEnable = false; rsDesc.SlopeScaledDepthBias = 0; rasterizerState = device.CreateRasterizerState( rsDesc); device.RS.SetState( rasterizerState ); // If we don't have a D2D render target, need to create all of the resources // required to render to one here. // Ensure that nobody is holding onto one of the old resources device.OM.SetRenderTargets(new RenderTargetView[] {null}); InitializeDepthStencil(width, height); // Create views on the RT buffers and set them on the device RenderTargetViewDescription renderDesc = new RenderTargetViewDescription(); renderDesc.Format = Format.R8G8B8A8_UNORM; renderDesc.ViewDimension = RenderTargetViewDimension.Texture2D; renderDesc.Texture2D.MipSlice = 0; using (D3DResource spBackBufferResource = swapChain.GetBuffer<D3DResource>(0)) { renderTargetView = device.CreateRenderTargetView( spBackBufferResource, renderDesc); } device.OM.SetRenderTargets(new RenderTargetView[] {renderTargetView}, depthStencilView); SetViewport(width, height); // Create a D2D render target which can draw into the surface in the swap chain RenderTargetProperties props = new RenderTargetProperties( RenderTargetType.Default, new PixelFormat(Format.Unknown, AlphaMode.Premultiplied), 96, 96, RenderTargetUsage.None, FeatureLevel.Default); // Allocate a offscreen D3D surface for D2D to render our 2D content into Texture2DDescription tex2DDescription; tex2DDescription.ArraySize = 1; tex2DDescription.BindFlags = BindFlag.RenderTarget | BindFlag.ShaderResource; tex2DDescription.CpuAccessFlags = CpuAccessFlag.Unspecified; tex2DDescription.Format = Format.R8G8B8A8_UNORM; tex2DDescription.Height = 4096; tex2DDescription.Width = 512; tex2DDescription.MipLevels = 1; tex2DDescription.MiscFlags = 0; tex2DDescription.SampleDescription.Count = 1; tex2DDescription.SampleDescription.Quality = 0; tex2DDescription.Usage = Usage.Default; offscreenTexture = device.CreateTexture2D(tex2DDescription); using (Surface dxgiSurface = offscreenTexture.GetDXGISurface()) { // Create a D2D render target which can draw into our offscreen D3D surface renderTarget = d2DFactory.CreateDxgiSurfaceRenderTarget( dxgiSurface, props); } PixelFormat alphaOnlyFormat = new PixelFormat(Format.A8_UNORM, AlphaMode.Premultiplied); opacityRenderTarget = renderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.None, alphaOnlyFormat); // Load pixel shader // Open precompiled vertex shader // This file was compiled using DirectX's SDK Shader compilation tool: // fxc.exe /T fx_4_0 /Fo SciFiText.fxo SciFiText.fx shader = LoadResourceShader(device, "SciFiTextDemo.SciFiText.fxo"); // Obtain the technique technique = shader.GetTechniqueByName("Render"); // Obtain the variables worldMatrixVariable = shader.GetVariableByName("World").AsMatrix(); viewMatrixVariable = shader.GetVariableByName("View").AsMatrix(); projectionMarixVariable = shader.GetVariableByName("Projection").AsMatrix(); diffuseVariable = shader.GetVariableByName("txDiffuse").AsShaderResource(); // Create the input layout PassDescription passDesc = new PassDescription(); passDesc = technique.GetPassByIndex(0).Description; vertexLayout = device.CreateInputLayout( inputLayoutDescriptions, passDesc.InputAssemblerInputSignature, passDesc.InputAssemblerInputSignatureSize ); // Set the input layout device.IA.SetInputLayout( vertexLayout ); IntPtr verticesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.VerticesInstance)); Marshal.StructureToPtr(VertexArray.VerticesInstance, verticesDataPtr, true); BufferDescription bd = new BufferDescription(); bd.Usage = Usage.Default; bd.ByteWidth = (uint) Marshal.SizeOf(VertexArray.VerticesInstance); bd.BindFlags = BindFlag.VertexBuffer; bd.CpuAccessFlags = CpuAccessFlag.Unspecified; bd.MiscFlags = ResourceMiscFlag.Undefined; SubresourceData InitData = new SubresourceData() { SysMem = verticesDataPtr }; vertexBuffer = device.CreateBuffer( bd, InitData ); Marshal.FreeHGlobal(verticesDataPtr); // Set vertex buffer uint stride = (uint) Marshal.SizeOf(typeof (SimpleVertex)); uint offset = 0; device.IA.SetVertexBuffers( 0, new D3DBuffer[] {vertexBuffer}, new uint[] {stride}, new uint[] {offset} ); IntPtr indicesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.IndicesInstance)); Marshal.StructureToPtr(VertexArray.IndicesInstance, indicesDataPtr, true); bd.Usage = Usage.Default; bd.ByteWidth = (uint) Marshal.SizeOf(VertexArray.IndicesInstance); bd.BindFlags = BindFlag.IndexBuffer; bd.CpuAccessFlags = 0; bd.MiscFlags = 0; InitData.SysMem = indicesDataPtr; facesIndexBuffer = device.CreateBuffer( bd, InitData ); Marshal.FreeHGlobal(indicesDataPtr); // Set primitive topology device.IA.SetPrimitiveTopology(PrimitiveTopology.TriangleList); // Convert the D2D texture into a Shader Resource View textureResourceView = device.CreateShaderResourceView( offscreenTexture); // Initialize the world matrices worldMatrix = Matrix4x4F.Identity; // Initialize the view matrix Vector3F Eye = new Vector3F(0.0f, 0.0f, 13.0f); Vector3F At = new Vector3F(0.0f, -3.5f, 45.0f); Vector3F Up = new Vector3F(0.0f, 1.0f, 0.0f); viewMatrix = Camera.MatrixLookAtLH(Eye, At, Up); // Initialize the projection matrix projectionMatrix = Camera.MatrixPerspectiveFovLH( (float) Math.PI*0.1f, width/(float) height, 0.1f, 100.0f); // Update Variables that never change viewMatrixVariable.Matrix = viewMatrix; projectionMarixVariable.Matrix = projectionMatrix; GradientStop[] gradientStops = { new GradientStop(0.0f, new ColorF(Colors.Yellow)), new GradientStop(1.0f, new ColorF(Colors.Black)) }; GradientStopCollection spGradientStopCollection = renderTarget.CreateGradientStopCollection( gradientStops, Gamma.Gamma_22, ExtendMode.Clamp); // Create a linear gradient brush for text textBrush = renderTarget.CreateLinearGradientBrush( new LinearGradientBrushProperties(new Point2F(0, 0), new Point2F(0, -2048)), spGradientStopCollection ); }
public MaterialPass() { ShaderEntry = new ShaderEntry(); RasterizerStates = new RasterizerState(); BlendStates = new BlendState(); DepthStencilStates = new DepthStencilState(); }
public new void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect, Matrix?matrix) { base.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, matrix ?? Matrix.Identity); }
// ===== #region Draw // Draw public virtual void Draw() { // Entry logging #if IS_LOGGING_DRAW Log.Write(String.Format("Entering method for {0}", this.Name)); #endif // First, draw children for (int i = 0; i < this.Children.Count; i++) { this.Children[i].Draw(); } // Skip root if (this.Name == "View0001") { return; } // Create a rasterizer state RasterizerState rasterizerState = new RasterizerState() { // Enable clipped drawing ScissorTestEnable = true }; // Get scissor rectangle Box rect = this.screenBounds.IntersectionWith(this.screenFrame); // Set scissor rectangle // Globals.Game1.GraphicsDevice.ScissorRectangle = new Microsoft.Xna.Framework.Rectangle((int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height); // Begin clipped drawing Globals.DrawHelper.SpriteBatch.Begin( SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, rasterizerState); #if IS_DRAWING_PRIMITIVES // Proceed according to area if (this.screenFrame.Width == 0 || this.screenFrame.Height == 0) { // Case 1: Zero area Globals.DrawHelper.DrawPoint(this.screenBounds.TopLeft, Color.Black, false); } else { // Case 2: Non-zero area Globals.DrawHelper.FillRectangle(rect, this.Color); rect.Width -= 1; rect.Height -= 1; Globals.DrawHelper.DrawRectangle(rect, Color.Black * 0.2f, false); } #endif // If exists, draw text if (!String.IsNullOrEmpty(this.Text)) { Globals.DrawHelper.DrawString(Globals.FontManager.DefaultFont.Font, this.Text, this.screenBounds.TopLeft, 0, Color.Black); } // End clipped drawing Globals.DrawHelper.SpriteBatch.End(); // Exit logging #if IS_LOGGING_DRAW Log.Write(String.Format("Exiting method for {0}", this.Name)); #endif }
private unsafe void CreateDeviceObjects() { IO io = ImGui.GetIO(); // Build texture atlas FontTextureData texData = io.FontAtlas.GetTexDataAsRGBA32(); // Create DirectX Texture fontTexture = new Texture2D(Device, new Texture2DDescription() { Width = texData.Width, Height = texData.Height, MipLevels = 1, ArraySize = 1, Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 1), Usage = ResourceUsage.Default, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = 0 }, new SharpDX.DataRectangle(new IntPtr(texData.Pixels), texData.Width)); fontTextureView = new ShaderResourceView(Device, fontTexture, new ShaderResourceViewDescription() { Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm, Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0, } }); io.FontAtlas.SetTexID(FontTextureId); // Create texture sampler fontSampler = new SamplerState(Device, new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0.0f, ComparisonFunction = Comparison.Always, MinimumLod = 0.0f, MaximumLod = 0.0f }); // Compile Shader var vertexShaderByteCode = ShaderBytecode.Compile(vertexShaderCode, "vs_4_0", ShaderFlags.None, EffectFlags.None); var vertexShader = new VertexShader(Device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.Compile(pixelShaderCode, "ps_4_0", ShaderFlags.None, EffectFlags.None); var pixelShader = new PixelShader(Device, pixelShaderByteCode); inputLayout = new InputLayout(Device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32_Float, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 1), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 2) }); vertexConstantBuffer = new Buffer(Device, SharpDX.Utilities.SizeOf <SharpDX.Matrix>(), ResourceUsage.Dynamic, BindFlags.ConstantBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0); // Create the blending setup var blendStateDesc = new BlendStateDescription(); blendStateDesc.AlphaToCoverageEnable = true; blendStateDesc.RenderTarget[0].IsBlendEnabled = true; blendStateDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.SourceAlpha; blendStateDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; blendStateDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; blendStateDesc.RenderTarget[0].SourceBlend = BlendOption.InverseSourceAlpha; blendStateDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; blendStateDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; blendStateDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; blendState = new BlendState(Device, blendStateDesc); // Create the rasterizer state rasterizerState = new RasterizerState(Device, new RasterizerStateDescription() { FillMode = FillMode.Solid, CullMode = CullMode.None, IsScissorEnabled = true, IsDepthClipEnabled = true, }); // Create depth-stencil State depthStencilState = new DepthStencilState(Device, new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Always, IsStencilEnabled = false, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep } }); }
protected DrawElement(Device device, EffectPass usingEffectPass, RasterizerState drawMode) { Device = device; UsingEffectPass = usingEffectPass; DrawMode = drawMode; }
private AttributeCollection PrepareAttributes(Logger logger, List<AttributeData> attributes) { attributes = new List<AttributeData>(attributes); for (int i = 0; i < attributes.Count; i++) { var attribute = attributes[i]; bool attributeHandled = true; switch (attribute.Name) { case EffectData.AttributeKeys.Blending: BlendState = graphicsDevice.BlendStates[(string) attribute.Value]; if (BlendState == null) logger.Error("Unable to find registered BlendState [{0}]", (string)attribute.Value); break; case EffectData.AttributeKeys.BlendingColor: BlendStateColor = (Color4) (Vector4) attribute.Value; break; case EffectData.AttributeKeys.BlendingSampleMask: BlendStateSampleMask = (uint) attribute.Value; break; case EffectData.AttributeKeys.DepthStencil: DepthStencilState = graphicsDevice.DepthStencilStates[(string) attribute.Value]; if (DepthStencilState == null) logger.Error("Unable to find registered DepthStencilState [{0}]", (string)attribute.Value); break; case EffectData.AttributeKeys.DepthStencilReference: DepthStencilReference = (int) attribute.Value; break; case EffectData.AttributeKeys.Rasterizer: RasterizerState = graphicsDevice.RasterizerStates[(string) attribute.Value]; if (RasterizerState == null) logger.Error("Unable to find registered RasterizerState [{0}]", (string)attribute.Value); break; default: attributeHandled = false; break; } if (attributeHandled) { attributes.RemoveAt(i); i--; } } return new AttributeCollection(attributes); }
protected override void CreateDeviceDependentResources(DeviceManager deviceManager) { base.CreateDeviceDependentResources(deviceManager); // Release all resources RemoveAndDispose(ref vertexShader); //RemoveAndDispose(ref depthPixelShader); //RemoveAndDispose(ref depthPixelShaderBytecode); //RemoveAndDispose(ref lambertShader); RemoveAndDispose(ref blinnPhongShader); RemoveAndDispose(ref envMapVSShader); RemoveAndDispose(ref envMapGSShader); RemoveAndDispose(ref envMapPSShader); RemoveAndDispose(ref vertexLayout); RemoveAndDispose(ref perObjectBuffer); RemoveAndDispose(ref perFrameBuffer); RemoveAndDispose(ref perMaterialBuffer); RemoveAndDispose(ref perArmatureBuffer); RemoveAndDispose(ref depthStencilState); RemoveAndDispose(ref rasterizerState); // Get a reference to the Device1 instance and immediate context var device = deviceManager.Direct3DDevice; var context = deviceManager.Direct3DContext; // Compile and create the vertex shader and input layout using (var vertexShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\VS.hlsl", "VSMain", "vs_5_0")) { vertexShader = ToDispose(new VertexShader(device, vertexShaderBytecode)); // Layout from VertexShader input signature vertexLayout = ToDispose(new InputLayout(device, vertexShaderBytecode.GetPart(ShaderBytecodePart.InputSignatureBlob), new[] { // "SV_Position" = vertex coordinate in object space new InputElement("SV_Position", 0, Format.R32G32B32_Float, 0, 0), // "NORMAL" = the vertex normal new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), // "COLOR" new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 24, 0), // "UV" new InputElement("TEXCOORD", 0, Format.R32G32_Float, 28, 0), // "SkinIndices" new InputElement("BLENDINDICES", 0, Format.R32G32B32A32_UInt, 36, 0), // "SkinWeights" new InputElement("BLENDWEIGHT", 0, Format.R32G32B32A32_Float, 52, 0), })); } // Compile and create the pixel shader //using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\SimplePS.hlsl", "PSMain", "ps_5_0")) // pixelShader = ToDispose(new PixelShader(device, bytecode)); // Compile and create the depth vertex and pixel shaders // This shader is for checking what the depth buffer would look like //using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\DepthPS.hlsl", "PSMain", "ps_5_0")) // depthPixelShader = ToDispose(new PixelShader(device, bytecode)); // Compile and create the Lambert pixel shader //using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\DiffusePS.hlsl", "PSMain", "ps_5_0")) // lambertShader = ToDispose(new PixelShader(device, bytecode)); // Compile and create the blinn phong pixel shader using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\BlinnPhongPS.hlsl", "PSMain", "ps_5_0")) blinnPhongShader = ToDispose(new PixelShader(device, bytecode)); // Compile and create the Lambert pixel shader //using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\PhongPS.hlsl", "PSMain", "ps_5_0")) // phongShader = ToDispose(new PixelShader(device, bytecode)); // Compile DualMap VS and GS shaders using (var vsBytecode = HLSLCompiler.CompileFromFile(@"Shaders\DualParaboloidMap.hlsl", "VS_DualMap", "vs_5_0", null)) using (var gsBytecode = HLSLCompiler.CompileFromFile(@"Shaders\DualParaboloidMap.hlsl", "GS_DualMap", "gs_5_0", null)) using (var psBytecode = HLSLCompiler.CompileFromFile(@"Shaders\DualParaboloidMap.hlsl", "PS_DualMap", "ps_5_0", null)) { envMapVSShader = ToDispose(new VertexShader(device, vsBytecode)); envMapGSShader = ToDispose(new GeometryShader(device, gsBytecode)); envMapPSShader = ToDispose(new PixelShader(device, psBytecode)); } // IMPORTANT: A constant buffer's size must be a multiple of 16-bytes // use LayoutKind.Explicit and an explicit Size= to force this for structures // or alternatively add padding fields and use a LayoutKind.Sequential and Pack=1 // Create the constant buffer that will // store our worldViewProjection matrix perObjectBuffer = ToDispose(new SharpDX.Direct3D11.Buffer(device, Utilities.SizeOf <ConstantBuffers.PerObject>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0)); // Create the per frame constant buffer // lighting / camera position perFrameBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <ConstantBuffers.PerFrame>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0)); // Create the per material constant buffer perMaterialBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <ConstantBuffers.PerMaterial>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0)); // Create the per armature/skeletong constant buffer perArmatureBuffer = ToDispose(new Buffer(device, ConstantBuffers.PerArmature.Size(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0)); // Configure the depth buffer to discard pixels that are // further than the current pixel. depthStencilState = ToDispose(new DepthStencilState(device, new DepthStencilStateDescription() { IsDepthEnabled = true, // enable depth? DepthComparison = Comparison.Less, DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.All, IsStencilEnabled = false, // enable stencil? StencilReadMask = 0xff, // 0xff (no mask) StencilWriteMask = 0xff, // 0xff (no mask) // Configure FrontFace depth/stencil operations FrontFace = new DepthStencilOperationDescription() { Comparison = Comparison.Always, PassOperation = StencilOperation.Keep, FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment }, // Configure BackFace depth/stencil operations BackFace = new DepthStencilOperationDescription() { Comparison = Comparison.Always, PassOperation = StencilOperation.Keep, FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement }, })); rasterizerState = ToDispose(new RasterizerState(this.DeviceManager.Direct3DDevice, new RasterizerStateDescription() { FillMode = FillMode.Solid, CullMode = CullMode.Back, })); // Initialize the ImmediateContext pipeline stages //InitializeContext(context, true); }