public void Affect(GraphicsDevice device, SamplerState currentState) { SamplerState internalState = new SamplerState(); // Filter internalState.Filter = Filter.HasValue ? Filter.Value : currentState.Filter; // AddressU internalState.AddressU = AddressU.HasValue ? AddressU.Value : currentState.AddressU; // AddressV internalState.AddressV = AddressV.HasValue ? AddressV.Value : currentState.AddressV; // MaxAnisotropy internalState.MaxAnisotropy = MaxAnisotropy.HasValue ? MaxAnisotropy.Value : currentState.MaxAnisotropy; // MaxMipLevel internalState.MaxMipLevel = MaxMipLevel.HasValue ? MaxMipLevel.Value : currentState.MaxMipLevel; // MipMapLevelOfDetailBias internalState.MipMapLevelOfDetailBias = MipMapLevelOfDetailBias.HasValue ? MipMapLevelOfDetailBias.Value : currentState.MipMapLevelOfDetailBias; // Finally apply the state device.SamplerStates[samplerIndex] = internalState; }
/// <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; }
public void upload(ByteArray vertexProgram, ByteArray fragmentProgram) { // create array to hold sampler states var samplerStates = new SamplerState[16]; // convert shaders from AGAL to GLSL var glslVertex = AGALConverter.ConvertToGLSL(vertexProgram, null); var glslFragment = AGALConverter.ConvertToGLSL(fragmentProgram, samplerStates); // upload as GLSL uploadFromGLSL(glslVertex, glslFragment, samplerStates); }
public void upload(ByteArray vertexProgram, ByteArray fragmentProgram) { // create array to hold sampler states var samplerStates = new SamplerState[Context3D.MaxSamplers]; // convert shaders from AGAL to GLSL var glslVertex = AGALConverter.ConvertToGLSL(vertexProgram, null); var glslFragment = AGALConverter.ConvertToGLSL(fragmentProgram, samplerStates); // upload as GLSL uploadFromGLSL(glslVertex, glslFragment); // set sampler states from agal for (int i=0; i < samplerStates.Length; i++) { setSamplerState(i, samplerStates[i]); } }
// sets the sampler state associated with this texture // due to the way GL works, sampler states are parameters of texture objects public void setSamplerState(SamplerState state) { // prevent redundant setting of sampler state if (!state.Equals(mSamplerState)) { // set texture GL.BindTexture(mTextureTarget, mTextureId); // apply state to texture GL.TexParameter (mTextureTarget, TextureParameterName.TextureMinFilter, (int)state.MinFilter); GL.TexParameter (mTextureTarget, TextureParameterName.TextureMagFilter, (int)state.MagFilter); GL.TexParameter (mTextureTarget, TextureParameterName.TextureWrapS, (int)state.WrapModeS); GL.TexParameter (mTextureTarget, TextureParameterName.TextureWrapT, (int)state.WrapModeT); if (state.LodBias != 0.0) { throw new System.NotImplementedException("Lod bias setting not supported yet"); } mSamplerState = state; } }
/// <summary> /// Initializes a new instance of the <see cref="TextureShader" /> class and creates the sampler. /// </summary> /// <param name="device">The device.</param> /// <param name="vertexShaderPath">The vertex shader path.</param> /// <param name="pixelShaderPath">The pixel shader path.</param> protected TextureShader(Device device, string vertexShaderPath, string pixelShaderPath, IInputLayoutProvider inputLayoutMaker) : base(device, vertexShaderPath, pixelShaderPath, inputLayoutMaker) { SamplerDescription sampleDesc = new SamplerDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0f, MaximumAnisotropy = 1, ComparisonFunction = Comparison.Always, BorderColor = new Color4(0, 0, 0, 0), MinimumLod = 0, MaximumLod = float.MaxValue }; sampler = SamplerState.FromDescription(device, sampleDesc); }
/// <summary> /// Initializes device dependant resources. /// </summary> private void Initialize() { var device = m_directCanvasFactory.DeviceContext.Device; /* Here we create a new sampler for sampling input within * our pixel shader */ var sampDesc = new SamplerDescription(); sampDesc.AddressU = TextureAddressMode.Clamp; sampDesc.AddressV = TextureAddressMode.Clamp; sampDesc.AddressW = TextureAddressMode.Clamp; sampDesc.BorderColor = new Color4(0, 0, 0, 0).InternalColor4; sampDesc.ComparisonFunction = Comparison.Never; sampDesc.Filter = Filter.MinMagMipLinear; sampDesc.MaximumAnisotropy = 10; sampDesc.MaximumLod = float.MaxValue; sampDesc.MinimumLod = 0; sampDesc.MipLodBias = 0; m_linearSamplerState = SamplerState.FromDescription(device, sampDesc); sampDesc.Filter = Filter.MinMagMipPoint; m_pointSamplerState = SamplerState.FromDescription(device, sampDesc); /* Here we have a hard coded blend state. This should be configurable in * the future. Like the composer has */ var blendDesc = new BlendStateDescription(); blendDesc.IsAlphaToCoverageEnabled = false; blendDesc.BlendOperation = BlendOperation.Add; blendDesc.AlphaBlendOperation = BlendOperation.Add; blendDesc.DestinationBlend = BlendOption.InverseSourceAlpha; blendDesc.DestinationAlphaBlend = BlendOption.One; blendDesc.SourceBlend = BlendOption.One; blendDesc.SourceAlphaBlend = BlendOption.One; for (uint i = 0; i < 8; i++) { blendDesc.SetWriteMask(i, ColorWriteMaskFlags.All); blendDesc.SetBlendEnable(i, true); } m_alphaBlendState = BlendState.FromDescription(device, blendDesc); }
public static void SetSpriteBatchForPlayerLayerCustomDraw(BlendState blendState, SamplerState samplerState) { Main.spriteBatch.End(); Main.spriteBatch.Begin(SpriteSortMode.Immediate, blendState, samplerState, DepthStencilState.None, Main.instance.Rasterizer, null, Main.GameViewMatrix.TransformationMatrix); }
/// <summary> /// Applies the specified sampler state to this sampler. /// </summary> /// <param name="state">The sampler state to apply.</param> public void ApplySamplerState(SamplerState state) { Contract.Require(state, nameof(state)); var textureWrapR = OpenGLSamplerState.GetTextureAddressModeGL(state.AddressW); if (textureWrapR != cachedTextureWrapR) { cachedTextureWrapR = textureWrapR; gl.SamplerParameteri(sampler, gl.GL_TEXTURE_WRAP_R, textureWrapR); gl.ThrowIfError(); } var textureWrapS = OpenGLSamplerState.GetTextureAddressModeGL(state.AddressU); if (textureWrapS != cachedTextureWrapS) { cachedTextureWrapS = textureWrapS; gl.SamplerParameteri(sampler, gl.GL_TEXTURE_WRAP_S, textureWrapS); gl.ThrowIfError(); } var textureWrapT = OpenGLSamplerState.GetTextureAddressModeGL(state.AddressV); if (textureWrapT != cachedTextureWrapT) { cachedTextureWrapT = textureWrapT; gl.SamplerParameteri(sampler, gl.GL_TEXTURE_WRAP_T, textureWrapT); gl.ThrowIfError(); } if (state.MipMapLevelOfDetailBias != 0) { if (gl.IsMapMapLevelOfDetailBiasAvailable) { if (cachedMipMapLODBias != state.MipMapLevelOfDetailBias) { cachedMipMapLODBias = state.MipMapLevelOfDetailBias; gl.SamplerParameterf(sampler, gl.GL_TEXTURE_LOD_BIAS, state.MipMapLevelOfDetailBias); gl.ThrowIfError(); } } else { throw new NotSupportedException(OpenGLStrings.UnsupportedLODBiasGLES); } } switch (state.Filter) { case TextureFilter.Point: if (cachedMaxAnisotropy != 1f) { cachedMaxAnisotropy = 1f; gl.SamplerParameterf(sampler, gl.GL_TEXTURE_MAX_ANISOTROPY_EXT, 1f); gl.ThrowIfError(); } if (cachedMinFilter != gl.GL_NEAREST) { cachedMinFilter = gl.GL_NEAREST; gl.SamplerParameterf(sampler, gl.GL_TEXTURE_MIN_FILTER, (int)gl.GL_NEAREST); gl.ThrowIfError(); } if (cachedMagFilter != gl.GL_NEAREST) { cachedMagFilter = gl.GL_NEAREST; gl.SamplerParameterf(sampler, gl.GL_TEXTURE_MAG_FILTER, (int)gl.GL_NEAREST); gl.ThrowIfError(); } break; case TextureFilter.Linear: if (gl.IsAnisotropicFilteringAvailable) { if (cachedMaxAnisotropy != 1f) { cachedMaxAnisotropy = 1f; gl.SamplerParameterf(sampler, gl.GL_TEXTURE_MAX_ANISOTROPY_EXT, 1f); gl.ThrowIfError(); } } if (cachedMinFilter != gl.GL_LINEAR) { cachedMinFilter = gl.GL_LINEAR; gl.SamplerParameteri(sampler, gl.GL_TEXTURE_MIN_FILTER, (int)gl.GL_LINEAR); gl.ThrowIfError(); } if (cachedMagFilter != gl.GL_LINEAR) { cachedMagFilter = gl.GL_LINEAR; gl.SamplerParameteri(sampler, gl.GL_TEXTURE_MAG_FILTER, (int)gl.GL_LINEAR); gl.ThrowIfError(); } break; case TextureFilter.Anisotropic: if (gl.IsAnisotropicFilteringAvailable) { var maxAnisotropy = Math.Min(1f, state.MaxAnisotropy); if (maxAnisotropy != cachedMaxAnisotropy) { cachedMaxAnisotropy = maxAnisotropy; gl.SamplerParameterf(sampler, gl.GL_TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy); gl.ThrowIfError(); } } if (cachedMinFilter != gl.GL_LINEAR) { cachedMinFilter = gl.GL_LINEAR; gl.SamplerParameteri(sampler, gl.GL_TEXTURE_MIN_FILTER, (int)gl.GL_LINEAR); gl.ThrowIfError(); } if (cachedMagFilter != gl.GL_LINEAR) { cachedMagFilter = gl.GL_LINEAR; gl.SamplerParameteri(sampler, gl.GL_TEXTURE_MAG_FILTER, (int)gl.GL_LINEAR); gl.ThrowIfError(); } break; default: throw new NotSupportedException(); } }
public void Dispose() { if(m_linearSamplerState != null) { m_linearSamplerState.Dispose(); m_linearSamplerState = null; } if (m_pointSamplerState != null) { m_pointSamplerState.Dispose(); m_pointSamplerState = null; } if(m_alphaBlendState != null) { m_alphaBlendState.Dispose(); m_alphaBlendState = null; } }
public NifuuGame(IntPtr?drawSurface, Vector2 RenderResolution, Vector2 DisplayResolution, string FontLocation, string FadeLocation, SamplerState Sampler, bool AllowWindowResize = false, bool DisplayMouse = true) { Content.RootDirectory = "Content"; Graphics = new GraphicsDeviceManager(this); _RenderRes = RenderResolution; SetResolution(DisplayResolution); Window.AllowUserResizing = AllowWindowResize; IsMouseVisible = DisplayMouse; _Sampler = Sampler; _FontLoc = FontLocation; _FadeLoc = FadeLocation; if (drawSurface != null) { _DrawSurface = drawSurface.Value; Graphics.PreparingDeviceSettings += Graphics_PreparingDeviceSettings; System.Windows.Forms.Control f = System.Windows.Forms.Form.FromHandle(this.Window.Handle); f.VisibleChanged += F_VisibleChanged; } }
public void SetSamplerState(int sampler, SamplerState state, TextureAddress value) { SetSamplerState(sampler, state, (int)value); }
public void OnInitialise(InitialiseMessage msg) { // Initialise renderer Console.WriteLine("Initialising renderer..."); rendermsg = new RenderMessage(); updatemsg = new UpdateMessage(); // Create the window window = new RenderForm("Castle Renderer - 11030062"); window.Width = 1280; window.Height = 720; // Add form events window.FormClosed += window_FormClosed; // Defaults ClearColour = new Color4(1.0f, 0.0f, 0.0f, 1.0f); // Setup the device var description = new SwapChainDescription() { BufferCount = 1, Usage = Usage.RenderTargetOutput, OutputHandle = window.Handle, IsWindowed = true, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm), SampleDescription = new SampleDescription(1, 0), Flags = SwapChainFlags.AllowModeSwitch, SwapEffect = SwapEffect.Discard }; Device tmp; var result = Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out tmp, out swapchain); if (result.IsFailure) { Console.WriteLine("Failed to create Direct3D11 device (" + result.Code.ToString() + ":" + result.Description + ")"); return; } Device = tmp; context = Device.ImmediateContext; using (var factory = swapchain.GetParent<Factory>()) factory.SetWindowAssociation(window.Handle, WindowAssociationFlags.IgnoreAltEnter); // Check AA stuff int q = Device.CheckMultisampleQualityLevels(Format.R8G8B8A8_UNorm, 8); // Setup the viewport viewport = new Viewport(0.0f, 0.0f, window.ClientSize.Width, window.ClientSize.Height); viewport.MinZ = 0.0f; viewport.MaxZ = 1.0f; context.Rasterizer.SetViewports(viewport); // Setup the backbuffer using (var resource = Resource.FromSwapChain<Texture2D>(swapchain, 0)) rtBackbuffer = new RenderTargetView(Device, resource); // Setup depth for backbuffer { Texture2DDescription texdesc = new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, Format = Format.D32_Float, Width = (int)viewport.Width, Height = (int)viewport.Height, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }; texDepthBuffer = new Texture2D(Device, texdesc); DepthStencilViewDescription viewdesc = new DepthStencilViewDescription() { ArraySize = 0, Format = Format.D32_Float, Dimension = DepthStencilViewDimension.Texture2D, MipSlice = 0, Flags = 0, FirstArraySlice = 0 }; vwDepthBuffer = new DepthStencilView(Device, texDepthBuffer, viewdesc); } // Setup states #region Depth States // Setup depth states { DepthStencilStateDescription desc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; Depth_Enabled = DepthStencilState.FromDescription(Device, desc); } { DepthStencilStateDescription desc = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.Zero, DepthComparison = Comparison.Less }; Depth_Disabled = DepthStencilState.FromDescription(Device, desc); } { DepthStencilStateDescription desc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.Zero, DepthComparison = Comparison.Less }; Depth_ReadOnly = DepthStencilState.FromDescription(Device, desc); } #endregion #region Sampler States Sampler_Clamp = SamplerState.FromDescription(Device, new SamplerDescription() { AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, Filter = Filter.Anisotropic, MinimumLod = 0.0f, MaximumLod = float.MaxValue, MaximumAnisotropy = 16 }); Sampler_Clamp_Point = SamplerState.FromDescription(Device, new SamplerDescription() { AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, Filter = Filter.MinMagMipPoint }); Sampler_Clamp_Linear = SamplerState.FromDescription(Device, new SamplerDescription() { AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, Filter = Filter.MinMagMipLinear }); Sampler_Wrap = SamplerState.FromDescription(Device, new SamplerDescription() { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, Filter = Filter.Anisotropic, MinimumLod = 0.0f, MaximumLod = float.MaxValue, MaximumAnisotropy = 16 }); #endregion #region Rasterizer States Culling_Backface = RasterizerState.FromDescription(Device, new RasterizerStateDescription() { CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsAntialiasedLineEnabled = false, IsFrontCounterclockwise = false, IsMultisampleEnabled = true, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }); Culling_Frontface = RasterizerState.FromDescription(Device, new RasterizerStateDescription() { CullMode = CullMode.Front, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsAntialiasedLineEnabled = false, IsFrontCounterclockwise = false, IsMultisampleEnabled = true, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }); Culling_None = RasterizerState.FromDescription(Device, new RasterizerStateDescription() { CullMode = CullMode.None, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsAntialiasedLineEnabled = false, IsFrontCounterclockwise = false, IsMultisampleEnabled = true, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }); #endregion #region Blend States { BlendStateDescription desc = new BlendStateDescription(); desc.RenderTargets[0].BlendEnable = true; desc.RenderTargets[0].BlendOperation = BlendOperation.Add; desc.RenderTargets[0].SourceBlend = BlendOption.One; desc.RenderTargets[0].DestinationBlend = BlendOption.Zero; desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add; desc.RenderTargets[0].SourceBlendAlpha = BlendOption.One; desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero; desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; Blend_Opaque = BlendState.FromDescription(Device, desc); } { BlendStateDescription desc = new BlendStateDescription(); desc.RenderTargets[0].BlendEnable = true; desc.RenderTargets[0].BlendOperation = BlendOperation.Add; desc.RenderTargets[0].SourceBlend = BlendOption.SourceAlpha; desc.RenderTargets[0].DestinationBlend = BlendOption.InverseSourceAlpha; desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add; desc.RenderTargets[0].SourceBlendAlpha = BlendOption.One; desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero; desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; Blend_Alpha = BlendState.FromDescription(Device, desc); } { BlendStateDescription desc = new BlendStateDescription(); desc.RenderTargets[0].BlendEnable = true; desc.RenderTargets[0].BlendOperation = BlendOperation.Add; desc.RenderTargets[0].SourceBlend = BlendOption.One; desc.RenderTargets[0].DestinationBlend = BlendOption.One; desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add; desc.RenderTargets[0].SourceBlendAlpha = BlendOption.One; desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero; desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; Blend_Add = BlendState.FromDescription(Device, desc); } { BlendStateDescription desc = new BlendStateDescription(); desc.RenderTargets[0].BlendEnable = true; desc.RenderTargets[0].BlendOperation = BlendOperation.Add; desc.RenderTargets[0].SourceBlend = BlendOption.DestinationColor; desc.RenderTargets[0].DestinationBlend = BlendOption.Zero; desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add; desc.RenderTargets[0].SourceBlendAlpha = BlendOption.One; desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero; desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; Blend_Multiply = BlendState.FromDescription(Device, desc); } #endregion // Setup default states Depth = Depth_Enabled; Culling = Culling_Backface; Blend = Blend_Opaque; // Setup other objects shaderresourcemap = new Dictionary<Resource, ShaderResourceView>(); resourceviewslots = new ShaderResourceViewData[MaxPixelShaderResourceViewSlots]; // Send the window created message WindowCreatedMessage windowcreatedmsg = new WindowCreatedMessage(); windowcreatedmsg.Form = window; Owner.MessagePool.SendMessage(windowcreatedmsg); // Show the form window.Show(); }
private bool InitializeShader(Device device, IntPtr windowsHandler, string vsFileName, string psFileName) { try { // Setup full pathes vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName; psFileName = DSystemConfiguration.ShaderFilePath + psFileName; // Compile the Vertex Shader & Pixel Shader code. ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "GlowVertexShader", DSystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None); ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "GlowPixelShader", DSystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None); // Create the Vertex & Pixel Shaders from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType structure in the Model and in the shader. InputElement[] inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "TEXCOORD", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; // Create the vertex input the layout. Kin dof like a Vertex Declaration. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant Matrix buffer that is in the vertex shader. BufferDescription matrixBufferDescription = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <DMatrixBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDescription); // Setup the description of the dynamic glow constant buffer that is in the pixel shader. BufferDescription glowBufferDescription = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <DGlowBufferType>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the pixel shader constant buffer from within this class. ConstantGlowBuffer = new SharpDX.Direct3D11.Buffer(device, glowBufferDescription); // Create a texture sampler state description. SamplerStateDescription samplerDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0, MaximumAnisotropy = 1, ComparisonFunction = Comparison.Always, BorderColor = new Color4(0, 0, 0, 0), // Black Border. MinimumLod = 0, MaximumLod = float.MaxValue }; // Create the texture sampler state. SamplerState = new SamplerState(device, samplerDesc); return(true); } catch (Exception ex) { MessageBox.Show("Error initializing shader. Error is " + ex.Message); return(false); } }
private void SetSamplerState(int sampler, SamplerState type, bool value) { SetSamplerState( sampler, type, value ? 1 : 0 ); }
public void SetValue(string name, SamplerState sampler) { SetValueImpl(name, sampler); }
public ScreenShaderData UseImage(string path, int index = 0, SamplerState samplerState = null) { this._uImages[index] = TextureManager.AsyncLoad(path); this._samplerStates[index] = samplerState; return(this); }
private bool InitializeShader(Device device, string vsFilename, string psFilename) { try { ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFilename, "FontVertexShader", "vs_5_0", ShaderFlags.EnableStrictness, EffectFlags.None); ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFilename, "FontPixelShader", "ps_5_0", ShaderFlags.EnableStrictness, EffectFlags.None); _vertexShader = new VertexShader(device, vertexShaderByteCode); _pixelShader = new PixelShader(device, pixelShaderByteCode); InputElement[] inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "TEXCOORD", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; _layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); BufferDescription constantBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <ConstantBufferType>(), // was Matrix BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; _constantBuffer = new SharpDX.Direct3D11.Buffer(device, constantBufferDesc); var samplerDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0, MaximumAnisotropy = 1, ComparisonFunction = Comparison.Always, BorderColor = new Color4(0, 0, 0, 0), MinimumLod = 0, MaximumLod = float.MaxValue }; _sampleState = new SamplerState(device, samplerDesc); var pixelBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <PixelBufferType>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; _pixelBuffer = new SharpDX.Direct3D11.Buffer(device, pixelBufferDesc); return(true); } catch (Exception ex) { MessageBox.Show("Error initializing shader. Error is " + ex.Message); return(false); } }
private void SetSampler(CommonShaderStage stage, ShaderStageCache cache, int slot, SamplerState sampler) { if (cache.Samplers[slot] != sampler) { stage.SetSampler(slot, sampler); cache.Samplers[slot] = sampler; } }
public ObjectParameterKey <SamplerState> GetSamplerKey(SamplerStateDescription samplerStateDesc, GraphicsDevice graphicsDevice) { ObjectParameterKey <SamplerState> key; if (!declaredSamplerStates.TryGetValue(samplerStateDesc, out key)) { key = MaterialKeys.Sampler.ComposeWith("i" + declaredSamplerStates.Count.ToString(CultureInfo.InvariantCulture)); declaredSamplerStates.Add(samplerStateDesc, key); } var samplerState = graphicsDevice != null?SamplerState.New(graphicsDevice, samplerStateDesc) : SamplerState.NewFake(samplerStateDesc); Parameters.Set(key, samplerState); return(key); }
private Result GetSamplerState(IntPtr devicePointer, int sampler, SamplerState type, IntPtr value) { throw new NotImplementedException(); }
internal static void OnBegin(SpriteBatch __instance, SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect, Matrix transformMatrix) { DrawState.OnBegin( __instance, sortMode, blendState ?? BlendState.AlphaBlend, samplerState ?? SamplerState.PointClamp, depthStencilState ?? DepthStencilState.None, rasterizerState ?? RasterizerState.CullCounterClockwise, effect, transformMatrix ); }
public void SetByName(string name, SamplerState sampler) { if (sampler != null) { this.effect.GetVariableByName(name).AsSampler().SetSamplerState(0,sampler); } else { this.effect.GetVariableByName(name).AsSampler().UndoSetSamplerState(0); } }
public DebugRenderer() : base(RenderSurface.Default, SpriteSortMode.Deferred) { BlendState = BlendState.NonPremultiplied; // BlendState.AlphaBlend; SamplerState = SamplerState.LinearClamp; }
public void DrawCustomTexture(SpriteTexture customTex, ref Rectangle textureSourceRect, ref RectangleF bounds, float rotation, SamplerState sampler, int groupId = 0, ByteColor?color = null) { var offset = new UniRectangle(0, 0, bounds.Width, bounds.Height); var destinationRegion = calculateDestinationRectangle( ref bounds, ref offset ); ByteColor col; if (!color.HasValue) { col = _defaultColor; } else { col = (ByteColor)color; } spriteRenderer.Draw(customTex, ref destinationRegion, ref textureSourceRect, ref col, rotation, sampler, drawGroupId: groupId); }
/// <summary> /// Creates a new instance of the SpriteRenderer /// </summary> /// <param name="device">The device to use</param> /// <param name="maxSpriteInstances">The maximum sprite instances that can be cached before a flush happens</param> public SpriteRenderer(Device device, int maxSpriteInstances = 10000) { /* Initialize our arrays to hold our sprite data */ m_spriteRenderData = new SpriteRenderData[maxSpriteInstances]; m_spriteDrawData = new SpriteDrawData[maxSpriteInstances]; /* Initialize all the items in the array */ for (int i = 0; i < maxSpriteInstances; i++) { m_spriteRenderData[i] = new SpriteRenderData(); } m_maxSpriteInstances = maxSpriteInstances; m_device = device; /* Create our default blend states using our helper */ m_blendStates = SpriteRendererBlendStateHelper.InitializeDefaultBlendStates(m_device); /* Create our vertex shader */ m_vertexShaderInstanced10 = new VertexShader10(device, SHADER_RESOURCE_NAME, Assembly.GetExecutingAssembly(), "SpriteInstancedVS", ShaderVersion.Vs_4_0); /* Create our pixel shader */ m_pixelShader10 = new PixelShader10(device, SHADER_RESOURCE_NAME, Assembly.GetExecutingAssembly(), "SpritePS", ShaderVersion.Ps_4_0,ShaderFlags.Debug); /* Create a new sprite quad that holds our GPU buffers */ m_spriteQuad = new SpriteQuad(device, maxSpriteInstances); m_spriteQuadShaderBinding = new GeometryInputShaderBinding(m_spriteQuad, m_vertexShaderInstanced10, m_pixelShader10); var rastDesc = new RasterizerStateDescription(); rastDesc.IsAntialiasedLineEnabled = false; rastDesc.CullMode = CullMode.None; rastDesc.DepthBias = 0; rastDesc.DepthBiasClamp = 1.0f; rastDesc.IsDepthClipEnabled = false; rastDesc.FillMode = FillMode.Solid; rastDesc.IsFrontCounterclockwise = false; rastDesc.IsMultisampleEnabled = false; rastDesc.IsScissorEnabled = false; rastDesc.SlopeScaledDepthBias = 0; m_rasterizerState = RasterizerState.FromDescription(m_device, rastDesc); var dsDesc = new DepthStencilStateDescription(); dsDesc.IsDepthEnabled = false; dsDesc.DepthWriteMask = DepthWriteMask.All; dsDesc.DepthComparison = Comparison.Less; dsDesc.IsStencilEnabled = false; dsDesc.StencilReadMask = 0xff; dsDesc.StencilWriteMask = 0xff; dsDesc.FrontFace = new DepthStencilOperationDescription{ DepthFailOperation = StencilOperation.Keep, FailOperation = StencilOperation.Replace, Comparison = Comparison.Always }; dsDesc.BackFace = dsDesc.FrontFace; m_dsState = DepthStencilState.FromDescription(m_device, dsDesc); var sampDesc = new SamplerDescription(); sampDesc.AddressU = TextureAddressMode.Wrap; sampDesc.AddressV = TextureAddressMode.Wrap; sampDesc.AddressW = TextureAddressMode.Wrap; sampDesc.BorderColor = new Color4(0, 0, 0, 0).InternalColor4; sampDesc.ComparisonFunction = Comparison.Never; sampDesc.Filter = Filter.MinMagMipLinear; sampDesc.MaximumAnisotropy = 1; sampDesc.MaximumLod = float.MaxValue; sampDesc.MinimumLod = 0; sampDesc.MipLodBias = 0; m_linearSamplerState = SamplerState.FromDescription(m_device, sampDesc); sampDesc.Filter = Filter.MinMagMipPoint; m_pointSamplerState = SamplerState.FromDescription(m_device, sampDesc); }
// sets the sampler state for a sampler when this program is used public void setSamplerState(int sampler, SamplerState state) { mSamplerStates[sampler] = state; }
public void SetSamplerState(int sampler, SamplerState state, TextureFilter value) { device.SetSamplerState(sampler, state, value); }
public void CloseD3D11() { CloseSharedResource(); if (_mainRenderTargerView != null) { _mainRenderTargerView.Dispose(); _mainRenderTargerView = null; } if (_vertexShaderConstansData != IntPtr.Zero) { Marshal.FreeHGlobal(_vertexShaderConstansData); _vertexShaderConstansData = IntPtr.Zero; } if (_swapChain != null) { _swapChain.Dispose(); _swapChain = null; } if (_dxgiFactory != null) { _dxgiFactory.Dispose(); _dxgiFactory = null; } if (_dxiAdapter != null) { _dxiAdapter.Dispose(); _dxiAdapter = null; } if (_d3d11Device != null) { _d3d11Device.Dispose(); _d3d11Device = null; } if (_dxgiDevice != null) { _dxgiDevice.Dispose(); _dxgiDevice = null; } if (_vertexShader != null) { _vertexShader.Dispose(); _vertexShader = null; } if (_pixelShader != null) { _pixelShader.Dispose(); _pixelShader = null; } if (_vertexShaderConstans != null) { _vertexShaderConstans.Dispose(); _vertexShaderConstans = null; } if (_samplerState != null) { _samplerState.Dispose(); _samplerState = null; } if (_rasterizerState != null) { _rasterizerState.Dispose(); _rasterizerState = null; } if (_inputLayout != null) { _inputLayout.Dispose(); _inputLayout = null; } }
public void SetSamplerState(int sampler, SamplerState state, TextureAddress value) { device.SetSamplerState(sampler, state, value); }
private bool InitializeShader(Device device, IntPtr windowHandler, string vsFileName, string psFileName) { try { // Setup full pathes vsFileName = SystemConfiguration.ShadersFilePath + vsFileName; psFileName = SystemConfiguration.ShadersFilePath + psFileName; // Compile the vertex shader code. var vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "HeightMapTerrainVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None); // Compile the pixel shader code. var pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "HeightMapTerrainPixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None); // Create the vertex shader from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); // Create the pixel shader from the buffer. PixelShader = new PixelShader(device, pixelShaderByteCode); // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType structure in the Model and in the shader. var inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "TEXCOORD", SemanticIndex = 0, Format = Format.R32G32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "NORMAL", SemanticIndex = 0, Format = Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; // Create the vertex input the layout. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Create a texture sampler state description. var samplerDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0, MaximumAnisotropy = 1, ComparisonFunction = Comparison.Always, BorderColor = new Color4(0, 0, 0, 0), MinimumLod = 0, MaximumLod = float.MaxValue }; // Create the texture sampler state. SampleState = new SamplerState(device, samplerDesc); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var matrixBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <MatrixBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new Buffer(device, matrixBufferDesc); // Setup the description of the light dynamic constant bufffer that is in the pixel shader. // Note that ByteWidth alwalys needs to be a multiple of the 16 if using D3D11_BIND_CONSTANT_BUFFER or CreateBuffer will fail. var lightBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <LightBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantLightBuffer = new Buffer(device, lightBufferDesc); return(true); } catch (Exception ex) { MessageBox.Show("Error initializing shader. Error is " + ex.Message); return(false); }; }
public static void ResetSpriteBatchForPlayerDrawLayers(SamplerState samplerState) { Main.spriteBatch.End(); Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, samplerState, DepthStencilState.None, Main.instance.Rasterizer, null, Main.GameViewMatrix.TransformationMatrix); }
public void Dispose() { if(m_spriteQuad != null) { m_spriteQuad.Dispose(); m_spriteQuad = null; } if(m_linearSamplerState != null) { m_linearSamplerState.Dispose(); m_linearSamplerState = null; } if(m_pointSamplerState != null) { m_pointSamplerState.Dispose(); m_pointSamplerState = null; } if(m_spriteQuadShaderBinding != null) { m_spriteQuadShaderBinding.Dispose(); m_spriteQuadShaderBinding.Dispose(); } if(m_vertexShaderInstanced10 != null) { m_vertexShaderInstanced10.Dispose(); m_vertexShaderInstanced10 = null; } foreach (var blendState in m_blendStates) { blendState.Value.Dispose(); } m_blendStates.Clear(); if(m_pixelShader10 != null) { m_pixelShader10.Dispose(); m_pixelShader10 = null; } }
private void DrawPlayerFull(Camera camera, Player drawPlayer) { SpriteBatch spriteBatch = camera.SpriteBatch; SamplerState samplerState = camera.Sampler; if (drawPlayer.mount.Active && drawPlayer.fullRotation != 0f) { samplerState = MountedSamplerState; } spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, samplerState, DepthStencilState.None, camera.Rasterizer, null, camera.GameViewMatrix.TransformationMatrix); if (Main.gamePaused) { drawPlayer.PlayerFrame(); } if (drawPlayer.ghost) { for (int i = 0; i < 3; i++) { Vector2 vector = drawPlayer.shadowPos[i]; vector = drawPlayer.position - drawPlayer.velocity * (2 + i * 2); DrawGhost(camera, drawPlayer, vector, 0.5f + 0.2f * (float)i); } DrawGhost(camera, drawPlayer, drawPlayer.position); } else { if (drawPlayer.inventory[drawPlayer.selectedItem].flame || drawPlayer.head == 137 || drawPlayer.wings == 22) { drawPlayer.itemFlameCount--; if (drawPlayer.itemFlameCount <= 0) { drawPlayer.itemFlameCount = 5; for (int j = 0; j < 7; j++) { drawPlayer.itemFlamePos[j].X = (float)Main.rand.Next(-10, 11) * 0.15f; drawPlayer.itemFlamePos[j].Y = (float)Main.rand.Next(-10, 1) * 0.35f; } } } if (drawPlayer.armorEffectDrawShadowEOCShield) { int num = drawPlayer.eocDash / 4; if (num > 3) { num = 3; } for (int k = 0; k < num; k++) { DrawPlayer(camera, drawPlayer, drawPlayer.shadowPos[k], drawPlayer.shadowRotation[k], drawPlayer.shadowOrigin[k], 0.5f + 0.2f * (float)k); } } Vector2 position = default(Vector2); if (drawPlayer.invis) { drawPlayer.armorEffectDrawOutlines = false; drawPlayer.armorEffectDrawShadow = false; drawPlayer.armorEffectDrawShadowSubtle = false; position = drawPlayer.position; if (drawPlayer.aggro <= -750) { DrawPlayer(camera, drawPlayer, position, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin, 1f); } else { drawPlayer.invis = false; DrawPlayer(camera, drawPlayer, position, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin); drawPlayer.invis = true; } } if (drawPlayer.armorEffectDrawOutlines) { _ = drawPlayer.position; if (!Main.gamePaused) { drawPlayer.ghostFade += drawPlayer.ghostDir * 0.075f; } if ((double)drawPlayer.ghostFade < 0.1) { drawPlayer.ghostDir = 1f; drawPlayer.ghostFade = 0.1f; } else if ((double)drawPlayer.ghostFade > 0.9) { drawPlayer.ghostDir = -1f; drawPlayer.ghostFade = 0.9f; } float num2 = drawPlayer.ghostFade * 5f; for (int l = 0; l < 4; l++) { float num3; float num4; switch (l) { default: num3 = num2; num4 = 0f; break; case 1: num3 = 0f - num2; num4 = 0f; break; case 2: num3 = 0f; num4 = num2; break; case 3: num3 = 0f; num4 = 0f - num2; break; } position = new Vector2(drawPlayer.position.X + num3, drawPlayer.position.Y + drawPlayer.gfxOffY + num4); DrawPlayer(camera, drawPlayer, position, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin, drawPlayer.ghostFade); } } if (drawPlayer.armorEffectDrawOutlinesForbidden) { _ = drawPlayer.position; if (!Main.gamePaused) { drawPlayer.ghostFade += drawPlayer.ghostDir * 0.025f; } if ((double)drawPlayer.ghostFade < 0.1) { drawPlayer.ghostDir = 1f; drawPlayer.ghostFade = 0.1f; } else if ((double)drawPlayer.ghostFade > 0.9) { drawPlayer.ghostDir = -1f; drawPlayer.ghostFade = 0.9f; } float num5 = drawPlayer.ghostFade * 5f; for (int m = 0; m < 4; m++) { float num6; float num7; switch (m) { default: num6 = num5; num7 = 0f; break; case 1: num6 = 0f - num5; num7 = 0f; break; case 2: num6 = 0f; num7 = num5; break; case 3: num6 = 0f; num7 = 0f - num5; break; } position = new Vector2(drawPlayer.position.X + num6, drawPlayer.position.Y + drawPlayer.gfxOffY + num7); DrawPlayer(camera, drawPlayer, position, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin, drawPlayer.ghostFade); } } if (drawPlayer.armorEffectDrawShadowBasilisk) { int num8 = (int)(drawPlayer.basiliskCharge * 3f); for (int n = 0; n < num8; n++) { DrawPlayer(camera, drawPlayer, drawPlayer.shadowPos[n], drawPlayer.shadowRotation[n], drawPlayer.shadowOrigin[n], 0.5f + 0.2f * (float)n); } } else if (drawPlayer.armorEffectDrawShadow) { for (int num9 = 0; num9 < 3; num9++) { DrawPlayer(camera, drawPlayer, drawPlayer.shadowPos[num9], drawPlayer.shadowRotation[num9], drawPlayer.shadowOrigin[num9], 0.5f + 0.2f * (float)num9); } } if (drawPlayer.armorEffectDrawShadowLokis) { for (int num10 = 0; num10 < 3; num10++) { DrawPlayer(camera, drawPlayer, Vector2.Lerp(drawPlayer.shadowPos[num10], drawPlayer.position + new Vector2(0f, drawPlayer.gfxOffY), 0.5f), drawPlayer.shadowRotation[num10], drawPlayer.shadowOrigin[num10], MathHelper.Lerp(1f, 0.5f + 0.2f * (float)num10, 0.5f)); } } if (drawPlayer.armorEffectDrawShadowSubtle) { for (int num11 = 0; num11 < 4; num11++) { position.X = drawPlayer.position.X + (float)Main.rand.Next(-20, 21) * 0.1f; position.Y = drawPlayer.position.Y + (float)Main.rand.Next(-20, 21) * 0.1f + drawPlayer.gfxOffY; DrawPlayer(camera, drawPlayer, position, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin, 0.9f); } } if (drawPlayer.shadowDodge) { drawPlayer.shadowDodgeCount += 1f; if (drawPlayer.shadowDodgeCount > 30f) { drawPlayer.shadowDodgeCount = 30f; } } else { drawPlayer.shadowDodgeCount -= 1f; if (drawPlayer.shadowDodgeCount < 0f) { drawPlayer.shadowDodgeCount = 0f; } } if (drawPlayer.shadowDodgeCount > 0f) { _ = drawPlayer.position; position.X = drawPlayer.position.X + drawPlayer.shadowDodgeCount; position.Y = drawPlayer.position.Y + drawPlayer.gfxOffY; DrawPlayer(camera, drawPlayer, position, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin, 0.5f + (float)Main.rand.Next(-10, 11) * 0.005f); position.X = drawPlayer.position.X - drawPlayer.shadowDodgeCount; DrawPlayer(camera, drawPlayer, position, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin, 0.5f + (float)Main.rand.Next(-10, 11) * 0.005f); } if (drawPlayer.brainOfConfusionDodgeAnimationCounter > 0) { Vector2 value = drawPlayer.position + new Vector2(0f, drawPlayer.gfxOffY); float lerpValue = Utils.GetLerpValue(300f, 270f, drawPlayer.brainOfConfusionDodgeAnimationCounter); float y = MathHelper.Lerp(2f, 120f, lerpValue); if (lerpValue >= 0f && lerpValue <= 1f) { for (float num12 = 0f; num12 < (float)Math.PI * 2f; num12 += (float)Math.PI / 3f) { position = value + new Vector2(0f, y).RotatedBy((float)Math.PI * 2f * lerpValue * 0.5f + num12); DrawPlayer(camera, drawPlayer, position, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin, lerpValue); } } } position = drawPlayer.position; position.Y += drawPlayer.gfxOffY; if (drawPlayer.stoned) { DrawPlayerStoned(camera, drawPlayer, position); } else if (!drawPlayer.invis) { DrawPlayer(camera, drawPlayer, position, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin); } } spriteBatch.End(); }
public void SetSamplerState(int sampler, SamplerState state, int value) { device.SetSamplerState(sampler, state, value); }
protected override async Task LoadContent() { await base.LoadContent(); pipelineState = new MutablePipelineState(GraphicsDevice); var vertices = new Vertex[4]; vertices[0] = new Vertex { Position = new Vector3(-1, -1, 0.5f), TexCoords = new Vector2(0, 0) }; vertices[1] = new Vertex { Position = new Vector3(-1, 1, 0.5f), TexCoords = new Vector2(3, 0) }; vertices[2] = new Vertex { Position = new Vector3(1, 1, 0.5f), TexCoords = new Vector2(3, 3) }; vertices[3] = new Vertex { Position = new Vector3(1, -1, 0.5f), TexCoords = new Vector2(0, 3) }; var indices = new short[] { 0, 1, 2, 0, 2, 3 }; var vertexBuffer = Buffer.Vertex.New(GraphicsDevice, vertices, GraphicsResourceUsage.Default); var indexBuffer = Buffer.Index.New(GraphicsDevice, indices, GraphicsResourceUsage.Default); var meshDraw = new MeshDraw { DrawCount = 4, PrimitiveType = PrimitiveType.TriangleList, VertexBuffers = new[] { new VertexBufferBinding(vertexBuffer, new VertexDeclaration(VertexElement.Position <Vector3>(), VertexElement.TextureCoordinate <Vector2>()), 4) }, IndexBuffer = new IndexBufferBinding(indexBuffer, false, indices.Length), }; mesh = new Mesh { Draw = meshDraw, }; simpleEffect = new EffectInstance(new Effect(GraphicsDevice, SpriteEffect.Bytecode)); simpleEffect.Parameters.Set(TexturingKeys.Texture0, UVTexture); simpleEffect.UpdateEffect(GraphicsDevice); // TODO GRAPHICS REFACTOR //vao = VertexArrayObject.New(GraphicsDevice, mesh.Draw.IndexBuffer, mesh.Draw.VertexBuffers); myDraws = new DrawOptions[3]; myDraws[0] = new DrawOptions { Sampler = GraphicsDevice.SamplerStates.LinearClamp, Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(-0.5f, 0.5f, 0f)) }; myDraws[1] = new DrawOptions { Sampler = GraphicsDevice.SamplerStates.LinearWrap, Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(0.5f, 0.5f, 0f)) }; myDraws[2] = new DrawOptions { Sampler = SamplerState.New(GraphicsDevice, new SamplerStateDescription(TextureFilter.Linear, TextureAddressMode.Mirror)), Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(0.5f, -0.5f, 0f)) }; //var borderDescription = new SamplerStateDescription(TextureFilter.Linear, TextureAddressMode.Border) { BorderColor = Color.Purple }; //var border = SamplerState.New(GraphicsDevice, borderDescription); //myDraws[3] = new DrawOptions { Sampler = border, Transform = Matrix.Multiply(Matrix.Scale(0.3f), Matrix.Translation(-0.5f, -0.5f, 0f)) }; }
/// <summary> /// Creates stock states /// </summary> static SamplerState () { LinearWrap = Create( Filter.MinMagMipLinear , AddressMode.Wrap, new Color4(0f) ); LinearClamp = Create( Filter.MinMagMipLinear , AddressMode.Clamp, new Color4(0f) ); PointWrap = Create( Filter.MinMagMipPoint , AddressMode.Wrap, new Color4(0f) ); PointClamp = Create( Filter.MinMagMipPoint , AddressMode.Clamp, new Color4(0f) ); AnisotropicWrap = Create( Filter.Anisotropic , AddressMode.Wrap, new Color4(0f) ); AnisotropicClamp = Create( Filter.Anisotropic , AddressMode.Clamp, new Color4(0f) ); ShadowSampler = Create( Filter.CmpMinMagLinearMipPoint, AddressMode.Clamp, new Color4( 0.0f, 1.0f, 1.0f, 1.0f ), ComparisonFunc.Less ); LinearPointBorder0 = Create( Filter.MinMagLinearMipPoint, AddressMode.Border, new Color4(0f) ); LinearPointClamp = Create( Filter.MinMagLinearMipPoint, AddressMode.Clamp, new Color4(0f) ); LinearPointWrap = Create( Filter.MinMagLinearMipPoint, AddressMode.Wrap, new Color4(0f) ); PointBorder1 = Create( Filter.MinMagMipPoint, AddressMode.Border, new Color4(1f) ); LinearClamp4Mips = Create( Filter.MinMagMipLinear, AddressMode.Clamp, new Color4(1f), ComparisonFunc.Always, 4 ); }
public BasicShader(Device device) { byte[] vspnctbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCT.cso"); byte[] vspncttbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCTT.cso"); byte[] vspnctttbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCTTT.cso"); byte[] vspncctbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCCT.cso"); byte[] vspnccttbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCCTT.cso"); byte[] vspncctttbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCCTTT.cso"); byte[] vspnctxbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCTX.cso"); byte[] vspncctxbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCCTX.cso"); byte[] vspncttxbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCTTX.cso"); byte[] vspnccttxbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCCTTX.cso"); byte[] vspnctttxbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCTTTX.cso"); byte[] vspncctttxbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCCTTTX.cso"); byte[] vspbbnctbytes = File.ReadAllBytes("Shaders\\BasicVS_PBBNCT.cso"); byte[] vspbbnctxbytes = File.ReadAllBytes("Shaders\\BasicVS_PBBNCTX.cso"); byte[] vspbbncttbytes = File.ReadAllBytes("Shaders\\BasicVS_PBBNCTT.cso"); byte[] vspbbnctttbytes = File.ReadAllBytes("Shaders\\BasicVS_PBBNCTTT.cso"); byte[] vspbbncctbytes = File.ReadAllBytes("Shaders\\BasicVS_PBBNCCT.cso"); byte[] vspbbncctxbytes = File.ReadAllBytes("Shaders\\BasicVS_PBBNCCTX.cso"); byte[] vspbbnccttxbytes = File.ReadAllBytes("Shaders\\BasicVS_PBBNCCTTX.cso"); byte[] vspbbncttxbytes = File.ReadAllBytes("Shaders\\BasicVS_PBBNCTTX.cso"); byte[] vsboxbytes = File.ReadAllBytes("Shaders\\BasicVS_Box.cso"); byte[] vsspherebytes = File.ReadAllBytes("Shaders\\BasicVS_Sphere.cso"); byte[] vscapsulebytes = File.ReadAllBytes("Shaders\\BasicVS_Capsule.cso"); byte[] vscylinderbytes = File.ReadAllBytes("Shaders\\BasicVS_Cylinder.cso"); byte[] psbytes = File.ReadAllBytes("Shaders\\BasicPS.cso"); byte[] psdefbytes = File.ReadAllBytes("Shaders\\BasicPS_Deferred.cso"); basicvspnct = new VertexShader(device, vspnctbytes); basicvspnctt = new VertexShader(device, vspncttbytes); basicvspncttt = new VertexShader(device, vspnctttbytes); basicvspncct = new VertexShader(device, vspncctbytes); basicvspncctt = new VertexShader(device, vspnccttbytes); basicvspnccttt = new VertexShader(device, vspncctttbytes); basicvspnctx = new VertexShader(device, vspnctxbytes); basicvspncctx = new VertexShader(device, vspncctxbytes); basicvspncttx = new VertexShader(device, vspncttxbytes); basicvspnccttx = new VertexShader(device, vspnccttxbytes); basicvspnctttx = new VertexShader(device, vspnctttxbytes); basicvspncctttx = new VertexShader(device, vspncctttxbytes); basicvspbbnct = new VertexShader(device, vspbbnctbytes); basicvspbbnctx = new VertexShader(device, vspbbnctxbytes); basicvspbbnctt = new VertexShader(device, vspbbncttbytes); basicvspbbncttt = new VertexShader(device, vspbbnctttbytes); basicvspbbncct = new VertexShader(device, vspbbncctbytes); basicvspbbncctx = new VertexShader(device, vspbbncctxbytes); basicvspbbnccttx = new VertexShader(device, vspbbnccttxbytes); basicvspbbncttx = new VertexShader(device, vspbbncttxbytes); basicvsbox = new VertexShader(device, vsboxbytes); basicvssphere = new VertexShader(device, vsspherebytes); basicvscapsule = new VertexShader(device, vscapsulebytes); basicvscylinder = new VertexShader(device, vscylinderbytes); basicps = new PixelShader(device, psbytes); basicpsdef = new PixelShader(device, psdefbytes); VSSceneVars = new GpuVarsBuffer <BasicShaderVSSceneVars>(device); VSEntityVars = new GpuVarsBuffer <BasicShaderVSEntityVars>(device); VSModelVars = new GpuVarsBuffer <BasicShaderVSModelVars>(device); VSGeomVars = new GpuVarsBuffer <BasicShaderVSGeomVars>(device); PSSceneVars = new GpuVarsBuffer <BasicShaderPSSceneVars>(device); PSGeomVars = new GpuVarsBuffer <BasicShaderPSGeomVars>(device); InstGlobalVars = new GpuVarsBuffer <BasicShaderInstGlobals>(device); InstLocalVars = new GpuVarsBuffer <BasicShaderInstLocals>(device); BoneMatrices = new GpuABuffer <Matrix3_s>(device, 255); ClothVertices = new GpuABuffer <Vector4>(device, 254); InitInstGlobalVars(); //supported layouts - requires Position, Normal, Colour, Texcoord layouts.Add(VertexType.Default, new InputLayout(device, vspnctbytes, VertexTypeGTAV.GetLayout(VertexType.Default))); layouts.Add(VertexType.PNCH2, new InputLayout(device, vspnctbytes, VertexTypeGTAV.GetLayout(VertexType.PNCH2, VertexDeclarationTypes.Types3)));//TODO? layouts.Add(VertexType.PNCTT, new InputLayout(device, vspncttbytes, VertexTypeGTAV.GetLayout(VertexType.PNCTT))); layouts.Add(VertexType.PNCTTT, new InputLayout(device, vspnctttbytes, VertexTypeGTAV.GetLayout(VertexType.PNCTTT))); layouts.Add(VertexType.PNCCT, new InputLayout(device, vspncctbytes, VertexTypeGTAV.GetLayout(VertexType.PNCCT))); layouts.Add(VertexType.PNCCTT, new InputLayout(device, vspnccttbytes, VertexTypeGTAV.GetLayout(VertexType.PNCCTT))); layouts.Add(VertexType.PNCCTTTT, new InputLayout(device, vspncctttbytes, VertexTypeGTAV.GetLayout(VertexType.PNCCTTTT)));//TODO..? //normalmap layouts - requires Position, Normal, Colour, Texcoord, Tangent (X) layouts.Add(VertexType.DefaultEx, new InputLayout(device, vspnctxbytes, VertexTypeGTAV.GetLayout(VertexType.DefaultEx))); layouts.Add(VertexType.PCCH2H4, new InputLayout(device, vspnctxbytes, VertexTypeGTAV.GetLayout(VertexType.PCCH2H4, VertexDeclarationTypes.Types2))); layouts.Add(VertexType.PNCCTX, new InputLayout(device, vspncctxbytes, VertexTypeGTAV.GetLayout(VertexType.PNCCTX))); layouts.Add(VertexType.PNCTTX, new InputLayout(device, vspncttxbytes, VertexTypeGTAV.GetLayout(VertexType.PNCTTX))); layouts.Add(VertexType.PNCCTTX, new InputLayout(device, vspnccttxbytes, VertexTypeGTAV.GetLayout(VertexType.PNCCTTX))); layouts.Add(VertexType.PNCCTTX_2, new InputLayout(device, vspnccttxbytes, VertexTypeGTAV.GetLayout(VertexType.PNCCTTX_2))); layouts.Add(VertexType.PNCTTTX, new InputLayout(device, vspnctttxbytes, VertexTypeGTAV.GetLayout(VertexType.PNCTTTX))); layouts.Add(VertexType.PNCTTTX_2, new InputLayout(device, vspnctttxbytes, VertexTypeGTAV.GetLayout(VertexType.PNCTTTX_2))); layouts.Add(VertexType.PNCTTTX_3, new InputLayout(device, vspnctttxbytes, VertexTypeGTAV.GetLayout(VertexType.PNCTTTX_3))); layouts.Add(VertexType.PNCTTTTX, new InputLayout(device, vspnctttxbytes, VertexTypeGTAV.GetLayout(VertexType.PNCTTTTX)));//TODO layouts.Add(VertexType.PNCCTTTX, new InputLayout(device, vspncctttxbytes, VertexTypeGTAV.GetLayout(VertexType.PNCCTTTX))); //skinned layouts layouts.Add(VertexType.PBBNCT, new InputLayout(device, vspbbnctbytes, VertexTypeGTAV.GetLayout(VertexType.PBBNCT))); layouts.Add(VertexType.PBBNCTX, new InputLayout(device, vspbbnctxbytes, VertexTypeGTAV.GetLayout(VertexType.PBBNCTX))); layouts.Add(VertexType.PBBNCTT, new InputLayout(device, vspbbncttbytes, VertexTypeGTAV.GetLayout(VertexType.PBBNCTT))); layouts.Add(VertexType.PBBNCTTT, new InputLayout(device, vspbbnctttbytes, VertexTypeGTAV.GetLayout(VertexType.PBBNCTTT))); layouts.Add(VertexType.PBBNCCT, new InputLayout(device, vspbbncctbytes, VertexTypeGTAV.GetLayout(VertexType.PBBNCCT))); layouts.Add(VertexType.PBBNCCTT, new InputLayout(device, vspbbncctbytes, VertexTypeGTAV.GetLayout(VertexType.PBBNCCTT)));//TODO layouts.Add(VertexType.PBBNCCTX, new InputLayout(device, vspbbncctxbytes, VertexTypeGTAV.GetLayout(VertexType.PBBNCCTX))); layouts.Add(VertexType.PBBNCTTX, new InputLayout(device, vspbbncttxbytes, VertexTypeGTAV.GetLayout(VertexType.PBBNCTTX))); layouts.Add(VertexType.PBBNCTTTX, new InputLayout(device, vspbbncttxbytes, VertexTypeGTAV.GetLayout(VertexType.PBBNCTTTX)));//TODO layouts.Add(VertexType.PBBNCCTTX, new InputLayout(device, vspbbnccttxbytes, VertexTypeGTAV.GetLayout(VertexType.PBBNCCTTX))); //PBBCCT todo //PBBNC todo texsampler = new SamplerState(device, new SamplerStateDescription() { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = Color.Black, ComparisonFunction = Comparison.Always, Filter = Filter.MinMagMipLinear, MaximumAnisotropy = 1, MaximumLod = float.MaxValue, MinimumLod = 0, MipLodBias = 0, }); texsampleranis = new SamplerState(device, new SamplerStateDescription() { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = Color.Black, ComparisonFunction = Comparison.Always, Filter = Filter.Anisotropic, MaximumAnisotropy = 8, MaximumLod = float.MaxValue, MinimumLod = 0, MipLodBias = 0, }); texsamplertnt = new SamplerState(device, new SamplerStateDescription() { AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = Color.White, ComparisonFunction = Comparison.Always, Filter = Filter.MinMagMipPoint, MaximumAnisotropy = 1, MaximumLod = float.MaxValue, MinimumLod = 0, MipLodBias = 0, }); texsamplertntyft = new SamplerState(device, new SamplerStateDescription() { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = Color.White, ComparisonFunction = Comparison.Always, Filter = Filter.MinMagMipPoint, MaximumAnisotropy = 1, MaximumLod = float.MaxValue, MinimumLod = 0, MipLodBias = 0, }); cube = new UnitCube(device, vsboxbytes, false, false, true); sphere = new UnitSphere(device, vsspherebytes, 4); capsule = new UnitCapsule(device, vscapsulebytes, 4); cylinder = new UnitCylinder(device, vscylinderbytes, 8); defaultBoneMatrices = new Matrix3_s[255]; for (int i = 0; i < 255; i++) { defaultBoneMatrices[i].Row1 = Vector4.UnitX; defaultBoneMatrices[i].Row2 = Vector4.UnitY; defaultBoneMatrices[i].Row3 = Vector4.UnitZ; } }
/// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposable"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposable) { Contract.Ensures(!disposable || disposable ==(sampler==null)); if (disposable) { if (sampler != null) { sampler.Dispose(); sampler = null; } } base.Dispose(disposable); }
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); }
public void CreateShaders(string code) { UpdateRenderer = true; // load and compile the vertex shader using (var bytecode = ShaderBytecode.Compile(code, "VShader", "vs_5_0", ShaderFlags.None, EffectFlags.None)) { inputSignature = ShaderSignature.GetInputSignature(bytecode); vertexShader = new VertexShader(device, bytecode); } // load and compile the pixel shader using (var bytecode = ShaderBytecode.Compile(code, "PShader", "ps_5_0", ShaderFlags.None, EffectFlags.None)) pixelShader = new PixelShader(device, bytecode); string compilationError = ""; //ShaderBytecode compiledShader = ShaderBytecode.CompileFromFile("vteffect.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null, out compilationError); //fx = new Effect(device, compiledShader); // create test vertex data, making sure to rewind the stream afterward vertices = new DataStream(20 * 4, true, true); vertices.Write(new Vector3(-1f, -1f, 0.5f)); vertices.Write(new Vector2(0f, 1f)); vertices.Write(new Vector3(-1f, 1f, 0.5f)); vertices.Write(new Vector2(0f, 0f)); vertices.Write(new Vector3(1f, -1f, 0.5f)); vertices.Write(new Vector2(1f, 1f)); vertices.Write(new Vector3(1f, 1f, 0.5f)); vertices.Write(new Vector2(1f, 0f)); vertices.Position = 0; // create the vertex layout and buffer var elements = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }; layout = new InputLayout(device, inputSignature, elements); vertexBuffer = new SlimDX.Direct3D11.Buffer(device, vertices, 20 * 4, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0); List<int> indices = new List<int>(); indices.Add(0); indices.Add(1); indices.Add(2); indices.Add(2); indices.Add(1); indices.Add(3); var ibd = new BufferDescription(sizeof(int) * indices.Count, ResourceUsage.Immutable, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); indexBuffer = new SlimDX.Direct3D11.Buffer(device, new DataStream(indices.ToArray(), false, false), ibd); // configure the Input Assembler portion of the pipeline with the vertex data context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 20, 0)); context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0); // set the shaders context.VertexShader.Set(vertexShader); context.PixelShader.Set(pixelShader); SamplerDescription sampleDesc = new SamplerDescription(); sampleDesc.Filter = Filter.MinMagMipPoint; sampleDesc.AddressU = TextureAddressMode.Clamp; sampleDesc.AddressV = TextureAddressMode.Clamp; sampleDesc.AddressW = TextureAddressMode.Clamp; sampleDesc.MipLodBias = 0.0f; sampleDesc.ComparisonFunction = Comparison.Always; sampleDesc.BorderColor = new Color4(0, 0, 0, 0); sampleDesc.MinimumLod = 0; sampleDesc.MaximumLod = 1; sampleState = SamplerState.FromDescription(device, sampleDesc); SamplerDescription indSampleDesc = new SamplerDescription(); sampleDesc.Filter = Filter.MinMagMipPoint; sampleDesc.AddressU = TextureAddressMode.Wrap; sampleDesc.AddressV = TextureAddressMode.Wrap; sampleDesc.AddressW = TextureAddressMode.Wrap; sampleDesc.MipLodBias = 0.0f; sampleDesc.ComparisonFunction = Comparison.Always; sampleDesc.BorderColor = new Color4(0, 0, 0, 0); sampleDesc.MinimumLod = 0; sampleDesc.MaximumLod = 1; indSampleState = SamplerState.FromDescription(device, sampleDesc); ImageLoadInformation loadInfo = new ImageLoadInformation() { Width = 2, Height = 2 }; loadInfo.BindFlags = BindFlags.ShaderResource; loadInfo.CpuAccessFlags = CpuAccessFlags.None; loadInfo.Depth = 4; loadInfo.FilterFlags = FilterFlags.Point; loadInfo.FirstMipLevel = 0; loadInfo.Format = Format.R8G8B8A8_SInt; loadInfo.MipLevels = 0; loadInfo.Usage = ResourceUsage.Default; texture = new Texture2D(device, new Texture2DDescription { BindFlags = BindFlags.ShaderResource, ArraySize = 1024, Width = 128, Height = 128, Usage = ResourceUsage.Default, CpuAccessFlags = CpuAccessFlags.None, Format = Format.R8G8B8A8_UNorm, SampleDescription = new SampleDescription(1, 0), MipLevels = 1, OptionFlags = ResourceOptionFlags.None });//Texture2D.FromFile(device,"Tourism_Industrial_d.png"); resourceView = new ShaderResourceView(device, texture); device.ImmediateContext.PixelShader.SetShaderResource(resourceView, 0); context.PixelShader.SetShaderResource(resourceView, 0); context.PixelShader.SetSampler(sampleState, 0); context.PixelShader.SetSampler(indSampleState, 1); if (currentEntry != null) SetTexture(currentEntry); }
public new void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState) { base.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState); }
/// <summary> /// Sets a sampler state to the shader pipeline. /// </summary> /// <param name="stage">The shader stage.</param> /// <param name="slot">The binding slot.</param> /// <param name="samplerState">The sampler state to set.</param> internal void SetSamplerState(ShaderStage stage, int slot, SamplerState samplerState) { if (stage == ShaderStage.None) throw new ArgumentException("Cannot use Stage.None", "stage"); int stageIndex = (int)stage - 1; int slotIndex = stageIndex*SamplerStateCount + slot; if (samplerStates[slotIndex] != samplerState) { samplerStates[slotIndex] = samplerState; shaderStages[stageIndex].SetSampler(slot, samplerState != null ? (SharpDX.Direct3D11.SamplerState)samplerState.NativeDeviceChild : null); } }
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 RenderObject(Device device) { cb.vp = Matrix.Identity; cb.world = Matrix.Identity; // load and compile the vertex shader using (var bytecode = ShaderBytecode.CompileFromFile("simple.fx", "VShader", "vs_4_0", ShaderFlags.None, EffectFlags.None)) { vsInputSignature = ShaderSignature.GetInputSignature(bytecode); vertexShader = new VertexShader(device, bytecode); } // load and compile the pixel shader using (var bytecode = ShaderBytecode.CompileFromFile("simple.fx", "PShader", "ps_4_0", ShaderFlags.None, EffectFlags.None)) pixelShader = new PixelShader(device, bytecode); // Old school style. /* vertexSize = 24; vertexCount = 3; var vertexStream = new DataStream(vertexSize * vertexCount, true, true); vertexStream.Write(new Vector3(0.0f, 5.0f, 0.5f)); vertexStream.Write(new Vector3(1, 0, 0)); // color vertexStream.Write(new Vector3(5.0f, -5.0f, 0.5f)); vertexStream.Write(new Vector3(0, 1, 0)); // color vertexStream.Write(new Vector3(-5.0f, -5.0f, 0.5f)); vertexStream.Write(new Vector3(0, 0, 1)); // color vertexStream.Position = 0; */ // Use struct Vertex[] vertices = new Vertex[] { new Vertex() { pos = new Vector3(0.0f, 50.0f, 0.5f), col = new Vector3(1, 0, 0), uv = new Vector2(0, 0) }, new Vertex() { pos = new Vector3(50.0f, -50.0f, 0.5f), col = new Vector3(1, 1, 0), uv = new Vector2(1, 0) }, new Vertex() { pos = new Vector3(-50.0f, -50.0f, 0.5f), col = new Vector3(0, 1, 1), uv = new Vector2(1, 1) }, }; vertexSize = Marshal.SizeOf(typeof(Vertex)); vertexCount = vertices.Length; var vertexStream = new DataStream(vertexSize * vertexCount, true, true); foreach (var vertex in vertices) { vertexStream.Write(vertex); } vertexStream.Position = 0; // create the vertex layout and buffer var elements = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0), new InputElement("COLOR", 0, Format.R32G32B32_Float, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 0) }; vertexBufferLayout = new InputLayout(device, vsInputSignature, elements); vertexBuffer = new Buffer(device, vertexStream, vertexSize * vertexCount, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); vertexStream.Close(); // Setup Constant Buffers constantBuffer = new Buffer(device, Marshal.SizeOf(typeof(ConstantBuffer)), ResourceUsage.Dynamic, BindFlags.ConstantBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0); // http://asc-chalmers-project.googlecode.com/svn-history/r26/trunk/Source/AdvGraphicsProject/Program.cs // Try load a texture SamplerDescription samplerDescription = new SamplerDescription(); samplerDescription.AddressU = TextureAddressMode.Wrap; samplerDescription.AddressV = TextureAddressMode.Wrap; samplerDescription.AddressW = TextureAddressMode.Wrap; samplerDescription.Filter = Filter.MinPointMagMipLinear; samplerLinear = SamplerState.FromDescription(device, samplerDescription); texture = Texture2D.FromFile(device, "Data/cco.png"); textureView = new ShaderResourceView(device, texture); var desc = new BlendStateDescription() { AlphaToCoverageEnable = true, IndependentBlendEnable = true }; desc.RenderTargets[0].BlendEnable = false; desc.RenderTargets[0].BlendOperation = BlendOperation.Add; desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add; desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.Alpha; desc.RenderTargets[0].SourceBlend = BlendOption.SourceAlpha; desc.RenderTargets[0].DestinationBlend = BlendOption.InverseSourceAlpha; desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.InverseSourceAlpha; desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; blendState = BlendState.FromDescription(device, desc); }
private void RecursiveDrawWithClipping(RenderDrawContext context, UIElement element, ref Matrix worldViewProj, SamplerState samplerState) { // if the element is not visible, we also remove all its children if (!element.IsVisible) { return; } var renderer = rendererManager.GetRenderer(element); renderingContext.DepthBias = element.DepthBias; // render the clipping region of the element if (element.ClipToBounds) { // flush current elements batch.End(); // render the clipping region batch.Begin(context.GraphicsContext, ref worldViewProj, BlendStates.ColorDisabled, samplerState, null, uiSystem.IncreaseStencilValueState, renderingContext.StencilTestReferenceValue); renderer.RenderClipping(element, renderingContext); batch.End(); // update context and restart the batch renderingContext.StencilTestReferenceValue += 1; batch.Begin(context.GraphicsContext, ref worldViewProj, BlendStates.AlphaBlend, samplerState, null, uiSystem.KeepStencilValueState, renderingContext.StencilTestReferenceValue); } // render the design of the element renderer.RenderColor(element, renderingContext); // render the children foreach (var child in element.VisualChildrenCollection) { RecursiveDrawWithClipping(context, child, ref worldViewProj, samplerState); } // clear the element clipping region from the stencil buffer if (element.ClipToBounds) { // flush current elements batch.End(); renderingContext.DepthBias = element.MaxChildrenDepthBias; // render the clipping region batch.Begin(context.GraphicsContext, ref worldViewProj, BlendStates.ColorDisabled, samplerState, null, uiSystem.DecreaseStencilValueState, renderingContext.StencilTestReferenceValue); renderer.RenderClipping(element, renderingContext); batch.End(); // update context and restart the batch renderingContext.StencilTestReferenceValue -= 1; batch.Begin(context.GraphicsContext, ref worldViewProj, BlendStates.AlphaBlend, samplerState, null, uiSystem.KeepStencilValueState, renderingContext.StencilTestReferenceValue); } }
private void SetSamplerState(int sampler, SamplerState type, int value) { var oldVal = ActiveD3D9Device.GetSamplerState( sampler, type ); if (oldVal == value) return; ActiveD3D9Device.SetSamplerState(sampler, type, value); }
public T Sample(SamplerState _sampler, float3 _uvw) { return(new T()); }
public void SetSamplerState(int sampler, SamplerState state, int value) { #if DEBUG_STATE_MANAGER int s = device.GetSamplerState(sampler, state); if (samplerStates[sampler, (int)state] != -1 && samplerStates[sampler, (int)state] != s) throw new Exception("State inconsistent, " + samplerStates[sampler, (int)state] + " != " + s); #endif if (samplerStates[sampler, (int)state] != value) { device.SetSamplerState(sampler, state, value); samplerStates[sampler, (int)state] = value; } }
public T SampleLevel(SamplerState _sampler, float3 _uvw, double _Mip) { return(new T()); }
public void SetSamplerState(int sampler, SamplerState state, TextureFilter value) { SetSamplerState(sampler, state, (int)value); }
public void SetSamplerState(SamplerState samplerState) { SamplerState = samplerState; }
public void uploadFromGLSL (string vertexShaderSource, string fragmentShaderSource, SamplerState[] samplerStates = null) { // delete existing shaders deleteShaders (); //Console.WriteLine (vertexShaderSource); //Console.WriteLine (fragmentShaderSource); mVertexSource = vertexShaderSource; mFragmentSource = fragmentShaderSource; // compiler vertex shader mVertexShaderId = GL.CreateShader (ShaderType.VertexShader); GL.ShaderSource (mVertexShaderId, vertexShaderSource); GL.CompileShader (mVertexShaderId); var vertexInfoLog = GL.GetShaderInfoLog (mVertexShaderId); if (!string.IsNullOrEmpty (vertexInfoLog)) { Console.Write ("vertex: {0}", vertexInfoLog); throw new Exception("Error compiling vertex shader: " + vertexInfoLog); } // compile fragment shader mFragmentShaderId = GL.CreateShader (ShaderType.FragmentShader); GL.ShaderSource (mFragmentShaderId, fragmentShaderSource); GL.CompileShader (mFragmentShaderId); var fragmentInfoLog = GL.GetShaderInfoLog (mFragmentShaderId); if (!string.IsNullOrEmpty (fragmentInfoLog)) { Console.Write ("fragment: {0}", fragmentInfoLog); throw new Exception("Error compiling fragment shader: " + fragmentInfoLog); } // create program mProgramId = GL.CreateProgram (); GL.AttachShader (mProgramId, mVertexShaderId); GL.AttachShader (mProgramId, mFragmentShaderId); // bind all attribute locations for (int i=0; i < 16; i++) { var name = "va" + i; if (vertexShaderSource.Contains(" " + name)) { GL.BindAttribLocation (mProgramId, i, name); } } // Link the program GL.LinkProgram (mProgramId); var infoLog = GL.GetProgramInfoLog (mProgramId); if (!string.IsNullOrEmpty (infoLog)) { Console.Write ("program: {0}", infoLog); } // build uniform list buildUniformList(); // process sampler states mSamplerUsageMask = 0; for (int i=0; i < mSamplerStates.Length; i++) { // copy over sampler state from provided array mSamplerStates[i] = (samplerStates!=null) ? samplerStates[i] : null; // set sampler usage mask if (mSamplerStates[i] != null) { mSamplerUsageMask |= (1 << i); } } }
/// <summary> /// Create any device dependent resources here. /// This method will be called when the device is first /// initialized or recreated after being removed or reset. /// </summary> protected override void CreateDeviceDependentResources() { // Ensure that if already set the device resources // are correctly disposed of before recreating RemoveAndDispose(ref vertexBuffer); //RemoveAndDispose(ref indexBuffer); // Retrieve our SharpDX.Direct3D11.Device1 instance // Get a reference to the Device1 instance and immediate context var device = DeviceManager.Direct3DDevice; var context = DeviceManager.Direct3DContext; ShaderFlags shaderFlags = ShaderFlags.None; #if DEBUG shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization; #endif // Use our HLSL file include handler to resolve #include directives in the HLSL source var includeHandler = new HLSLFileIncludeHandler(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "Shaders")); // Compile and create the vertex shader vertexShaderBytecode = ToDispose(ShaderBytecode.CompileFromFile(@"Shaders\SAQuad.hlsl", "VSMain", "vs_5_0", shaderFlags, EffectFlags.None, null, includeHandler)); vertexShader = ToDispose(new VertexShader(device, vertexShaderBytecode)); // Compile and create the pixel shader using (var bytecode = ToDispose(ShaderBytecode.CompileFromFile(@"Shaders\SAQuad.hlsl", "PSMain", "ps_5_0", shaderFlags, EffectFlags.None, null, includeHandler))) pixelShader = ToDispose(new PixelShader(device, bytecode)); using (var bytecode = ToDispose(ShaderBytecode.CompileFromFile(@"Shaders\SAQuad.hlsl", "PSMainMultisample", "ps_5_0", shaderFlags, EffectFlags.None, null, includeHandler))) pixelShaderMS = ToDispose(new PixelShader(device, bytecode)); // Layout from VertexShader input signature vertexLayout = ToDispose(new InputLayout(device, vertexShaderBytecode.GetPart(ShaderBytecodePart.InputSignatureBlob), //ShaderSignature.GetInputSignature(vertexShaderBytecode), new[] { // "SV_Position" = vertex coordinate in object space new InputElement("SV_Position", 0, Format.R32G32B32_Float, 0, 0), })); linearSampleState = ToDispose(new SamplerState(device, new SamplerStateDescription { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, ComparisonFunction = Comparison.Never, MinimumLod = 0, MaximumLod = float.MaxValue })); pointSamplerState = ToDispose(new SamplerState(device, new SamplerStateDescription { Filter = Filter.MinMagMipPoint, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, ComparisonFunction = Comparison.Never, MinimumLod = 0, MaximumLod = float.MaxValue })); // Create vertex buffer vertexBuffer = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, new SimpleVertex[] { /* Position: float x 3 */ new SimpleVertex(-1.0f, -1.0f, 0.5f), new SimpleVertex(-1.0f, 1.0f, 0.5f), new SimpleVertex(1.0f, -1.0f, 0.5f), new SimpleVertex(1.0f, 1.0f, 0.5f), })); vertexBinding = new VertexBufferBinding(vertexBuffer, Utilities.SizeOf <SimpleVertex>(), 0); // Triangle strip: // v1 v3 // |\ | // | \ B| // | A\ | // | \| // v0 v2 }
public BasicShader(Device device) { byte[] vspnctbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCT.cso"); byte[] vspncctbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCCT.cso"); byte[] vspnccttbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCCTT.cso"); byte[] vspncctttbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCCTTT.cso"); byte[] vspnctxbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCTX.cso"); byte[] vspncctxbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCCTX.cso"); byte[] vspncttxbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCTTX.cso"); byte[] vspnccttxbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCCTTX.cso"); byte[] vspnctttxbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCTTTX.cso"); byte[] vspncctttxbytes = File.ReadAllBytes("Shaders\\BasicVS_PNCCTTTX.cso"); byte[] vsboxbytes = File.ReadAllBytes("Shaders\\BasicVS_Box.cso"); byte[] vsspherebytes = File.ReadAllBytes("Shaders\\BasicVS_Sphere.cso"); byte[] vscapsulebytes = File.ReadAllBytes("Shaders\\BasicVS_Capsule.cso"); byte[] vscylinderbytes = File.ReadAllBytes("Shaders\\BasicVS_Cylinder.cso"); byte[] psbytes = File.ReadAllBytes("Shaders\\BasicPS.cso"); basicvspnct = new VertexShader(device, vspnctbytes); basicvspncct = new VertexShader(device, vspncctbytes); basicvspncctt = new VertexShader(device, vspnccttbytes); basicvspnccttt = new VertexShader(device, vspncctttbytes); basicvspnctx = new VertexShader(device, vspnctxbytes); basicvspncctx = new VertexShader(device, vspncctxbytes); basicvspncttx = new VertexShader(device, vspncttxbytes); basicvspnccttx = new VertexShader(device, vspnccttxbytes); basicvspnctttx = new VertexShader(device, vspnctttxbytes); basicvspncctttx = new VertexShader(device, vspncctttxbytes); basicvsbox = new VertexShader(device, vsboxbytes); basicvssphere = new VertexShader(device, vsspherebytes); basicvscapsule = new VertexShader(device, vscapsulebytes); basicvscylinder = new VertexShader(device, vscylinderbytes); basicps = new PixelShader(device, psbytes); VSSceneVars = new GpuVarsBuffer <BasicShaderVSSceneVars>(device); VSEntityVars = new GpuVarsBuffer <BasicShaderVSEntityVars>(device); VSModelVars = new GpuVarsBuffer <BasicShaderVSModelVars>(device); VSGeomVars = new GpuVarsBuffer <BasicShaderVSGeomVars>(device); PSSceneVars = new GpuVarsBuffer <BasicShaderPSSceneVars>(device); PSGeomVars = new GpuVarsBuffer <BasicShaderPSGeomVars>(device); InstGlobalVars = new GpuVarsBuffer <BasicShaderInstGlobals>(device); InstLocalVars = new GpuVarsBuffer <BasicShaderInstLocals>(device); InitInstGlobalVars(); //supported layouts - requires Position, Normal, Colour, Texcoord layouts.Add(VertexType.Default, new InputLayout(device, vspnctbytes, VertexTypeDefault.GetLayout())); layouts.Add(VertexType.PNCH2, new InputLayout(device, vspnctbytes, VertexTypePNCH2.GetLayout())); layouts.Add(VertexType.PCCNCT, new InputLayout(device, vspncctbytes, VertexTypePCCNCT.GetLayout())); layouts.Add(VertexType.PCCNCCT, new InputLayout(device, vspncctbytes, VertexTypePCCNCCT.GetLayout())); layouts.Add(VertexType.PNCCT, new InputLayout(device, vspncctbytes, VertexTypePNCCT.GetLayout())); layouts.Add(VertexType.PNCCTT, new InputLayout(device, vspnccttbytes, VertexTypePNCCTT.GetLayout())); layouts.Add(VertexType.PNCCTTTT, new InputLayout(device, vspncctttbytes, VertexTypePNCCTTTT.GetLayout())); //normalmap layouts - requires Position, Normal, Colour, Texcoord, Tangent (X) layouts.Add(VertexType.DefaultEx, new InputLayout(device, vspnctxbytes, VertexTypeDefaultEx.GetLayout())); layouts.Add(VertexType.PCCH2H4, new InputLayout(device, vspnctxbytes, VertexTypePCCH2H4.GetLayout())); layouts.Add(VertexType.PCCNCTX, new InputLayout(device, vspncctxbytes, VertexTypePCCNCTX.GetLayout())); layouts.Add(VertexType.PCCNCCTX, new InputLayout(device, vspncctxbytes, VertexTypePCCNCCTX.GetLayout())); layouts.Add(VertexType.PNCCTX, new InputLayout(device, vspncctxbytes, VertexTypePNCCTX.GetLayout())); layouts.Add(VertexType.PNCTTX, new InputLayout(device, vspncttxbytes, VertexTypePNCTTX.GetLayout())); layouts.Add(VertexType.PNCCTTX, new InputLayout(device, vspnccttxbytes, VertexTypePNCCTTX.GetLayout())); layouts.Add(VertexType.PNCCTTX_2, new InputLayout(device, vspnccttxbytes, VertexTypePNCCTTX_2.GetLayout())); layouts.Add(VertexType.PCCNCCTTX, new InputLayout(device, vspnccttxbytes, VertexTypePCCNCCTTX.GetLayout())); layouts.Add(VertexType.PNCTTTX, new InputLayout(device, vspnctttxbytes, VertexTypePNCTTTX.GetLayout())); layouts.Add(VertexType.PNCTTTX_2, new InputLayout(device, vspnctttxbytes, VertexTypePNCTTTX_2.GetLayout())); layouts.Add(VertexType.PNCTTTX_3, new InputLayout(device, vspnctttxbytes, VertexTypePNCTTTX_3.GetLayout())); layouts.Add(VertexType.PNCTTTTX, new InputLayout(device, vspnctttxbytes, VertexTypePNCTTTTX.GetLayout())); layouts.Add(VertexType.PNCCTTTX, new InputLayout(device, vspncctttxbytes, VertexTypePNCCTTTX.GetLayout())); layouts.Add(VertexType.PCCNCTTTX, new InputLayout(device, vspncctttxbytes, VertexTypePCCNCTTTX.GetLayout())); layouts.Add(VertexType.PCCNCTT, new InputLayout(device, vspnccttbytes, VertexTypePCCNCTT.GetLayout())); layouts.Add(VertexType.PCCNCTTX, new InputLayout(device, vspnccttxbytes, VertexTypePCCNCTTX.GetLayout())); layouts.Add(VertexType.PCCNCTTT, new InputLayout(device, vspncctttbytes, VertexTypePCCNCTTT.GetLayout())); layouts.Add(VertexType.PNCTT, new InputLayout(device, vspnctbytes, VertexTypePNCTT.GetLayout())); layouts.Add(VertexType.PNCTTT, new InputLayout(device, vspnctbytes, VertexTypePNCTTT.GetLayout())); texsampler = new SamplerState(device, new SamplerStateDescription() { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = Color.Black, ComparisonFunction = Comparison.Always, Filter = Filter.MinMagMipLinear, MaximumAnisotropy = 1, MaximumLod = float.MaxValue, MinimumLod = 0, MipLodBias = 0, }); texsampleranis = new SamplerState(device, new SamplerStateDescription() { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = Color.Black, ComparisonFunction = Comparison.Always, Filter = Filter.Anisotropic, MaximumAnisotropy = 8, MaximumLod = float.MaxValue, MinimumLod = 0, MipLodBias = 0, }); texsamplertnt = new SamplerState(device, new SamplerStateDescription() { AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = Color.White, ComparisonFunction = Comparison.Always, Filter = Filter.MinMagMipPoint, MaximumAnisotropy = 1, MaximumLod = float.MaxValue, MinimumLod = 0, MipLodBias = 0, }); texsamplertntyft = new SamplerState(device, new SamplerStateDescription() { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = Color.White, ComparisonFunction = Comparison.Always, Filter = Filter.MinMagMipPoint, MaximumAnisotropy = 1, MaximumLod = float.MaxValue, MinimumLod = 0, MipLodBias = 0, }); cube = new UnitCube(device, vsboxbytes, false, false, true); sphere = new UnitSphere(device, vsspherebytes, 4); capsule = new UnitCapsule(device, vscapsulebytes, 4); cylinder = new UnitCylinder(device, vscylinderbytes, 8); }
public void InitializeD3D11(IntPtr wndHandle, int width, int height) { CloseD3D11(); _dxgiFactory = new Factory1(); _dxiAdapter = _dxgiFactory.Adapters[0]; _d3d11Device = new Device(_dxiAdapter, DeviceCreationFlags.BgraSupport, FeatureLevel.Level_11_0); _dxgiDevice = _d3d11Device.QueryInterface <DXGIDevice>(); _dxgiDevice.MaximumFrameLatency = 1; // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("VSShader.fx", "main", "vs_4_0", ShaderFlags.None, EffectFlags.None); _vertexShader = new VertexShader(_d3d11Device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("PSShader.fx", "main", "ps_4_0", ShaderFlags.None, EffectFlags.None); _pixelShader = new PixelShader(_d3d11Device, pixelShaderByteCode); InputElement[] inputElements = new InputElement[3]; inputElements[0] = new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0); inputElements[1] = new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0); inputElements[2] = new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 20, 0, InputClassification.PerVertexData, 0); _inputLayout = new InputLayout(_d3d11Device, vertexShaderByteCode, inputElements); BufferDescription vertexShaderDesc = new BufferDescription(Matrix.SizeInBytes * 2, BindFlags.ConstantBuffer, ResourceUsage.Default); _vertexShaderConstans = new Buffer(_d3d11Device, vertexShaderDesc); SamplerStateDescription samplerStateDescription = new SamplerStateDescription(); samplerStateDescription.Filter = Filter.MinMagMipLinear; samplerStateDescription.AddressU = TextureAddressMode.Clamp; samplerStateDescription.AddressV = TextureAddressMode.Clamp; samplerStateDescription.AddressW = TextureAddressMode.Clamp; samplerStateDescription.MipLodBias = 0.0f; samplerStateDescription.MaximumAnisotropy = 1; samplerStateDescription.ComparisonFunction = Comparison.Always; samplerStateDescription.MinimumLod = 0.0f; samplerStateDescription.MaximumLod = float.MaxValue; _samplerState = new SamplerState(_d3d11Device, samplerStateDescription); RasterizerStateDescription rasterizerStateDescription = new RasterizerStateDescription(); rasterizerStateDescription.IsAntialiasedLineEnabled = false; rasterizerStateDescription.CullMode = CullMode.None; rasterizerStateDescription.DepthBias = 0; rasterizerStateDescription.DepthBiasClamp = 0.0f; rasterizerStateDescription.IsDepthClipEnabled = true; rasterizerStateDescription.FillMode = FillMode.Solid; rasterizerStateDescription.IsFrontCounterClockwise = false; rasterizerStateDescription.IsMultisampleEnabled = false; rasterizerStateDescription.IsScissorEnabled = false; rasterizerStateDescription.SlopeScaledDepthBias = 0.0f; _rasterizerState = new RasterizerState(_d3d11Device, rasterizerStateDescription); _d3d11Device.ImmediateContext.InputAssembler.InputLayout = _inputLayout; _d3d11Device.ImmediateContext.VertexShader.SetShader(_vertexShader, null, 0); _d3d11Device.ImmediateContext.VertexShader.SetConstantBuffers(0, 1, _vertexShaderConstans); SwapChainDescription swapChainDescription = new SwapChainDescription(); swapChainDescription.ModeDescription.Width = width; swapChainDescription.ModeDescription.Height = height; swapChainDescription.ModeDescription.Format = Format.B8G8R8A8_UNorm; swapChainDescription.ModeDescription.RefreshRate.Numerator = 1; //pretty ugly //its better to autodetect screen refresh rate swapChainDescription.ModeDescription.RefreshRate.Denominator = 60; swapChainDescription.SampleDescription.Count = 1; swapChainDescription.SampleDescription.Quality = 0; swapChainDescription.Usage = Usage.RenderTargetOutput; swapChainDescription.BufferCount = 2; swapChainDescription.ModeDescription.Scaling = DisplayModeScaling.Unspecified; swapChainDescription.SwapEffect = SwapEffect.FlipSequential; swapChainDescription.Flags = 0; swapChainDescription.IsWindowed = true; swapChainDescription.OutputHandle = wndHandle; _swapChain = new SwapChain(_dxgiFactory, _d3d11Device, swapChainDescription); _dxgiFactory.MakeWindowAssociation(wndHandle, WindowAssociationFlags.IgnoreAll); Texture2D backBuffer = _swapChain.GetBackBuffer <Texture2D>(0); _mainRenderTargerView = new RenderTargetView(_d3d11Device, backBuffer); backBuffer.Dispose(); backBuffer = null; Matrix projection = Matrix.Identity; Matrix view = new Matrix(); /* Update the view matrix */ view[0, 0] = 2.0f / (float)width; view[0, 1] = 0.0f; view[0, 2] = 0.0f; view[0, 3] = 0.0f; view[1, 0] = 0.0f; view[1, 1] = -2.0f / (float)height; view[1, 2] = 0.0f; view[1, 3] = 0.0f; view[2, 0] = 0.0f; view[2, 1] = 0.0f; view[2, 2] = 1.0f; view[2, 3] = 0.0f; view[3, 0] = -1.0f; view[3, 1] = 1.0f; view[3, 2] = 0.0f; view[3, 3] = 1.0f; VertexShaderConstants vertexShaderConstansData = new VertexShaderConstants(); vertexShaderConstansData.projectionAndView = Matrix.Multiply(view, projection); vertexShaderConstansData.model = Matrix.Identity; _vertexShaderConstansData = Marshal.AllocHGlobal(Marshal.SizeOf(vertexShaderConstansData)); Marshal.StructureToPtr(vertexShaderConstansData, _vertexShaderConstansData, false); _d3d11Device.ImmediateContext.UpdateSubresource(ref vertexShaderConstansData, _vertexShaderConstans); ViewPort viewPort = new ViewPort(); viewPort.X = 0; viewPort.Y = 0; viewPort.Width = width; viewPort.Height = height; viewPort.MinDepth = 0.0f; viewPort.MaxDepth = 1.0f; _d3d11Device.ImmediateContext.Rasterizer.SetViewport(viewPort); float minu, maxu, minv, maxv; minu = 0.0f; maxu = 1.0f; minv = 0.0f; maxv = 1.0f; // Instantiate Vertex buiffer from vertex data var vertices = Buffer.Create(_d3d11Device, BindFlags.VertexBuffer, new[] { //ul 0.0f, 0.0f, 0.0f, minu, minv, 1.0f, 1.0f, 1.0f, 1.0f, //dl 0.0f, (float)height, 0.0f, minu, maxv, 1.0f, 1.0f, 1.0f, 1.0f, //ur (float)width, 0.0f, 0.0f, maxu, minv, 1.0f, 1.0f, 1.0f, 1.0f, //dr (float)width, (float)height, 0.0f, maxu, maxv, 1.0f, 1.0f, 1.0f, 1.0f }); _d3d11Device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 36, 0)); _d3d11Device.ImmediateContext.Rasterizer.State = _rasterizerState; _d3d11Device.ImmediateContext.PixelShader.SetShader(_pixelShader, null, 0); _d3d11Device.ImmediateContext.PixelShader.SetSamplers(0, 1, _samplerState); _d3d11Device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip; }
public abstract void BindSamplerState(Renderer renderer, string name, SamplerState state);
private void DrawPlayerFull(Camera camera, Player drawPlayer) { SpriteBatch spriteBatch = camera.SpriteBatch; SamplerState samplerState = camera.Sampler; if (drawPlayer.mount.Active && (double)drawPlayer.fullRotation != 0.0) { samplerState = LegacyPlayerRenderer.MountedSamplerState; } spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, samplerState, DepthStencilState.None, camera.Rasterizer, (Effect)null, camera.GameViewMatrix.TransformationMatrix); if (Main.gamePaused) { drawPlayer.PlayerFrame(); } if (drawPlayer.ghost) { for (int index = 0; index < 3; ++index) { Vector2 shadowPo = drawPlayer.shadowPos[index]; Vector2 position = drawPlayer.position - drawPlayer.velocity * (float)(2 + index * 2); this.DrawGhost(camera, drawPlayer, position, (float)(0.5 + 0.200000002980232 * (double)index)); } this.DrawGhost(camera, drawPlayer, drawPlayer.position, 0.0f); } else { if (drawPlayer.inventory[drawPlayer.selectedItem].flame || drawPlayer.head == 137 || drawPlayer.wings == 22) { --drawPlayer.itemFlameCount; if (drawPlayer.itemFlameCount <= 0) { drawPlayer.itemFlameCount = 5; for (int index = 0; index < 7; ++index) { drawPlayer.itemFlamePos[index].X = (float)Main.rand.Next(-10, 11) * 0.15f; drawPlayer.itemFlamePos[index].Y = (float)Main.rand.Next(-10, 1) * 0.35f; } } } if (drawPlayer.armorEffectDrawShadowEOCShield) { int num = drawPlayer.eocDash / 4; if (num > 3) { num = 3; } for (int index = 0; index < num; ++index) { this.DrawPlayer(camera, drawPlayer, drawPlayer.shadowPos[index], drawPlayer.shadowRotation[index], drawPlayer.shadowOrigin[index], (float)(0.5 + 0.200000002980232 * (double)index), 1f); } } Vector2 position1; if (drawPlayer.invis) { drawPlayer.armorEffectDrawOutlines = false; drawPlayer.armorEffectDrawShadow = false; drawPlayer.armorEffectDrawShadowSubtle = false; position1 = drawPlayer.position; if (drawPlayer.aggro <= -750) { this.DrawPlayer(camera, drawPlayer, position1, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin, 1f, 1f); } else { drawPlayer.invis = false; this.DrawPlayer(camera, drawPlayer, position1, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin, 0.0f, 1f); drawPlayer.invis = true; } } if (drawPlayer.armorEffectDrawOutlines) { Vector2 position2 = drawPlayer.position; if (!Main.gamePaused) { drawPlayer.ghostFade += drawPlayer.ghostDir * 0.075f; } if ((double)drawPlayer.ghostFade < 0.1) { drawPlayer.ghostDir = 1f; drawPlayer.ghostFade = 0.1f; } else if ((double)drawPlayer.ghostFade > 0.9) { drawPlayer.ghostDir = -1f; drawPlayer.ghostFade = 0.9f; } float num1 = drawPlayer.ghostFade * 5f; for (int index = 0; index < 4; ++index) { float num2; float num3; switch (index) { case 1: num2 = -num1; num3 = 0.0f; break; case 2: num2 = 0.0f; num3 = num1; break; case 3: num2 = 0.0f; num3 = -num1; break; default: num2 = num1; num3 = 0.0f; break; } position1 = new Vector2(drawPlayer.position.X + num2, drawPlayer.position.Y + drawPlayer.gfxOffY + num3); this.DrawPlayer(camera, drawPlayer, position1, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin, drawPlayer.ghostFade, 1f); } } if (drawPlayer.armorEffectDrawOutlinesForbidden) { Vector2 position2 = drawPlayer.position; if (!Main.gamePaused) { drawPlayer.ghostFade += drawPlayer.ghostDir * 0.025f; } if ((double)drawPlayer.ghostFade < 0.1) { drawPlayer.ghostDir = 1f; drawPlayer.ghostFade = 0.1f; } else if ((double)drawPlayer.ghostFade > 0.9) { drawPlayer.ghostDir = -1f; drawPlayer.ghostFade = 0.9f; } float num1 = drawPlayer.ghostFade * 5f; for (int index = 0; index < 4; ++index) { float num2; float num3; switch (index) { case 1: num2 = -num1; num3 = 0.0f; break; case 2: num2 = 0.0f; num3 = num1; break; case 3: num2 = 0.0f; num3 = -num1; break; default: num2 = num1; num3 = 0.0f; break; } position1 = new Vector2(drawPlayer.position.X + num2, drawPlayer.position.Y + drawPlayer.gfxOffY + num3); this.DrawPlayer(camera, drawPlayer, position1, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin, drawPlayer.ghostFade, 1f); } } if (drawPlayer.armorEffectDrawShadowBasilisk) { int num = (int)((double)drawPlayer.basiliskCharge * 3.0); for (int index = 0; index < num; ++index) { this.DrawPlayer(camera, drawPlayer, drawPlayer.shadowPos[index], drawPlayer.shadowRotation[index], drawPlayer.shadowOrigin[index], (float)(0.5 + 0.200000002980232 * (double)index), 1f); } } else if (drawPlayer.armorEffectDrawShadow) { for (int index = 0; index < 3; ++index) { this.DrawPlayer(camera, drawPlayer, drawPlayer.shadowPos[index], drawPlayer.shadowRotation[index], drawPlayer.shadowOrigin[index], (float)(0.5 + 0.200000002980232 * (double)index), 1f); } } if (drawPlayer.armorEffectDrawShadowLokis) { for (int index = 0; index < 3; ++index) { this.DrawPlayer(camera, drawPlayer, Vector2.Lerp(drawPlayer.shadowPos[index], drawPlayer.position + new Vector2(0.0f, drawPlayer.gfxOffY), 0.5f), drawPlayer.shadowRotation[index], drawPlayer.shadowOrigin[index], MathHelper.Lerp(1f, (float)(0.5 + 0.200000002980232 * (double)index), 0.5f), 1f); } } if (drawPlayer.armorEffectDrawShadowSubtle) { for (int index = 0; index < 4; ++index) { position1.X = drawPlayer.position.X + (float)Main.rand.Next(-20, 21) * 0.1f; position1.Y = drawPlayer.position.Y + (float)Main.rand.Next(-20, 21) * 0.1f + drawPlayer.gfxOffY; this.DrawPlayer(camera, drawPlayer, position1, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin, 0.9f, 1f); } } if (drawPlayer.shadowDodge) { ++drawPlayer.shadowDodgeCount; if ((double)drawPlayer.shadowDodgeCount > 30.0) { drawPlayer.shadowDodgeCount = 30f; } } else { --drawPlayer.shadowDodgeCount; if ((double)drawPlayer.shadowDodgeCount < 0.0) { drawPlayer.shadowDodgeCount = 0.0f; } } if ((double)drawPlayer.shadowDodgeCount > 0.0) { Vector2 position2 = drawPlayer.position; position1.X = drawPlayer.position.X + drawPlayer.shadowDodgeCount; position1.Y = drawPlayer.position.Y + drawPlayer.gfxOffY; this.DrawPlayer(camera, drawPlayer, position1, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin, (float)(0.5 + (double)Main.rand.Next(-10, 11) * 0.00499999988824129), 1f); position1.X = drawPlayer.position.X - drawPlayer.shadowDodgeCount; this.DrawPlayer(camera, drawPlayer, position1, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin, (float)(0.5 + (double)Main.rand.Next(-10, 11) * 0.00499999988824129), 1f); } if (drawPlayer.brainOfConfusionDodgeAnimationCounter > 0) { Vector2 vector2 = drawPlayer.position + new Vector2(0.0f, drawPlayer.gfxOffY); float lerpValue = Utils.GetLerpValue(300f, 270f, (float)drawPlayer.brainOfConfusionDodgeAnimationCounter, false); float y = MathHelper.Lerp(2f, 120f, lerpValue); if ((double)lerpValue >= 0.0 && (double)lerpValue <= 1.0) { for (float num = 0.0f; (double)num < 6.28318548202515; num += 1.047198f) { position1 = vector2 + new Vector2(0.0f, y).RotatedBy(6.28318548202515 * (double)lerpValue * 0.5 + (double)num, new Vector2()); this.DrawPlayer(camera, drawPlayer, position1, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin, lerpValue, 1f); } } } position1 = drawPlayer.position; position1.Y += drawPlayer.gfxOffY; if (drawPlayer.stoned) { this.DrawPlayerStoned(camera, drawPlayer, position1); } else if (!drawPlayer.invis) { this.DrawPlayer(camera, drawPlayer, position1, drawPlayer.fullRotation, drawPlayer.fullRotationOrigin, 0.0f, 1f); } } spriteBatch.End(); }