private void Init() { _NormalVar = GetVariableByName("g_Normal").AsShaderResource(); _MaskVar = GetVariableByName("g_Mask").AsShaderResource(); _CustomizeParameterVar = new CustomizeParameterEffectVariable(this); }
private void Init() { _DiffuseVar = GetVariableByName("g_Diffuse").AsShaderResource(); _SpecularVar = GetVariableByName("g_Specular").AsShaderResource(); _NormalVar = GetVariableByName("g_Normal").AsShaderResource(); _MaskVar = GetVariableByName("g_Mask").AsShaderResource(); _TableVar = GetVariableByName("g_Table").AsShaderResource(); }
private void Init() { _Diffuse0Var = GetVariableByName("g_Diffuse0").AsShaderResource(); _Specular0Var = GetVariableByName("g_Specular0").AsShaderResource(); _Normal0Var = GetVariableByName("g_Normal0").AsShaderResource(); _Diffuse1Var = GetVariableByName("g_Diffuse1").AsShaderResource(); _Specular1Var = GetVariableByName("g_Specular1").AsShaderResource(); _Normal1Var = GetVariableByName("g_Normal1").AsShaderResource(); }
public override void Attach(IRenderHost host) { // --- attach this.renderTechnique = Techniques.RenderBillboard; this.effect = EffectsManager.Instance.GetEffect(renderTechnique); this.renderHost = host; // --- get variables this.vertexLayout = EffectsManager.Instance.GetLayout(this.renderTechnique); this.effectTechnique = effect.GetTechniqueByName(this.renderTechnique.Name); // --- transformations this.effectTransforms = new EffectTransformVariables(this.effect); // --- shader variables this.vViewport = effect.GetVariableByName("vViewport").AsVector(); // --- get geometry var geometry = this.Geometry as BillboardText3D; if (geometry == null) { return; } // --- material // this.AttachMaterial(); billboardTextureVariable = effect.GetVariableByName("billboardTexture").AsShaderResource(); var textureBytes = geometry.Texture.ToByteArray(); billboardTextureView = ShaderResourceView.FromMemory(Device, textureBytes); billboardTextureVariable.SetResource(billboardTextureView); // -- set geometry if given vertexBuffer = Device.CreateBuffer(BindFlags.VertexBuffer, DefaultVertex.SizeInBytes, CreateBillboardVertexArray()); /// --- set rasterstate this.OnRasterStateChanged(this.DepthBias); /// --- flush this.Device.ImmediateContext.Flush(); }
public override void Attach(IRenderHost host) { // --- attach renderTechnique = host.RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.BillboardText]; effect = host.EffectsManager.GetEffect(renderTechnique); renderHost = host; // --- get variables vertexLayout = renderHost.EffectsManager.GetLayout(renderTechnique); effectTechnique = effect.GetTechniqueByName(renderTechnique.Name); // --- transformations effectTransforms = new EffectTransformVariables(effect); // --- shader variables vViewport = effect.GetVariableByName("vViewport").AsVector(); // --- get geometry var geometry = Geometry as BillboardText3D; if (geometry == null) { return; } // --- material // this.AttachMaterial(); billboardTextureVariable = effect.GetVariableByName("billboardTexture").AsShaderResource(); var textureBytes = BillboardText3D.Texture.ToByteArray(); // billboardTextureView =new ShaderResourceView(Device, BillboardText3D.Texture); billboardTextureVariable.SetResource(billboardTextureView); // -- set geometry if given vertexBuffer = Device.CreateBuffer(BindFlags.VertexBuffer, VertexSizeInBytes, CreateBillboardVertexArray()); /// --- set rasterstate OnRasterStateChanged(DepthBias); /// --- flush Device.ImmediateContext.Flush(); }
private void BuildFX() { SharpDX.D3DCompiler.ShaderBytecode compiledShader = null; try { compiledShader = new SharpDX.D3DCompiler.ShaderBytecode(System.IO.File.ReadAllBytes("fx/lighting.fxo")); _fx = new D3D11.Effect(Device, compiledShader); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } finally { Util.ReleaseCom(ref compiledShader); } _tech = _fx.GetTechniqueByName("LightTech"); _fxWVP = _fx.GetVariableByName("gWorldViewProj").AsMatrix(); _fxWorld = _fx.GetVariableByName("gWorld").AsMatrix(); _fxWIT = _fx.GetVariableByName("gWorldInvTranspose").AsMatrix(); _fxEyePosW = _fx.GetVariableByName("gEyePosW").AsVector(); _fxDirLight = _fx.GetVariableByName("gDirLight"); _fxPointLight = _fx.GetVariableByName("gPointLight"); _fxSpotLight = _fx.GetVariableByName("gSpotLight"); _fxMaterial = _fx.GetVariableByName("gMaterial"); _fxDiffuseMap = _fx.GetVariableByName("gDiffuseMap").AsShaderResource(); _fxRefractiveMap = _fx.GetVariableByName("gRefractiveMap").AsShaderResource(); _fxClipPlane = _fx.GetVariableByName("gClipPlane").AsVector(); _fxReflectViewProj = _fx.GetVariableByName("gReflectViewProj").AsMatrix(); _fxReflectiveMap = _fx.GetVariableByName("gReflectiveMap").AsShaderResource(); _fxgRefractionPositionMap = _fx.GetVariableByName("gRefractionPositionMap").AsShaderResource(); _fxUseStructBuf = _fx.GetVariableByName("gUseStructBuf").AsScalar(); _fxSolutionSR = _fx.GetVariableByName("gSolution").AsShaderResource(); }
private void CompileShader(Device device, string fullPath) { _File = fullPath; _CompiledEffect = ShaderBytecode.CompileFromFile(_File, "SpriteTech", "fx_5_0"); if (_CompiledEffect.HasErrors) { Log.Write("Shader compilation failed with status code: {0} - {1} | Path: {2}", _CompiledEffect.ResultCode.Code, _CompiledEffect.Message, _File); return; } _Effect = new Effect(device, _CompiledEffect); _EffectTechnique = _Effect.GetTechniqueByName("SpriteTech"); _SpriteMap = _Effect.GetVariableByName("SpriteTex").AsShaderResource(); var _EffectPass = _EffectTechnique.GetPassByIndex(0).Description.Signature; InputElement[] _LayoutDescription = { new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 20, 0, InputClassification.PerVertexData, 0) }; _InputLayout = new InputLayout(device, _EffectPass, _LayoutDescription); }
public void Initialize() { var direct2Dsettings = new RenderTarget.Configuration.CreationSettings( new Size(_settings.Width, _settings.Height), false, new SampleDescription(1, 0), RenderTarget.Configuration.RenderTargetClearSettings.Default, RenderTarget.Configuration.DepthStencilClearSettings.Default); RenderTargetDirect2D = _deviceManager.RenderTargetManager.CreateDirect2DRenderTarget(direct2Dsettings); _screenQuad = MeshFactory.CreateScreenQuad(_deviceManager.Device); //_screenQuadBinding = new VertexBufferBinding(_screenQuad, 20, 0); _effect = _deviceManager.ShaderCompiler.CreateEffectFromFile(@"..\..\Shaders\staging.fx"); _pass = _effect.GetTechniqueByIndex(0).GetPassByIndex(0); //_elements = new[] // { // new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), // new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0), // }; _screenQuadBufferLayout = new InputLayout(_deviceManager.Device, _pass.Description.Signature, VertexPositionTexture.InputElements); //_screenQuadBufferLayout = new InputLayout(_deviceManager.Device, _pass.Description.Signature, _elements); _shaderResource = _effect.GetVariableByName("source").AsShaderResource(); var bsd = new BlendStateDescription(); bsd.RenderTarget[0].IsBlendEnabled = true; bsd.RenderTarget[0].SourceBlend = BlendOption.SourceColor; bsd.RenderTarget[0].DestinationBlend = BlendOption.BlendFactor; bsd.RenderTarget[0].BlendOperation = BlendOperation.Add; bsd.RenderTarget[0].SourceAlphaBlend = BlendOption.One; bsd.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; bsd.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _blendStateTransparent = new BlendState(_deviceManager.Device, bsd); }
public bool Initialize() { Debug.Assert(!_initialized); #region Shaders string SpriteFX = @"Texture2D SpriteTex; SamplerState samLinear { Filter = MIN_MAG_MIP_LINEAR; AddressU = WRAP; AddressV = WRAP; }; struct VertexIn { float3 PosNdc : POSITION; float2 Tex : TEXCOORD; float4 Color : COLOR; }; struct VertexOut { float4 PosNdc : SV_POSITION; float2 Tex : TEXCOORD; float4 Color : COLOR; }; VertexOut VS(VertexIn vin) { VertexOut vout; vout.PosNdc = float4(vin.PosNdc, 1.0f); vout.Tex = vin.Tex; vout.Color = vin.Color; return vout; }; float4 PS(VertexOut pin) : SV_Target { return pin.Color*SpriteTex.Sample(samLinear, pin.Tex); }; technique11 SpriteTech { pass P0 { SetVertexShader( CompileShader( vs_5_0, VS() ) ); SetHullShader( NULL ); SetDomainShader( NULL ); SetGeometryShader( NULL ); SetPixelShader( CompileShader( ps_5_0, PS() ) ); } };"; #endregion _compiledFX = ShaderBytecode.Compile(SpriteFX, "SpriteTech", "fx_5_0"); { if (_compiledFX.HasErrors) return false; _effect = new Effect(_device, _compiledFX); { _spriteTech = _effect.GetTechniqueByName("SpriteTech"); _spriteMap = _effect.GetVariableByName("SpriteTex").AsShaderResource(); var pass = _spriteTech.GetPassByIndex(0).Description.Signature; InputElement[] layoutDesc = { new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 20, 0, InputClassification.PerVertexData, 0) }; _inputLayout = new InputLayout(_device, pass, layoutDesc); // Create Vertex Buffer BufferDescription vbd = new BufferDescription { SizeInBytes = 2048 * Marshal.SizeOf(typeof(SpriteVertex)), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; _VB = new SharpDX.Direct3D11.Buffer(_device, vbd); // Create and initialise Index Buffer short[] indices = new short[3072]; for (ushort i = 0; i < 512; ++i) { indices[i * 6] = (short)(i * 4); indices[i * 6 + 1] = (short)(i * 4 + 1); indices[i * 6 + 2] = (short)(i * 4 + 2); indices[i * 6 + 3] = (short)(i * 4); indices[i * 6 + 4] = (short)(i * 4 + 2); indices[i * 6 + 5] = (short)(i * 4 + 3); } _indexBuffer = Marshal.AllocHGlobal(indices.Length * Marshal.SizeOf(indices[0])); Marshal.Copy(indices, 0, _indexBuffer, indices.Length); BufferDescription ibd = new BufferDescription { SizeInBytes = 3072 * Marshal.SizeOf(typeof(short)), Usage = ResourceUsage.Immutable, BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; _IB = new SharpDX.Direct3D11.Buffer(_device, _indexBuffer, ibd); BlendStateDescription transparentDesc = new BlendStateDescription() { AlphaToCoverageEnable = false, IndependentBlendEnable = false, }; transparentDesc.RenderTarget[0].IsBlendEnabled = true; transparentDesc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; transparentDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; transparentDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; transparentDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; transparentDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; transparentDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; transparentDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _transparentBS = new BlendState(_device, transparentDesc); } } _initialized = true; return true; }
void CreateBuffers() { DisposeBuffers(); // New RenderTargetView from the backbuffer using (var bb = Texture2D.FromSwapChain<Texture2D>(_swapChain, 0)) { renderView = new RenderTargetView(_device, bb); } Texture2DDescription gBufferDesc = new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, Format = Format.R8G8B8A8_UNorm, Width = _width, Height = _height, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }; gBufferLight = new Texture2D(_device, gBufferDesc); gBufferLightView = new RenderTargetView(_device, gBufferLight); gBufferNormal = new Texture2D(_device, gBufferDesc); gBufferNormalView = new RenderTargetView(_device, gBufferNormal); gBufferDiffuse = new Texture2D(_device, gBufferDesc); gBufferDiffuseView = new RenderTargetView(_device, gBufferDiffuse); gBufferViews = new RenderTargetView[] { gBufferLightView, gBufferNormalView, gBufferDiffuseView }; ShaderResourceViewDescription gBufferResourceDesc = new ShaderResourceViewDescription() { Format = Format.R8G8B8A8_UNorm, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0 } }; lightBufferRes = new ShaderResourceView(_device, gBufferLight, gBufferResourceDesc); normalBufferRes = new ShaderResourceView(_device, gBufferNormal, gBufferResourceDesc); diffuseBufferRes = new ShaderResourceView(_device, gBufferDiffuse, gBufferResourceDesc); Texture2DDescription depthDesc = new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, Format = Format.R32_Typeless, Width = _width, Height = _height, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }; DepthStencilViewDescription depthViewDesc = new DepthStencilViewDescription() { Dimension = DepthStencilViewDimension.Texture2D, Format = Format.D32_Float, }; ShaderResourceViewDescription resourceDesc = new ShaderResourceViewDescription() { Format = Format.R32_Float, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0 } }; depthTexture = new Texture2D(_device, depthDesc); depthView = new DepthStencilView(_device, depthTexture, depthViewDesc); depthRes = new ShaderResourceView(_device, depthTexture, resourceDesc); lightDepthTexture = new Texture2D(_device, depthDesc); lightDepthView = new DepthStencilView(_device, lightDepthTexture, depthViewDesc); lightDepthRes = new ShaderResourceView(_device, lightDepthTexture, resourceDesc); lightBufferVar = effect2.GetVariableByName("lightBuffer").AsShaderResource(); normalBufferVar = effect2.GetVariableByName("normalBuffer").AsShaderResource(); diffuseBufferVar = effect2.GetVariableByName("diffuseBuffer").AsShaderResource(); depthMapVar = effect2.GetVariableByName("depthMap").AsShaderResource(); lightDepthMapVar = effect2.GetVariableByName("lightDepthMap").AsShaderResource(); _immediateContext.Rasterizer.SetViewport(new ViewportF(0, 0, _width, _height)); }
public WavesSimulator(IntPtr hInst) : base(hInst) { //Geometry Related Buffers _ballIB = null; _ballVB = null; _groundVB = null; _groundIB = null; _wavesVB = null; _wavesIB = null; _ballIndexCount = 0; _groundIndexCount = 0; //WVP Matrices _groundWorld = Matrix.Identity; _wavesWorld = Matrix.Translation(0, -2.0f, 0); _ballWorld = Matrix.Translation(-30, 15, 0); _view = Matrix.Identity; _proj = Matrix.Identity; _reflectView = Matrix.Identity; //Rendering Effects Related _fx = null; _fxWVP = null; _tech = null; _fxWorld = null; _fxWIT = null; _fxEyePosW = null; _fxDirLight = null; _fxPointLight = null; _fxSpotLight = null; _fxMaterial = null; _fxDiffuseMap = null; _fxRefractiveMap = null; _fxClipPlane = null; _fxReflectiveMap = null; _fxReflectViewProj = null; _fxUseStructBuf = null; _fxgRefractionPositionMap = null; //Textures and Views refractText = null; refractRenderTargetView = null; refractResourceView = null; reflectRenderTargetView = null; reflectResourceView = null; reflectText = null; positionMapRenderTargetView = null; positionMapResourceView = null; positionMapText = null; _groundMapSRV = null; _groundMap = null; //Input Format _inputLayout = null; //Camera Related _theta = 1.5f * MathF.PI; _phi = 0.1f * MathF.PI; _radius = 200.0f; _lastMousePos = new System.Drawing.Point(0, 0); _eyePosW = new Vector3(); //Shading and Lighting _alphaBlend = null; _dirLight = new DirectionalLight { Ambient = new Color4(0.2f, 0.2f, 0.2f, 1), Diffuse = new Color4(0.5f, 0.5f, 0.5f, 1), Specular = new Color4(0.5f, 0.5f, 0.5f, 1), Direction = new Vector3(0.57735f, -0.57735f, 0.57735f) }; _pointLight = new PointLight { Ambient = new Color4(0.3f, 0.3f, 0.3f, 1), Diffuse = new Color4(0.7f, 0.7f, 0.7f, 1), Specular = new Color4(0.7f, 0.7f, 0.7f, 1), Attenuation = new Vector3(0.1f, 0.1f, 0.1f), Range = 25.0f }; _spotLight = new SpotLight { Ambient = new Color4(0, 0, 0, 0), Diffuse = new Color4(1.0f, 1.0f, 1.0f, 1), Specular = Color.White, Attenuation = new Vector3(1.0f, 0.0f, 0.0f), Spot = 96.0f, Range = 10000.0f }; _landMaterial = new Material { Ambient = new Color4(1f, 1f, 1f, 1.0f), Diffuse = new Color4(1, 1, 1, 1.0f), Specular = new Color4(0.2f, 0.2f, 0.2f, 16.0f), Reflect = new Color4(1.0f, 1f, 1f, 1f) }; _wavesMaterial = new Material { Ambient = new Color4(1, 1, 1, 0.8f), Diffuse = new Color4(0.137f, 0.42f, 0.556f, 1.0f), Specular = new Color4(0.8f, 0.8f, 0.8f, 96.0f), Reflect = new Color4(2f, 1, 1, 1) //R component of Reflect is used for Gama Correction in Effect }; _disposed = false; MainWindowCaption = "Waves Simulator"; }
public DrawingManager(DeviceManager deviceManager) { _device = deviceManager.Device; _context = deviceManager.Context; _vertexLayouts = deviceManager.VertexLayouts; var effect = deviceManager.Effect; _standardSmooth = effect.GetTechniqueByName("Standard|Smooth"); _standardFlat = effect.GetTechniqueByName("Standard|Flat"); _standardWireframe = effect.GetTechniqueByName("Standard|Wireframe"); _prelitSmooth = effect.GetTechniqueByName("Prelit|Smooth"); _prelitFlat = effect.GetTechniqueByName("Prelit|Flat"); _prelitWireframe = effect.GetTechniqueByName("Prelit|Wireframe"); _worldMatrix = effect.GetVariableByName("g_WorldMatrix").AsMatrix(); _postWorldMatrix = effect.GetVariableByName("g_PostWorldMatrix").AsMatrix(); _viewMatrix = effect.GetVariableByName("g_ViewMatrix").AsMatrix(); _projectionMatrix = effect.GetVariableByName("g_ProjectionMatrix").AsMatrix(); _color = effect.GetVariableByName("g_Color").AsVector(); _opacity = effect.GetVariableByName("g_Opacity").AsScalar(); _ambient = effect.GetVariableByName("g_Ambient").AsScalar(); _diffuse = effect.GetVariableByName("g_Diffuse").AsScalar(); _texture = effect.GetVariableByName("g_Texture").AsShaderResource(); _mask = effect.GetVariableByName("g_Mask").AsShaderResource(); _textureSampler = effect.GetVariableByName("g_TextureSampler").AsSampler(); _hasTexture = effect.GetVariableByName("g_HasTexture").AsScalar(); _hasMask = effect.GetVariableByName("g_HasMask").AsScalar(); _isInstanced = effect.GetVariableByName("g_IsInstanced").AsScalar(); _isColorTinted = effect.GetVariableByName("g_IsColorTinted").AsScalar(); _globalLight = effect.GetVariableByName("g_GlobalLight"); _lightViewProjectionMatrix = effect.GetVariableByName("g_LightViewProjectionMatrix").AsMatrix(); //Set the states to Unknown initially. _currentDrawingState = DrawingState.Unknown; _currentTopologyState = PrimitiveTopologyState.Unknown; //Set the default of the g_PostWorldMatrix to Identity, so it isn't required to be set. _postWorldMatrix.SetMatrix(Matrix.Identity); //Setup shadow map technique. var shadowEffect = deviceManager.ShadowEffect; _shadowMapStandard = shadowEffect.GetTechniqueByName("ShadowMapTechnique|Standard"); _shadowMapPrelit = shadowEffect.GetTechniqueByName("ShadowMapTechnique|Prelit"); _isShadowInstanced = shadowEffect.GetVariableByName("g_IsInstanced").AsScalar(); _shadowWorldMatrix = shadowEffect.GetVariableByName("g_WorldMatrix").AsMatrix(); _shadowHasMask = shadowEffect.GetVariableByName("g_HasMask").AsScalar(); _shadowMask = shadowEffect.GetVariableByName("g_Mask").AsShaderResource(); _shadowLightViewProjectionMatrix = shadowEffect.GetVariableByName("g_LightViewProjectionMatrix").AsMatrix(); }
public override void Attach(IRenderHost host) { this.width = (int)(Resolution.X + 0.5f); //faktor* oneK; this.height = (int)(this.Resolution.Y + 0.5f); // faktor* oneK; base.effectName = Techniques.RenderColors; base.Attach(host); if (!host.IsShadowMapEnabled) { return; } // gen shadow map this.depthBufferSM = new Texture2D(device, new Texture2DDescription() { Format = Format.R32_Typeless, //!!!! because of depth and shader resource //Format = global::SharpDX.DXGI.Format.B8G8R8A8_UNorm, ArraySize = 1, MipLevels = 1, Width = width, Height = height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource, //!!!! CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, }); this.colorBufferSM = new Texture2D(this.device, new Texture2DDescription { BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm, Width = width, Height = height, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.None, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1 }); this.renderTargetSM = new RenderTargetView(this.device, colorBufferSM) { }; this.depthViewSM = new DepthStencilView(device, depthBufferSM, new DepthStencilViewDescription() { Format = Format.D32_Float, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }); this.texShadowMapView = new ShaderResourceView(device, depthBufferSM, new ShaderResourceViewDescription() { Format = Format.R32_Float, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0, } }); //!!!! this.texColorMapView = new ShaderResourceView(this.device, colorBufferSM, new ShaderResourceViewDescription() { Format = Format.B8G8R8A8_UNorm, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0, } }); this.texShadowMapVariable = effect.GetVariableByName("texShadowMap").AsShaderResource(); this.vShadowMapInfoVariable = effect.GetVariableByName("vShadowMapInfo").AsVector(); this.vShadowMapSizeVariable = effect.GetVariableByName("vShadowMapSize").AsVector(); this.shadowPassContext = new RenderContext((DPFCanvas)host, this.effect); }
/// <summary> /// deviceを作成します。 /// </summary> /// <param name="control">レンダリング先となるcontrol</param> /// <param name="tso_config">設定</param> /// <returns>deviceの作成に成功したか</returns> public bool InitializeApplication(Control control, TSOConfig tso_config) { this.tso_config = tso_config; SetControl(control); control.MouseDown += new MouseEventHandler(form_OnMouseDown); control.MouseMove += new MouseEventHandler(form_OnMouseMove); { device = new Device(DriverType.Hardware, DeviceCreationFlags.None); var desc = new SharpDX.DXGI.SwapChainDescription() { BufferCount = 1, Usage = SharpDX.DXGI.Usage.RenderTargetOutput, OutputHandle = control.Handle, IsWindowed = true, ModeDescription = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm), SampleDescription = DetectSampleDescription(device, SharpDX.DXGI.Format.D32_Float), Flags = SharpDX.DXGI.SwapChainFlags.AllowModeSwitch, SwapEffect = SharpDX.DXGI.SwapEffect.Discard }; dxgi_factory = new SharpDX.DXGI.Factory(); swap_chain = new SharpDX.DXGI.SwapChain(dxgi_factory, device, desc); } ctx = device.ImmediateContext; Stopwatch sw = new Stopwatch(); sw.Start(); string effect_file = Path.Combine(Application.StartupPath, @"toonshader.fx.bin"); if (! File.Exists(effect_file)) { Console.WriteLine("File not found: " + effect_file); return false; } try { var shader_bytecode = ShaderBytecode.FromFile(effect_file); effect = new Effect(device, shader_bytecode); } catch (SharpDX.CompilationException e) { Console.WriteLine(e.Message + ": " + effect_file); return false; } sw.Stop(); Console.WriteLine("toonshader.fx.bin read time: " + sw.Elapsed); string techmap_file = Path.Combine(Application.StartupPath, @"techmap.txt"); if (! File.Exists(techmap_file)) { Console.WriteLine("File not found: " + techmap_file); return false; } techmap.Load(techmap_file); World_variable = effect.GetVariableBySemantic("World").AsMatrix(); WorldView_variable = effect.GetVariableBySemantic("WorldView").AsMatrix(); WorldViewProjection_variable = effect.GetVariableBySemantic("WorldViewProjection").AsMatrix(); /* for HUD */ Projection_variable = effect.GetVariableBySemantic("Projection").AsMatrix(); LocalBoneMats_variable = effect.GetVariableByName("LocalBoneMats").AsMatrix(); LightDirForced_variable = effect.GetVariableByName("LightDirForced").AsVector(); UVSCR_variable = effect.GetVariableByName("UVSCR").AsVector(); cb_variable = effect.GetConstantBufferByName("cb"); ShadeTex_texture_variable = effect.GetVariableByName("ShadeTex_texture").AsShaderResource(); ColorTex_texture_variable = effect.GetVariableByName("ColorTex_texture").AsShaderResource(); figures.Camera = camera; figures.TSOFileOpen += delegate(TSOFile tso) { tso.Open(device, effect); techmap.AssignTechniqueIndices(tso); }; // Define an input layout to be passed to the vertex shader. var technique = effect.GetTechniqueByIndex(0); il = new InputLayout(device, technique.GetPassByIndex(0).Description.Signature, TSOSubMesh.ie); // Setup the immediate context to use the shaders and model we defined. ctx.InputAssembler.InputLayout = il; camera.Update(); DefineBlendState(); DefineDepthStencilState(); DefineRasterizerState(); return true; }
/// <summary> /// deviceを作成します。 /// </summary> /// <param name="control">レンダリング先となるcontrol</param> /// <param name="ocu_config">設定</param> /// <returns>deviceの作成に成功したか</returns> public bool InitializeApplication(Control control, OcuConfig ocu_config) { this.ocu_config = ocu_config; oculus = new OculusWrap.Wrap(); // Initialize the Oculus runtime. bool success = oculus.Initialize(); if (!success) { MessageBox.Show("Failed to initialize the Oculus runtime library.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } // Use the head mounted display, if it's available, otherwise use the debug HMD. int numberOfHeadMountedDisplays = oculus.Hmd_Detect(); if (numberOfHeadMountedDisplays > 0) hmd = oculus.Hmd_Create(0); else hmd = oculus.Hmd_CreateDebug(OculusWrap.OVR.HmdType.DK2); if (hmd == null) { MessageBox.Show("Oculus Rift not detected.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (hmd.ProductName == string.Empty) MessageBox.Show("The HMD is not enabled.", "There's a tear in the Rift", MessageBoxButtons.OK, MessageBoxIcon.Error); // Specify which head tracking capabilities to enable. hmd.SetEnabledCaps(OculusWrap.OVR.HmdCaps.LowPersistence | OculusWrap.OVR.HmdCaps.DynamicPrediction); // Start the sensor which informs of the Rift's pose and motion hmd.ConfigureTracking(OculusWrap.OVR.TrackingCaps.ovrTrackingCap_Orientation | OculusWrap.OVR.TrackingCaps.ovrTrackingCap_MagYawCorrection | OculusWrap.OVR.TrackingCaps.ovrTrackingCap_Position, OculusWrap.OVR.TrackingCaps.None); // Create DirectX drawing device. device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.None); ctx = device.ImmediateContext; Stopwatch sw = new Stopwatch(); sw.Start(); string effect_file = Path.Combine(Application.StartupPath, @"toonshader.fx.bin"); if (! File.Exists(effect_file)) { Console.WriteLine("File not found: " + effect_file); return false; } try { var shader_bytecode = ShaderBytecode.FromFile(effect_file); effect = new Effect(device, shader_bytecode); } catch (SharpDX.CompilationException e) { Console.WriteLine(e.Message + ": " + effect_file); return false; } sw.Stop(); Console.WriteLine("toonshader.fx.bin read time: " + sw.Elapsed); string techmap_file = Path.Combine(Application.StartupPath, @"techmap.txt"); if (!File.Exists(techmap_file)) { Console.WriteLine("File not found: " + techmap_file); return false; } techmap.Load(techmap_file); control.MouseDown += new MouseEventHandler(form_OnMouseDown); // Define the properties of the swap chain. SwapChainDescription swapChainDescription = DefineSwapChainDescription(control); // Create DirectX Graphics Interface factory, used to create the swap chain. dxgi_factory = new SharpDX.DXGI.Factory(); // Create the swap chain. swap_chain = new SwapChain(dxgi_factory, device, swapChainDescription); // Retrieve the back buffer of the swap chain. buf0 = swap_chain.GetBackBuffer<Texture2D>(0); buf0_view = new RenderTargetView(device, buf0); // Create a depth buffer, using the same width and height as the back buffer. Texture2DDescription depthBufferDescription = DefineDepthBufferDescription(control); // Create the depth buffer. ztex = new Texture2D(device, depthBufferDescription); ztex_view = new DepthStencilView(device, ztex); ctx.OutputMerger.SetRenderTargets(ztex_view, buf0_view); viewport = new Viewport(0, 0, hmd.Resolution.Width, hmd.Resolution.Height, 0.0f, 1.0f); ctx.Rasterizer.SetViewport(viewport); // Retrieve the DXGI device, in order to set the maximum frame latency. using (SharpDX.DXGI.Device1 dxgiDevice = device.QueryInterface<SharpDX.DXGI.Device1>()) { dxgiDevice.MaximumFrameLatency = 1; } layers = new OculusWrap.Layers(); layer_eye_fov = layers.AddLayerEyeFov(); CreateEyeTextures(); CreateMirrorTexture(control); World_variable = effect.GetVariableBySemantic("World").AsMatrix(); WorldView_variable = effect.GetVariableBySemantic("WorldView").AsMatrix(); WorldViewProjection_variable = effect.GetVariableBySemantic("WorldViewProjection").AsMatrix(); /* for HUD */ Projection_variable = effect.GetVariableBySemantic("Projection").AsMatrix(); LocalBoneMats_variable = effect.GetVariableByName("LocalBoneMats").AsMatrix(); LightDirForced_variable = effect.GetVariableByName("LightDirForced").AsVector(); UVSCR_variable = effect.GetVariableByName("UVSCR").AsVector(); cb_variable = effect.GetConstantBufferByName("cb"); ShadeTex_texture_variable = effect.GetVariableByName("ShadeTex_texture").AsShaderResource(); ColorTex_texture_variable = effect.GetVariableByName("ColorTex_texture").AsShaderResource(); //figures.Camera = camera; figures.TSOFileOpen += delegate(TSOFile tso) { tso.Open(device, effect); techmap.AssignTechniqueIndices(tso); }; // Define an input layout to be passed to the vertex shader. var technique = effect.GetTechniqueByIndex(0); il = new InputLayout(device, technique.GetPassByIndex(0).Description.Signature, TSOSubMesh.ie); // Setup the immediate context to use the shaders and model we defined. ctx.InputAssembler.InputLayout = il; DefineBlendState(); DefineDepthStencilState(); DefineRasterizerState(); main_camera = new Camera() { Position = ocu_config.Position, Rotation = Quaternion.Identity, }; directInput = new DirectInput(); keyboard = new Keyboard(directInput); keyboard.Acquire(); keyboardState = keyboard.GetCurrentState(); return true; }
private void Init() { _ColorMap0Var = GetVariableByName("g_ColorMap0").AsShaderResource(); _SpecularMap0Var = GetVariableByName("g_SpecularMap0").AsShaderResource(); _NormalMap0Var = GetVariableByName("g_NormalMap0").AsShaderResource(); _ColorVar = GetVariableByName("g_Color").AsVector(); }
public void Initialize() { Form.SizeChanged += (o, args) => { if (_swapChain == null) return; renderView.Dispose(); depthView.Dispose(); DisposeBuffers(); if (Form.WindowState == FormWindowState.Minimized) return; Width = Form.ClientSize.Width; Height = Form.ClientSize.Height; _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0); CreateBuffers(); SetSceneConstants(); }; Width = 1024; Height = 768; NearPlane = 1.0f; FarPlane = 200.0f; FieldOfView = (float)Math.PI / 4; try { OnInitializeDevice(); } catch (Exception e) { MessageBox.Show(e.ToString(), "Could not create DirectX 11 device."); return; } // shader.fx const ShaderFlags shaderFlags = ShaderFlags.None; //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization; string[] sources = new[] { "shader.fx", "grender.fx" }; using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), sources, shaderFlags)) { effect = new Effect(_device, shaderByteCode); } EffectTechnique technique = effect.GetTechniqueByName("GBufferCreate"); shadowGenPass = technique.GetPassByName("ShadowMap"); gBufferGenPass = technique.GetPassByName("GBufferGen"); debugDrawPass = technique.GetPassByName("DebugDraw"); BufferDescription sceneConstantsDesc = new BufferDescription() { SizeInBytes = Marshal.SizeOf(typeof(ShaderSceneConstants)), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None }; sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc); EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene"); effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer); RasterizerStateDescription _rasterizerStateDesc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, IsDepthClipEnabled = true, }; noCullState = new RasterizerState(_device, _rasterizerStateDesc); _rasterizerStateDesc.CullMode = CullMode.Back; backCullState = new RasterizerState(_device, _rasterizerStateDesc); _rasterizerStateDesc.CullMode = CullMode.Front; frontCullState = new RasterizerState(_device, _rasterizerStateDesc); _immediateContext.Rasterizer.State = CullingEnabled ? backCullState : noCullState; DepthStencilStateDescription depthDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; depthState = new DepthStencilState(_device, depthDesc); depthDesc.DepthWriteMask = DepthWriteMask.Zero; outsideLightVolumeDepthState = new DepthStencilState(_device, depthDesc); depthDesc.DepthComparison = Comparison.Greater; insideLightVolumeDepthState = new DepthStencilState(_device, depthDesc); DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc); // grender.fx technique = effect.GetTechniqueByName("DeferredShader"); gBufferRenderPass = technique.GetPassByName("DeferredShader"); gBufferPostProcessPass = technique.GetPassByName("Blur"); gBufferPostProcessPass2 = technique.GetPassByName("PostProcess"); gBufferOverlayPass = technique.GetPassByName("Overlay"); lightBufferVar = effect.GetVariableByName("lightBuffer").AsShaderResource(); normalBufferVar = effect.GetVariableByName("normalBuffer").AsShaderResource(); diffuseBufferVar = effect.GetVariableByName("diffuseBuffer").AsShaderResource(); depthMapVar = effect.GetVariableByName("depthMap").AsShaderResource(); shadowLightDepthBufferVar = effect.GetVariableByName("lightDepthMap").AsShaderResource(); sunLightDirectionVar = effect.GetVariableByName("SunLightDirection").AsVector(); viewportWidthVar = effect.GetVariableByName("ViewportWidth").AsScalar(); viewportHeightVar = effect.GetVariableByName("ViewportHeight").AsScalar(); viewParametersVar = effect.GetVariableByName("ViewParameters").AsVector(); overlayViewProjectionVar = effect.GetVariableByName("OverlayViewProjection").AsMatrix(); // light.fx using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), "light.fx", shaderFlags)) { lightShader = new Effect(_device, shaderByteCode); } technique = lightShader.GetTechniqueByIndex(0); lightAccumulationPass = technique.GetPassByName("Light"); lightWorldVar = lightShader.GetVariableByName("World").AsMatrix(); lightPositionRadiusVar = lightShader.GetVariableByName("PositionRadius").AsVector(); lightColorVar = lightShader.GetVariableByName("Color").AsVector(); lightProjectionVar = lightShader.GetVariableByName("Projection").AsMatrix(); lightViewVar = lightShader.GetVariableByName("View").AsMatrix(); lightViewInverseVar = lightShader.GetVariableByName("ViewInverse").AsMatrix(); lightViewportWidthVar = lightShader.GetVariableByName("ViewportWidth").AsScalar(); lightViewportHeightVar = lightShader.GetVariableByName("ViewportHeight").AsScalar(); lightEyePositionVar = lightShader.GetVariableByName("EyePosition").AsVector(); lightViewParametersVar = lightShader.GetVariableByName("ViewParameters").AsVector(); InputElement[] elements = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), }; lightVolumeInputLayout = new InputLayout(Device, lightShader.GetTechniqueByIndex(0).GetPassByName("Light").Description.Signature, elements); pointLightVolumeVertices = Light.CreatePointLightVolume(out pointLightVolumeIndices); BufferDescription vertexBufferDesc = new BufferDescription() { SizeInBytes = Vector3.SizeInBytes * pointLightVolumeVertices.Length, Usage = ResourceUsage.Default, BindFlags = BindFlags.VertexBuffer, }; using (var data = new SharpDX.DataStream(vertexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(pointLightVolumeVertices); data.Position = 0; pointLightVolumeVertexBuffer = new Buffer(Device, data, vertexBufferDesc); } pointLightVolumeVertexBufferBinding = new VertexBufferBinding(pointLightVolumeVertexBuffer, 12, 0); BufferDescription indexBufferDesc = new BufferDescription() { SizeInBytes = sizeof(uint) * pointLightVolumeIndices.Length, Usage = ResourceUsage.Default, BindFlags = BindFlags.IndexBuffer }; using (var data = new SharpDX.DataStream(indexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(pointLightVolumeIndices); data.Position = 0; pointLightVolumeIndexBuffer = new Buffer(Device, data, indexBufferDesc); } lightDepthBufferVar = lightShader.GetVariableByName("depthBuffer").AsShaderResource(); lightNormalBufferVar = lightShader.GetVariableByName("normalBuffer").AsShaderResource(); lights.Add(new Light(pointLightPosition, 60, new Vector4(1, 0.95f, 0.9f, 1))); //lights.Add(new Light(pointLightPosition, 60, new Vector4(0, 0, 1, 1))); //lights.Add(new Light(new Vector3(-10, 10, 10), 30, new Vector4(1, 0, 0, 1))); //lights.Add(new Light(new Vector3(10, 5, -10), 20, new Vector4(0, 1, 0, 1))); //lights.Add(new Light(new Vector3(-10, 5, -10), 20, new Vector4(1, 0, 1, 1))); Info = new InfoText(_device, 256, 256); _meshFactory = new MeshFactory(this); CreateBuffers(); }
private void Init() { _ColorMap0Var = GetVariableByName("g_ColorMap0").AsShaderResource(); _SpecularMap0Var = GetVariableByName("g_SpecularMap0").AsShaderResource(); _NormalMap0Var = GetVariableByName("g_NormalMap0").AsShaderResource(); _EnvironmentMap = GetVariableByName("g_EnvMap").AsShaderResource(); }