/// <summary> /// Initializes a new instance of the <see cref="PhongMaterialVariables"/> class. /// </summary> /// <param name="manager">The manager.</param> /// <param name="technique">The technique.</param> /// <param name="materialCore">The material core.</param> /// <param name="materialPassName">Name of the material pass.</param> /// <param name="wireframePassName">Name of the wireframe pass.</param> /// <param name="materialOITPassName">Name of the material oit pass.</param> /// <param name="wireframeOITPassName">Name of the wireframe oit pass.</param> /// <param name="shadowPassName">Name of the shadow pass.</param> /// <param name="tessellationPassName">Name of the tessellation pass.</param> /// <param name="tessellationOITPassName">Name of the tessellation oit pass.</param> /// <param name="depthPassName">Name of the depth pass</param> public PhongMaterialVariables(IEffectsManager manager, IRenderTechnique technique, PhongMaterialCore materialCore, string materialPassName = DefaultPassNames.Default, string wireframePassName = DefaultPassNames.Wireframe, string materialOITPassName = DefaultPassNames.OITPass, string wireframeOITPassName = DefaultPassNames.WireframeOITPass, string shadowPassName = DefaultPassNames.ShadowPass, string tessellationPassName = DefaultPassNames.MeshTriTessellation, string tessellationOITPassName = DefaultPassNames.MeshTriTessellationOIT, string depthPassName = DefaultPassNames.DepthPrepass) : base(manager, technique, DefaultMeshConstantBufferDesc, materialCore) { this.material = materialCore; texDiffuseSlot = texAlphaSlot = texDisplaceSlot = texNormalSlot = -1; samplerDiffuseSlot = samplerDisplaceSlot = samplerShadowSlot = -1; textureManager = manager.MaterialTextureManager; statePoolManager = manager.StateManager; MaterialPass = technique[materialPassName]; MaterialOITPass = technique[materialOITPassName]; ShadowPass = technique[shadowPassName]; WireframePass = technique[wireframePassName]; WireframeOITPass = technique[wireframeOITPassName]; TessellationPass = technique[tessellationPassName]; TessellationOITPass = technique[tessellationOITPassName]; DepthPass = technique[depthPassName]; UpdateMappings(MaterialPass); EnableTessellation = materialCore.EnableTessellation; currentMaterialPass = EnableTessellation ? TessellationPass : MaterialPass; currentOITPass = EnableTessellation ? TessellationOITPass : MaterialOITPass; }
/// <summary> /// /// </summary> /// <param name="technique"></param> /// <returns></returns> protected override bool OnAttach(IRenderTechnique technique) { DefaultShaderPass = technique[DefaultShaderPassName]; ShadowPass = technique[DefaultShadowPassName]; CreateRasterState(rasterDescription, true); return(true); }
private void UpdateMappings(ShaderPass shaderPass) { if (currentPass == shaderPass) { return; } currentPass = shaderPass; for (int i = 0; i < shaderPass.Shaders.Count; ++i) { var shader = shaderPass.Shaders[i]; if (shader.IsNULL || !EnumHelper.HasFlag(Constants.CanBindTextureStages, shader.ShaderType)) { continue; } int idx = shaderPass.Shaders[i].ShaderType.ToIndex(); TextureBindingMap[idx][DiffuseIdx] = shader.ShaderResourceViewMapping.TryGetBindSlot(ShaderDiffuseTexName); TextureBindingMap[idx][AlphaIdx] = shader.ShaderResourceViewMapping.TryGetBindSlot(ShaderAlphaTexName); TextureBindingMap[idx][NormalIdx] = shader.ShaderResourceViewMapping.TryGetBindSlot(ShaderNormalTexName); TextureBindingMap[idx][DisplaceIdx] = shader.ShaderResourceViewMapping.TryGetBindSlot(ShaderDisplaceTexName); SamplerBindingMap[idx][DiffuseIdx] = shader.SamplerMapping.TryGetBindSlot(ShaderSamplerDiffuseTexName); SamplerBindingMap[idx][AlphaIdx] = shader.SamplerMapping.TryGetBindSlot(ShaderSamplerAlphaTexName); SamplerBindingMap[idx][NormalIdx] = shader.SamplerMapping.TryGetBindSlot(ShaderSamplerNormalTexName); SamplerBindingMap[idx][DisplaceIdx] = shader.SamplerMapping.TryGetBindSlot(ShaderSamplerDisplaceTexName); SamplerBindingMap[idx][ShadowIdx] = shader.SamplerMapping.TryGetBindSlot(ShaderSamplerShadowMapName); } }
public override void Render(RenderContext context, DeviceContextProxy deviceContext) { if (!materialVariables.UpdateMaterialStruct(deviceContext, ref ModelMatrix, Matrix.SizeInBytes)) { return; } int slot = 0; buffer.AttachBuffers(deviceContext, ref slot, EffectTechnique.EffectsManager); cubeBackPass.BindShader(deviceContext); cubeBackPass.BindStates(deviceContext, StateType.All); var back = context.RenderHost.RenderBuffer.FullResRenderTargetPool.Get(global::SharpDX.DXGI.Format.R16G16B16A16_Float); BindTarget(null, back, deviceContext, (int)context.ActualWidth, (int)context.ActualHeight); deviceContext.DrawIndexed(buffer.IndexBuffer.ElementCount, 0, 0); context.RenderHost.SetDefaultRenderTargets(false); var pass = materialVariables.GetPass(RenderType.Opaque, context); if (pass != volumePass) { volumePass = pass; backTexSlot = volumePass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.VolumeBack); } materialVariables.BindMaterialResources(context, deviceContext, pass); volumePass.PixelShader.BindTexture(deviceContext, backTexSlot, back); volumePass.BindShader(deviceContext); volumePass.BindStates(deviceContext, StateType.All); deviceContext.DrawIndexed(buffer.IndexBuffer.ElementCount, 0, 0); volumePass.PixelShader.BindTexture(deviceContext, backTexSlot, null); context.RenderHost.RenderBuffer.FullResRenderTargetPool.Put(global::SharpDX.DXGI.Format.R16G16B16A16_Float, back); }
/// <summary> /// <see cref="IEffectMaterialVariables.BindMaterialTextures(DeviceContext, ShaderPass)"/> /// </summary> /// <param name="context"></param> /// <param name="shaderPass"></param> /// <returns></returns> public bool BindMaterialTextures(DeviceContext context, ShaderPass shaderPass) { if (material == null) { return(false); } UpdateMappings(shaderPass); if (HasTextures) { for (int i = 0; i < shaderPass.Shaders.Count; ++i) { var shader = shaderPass.Shaders[i]; if (shader.IsNULL || !EnumHelper.HasFlag(Constants.CanBindTextureStages, shader.ShaderType)) { continue; } OnBindMaterialTextures(context, shader); } } if (RenderShadowMap) { shaderPass.GetShader(ShaderStage.Pixel).BindSampler(context, SamplerBindingMap[ShaderStage.Pixel.ToIndex()][NUMSAMPLERS - 1], SamplerResources[NUMSAMPLERS - 1]); } return(true); }
protected override void OnRender(RenderContext context, DeviceContextProxy deviceContext) { ShaderPass pass = MaterialVariables.GetPass(this, context); if (pass.IsNULL) { return; } pass.BindShader(deviceContext); pass.BindStates(deviceContext, DefaultStateBinding); if (!BindMaterialTextures(deviceContext, pass)) { return; } if (context.RenderHost.IsShadowMapEnabled) { pass.PixelShader.BindTexture(deviceContext, shadowMapSlot, context.SharedResource.ShadowView); } DynamicReflector?.BindCubeMap(deviceContext); OnDraw(deviceContext, InstanceBuffer); DynamicReflector?.UnBindCubeMap(deviceContext); if (RenderWireframe && WireframePass != ShaderPass.NullPass) { if (RenderType == RenderType.Transparent && context.IsOITPass) { pass = WireframeOITPass; } else { pass = WireframePass; } pass.BindShader(deviceContext, false); pass.BindStates(deviceContext, DefaultStateBinding); deviceContext.SetRasterState(RasterStateWireframe); OnDraw(deviceContext, InstanceBuffer); } }
/// <summary> /// Called when [attach]. /// </summary> /// <param name="technique">The technique.</param> /// <returns></returns> protected override bool OnAttach(IRenderTechnique technique) { if (base.OnAttach(technique)) { VertexLayout = technique.Layout; updatePass = technique[DefaultParticlePassNames.Update]; insertPass = technique[DefaultParticlePassNames.Insert]; renderPass = technique[DefaultParticlePassNames.Default]; #region Get binding slots currentStateSlot = updatePass.GetShader(ShaderStage.Compute).UnorderedAccessViewMapping.TryGetBindSlot(CurrentSimStateUAVBufferName); newStateSlot = updatePass.GetShader(ShaderStage.Compute).UnorderedAccessViewMapping.TryGetBindSlot(NewSimStateUAVBufferName); renderStateSlot = renderPass.GetShader(ShaderStage.Vertex).ShaderResourceViewMapping.TryGetBindSlot(SimStateBufferName); textureSlot = renderPass.GetShader(ShaderStage.Pixel).ShaderResourceViewMapping.TryGetBindSlot(ShaderTextureBufferName); samplerSlot = renderPass.GetShader(ShaderStage.Pixel).SamplerMapping.TryGetBindSlot(ShaderTextureSamplerName); #endregion perFrameCB = technique.ConstantBufferPool.Register(DefaultBufferNames.ParticleFrameCB, ParticlePerFrame.SizeInBytes); insertCB = technique.ConstantBufferPool.Register(DefaultBufferNames.ParticleCreateParameters, ParticleInsertParameters.SizeInBytes); if (isInitialParticleChanged) { OnInitialParticleChanged(ParticleCount); } textureSampler = Collect(technique.EffectsManager.StateManager.Register(SamplerDescription)); OnTextureChanged(); OnBlendStateChanged(); return(true); } else { return(false); } }
private void UpdateMappings(ShaderPass shaderPass) { texDiffuseSlot = shaderPass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.DiffuseMapTB); texEmissiveSlot = shaderPass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.EmissiveTB); texNormalSlot = shaderPass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.NormalMapTB); texRMSlot = shaderPass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.RMMapTB); texAOSlot = shaderPass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.AOMapTB); texShadowSlot = shaderPass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.ShadowMapTB); texIrradianceSlot = shaderPass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.IrradianceMap); texSSAOSlot = shaderPass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.SSAOMapTB); texEnvironmentSlot = shaderPass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.CubeMapTB); samplerSurfaceSlot = shaderPass.PixelShader.SamplerMapping.TryGetBindSlot(DefaultSamplerStateNames.SurfaceSampler); samplerIBLSlot = shaderPass.PixelShader.SamplerMapping.TryGetBindSlot(DefaultSamplerStateNames.IBLSampler); samplerShadowSlot = shaderPass.PixelShader.SamplerMapping.TryGetBindSlot(DefaultSamplerStateNames.ShadowMapSampler); if (!shaderPass.DomainShader.IsNULL && material.EnableTessellation) { texDisplaceSlot = shaderPass.DomainShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.DisplacementMapTB); samplerDisplaceSlot = shaderPass.DomainShader.SamplerMapping.TryGetBindSlot(DefaultSamplerStateNames.DisplacementMapSampler); } else { texDisplaceSlot = shaderPass.VertexShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.DisplacementMapTB); samplerDisplaceSlot = shaderPass.VertexShader.SamplerMapping.TryGetBindSlot(DefaultSamplerStateNames.DisplacementMapSampler); } }
internal ShaderPassCollection(DeviceContext context, Shader shader, ShaderTechnique technique) { _passes = new ShaderPass[technique.PassCount]; for (int i = 0; i < _passes.Length; i++) _passes[i] = new ShaderPass(context, shader, shader.Effect.GetPass(technique.Handle, i), i); }
protected override void OnRender(RenderContext context, DeviceContextProxy deviceContext) { ShaderPass pass = MaterialVariables.GetPass(RenderType, context); if (pass.IsNULL) { return; } MaterialVariables.UpdateMaterialStruct(deviceContext, ref modelStruct); pass.BindShader(deviceContext); pass.BindStates(deviceContext, DefaultStateBinding); if (!materialVariables.BindMaterial(context, deviceContext, pass)) { return; } DynamicReflector?.BindCubeMap(deviceContext); DrawIndexed(deviceContext, GeometryBuffer.IndexBuffer, InstanceBuffer); DynamicReflector?.UnBindCubeMap(deviceContext); if (RenderWireframe && !WireframePass.IsNULL) { if (RenderType == RenderType.Transparent && context.IsOITPass) { pass = WireframeOITPass; } else { pass = WireframePass; } pass.BindShader(deviceContext, false); pass.BindStates(deviceContext, DefaultStateBinding); deviceContext.SetRasterState(RasterStateWireframe); DrawIndexed(deviceContext, GeometryBuffer.IndexBuffer, InstanceBuffer); } }
public GenericMaterialVariable(IEffectsManager manager, IRenderTechnique technique, GenericMaterialCore materialCore, ConstantBufferDescription constantBufferDescription, string materialShaderPassName = DefaultPassNames.Default, string shadowShaderPassName = DefaultPassNames.ShadowPass, string wireframePassName = DefaultPassNames.Wireframe, string depthPassName = DefaultPassNames.DepthPrepass) : base(manager, technique, constantBufferDescription, materialCore) { this.materialCore = materialCore; materialPass = technique[materialShaderPassName]; shadowPass = technique[shadowShaderPassName]; wireframePass = technique[wireframePassName]; depthPass = technique[depthPassName]; shaderResources = new KeyValuePair <int, ShaderResourceViewProxy> [materialPass.PixelShader.ShaderResourceViewMapping.Count]; for (var i = 0; i < materialPass.PixelShader.ShaderResourceViewMapping.Count; ++i) { var mapping = materialPass.PixelShader.ShaderResourceViewMapping.Mappings[i]; resourceIdxDict.Add(mapping.Value.Description.Name, i); shaderResources[i] = new KeyValuePair <int, ShaderResourceViewProxy>(mapping.Key, null); } samplerResources = new KeyValuePair <int, SamplerStateProxy> [materialPass.PixelShader.SamplerMapping.Count]; for (var i = 0; i < materialPass.PixelShader.SamplerMapping.Count; ++i) { var mapping = materialPass.PixelShader.SamplerMapping.Mappings[i]; samplerIdxDict.Add(mapping.Value.Name, i); samplerResources[i] = new KeyValuePair <int, SamplerStateProxy>(mapping.Key, null); } materialCore.UpdatingResource += MaterialCore_UpdatingResource; }
protected override bool OnAttach(IRenderTechnique technique) { DefaultShaderPass = technique[DefaultPassNames.Default]; samplerSlot = DefaultShaderPass.PixelShader.SamplerMapping.TryGetBindSlot(DefaultSamplerStateNames.ShadowMapSampler); shadowMapSlot = DefaultShaderPass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.ShadowMapTB); shadowSampler = Collect(technique.EffectsManager.StateManager.Register(DefaultSamplers.ShadowSampler)); return(true); }
/// <summary> /// Initializes a new instance of the <see cref="PassOnlyMaterialVariable"/> class. /// </summary> /// <param name="passName">Name of the pass.</param> /// <param name="technique">The technique.</param> /// <param name="shadowPassName">Name of the shadow pass.</param> /// <param name="wireframePassName">Name of the wireframe pass.</param> public PassOnlyMaterialVariable(string passName, IRenderTechnique technique, string shadowPassName = DefaultPassNames.ShadowPass, string wireframePassName = DefaultPassNames.Wireframe) : base(technique.EffectsManager, technique, DefaultMeshConstantBufferDesc, null) { this.passName = passName; MaterialPass = technique[passName]; ShadowPass = technique[shadowPassName]; WireframePass = technique[wireframePassName]; }
protected override bool OnAttach(IRenderTechnique technique) { buffer = Collect(new VolumeCubeBufferModel()); buffer.Geometry = BoxMesh; buffer.Topology = PrimitiveTopology.TriangleList; cubeBackPass = technique[DefaultPassNames.Backface]; return(true); }
protected override bool OnAttach(IRenderTechnique technique) { spritePass = technique[DefaultPassNames.Default]; texSlot = spritePass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.SpriteTB); samplerSlot = spritePass.PixelShader.SamplerMapping.TryGetBindSlot(DefaultSamplerStateNames.SpriteSampler); sampler = Collect(EffectTechnique.EffectsManager.StateManager.Register(DefaultSamplers.PointSamplerWrap)); return(true); }
/// <summary> /// Initializes a new instance of the <see cref="LineMaterialVariable"/> class. /// </summary> /// <param name="manager">The manager.</param> /// <param name="technique">The technique.</param> /// <param name="materialCore">The material core.</param> /// <param name="linePassName">Name of the line pass.</param> /// <param name="shadowPassName">Name of the shadow pass.</param> public LineMaterialVariable(IEffectsManager manager, IRenderTechnique technique, LineMaterialCore materialCore, string linePassName = DefaultPassNames.Default, string shadowPassName = DefaultPassNames.ShadowPass) : base(manager, technique, DefaultPointLineConstantBufferDesc, materialCore) { LinePass = technique[linePassName]; ShadowPass = technique[shadowPassName]; this.material = materialCore; }
ActiveFields GetActiveFieldsFromMasterNode(ToonMasterNode masterNode, ShaderPass pass) { var activeFields = new ActiveFields(); var baseActiveFields = activeFields.baseInstance; // Graph Vertex if (masterNode.IsSlotConnected(ToonMasterNode.PositionSlotId) || masterNode.IsSlotConnected(ToonMasterNode.VertNormalSlotId) || masterNode.IsSlotConnected(ToonMasterNode.VertTangentSlotId) || masterNode.IsSlotConnected(ToonMasterNode.OutlineWidthSlotId) ) { baseActiveFields.Add("features.graphVertex"); } // Graph Pixel (always enabled) baseActiveFields.Add("features.graphPixel"); if (masterNode.IsSlotConnected(ToonMasterNode.AlphaThresholdSlotId) || masterNode.GetInputSlots <Vector1MaterialSlot> ().First(x => x.id == ToonMasterNode.AlphaThresholdSlotId).value > 0.0f) { baseActiveFields.Add("AlphaClip"); } if (masterNode.model == ToonMasterNode.Model.Specular) { baseActiveFields.Add("SpecularSetup"); } if (masterNode.IsSlotConnected(ToonMasterNode.NormalSlotId)) { baseActiveFields.Add("Normal"); } // Keywords for transparent // #pragma shader_feature _SURFACE_TYPE_TRANSPARENT if (masterNode.surfaceType != SurfaceType.Opaque) { // transparent-only defines baseActiveFields.Add("SurfaceType.Transparent"); // #pragma shader_feature _ _BLENDMODE_ALPHA _BLENDMODE_ADD _BLENDMODE_PRE_MULTIPLY if (masterNode.alphaMode == AlphaMode.Alpha) { baseActiveFields.Add("BlendMode.Alpha"); } else if (masterNode.alphaMode == AlphaMode.Additive) { baseActiveFields.Add("BlendMode.Add"); } else if (masterNode.alphaMode == AlphaMode.Premultiply) { baseActiveFields.Add("BlendMode.Premultiply"); } } return(activeFields); }
protected override bool OnAttach(IRenderTechnique technique) { FXAAPass = technique[DefaultPassNames.FXAAPass]; LUMAPass = technique[DefaultPassNames.LumaPass]; textureSlot = FXAAPass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.DiffuseMapTB); samplerSlot = FXAAPass.PixelShader.SamplerMapping.TryGetBindSlot(DefaultSamplerStateNames.SurfaceSampler); sampler = Collect(technique.EffectsManager.StateManager.Register(DefaultSamplers.LinearSamplerClampAni1)); return(true); }
/// <summary> /// Initializes a new instance of the <see cref="PointMaterialVariable"/> class. /// </summary> /// <param name="manager">The manager.</param> /// <param name="technique">The technique.</param> /// <param name="materialCore">The material core.</param> /// <param name="defaultPassName">Default pass name</param> public PointMaterialVariable(IEffectsManager manager, IRenderTechnique technique, PointMaterialCore materialCore, string defaultPassName = DefaultPassNames.Default) : base(manager, technique, DefaultPointLineConstantBufferDesc, materialCore) { PointPass = technique[defaultPassName]; ShadowPass = technique[DefaultPassNames.ShadowPass]; DepthPass = technique[DefaultPassNames.DepthPrepass]; this.material = materialCore; }
internal ShaderPassCollection(DeviceContext context, Shader shader, ShaderTechnique technique) { _passes = new ShaderPass[technique.PassCount]; for (int i = 0; i < _passes.Length; i++) { _passes[i] = new ShaderPass(context, shader, shader.Effect.GetPass(technique.Handle, i), i); } }
/// <summary> /// Called when [attach]. /// </summary> /// <param name="technique">The technique.</param> /// <returns></returns> protected override bool OnAttach(IRenderTechnique technique) { DefaultShaderPass = technique.EffectsManager[DefaultRenderTechniqueNames.ScreenDuplication][DefaultPassNames.Default]; CursorShaderPass = technique.EffectsManager[DefaultRenderTechniqueNames.ScreenDuplication][DefaultPassNames.ScreenQuad]; textureBindSlot = DefaultShaderPass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.DiffuseMapTB); samplerBindSlot = DefaultShaderPass.PixelShader.SamplerMapping.TryGetBindSlot(DefaultSamplerStateNames.SurfaceSampler); textureSampler = technique.EffectsManager.StateManager.Register(DefaultSamplers.ScreenDupSampler); return(Initialize(technique.EffectsManager)); }
private static bool GenerateShaderPass(CustomMasterNode masterNode, ShaderPass pass, GenerationMode mode, ShaderGenerator result, List <string> sourceAssetDependencyPaths) { // UniversalShaderGraphUtilities.SetRenderState(masterNode.SurfaceType, masterNode.AlphaMode, masterNode.TwoSided.isOn, ref pass); var activeFields = GetActiveFieldsFromMasterNode(masterNode, pass); return(ShaderGraph.GenerationUtils.GenerateShaderPass(masterNode, pass, mode, activeFields, result, sourceAssetDependencyPaths, UniversalShaderGraphResources.s_Dependencies, UniversalShaderGraphResources.s_ResourceClassName, UniversalShaderGraphResources.s_AssemblyName)); }
protected override bool OnAttach(IRenderTechnique technique) { pass = technique[passName]; textureSlot = pass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.DiffuseMapTB); samplerSlot = pass.PixelShader.SamplerMapping.TryGetBindSlot(DefaultSamplerStateNames.SurfaceSampler); UpdateTexture(texture); UpdateSampler(); return(true); }
public override void GeneratePasses(ShaderGenerationContext context, out ShaderPass mainPass, out List <ShaderPass> additionalPasses) { mainPass = new ShaderPassLitForward(); additionalPasses = new List <ShaderPass>() { new ShaderPassShadow(), new ShaderPassDepthOnly(), new ShaderPassLitMeta(), }; }
protected override bool OnAttach(IRenderTechnique technique) { screenQuadPass = technique[DefaultPassNames.Default]; colorTexIndex = screenQuadPass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.OITColorTB); alphaTexIndex = screenQuadPass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.OITAlphaTB); samplerIndex = screenQuadPass.PixelShader.SamplerMapping.TryGetBindSlot(DefaultSamplerStateNames.SurfaceSampler); targetSampler = technique.EffectsManager.StateManager.Register(DefaultSamplers.LinearSamplerWrapAni1); RenderCount = 0; return(true); }
public VolumeMaterialVariable(IEffectsManager manager, IRenderTechnique technique, VolumeTextureMaterialCoreBase <T> material, string volumePassName = DefaultPassNames.Default) : base(manager, technique, DefaultVolumeConstantBufferDesc, material) { this.material = material; volumePass = technique[volumePassName]; texSlot = volumePass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.VolumeTB); gradientSlot = volumePass.PixelShader.ShaderResourceViewMapping.TryGetBindSlot(DefaultBufferNames.ColorStripe1DXTB); samplerSlot = volumePass.PixelShader.SamplerMapping.TryGetBindSlot(DefaultSamplerStateNames.VolumeSampler); }
bool GenerateShaderPass(ToonMasterNode masterNode, ShaderPass pass, GenerationMode mode, ShaderGenerator result, List <string> sourceAssetDependencyPaths) { UniversalShaderGraphUtilities.SetRenderState(masterNode.surfaceType, masterNode.alphaMode, masterNode.twoSided.isOn, ref pass); // apply master node options to active fields var activeFields = GetActiveFieldsFromMasterNode(masterNode, pass); return(ShaderGraph.GenerationUtils.GenerateShaderPass(masterNode, pass, mode, activeFields, result, sourceAssetDependencyPaths, UniversalShaderGraphResources.s_Dependencies, UniversalShaderGraphResources.s_ResourceClassName, UniversalShaderGraphResources.s_AssemblyName)); }
void Start() { radiusDelta = radius; meshFilter = GetComponentInChildren <MeshFilter>(); shaderPass = GetComponentInChildren <ShaderPass>(); // shaderPass.Print(colorTexture as Texture2D); positionTexture = new Texture2D(width, height, TextureFormat.RGBAFloat, false); BakeBackground(); BakePosition(); }
/// <summary> /// Initializes a new instance of the <see cref="PostEffectMeshOutlineBlurCore"/> class. /// </summary> public PostEffectBlurCore(ShaderPass blurVerticalPass, ShaderPass blurHorizontalPass, int textureSlot, int samplerSlot, SamplerStateDescription sampler, IEffectsManager manager) { screenBlurPassVertical = blurVerticalPass; screenBlurPassHorizontal = blurHorizontalPass; this.textureSlot = textureSlot; this.samplerSlot = samplerSlot; this.sampler = manager.StateManager.Register(sampler); modelCB = new ConstantBufferComponent(new ConstantBufferDescription(DefaultBufferNames.BorderEffectCB, BorderEffectStruct.SizeInBytes)); }
protected override void OnInitialPropertyBindings() { AddPropertyBinding(nameof(PBRMaterialCore.AlbedoColor), () => { WriteValue(PhongPBRMaterialStruct.DiffuseStr, material.AlbedoColor); }); AddPropertyBinding(nameof(PBRMaterialCore.EmissiveColor), () => { WriteValue(PhongPBRMaterialStruct.EmissiveStr, material.EmissiveColor); }); AddPropertyBinding(nameof(PBRMaterialCore.MetallicFactor), () => { WriteValue(PhongPBRMaterialStruct.ConstantMetallic, material.MetallicFactor); }); AddPropertyBinding(nameof(PBRMaterialCore.RoughnessFactor), () => { WriteValue(PhongPBRMaterialStruct.RoughnessStr, material.RoughnessFactor); }); AddPropertyBinding(nameof(PBRMaterialCore.AmbientOcclusionFactor), () => { WriteValue(PhongPBRMaterialStruct.AmbientOcclusionStr, material.AmbientOcclusionFactor); }); AddPropertyBinding(nameof(PBRMaterialCore.ReflectanceFactor), () => { WriteValue(PhongPBRMaterialStruct.ReflectanceStr, material.ReflectanceFactor); }); AddPropertyBinding(nameof(PBRMaterialCore.ClearCoatStrength), () => { WriteValue(PhongPBRMaterialStruct.ClearCoatStr, material.ClearCoatStrength); }); AddPropertyBinding(nameof(PBRMaterialCore.ClearCoatRoughness), () => { WriteValue(PhongPBRMaterialStruct.ClearCoatRoughnessStr, material.ClearCoatRoughness); }); AddPropertyBinding(nameof(PBRMaterialCore.RenderAlbedoMap), () => { WriteValue(PhongPBRMaterialStruct.HasDiffuseMapStr, material.RenderAlbedoMap && TextureResources[AlbedoMapIdx] != null ? 1 : 0); }); AddPropertyBinding(nameof(PBRMaterialCore.RenderEmissiveMap), () => { WriteValue(PhongPBRMaterialStruct.HasEmissiveMapStr, material.RenderEmissiveMap && TextureResources[EmissiveMapIdx] != null ? 1 : 0); }); AddPropertyBinding(nameof(PBRMaterialCore.RenderNormalMap), () => { WriteValue(PhongPBRMaterialStruct.HasNormalMapStr, material.RenderNormalMap && TextureResources[NormalMapIdx] != null ? 1 : 0); }); AddPropertyBinding(nameof(PBRMaterialCore.RenderDisplacementMap), () => { WriteValue(PhongPBRMaterialStruct.HasDisplacementMapStr, material.RenderDisplacementMap && TextureResources[DisplaceMapIdx] != null ? 1 : 0); }); AddPropertyBinding(nameof(PBRMaterialCore.RenderIrradianceMap), () => { WriteValue(PhongPBRMaterialStruct.HasIrradianceMapStr, material.RenderIrradianceMap && TextureResources[IrradianceMapIdx] != null ? 1 : 0); }); AddPropertyBinding(nameof(PBRMaterialCore.RenderRoughnessMetallicMap), () => { WriteValue(PhongPBRMaterialStruct.HasRMMapStr, material.RenderRoughnessMetallicMap && TextureResources[RMMapIdx] != null ? 1 : 0); }); AddPropertyBinding(nameof(PBRMaterialCore.RenderAmbientOcclusionMap), () => { WriteValue(PhongPBRMaterialStruct.HasAOMapStr, material.RenderAmbientOcclusionMap && TextureResources[AOMapIdx] != null ? 1 : 0); }); AddPropertyBinding(nameof(PBRMaterialCore.EnableAutoTangent), () => { WriteValue(PhongPBRMaterialStruct.EnableAutoTangent, material.EnableAutoTangent); }); AddPropertyBinding(nameof(PBRMaterialCore.DisplacementMapScaleMask), () => { WriteValue(PhongPBRMaterialStruct.DisplacementMapScaleMaskStr, material.DisplacementMapScaleMask); }); AddPropertyBinding(nameof(PBRMaterialCore.RenderShadowMap), () => { WriteValue(PhongPBRMaterialStruct.RenderShadowMapStr, material.RenderShadowMap ? 1 : 0); }); AddPropertyBinding(nameof(PBRMaterialCore.RenderEnvironmentMap), () => { WriteValue(PhongPBRMaterialStruct.HasCubeMapStr, material.RenderEnvironmentMap ? 1 : 0); }); AddPropertyBinding(nameof(PBRMaterialCore.MaxTessellationDistance), () => { WriteValue(PhongPBRMaterialStruct.MaxTessDistanceStr, material.MaxTessellationDistance); }); AddPropertyBinding(nameof(PBRMaterialCore.MinTessellationDistance), () => { WriteValue(PhongPBRMaterialStruct.MinTessDistanceStr, material.MinTessellationDistance); }); AddPropertyBinding(nameof(PBRMaterialCore.MaxDistanceTessellationFactor), () => { WriteValue(PhongPBRMaterialStruct.MaxDistTessFactorStr, material.MaxDistanceTessellationFactor); }); AddPropertyBinding(nameof(PBRMaterialCore.MinDistanceTessellationFactor), () => { WriteValue(PhongPBRMaterialStruct.MinDistTessFactorStr, material.MinDistanceTessellationFactor); }); AddPropertyBinding(nameof(PBRMaterialCore.UVTransform), () => { Matrix m = material.UVTransform; WriteValue(PhongPBRMaterialStruct.UVTransformR1Str, m.Column1); WriteValue(PhongPBRMaterialStruct.UVTransformR2Str, m.Column2); }); AddPropertyBinding(nameof(PBRMaterialCore.AlbedoMap), () => { CreateTextureView(material.AlbedoMap, AlbedoMapIdx); TriggerPropertyAction(nameof(PBRMaterialCore.RenderAlbedoMap)); }); AddPropertyBinding(nameof(PBRMaterialCore.EmissiveMap), () => { CreateTextureView(material.EmissiveMap, EmissiveMapIdx); TriggerPropertyAction(nameof(PBRMaterialCore.RenderEmissiveMap)); }); AddPropertyBinding(nameof(PBRMaterialCore.NormalMap), () => { CreateTextureView(material.NormalMap, NormalMapIdx); TriggerPropertyAction(nameof(PBRMaterialCore.RenderNormalMap)); }); AddPropertyBinding(nameof(PBRMaterialCore.IrradianceMap), () => { CreateTextureView(material.IrradianceMap, IrradianceMapIdx); TriggerPropertyAction(nameof(PBRMaterialCore.RenderIrradianceMap)); }); AddPropertyBinding(nameof(PBRMaterialCore.DisplacementMap), () => { CreateTextureView(material.DisplacementMap, DisplaceMapIdx); TriggerPropertyAction(nameof(PBRMaterialCore.RenderDisplacementMap)); }); AddPropertyBinding(nameof(PBRMaterialCore.RoughnessMetallicMap), () => { CreateTextureView(material.RoughnessMetallicMap, RMMapIdx); TriggerPropertyAction(nameof(PBRMaterialCore.RenderRoughnessMetallicMap)); }); AddPropertyBinding(nameof(PBRMaterialCore.AmbientOcculsionMap), () => { CreateTextureView(material.AmbientOcculsionMap, AOMapIdx); TriggerPropertyAction(nameof(PBRMaterialCore.RenderAmbientOcclusionMap)); }); AddPropertyBinding(nameof(PBRMaterialCore.SurfaceMapSampler), () => { CreateSampler(material.SurfaceMapSampler, SurfaceSamplerIdx); }); AddPropertyBinding(nameof(PBRMaterialCore.IBLSampler), () => { CreateSampler(material.IBLSampler, IBLSamplerIdx); }); AddPropertyBinding(nameof(PBRMaterialCore.DisplacementMapSampler), () => { CreateSampler(material.DisplacementMapSampler, DisplaceSamplerIdx); }); AddPropertyBinding(nameof(PBRMaterialCore.EnableTessellation), () => { currentMaterialPass = material.EnableTessellation ? TessMaterialPass : MaterialPass; UpdateMappings(MaterialPass); currentMaterialOITPass = material.EnableTessellation ? TessMaterialOITPass : MaterialOITPass; }); WriteValue(PhongPBRMaterialStruct.RenderPBR, true); // Make sure to set this flag AddPropertyBinding(nameof(PBRMaterialCore.EnableFlatShading), () => { WriteValue(PhongPBRMaterialStruct.RenderFlat, material.EnableFlatShading); }); AddPropertyBinding(nameof(PBRMaterialCore.VertexColorBlendingFactor), () => { WriteValue(PhongPBRMaterialStruct.VertColorBlending, material.VertexColorBlendingFactor); }); }
private static bool GenerateShaderPass(SpriteLitMasterNode masterNode, ShaderPass pass, GenerationMode mode, ShaderGenerator result, List <string> sourceAssetDependencyPaths) { UniversalShaderGraphUtilities.SetRenderState(SurfaceType.Transparent, AlphaMode.Alpha, true, ref pass); // apply master node options to active fields var activeFields = GetActiveFieldsFromMasterNode(masterNode, pass); // use standard shader pass generation return(ShaderGraph.GenerationUtils.GenerateShaderPass(masterNode, pass, mode, activeFields, result, sourceAssetDependencyPaths, UniversalShaderGraphResources.s_Dependencies, UniversalShaderGraphResources.s_ResourceClassName, UniversalShaderGraphResources.s_AssemblyName)); }
public string GCLighting(ShaderGenerate SG,ShaderPass SP){ string shaderCode = ""; string TempStr1; string TempStr2; string NormalizeNormals = ""; //if (SG.UsedWorldNormals==false) //NormalizeNormals=" s.Normal = normalize(s.Normal);\n"; string DiffusePart = ""; string SpecularPart = ""; string CustomPartD = ""; string CustomPartS = ""; string CustomPartA = ""; string CustomPart = ""; string Multiplier = ""; ShaderLayersLightingAll.CodeName="123ASD$#%"; ShaderLayersLightingAll.NameUnique.Text="LightingAllDiffuse"; ShaderLayersLightingAll.EndTag.Text="rgba"; ShaderLayersLightingDiffuse.CodeName="123ASD$#%"; ShaderLayersLightingDiffuse.NameUnique.Text="LightingDiffuse"; ShaderLayersLightingDiffuse.EndTag.Text="rgba"; ShaderLayersLightingSpecular.CodeName="123ASD$#%"; ShaderLayersLightingSpecular.NameUnique.Text="LightingSpecular"; ShaderLayersLightingSpecular.EndTag.Text="rgba"; CustomPartD = GCLayers(SG,"LightingDiffuse",ShaderLayersLightingAll,"c","rgba","",false,true).Replace("123ASD$#%","c"); CustomPartD += GCLayers(SG,"LightingDiffuse",ShaderLayersLightingDiffuse,"c","rgba","",false,true).Replace("123ASD$#%","c"); if (SpecularOn.On){ //ShaderLayersLightingAll.CodeName="spec"; ShaderLayersLightingSpecular.EndTag.Text="rgb"; ShaderLayersLightingAll.EndTag.Text="rgb"; ShaderLayersLightingAll.NameUnique.Text="LightingAllSpecular"; CustomPartS = GCLayers(SG,"LightingAllSpecular",ShaderLayersLightingAll,"Spec","rgb","",false,true).Replace("123ASD$#%","Spec"); CustomPartS += GCLayers(SG,"LightingSpecular",ShaderLayersLightingSpecular,"Spec","rgb","",false,true).Replace("123ASD$#%","Spec"); if (DiffuseLightingType.Type!=5) CustomPart = CustomPartD+"\n"+CustomPartS+"\nc.rgb = c.rgb*s.Albedo+Spec;\n"; else CustomPart = CustomPartD+"\n"+CustomPartS+"\n"; } else{ if (DiffuseLightingType.Type!=5) CustomPart = CustomPartD+"\n"+CustomPartS+"\nc.rgb = c.rgb*s.Albedo;\n"; else CustomPart = CustomPartD+"\n"+CustomPartS+"\n\n"; } ShaderLayersLightingAll.NameUnique.Text="LightingDirect"; ShaderLayersLightingAmbient.EndTag.Text="rgb"; ShaderLayersLightingAmbient.CodeName="gi.indirect.diffuse"; ShaderLayersLightingAmbient.NameUnique.Text="LightingIndirect"; CustomPartA = GCLayers(SG,"LightingIndirect",ShaderLayersLightingAmbient,"gi.indirect.diffuse","rgb","",false,true).Replace("123ASD$#%","gi.indirect.diffuse"); if ((DiffuseLightingType.Type==0||DiffuseLightingType.Type==4)&&UsesShellLighting(SP)) { DiffusePart = NormalizeNormals; if (DiffuseNormals.Get()=="1") DiffusePart += " half NdotL = 1; //Disabled using normals, so just set this to 1.\n"; else if (DiffuseNormals.Get()=="0") DiffusePart += " half NdotL = max (0, dot (s.Normal, lightDir)); //Calculate the dot of the faces normal and the lights direction. This means a lower number the further the angle of the face is from the light source.\n"; else DiffusePart += " half NdotL = lerp(max (0, dot (s.Normal, lightDir)),1,"+DiffuseNormals.Get()+"); //Calculate the dot of the faces normal and the lights direction. This means a lower number the further the angle of the face is from the light source. Finally, we blend this with the default value of 1 (Due to no normals being turned up)\n"; DiffusePart += " half4 c;\n"+ " c.rgb = lightColor * atten * NdotL"+Multiplier+"; //Output the final RGB color by multiplying the surfaces color with the light color, then by the distance from the light (or some function of it), and finally by the Dot of the normal and the light direction.\n"+ " c.a = s.Alpha; //Set the output alpha to the surface Alpha.\n"; } //#ifdef UNITY_GLOBAL_ILLUMINATION_INCLUDED if ((DiffuseLightingType.Type==1)&&UsesShellLighting(SP)) { TempStr1 = DiffuseSetting1.Get(); DiffusePart=NormalizeNormals+ " \n"+ " half roughness2=("+TempStr1+"*2)*("+TempStr1+"*2);\n"+ " half2 AandB = roughness2/(roughness2 + float2(0.33,0.09));//Computing some constants\n"+ " half2 oren_nayar = float2(1, 0) + float2(-0.5, 0.45) * AandB;\n"+ " \n"+ " //Theta and phi\n"+ " half2 cos_theta = saturate(float2(dot(s.Normal,lightDir),dot(s.Normal,viewDir)));\n"+ " half2 cos_theta2 = cos_theta * cos_theta;\n"+ " half sin_theta = sqrt((1-cos_theta2.x)*(1-cos_theta2.y));\n"+ " half3 light_plane = normalize(lightDir - cos_theta.x*s.Normal);\n"+ " half3 view_plane = normalize(viewDir - cos_theta.y*s.Normal);\n"+ " half cos_phi = saturate(dot(light_plane, view_plane));\n"+ " \n"+ " //composition\n"+ " half diffuse_oren_nayar = cos_phi * sin_theta / max(cos_theta.x, cos_theta.y);\n"+ " \n"+ " half diffuse = cos_theta.x * (oren_nayar.x + oren_nayar.y * diffuse_oren_nayar);\n"+ " half4 c;\n"+ " c.rgb = lightColor.rgb*(max(0,diffuse) * atten"+Multiplier+");\n"+ " c.a = s.Alpha;\n"; } if (DiffuseLightingType.Type==2&&UsesShellLighting(SP)) { DiffusePart=NormalizeNormals+ " half4 c;\n"+ " half3 Surf1 = lightColor.rgb * (max(0,dot (s.Normal, lightDir)) * atten"+Multiplier+");//Calculate lighting the standard way (See Diffuse lighting modes comments).\n"; TempStr1 = DiffuseSetting1.Get(); TempStr2 = DiffuseSetting2.Get(); DiffusePart+=" half3 Surf2 = lightColor.rgb * (max(0,dot (-s.Normal, lightDir)* "+TempStr1+"/2.0 + "+TempStr1+"/2.0) * atten"+Multiplier+");//Calculate diffuse lighting with inverted normals while taking the Wrap Amount into consideration.\n"+ " c.rgb = Surf1+(Surf2*(0.8-abs(dot(normalize(s.Normal), normalize(lightDir))))*"+TempStr1+" * "+TempStr2+".rgb);//Combine the two lightings together, by adding the standard one with the inverted one.\n"+ //" c.rgb = 1-dot(normalize(s.Normal), normalize(lightDir));\n"+ //" c.rgb = Surf1+(Surf2*"+TempStr1+" * "+TempStr2+".rgb);\n"+ " c.a = s.Alpha;\n"; } if (DiffuseLightingType.Type==5&&UsesShellLighting(SP)) { DiffusePart=NormalizeNormals+ " half4 c;\n"+ " //Just pass the color and alpha without adding any lighting.\n"+ " c.rgb = float3(1,1,1);\n"+ " c.a = s.Alpha;\n"; } if (DiffuseLightingType.Type==3||!UsesShellLighting(SP)) { DiffusePart=NormalizeNormals+ " half4 c;\n"+ " //Just pass the color and alpha without adding any lighting.\n"+ " c.rgb = float3(1,1,1);\n"+ " c.a = s.Alpha;\n"; } if (SpecularOn.On&&UsesShellLighting(SP)) { TempStr1 = SpecularOffset.Get(); if (TempStr1=="0") TempStr1 = ""; else TempStr1 = "+float3(sin((float)"+TempStr1+"),cos((float)"+TempStr1+"),tan((float)"+TempStr1+"))"; SpecularPart=" float3 Spec;\n"; if (SpecularLightingType.Type==0) { SpecularPart+=" half3 h = normalize (lightDir + viewDir"+TempStr1+"); \n"+ " float nh = max (0, dot (s.Normal, h));\n"+ " Spec = pow (nh, s.Smoothness*128.0) * s.Specular;\n"; } if (SpecularLightingType.Type==1) { SpecularPart+=" Spec = (dot(reflect(-lightDir, s.Normal),viewDir"+TempStr1+"));\n"+ " Spec = pow(max(0.0,Spec),s.Smoothness*128.0) * s.Specular;\n"; } if (SpecularLightingType.Type==2) { SpecularPart+=" Spec = abs(dot(s.Normal,reflect(-lightDir, -viewDir"+TempStr1+")));\n"+ //"Spec = Spec;\n"+ " Spec = (half3(1.0f,1.0f,1.0f)-(pow(sqrt(Spec),2 - s.Smoothness)));\n"+ " Spec = saturate(Spec)*s.Specular;"; } SpecularPart+=" Spec = Spec * atten * 2 * lightColor.rgb;\n"; //TempStr1 = SpecularColor.Get(); //SpecularPart+=" Spec = Spec * "+TempStr1+".rgb;\n"; if (SpecularEnergy.On==true) SpecularPart+=" Spec = Spec * ((((s.Smoothness*128.0f)+9.0f)/("+(9.0f*3.14f).ToString()+"))/9.0f);\n"; //SpecularPart+=" c.rgb+=Spec;\n"; } bool U4 = false; #if PRE_UNITY_5 U4 = true; #endif if (!(GCLightingName(SP)=="CLPBR_Standard"&&U4)){ shaderCode+="//Generate simpler lighting code:\n"+ "half4 Lighting"+GCLightingName(SP)+" (CSurfaceOutput s, half3 lightDir, half3 viewDir, half atten) {\n"; shaderCode+=" half3 SSlightColor = _LightColor0.rgb;\n"; shaderCode+=" half3 lightColor = _LightColor0.rgb;\n"; shaderCode+=" half3 SSnormal = s.Normal;\n"+ " half3 SSalbedo = s.Albedo;\n"+ " half3 SSspecular = s.Specular;\n"+ " half3 SSemission = s.Emission;\n"+ " half SSalpha = s.Alpha;\n"; foreach(ShaderLayerList SLL in ShaderLayersMasks) { if (SG.UsedMasks[SLL]>0&&SLL.IsLighting.On){ shaderCode+=SLL.GCVariable(); shaderCode+=GCLayers(SG,SLL.Name.Text,SLL,SLL.CodeName,SLL.EndTag.Text,SLL.Function,false,true); } } shaderCode+=DiffusePart; shaderCode+=SpecularPart; shaderCode+=CustomPart; shaderCode += " \n"+ " return c;\n"+ "}\n"; } shaderCode+="#ifdef UNITY_GLOBAL_ILLUMINATION_INCLUDED\n"; if (!U4) shaderCode+="#include \"UnityPBSLighting.cginc\" //Include some PBS stuff.\n"; if (SG.GI&&GCLightingName(SP)!="CLUnlit"&&GCLightingName(SP)!="CLPBR_Standard"){ shaderCode+="//Generate lighting code for each GI part:\n"+ "half4 Lighting"+GCLightingName(SP)+"Light (CSurfaceOutput s, half3 viewDir, UnityLight light) {\n"; shaderCode+=" half3 SSlightColor = _LightColor0;\n"+ " half3 lightColor = _LightColor0;\n"+ " half3 lightDir = light.dir;\n"+ " half3 atten = light.color/_LightColor0;\n"+ " half3 SSnormal = s.Normal;\n"+ " half3 SSalbedo = s.Albedo;\n"+ " half3 SSspecular = s.Specular;\n"+ " half3 SSemission = s.Emission;\n"+ " half SSalpha = s.Alpha;\n"; //if (SG.Temp){ foreach(ShaderLayerList SLL in ShaderLayersMasks) { if (SG.UsedMasks[SLL]>0&&SLL.IsLighting.On){ shaderCode+=SLL.GCVariable(); shaderCode+=GCLayers(SG,SLL.Name.Text,SLL,SLL.CodeName,SLL.EndTag.Text,SLL.Function,false,true); } } shaderCode+=DiffusePart.Replace("* atten",""); shaderCode+=SpecularPart.Replace("* atten",""); shaderCode+=CustomPart.Replace("* atten",""); //} /*else{ shaderCode+=DiffusePart.Replace("* atten * 2",""); shaderCode+=SpecularPart.Replace("* atten * 2",""); }*/ shaderCode += "\n"+ " return c;\n"+ "}"; shaderCode+="\n"+ "//Generate some other Lighting code. It calls the previous lighting code a few times for different lights depending on lightmapping modes and other things.\n"+ "half4 Lighting"+GCLightingName(SP)+" (CSurfaceOutput s, half3 viewDir, UnityGI gi) {\n"+ " half4 c;\n"+ " c = Lighting"+GCLightingName(SP)+"Light(s,viewDir,gi.light);\n"+ " #if defined(DIRLIGHTMAP_SEPARATE)\n"+ " #ifdef LIGHTMAP_ON\n"+ " c += Lighting"+GCLightingName(SP)+"Light(s,viewDir,gi.light2);\n"+ " #endif\n"+ " #ifdef DYNAMICLIGHTMAP_ON\n"+ " c += Lighting"+GCLightingName(SP)+"Light(s,viewDir,gi.light3);\n"+ " #endif\n"+ " #endif\n"+ " half3 SSlightColor = _LightColor0;\n"+ " half3 lightColor = _LightColor0;\n"+ " half3 lightDir = gi.light.dir;\n"+ " half3 atten = gi.light.color/_LightColor0;\n"+ " half3 SSnormal = s.Normal;\n"+ " half3 SSalbedo = s.Albedo;\n"+ " half3 SSspecular = s.Specular;\n"+ " half3 SSemission = s.Emission;\n"+ " half SSalpha = s.Alpha;\n"; foreach(ShaderLayerList SLL in ShaderLayersMasks) { if (SG.UsedMasks[SLL]>0&&SLL.IsLighting.On){ shaderCode+=SLL.GCVariable(); shaderCode+=GCLayers(SG,SLL.Name.Text,SLL,SLL.CodeName,SLL.EndTag.Text,SLL.Function,false,true); } } //if (!SG.Temp) shaderCode += "\n"+ " #ifdef UNITY_LIGHT_FUNCTION_APPLY_INDIRECT\n"+ CustomPartA+"\n"+ " c.rgb += s.Albedo * gi.indirect.diffuse;\n"+ " #endif\n"; shaderCode+=" return c;\n"+ "}\n"+ ""; shaderCode+="\n//Some weird Unity stuff for GI calculation (I think?).\n"+ "inline void Lighting"+GCLightingName(SP)+"_GI (CSurfaceOutput s,UnityGIInput data,inout UnityGI gi){\n"; if (SpecularOn.On){ shaderCode+="#if UNITY_VERSION >= 520\n"+ " UNITY_GI(gi, s, data);\n"+ "#else\n"+ " gi = UnityGlobalIllumination (data, 1.0, s.Smoothness, s.Normal,false);\n"+ "#endif\n"; //"}\n"; //" gi = UnityGlobalIllumination (data, 1.0, s.Smoothness, s.Normal, false);"; } else{ shaderCode+="#if UNITY_VERSION >= 520\n"+ " UNITY_GI(gi, s, data);\n"+ "#else\n"+ " gi = UnityGlobalIllumination (data, 1.0, 0.0, s.Normal,false);\n"+ "#endif\n"; //"}\n"; //" gi = UnityGlobalIllumination (data, 1.0, 0.0, s.Normal, false);"; } shaderCode+="\n"+ "}\n"; } else if (GCLightingName(SP)=="CLPBR_Standard"){ ShaderLayersLightingAll.CodeName="123ASD$#%"; ShaderLayersLightingAll.EndTag.Text="rgb"; ShaderLayersLightingAll.NameUnique.Text="LightingSpecular"; ShaderLayersLightingDiffuse.CodeName="123ASD$#%"; ShaderLayersLightingDiffuse.EndTag.Text="rgb"; ShaderLayersLightingSpecular.CodeName="123ASD$#%"; ShaderLayersLightingSpecular.EndTag.Text="rgb"; ShaderLayersLightingAmbient.CodeName="123ASD$#%"; ShaderLayersLightingAmbient.EndTag.Text="rgb"; CustomPartS = GCLayers(SG,"LightingAllSpecular",ShaderLayersLightingAll,"specularColor","rgb","",false,true).Replace("123ASD$#%","specularColor")+GCLayers(SG,"LightingSpecular",ShaderLayersLightingSpecular,"specularColor","rgb","",false,true).Replace("123ASD$#%","specularColor"); ShaderLayersLightingAll.NameUnique.Text="LightingDiffuse"; CustomPartD = GCLayers(SG,"LightingAllDiffuse",ShaderLayersLightingAll,"lightColor","rgb","",false,true).Replace("123ASD$#%","lightColor")+GCLayers(SG,"LightingDiffuse",ShaderLayersLightingDiffuse,"lightColor","rgb","",false,true).Replace("123ASD$#%","lightColor"); CustomPartA = GCLayers(SG,"LightingAmbient",ShaderLayersLightingAmbient,"gi.diffuse","rgb","",false,true).Replace("123ASD$#%","gi.diffuse"); ShaderLayersLightingAll.NameUnique.Text="LightingDirect"; shaderCode+="//Include a bunch of PBS Code from files UnityPBSLighting.cginc and UnityStandardBRDF.cginc for the purpose of custom lighting effects.\n"; shaderCode+=@" half4 BRDF1_Unity_PBSSS (half3 diffColor, half3 specColor, half oneMinusReflectivity, half oneMinusRoughness, half3 normal, half3 viewDir, UnityLight light, UnityIndirect gi) {"+ "\n half3 SSlightColor = _LightColor0;\n"+ " half3 lightDir = light.dir;\n"+ " half3 atten = light.color/_LightColor0;\n"+ " half3 SSnormal = normal;\n"+ " half3 SSalbedo = diffColor;\n"+ " half3 SSspecular = specColor;\n"+ " half3 SSemission = float3(0,0,0);\n"+ " half SSalpha = 1;\n"; foreach(ShaderLayerList SLL in ShaderLayersMasks) { if (SG.UsedMasks[SLL]>0&&SLL.IsLighting.On){ shaderCode+=SLL.GCVariable(); shaderCode+=GCLayers(SG,SLL.Name.Text,SLL,SLL.CodeName,SLL.EndTag.Text,SLL.Function,false,true); } } shaderCode+=@" half roughness = 1-oneMinusRoughness; half3 halfDir = normalize (light.dir + viewDir); half nl = light.ndotl; half nh = BlinnTerm (normal, halfDir); half nv = DotClamped (normal, viewDir); half lv = DotClamped (light.dir, viewDir); half lh = DotClamped (light.dir, halfDir); #if UNITY_BRDF_GGX half V = SmithGGXVisibilityTerm (nl, nv, roughness); half D = GGXTerm (nh, roughness); #else half V = SmithBeckmannVisibilityTerm (nl, nv, roughness); half D = NDFBlinnPhongNormalizedTerm (nh, RoughnessToSpecPower (roughness)); #endif half nlPow5 = Pow5 (1-nl); half nvPow5 = Pow5 (1-nv); half Fd90 = 0.5 + 2 * lh * lh * roughness; half disneyDiffuse = (1 + (Fd90-1) * nlPow5) * (1 + (Fd90-1) * nvPow5); // HACK: theoretically we should divide by Pi diffuseTerm and not multiply specularTerm! // BUT 1) that will make shader look significantly darker than Legacy ones // and 2) on engine side Non-important lights have to be divided by Pi to in cases when they are injected into ambient SH // NOTE: multiplication by Pi is part of single constant together with 1/4 now "; if (U4) shaderCode+=@"half specularTerm = max(0, (V * D * nl));// Torrance-Sparrow model, Fresnel is applied later (for optimization reasons)"; else shaderCode+=@"half specularTerm = max(0, (V * D * nl) * unity_LightGammaCorrectionConsts_PIDiv4);// Torrance-Sparrow model, Fresnel is applied later (for optimization reasons)"; shaderCode+=@" half diffuseTerm = disneyDiffuse * nl; half grazingTerm = saturate(oneMinusRoughness + (1-oneMinusReflectivity)); "; if (U4) shaderCode+=@"half3 lightColor = (light.color * diffuseTerm);"; else shaderCode+="\n"+CustomPartA+@" half3 lightColor = (gi.diffuse + light.color * diffuseTerm);"; shaderCode+=@" half3 specularColor = specularTerm*light.color * FresnelTerm (specColor, lh)+(gi.specular * FresnelLerp (specColor, grazingTerm, nv)); "+CustomPartD+"\n"+CustomPartS+@" half3 color = diffColor * lightColor + specularColor; return half4(color, 1); } // Based on Minimalist CookTorrance BRDF // Implementation is slightly different from original derivation: http://www.thetenthplanet.de/archives/255 // // * BlinnPhong as NDF // * Modified Kelemen and Szirmay-Kalos for Visibility term // * Fresnel approximated with 1/LdotH half4 BRDF2_Unity_PBSSS (half3 diffColor, half3 specColor, half oneMinusReflectivity, half oneMinusRoughness, half3 normal, half3 viewDir, UnityLight light, UnityIndirect gi) { half3 halfDir = normalize (light.dir + viewDir);"+ "\n half3 SSlightColor = _LightColor0;\n"+ " half3 lightDir = light.dir;\n"+ " half3 atten = light.color/_LightColor0;\n"+ " half3 SSnormal = normal;\n"+ " half3 SSalbedo = diffColor;\n"+ " half3 SSspecular = specColor;\n"+ " half3 SSemission = float3(0,0,0);\n"+ " half SSalpha = 1;\n"; foreach(ShaderLayerList SLL in ShaderLayersMasks) { if (SG.UsedMasks[SLL]>0&&SLL.IsLighting.On){ shaderCode+=SLL.GCVariable(); shaderCode+=GCLayers(SG,SLL.Name.Text,SLL,SLL.CodeName,SLL.EndTag.Text,SLL.Function,false,true); } } shaderCode+=@" half nl = light.ndotl; half nh = BlinnTerm (normal, halfDir); half nv = DotClamped (normal, viewDir); half lh = DotClamped (light.dir, halfDir); half roughness = 1-oneMinusRoughness; half specularPower = RoughnessToSpecPower (roughness); // Modified with approximate Visibility function that takes roughness into account // Original ((n+1)*N.H^n) / (8*Pi * L.H^3) didn't take into account roughness // and produced extremely bright specular at grazing angles // HACK: theoretically we should divide by Pi diffuseTerm and not multiply specularTerm! // BUT 1) that will make shader look significantly darker than Legacy ones // and 2) on engine side Non-important lights have to be divided by Pi to in cases when they are injected into ambient SH // NOTE: multiplication by Pi is cancelled with Pi in denominator half invV = lh * lh * oneMinusRoughness + roughness * roughness; // approx ModifiedKelemenVisibilityTerm(lh, 1-oneMinusRoughness); half invF = lh; half specular = ((specularPower + 1) * pow (nh, specularPower)) / (unity_LightGammaCorrectionConsts_8 * invV * invF + 1e-4f); // @TODO: might still need saturate(nl*specular) on Adreno/Mali half grazingTerm = saturate(oneMinusRoughness + (1-oneMinusReflectivity)); half3 lightColor = light.color * nl; half3 specularColor = specular * specColor * lightColor + gi.specular * FresnelLerpFast (specColor, grazingTerm, nv); "; if (!U4) shaderCode+="\n"+CustomPartA+@" lightColor += gi.diffuse; "; shaderCode+=@" "+CustomPartD+"\n"+CustomPartS+@" half3 color = diffColor* lightColor + specularColor; return half4(color, 1); }"+ /* half3 color = diffColor * lightColor + specularColor; half3 color = (diffColor + specular * specColor) * light.color * nl + gi.diffuse * diffColor + gi.specular * FresnelLerpFast (specColor, grazingTerm, nv);*/ @" // Old school, not microfacet based Modified Normalized Blinn-Phong BRDF // Implementation uses Lookup texture for performance // // * Normalized BlinnPhong in RDF form // * Implicit Visibility term // * No Fresnel term // // TODO: specular is too weak in Linear rendering mode half4 BRDF3_Unity_PBSSS (half3 diffColor, half3 specColor, half oneMinusReflectivity, half oneMinusRoughness, half3 normal, half3 viewDir, UnityLight light, UnityIndirect gi) { half LUT_RANGE = 16.0; // must match range in NHxRoughness() function in GeneratedTextures.cpp"+ "\n half3 SSlightColor = _LightColor0;\n"+ " half3 lightDir = light.dir;\n"+ " half3 atten = light.color/_LightColor0;\n"+ " half3 SSnormal = normal;\n"+ " half3 SSalbedo = diffColor;\n"+ " half3 SSspecular = specColor;\n"+ " half3 SSemission = float3(0,0,0);\n"+ " half SSalpha = 1;\n"; foreach(ShaderLayerList SLL in ShaderLayersMasks) { if (SG.UsedMasks[SLL]>0&&SLL.IsLighting.On){ shaderCode+=SLL.GCVariable(); shaderCode+=GCLayers(SG,SLL.Name.Text,SLL,SLL.CodeName,SLL.EndTag.Text,SLL.Function,false,true); } } shaderCode+=@" half3 reflDir = reflect (viewDir, normal); half3 halfDir = normalize (light.dir + viewDir); half nl = light.ndotl; half nh = BlinnTerm (normal, halfDir); half nv = DotClamped (normal, viewDir); // Vectorize Pow4 to save instructions half2 rlPow4AndFresnelTerm = Pow4 (half2(dot(reflDir, light.dir), 1-nv)); // use R.L instead of N.H to save couple of instructions half rlPow4 = rlPow4AndFresnelTerm.x; // power exponent must match kHorizontalWarpExp in NHxRoughness() function in GeneratedTextures.cpp half fresnelTerm = rlPow4AndFresnelTerm.y; "; if (U4) shaderCode+="#if 0 // Lookup texture to save instructions\n"; else shaderCode+="#if 1 // Lookup texture to save instructions\n"; shaderCode+=@" half specular = tex2D(unity_NHxRoughness, half2(rlPow4, 1-oneMinusRoughness)).UNITY_ATTEN_CHANNEL * LUT_RANGE; #else half roughness = 1-oneMinusRoughness; half n = RoughnessToSpecPower (roughness) * .25; half specular = (n + 2.0) / (2.0 * UNITY_PI * UNITY_PI) * pow(dot(reflDir, light.dir), n) * nl;// / unity_LightGammaCorrectionConsts_PI; //half specular = (1.0/(UNITY_PI*roughness*roughness)) * pow(dot(reflDir, light.dir), n) * nl;// / unity_LightGammaCorrectionConsts_PI; #endif half grazingTerm = saturate(oneMinusRoughness + (1-oneMinusReflectivity)); half3 lightColor = light.color * nl; half3 specularColor = specular * specColor * lightColor + gi.specular * lerp (specColor, grazingTerm, fresnelTerm);"; if (!U4) shaderCode+="\n"+CustomPartA+"\nlightColor += gi.diffuse; \n"; shaderCode+=""+CustomPartD+"\n"+CustomPartS+@" half3 color = diffColor* lightColor + specularColor; return half4(color, 1); } #if !defined (UNITY_BRDF_PBSSS) // allow to explicitly override BRDF in custom shader #if (SHADER_TARGET < 30) || defined(SHADER_API_PSP2) // Fallback to low fidelity one for pre-SM3.0 #define UNITY_BRDF_PBSSS BRDF3_Unity_PBSSS #elif defined(SHADER_API_MOBILE) // Somewhat simplified for mobile #define UNITY_BRDF_PBSSS BRDF2_Unity_PBSSS #else // Full quality for SM3+ PC / consoles #define UNITY_BRDF_PBSSS BRDF1_Unity_PBSSS #endif #endif"; if (U4) shaderCode+="\n//Generate lighting code similar to the Unity Standard Shader. Not gonna deny, I have no clue how much of it works.\n"+ "half4 LightingCLPBR_Standard (CSurfaceOutput s, half3 lightDir, half3 viewDir, half atten) {\n"+@" UnityLight l; l.color = _LightColor0.rgb*atten; /*#ifndef USING_DIRECTIONAL_LIGHT lightDir = normalize(_WorldSpaceLightPos0.xyz - s.worldPos); #else lightDir = _WorldSpaceLightPos0.xyz; #endif*/ l.dir = (lightDir); l.ndotl = max (0, dot (s.Normal, l.dir)); UnityIndirect l2; l2.diffuse = s.worldRefl*0.0001; float mip = pow(1-s.Smoothness,3.0/4.0) * UNITY_SPECCUBE_LOD_STEPS; half4 rgbm = texCUBElod(_Cube, float4(s.worldRefl,mip)); l2.specular = rgbm;//texCUBELOD(_Cube,s.worldRefl); #if !defined(UNITY_PASS_FORWARDBASE) l2.specular = float3(0,0,0); #endif //l2.diffuse = 0; half3 lightColor = _LightColor0.rgb;//CSurfaceOutput s, half3 viewDir, UnityGI gi){ s.Normal = normalize(s.Normal); // energy conservation half oneMinusReflectivity; s.Albedo = EnergyConservationBetweenDiffuseAndSpecular (s.Albedo, s.Specular, /*out*/ oneMinusReflectivity); // shader relies on pre-multiply alpha-blend (_SrcBlend = One, _DstBlend = OneMinusSrcAlpha) // this is necessary to handle transparency in physically correct way - only diffuse component gets affected by alpha half outputAlpha; s.Albedo = PreMultiplyAlpha (s.Albedo, s.Alpha, oneMinusReflectivity, /*out*/ outputAlpha); half4 c = UNITY_BRDF_PBSSS (s.Albedo, s.Specular, oneMinusReflectivity, s.Smoothness, s.Normal, viewDir, l, l2); //c.rgb += UNITY_BRDF_GI (s.Albedo, s.Specular, oneMinusReflectivity, s.Smoothness, s.Normal, viewDir, s.Occlusion, gi); c.a = outputAlpha; //c.rgb *= s.worldRefl; c.rgb+=l2.diffuse; return c; } "; else shaderCode+="\n//Generate lighting code similar to the Unity Standard Shader. Not gonna deny, I have no clue how much of it works.\n"+ "half4 LightingCLPBR_Standard (CSurfaceOutput s, half3 viewDir, UnityGI gi){\n"+ " s.Normal = normalize(s.Normal);\n"+ " // energy conservation\n"+ " half oneMinusReflectivity;\n"+ " s.Albedo = EnergyConservationBetweenDiffuseAndSpecular (s.Albedo, s.Specular, /*out*/ oneMinusReflectivity);\n"+ " // shader relies on pre-multiply alpha-blend (_SrcBlend = One, _DstBlend = OneMinusSrcAlpha)\n"+ " // this is necessary to handle transparency in physically correct way - only diffuse component gets affected by alpha\n"+ " half outputAlpha;\n"+ " s.Albedo = PreMultiplyAlpha (s.Albedo, s.Alpha, oneMinusReflectivity, /*out*/ outputAlpha);\n"+ " half4 c = UNITY_BRDF_PBSSS (s.Albedo, s.Specular, oneMinusReflectivity, s.Smoothness, s.Normal, viewDir, gi.light, gi.indirect);\n"+ " c.rgb += UNITY_BRDF_GI (s.Albedo, s.Specular, oneMinusReflectivity, s.Smoothness, s.Normal, viewDir, s.Occlusion, gi);\n"+ " c.a = outputAlpha;\n"+ " return c;\n"+ "}\n"; if (!U4){ shaderCode+="\n"+ "inline void Lighting"+GCLightingName(SP)+"_GI (CSurfaceOutput s,UnityGIInput data,inout UnityGI gi){\n"; if (SpecularOn.On){ shaderCode+="#if UNITY_VERSION >= 520\n"+ " UNITY_GI(gi, s, data);\n"+ "#else\n"+ " gi = UnityGlobalIllumination (data, 1.0, s.Smoothness, s.Normal);\n"+ "#endif\n"; //"}\n"; } else{ shaderCode+="#if UNITY_VERSION >= 520\n"+ " UNITY_GI(gi, s, data);\n"+ "#else\n"+ " gi = UnityGlobalIllumination (data, 1.0, 0.0, s.Normal);\n"+ "#endif\n"; //"}\n"; } shaderCode+="\n"+ "}\n"; } } shaderCode+="#endif\n"; return shaderCode; }
public bool UsesShellLighting(ShaderPass SP){ if (ShaderPassShells(SP)){ if (ShellsLighting.On) return true; return false; } return true; }
public string GCLabTags(ShaderPass SP) { string ShaderCode = ""; ShaderCode += " blend off //Disabled blending (No Transparency)\n"; if (!SG.Wireframe){ if (MiscFog.On==false) ShaderCode+="Fog {Mode Off}\n"; if (TransparencyReceive.On&&TransparencyOn.On) ShaderCode+="blend SrcAlpha OneMinusSrcAlpha//Standard Transparency\nZWrite Off\n"; if (ShaderPassShells(SP)&&ShellsBlendMode.Type==1) ShaderCode+="blend One One//Add Blend Mode\n"; if (ShaderPassShells(SP)&&ShellsBlendMode.Type==2) ShaderCode+="blend DstColor Zero//Multiply Blend Mode\n"; if (ShaderPassStandard(SP)&&BlendMode.Type==1&&TransparencyType.Type==1&&TransparencyOn.On) ShaderCode+="blend One One//Add Blend Mode\n"; if (ShaderPassStandard(SP)&&BlendMode.Type==2&&TransparencyType.Type==1&&TransparencyOn.On) ShaderCode+="blend DstColor Zero//Multiply Blend Mode\n"; } return ShaderCode; }
public string GCPass_Real(ShaderGenerate SG,ShaderPass SP,float Dist){ string ShaderCode = ""; //SG.Reset(); // int OldTransType = TransparencyType.Type; float OldTransAmount = TransparencyAmount.Float; ShaderInput OldTransInput = TransparencyAmount.Input; if (TransparencyZWrite.On&&TransparencyZWriteType.Type==1){ TransparencyAmount.Float = 1f; TransparencyAmount.Input = null; } ShaderCode+=" ZWrite On\n"; if (ShaderPassShells(SP)){ if (ShellsZWrite.On) ShaderCode+=" ZWrite On\n"; else ShaderCode+=" ZWrite Off\n"; } if (TransparencyOn.On&&TransparencyType.Type==1&&TransparencyZWrite.On==false) ShaderCode+=" ZWrite Off\n"; //else //ShaderCode+=" ZWrite On\n"; if (ShaderPassBase(SP)){ if (ShaderPassShells(SP)) ShaderCode+=" cull "+ShellsCull.CodeNames[ShellsCull.Type]+"//Culling specifies which sides of the models faces to hide.\n"; else ShaderCode+=" cull "+TechCull.CodeNames[TechCull.Type]+"//Culling specifies which sides of the models faces to hide.\n"; } ShaderCode+=GCLabTags(SP); ShaderCode+=" CGPROGRAM\n\n"; ShaderCode+=GCUniforms(SG); ShaderCode+=GCPragma(SG,SP); ShaderCode+=GCSurfaceOutput(); ShaderCode+=GCInputs(SG); ShaderCode+=GCFunctions(SG); ShaderCode+=GCLighting(SG,SP); ShaderCode+=GCVertex(SG,SP,Dist); ShaderCode+=GCFragment(SG,SP,Dist); ShaderCode+=" ENDCG\n"; if (TransparencyZWrite.On&&TransparencyZWriteType.Type==1){ TransparencyAmount.Input = OldTransInput; TransparencyAmount.Float = OldTransAmount; } return ShaderCode; }
public bool ShaderPassBase(ShaderPass SP){ if (SP == ShaderPass.Base||SP == ShaderPass.ShellBase||ShaderPassMask(SP)) return true; return false; }
public string GCVertex(ShaderGenerate SG, ShaderPass SP, float Dist){ SG.InVertex = true; string shaderCode = ""; if (Dist>0||ShaderLayersVertex.Count>0||ShellsOn.On||TessellationOn.On) shaderCode+=@"//Create a struct for the inputs of the vertex shader which includes whatever Shader Sandwich might need. struct appdata_min { float4 vertex : POSITION; float4 tangent : TANGENT; float3 normal : NORMAL; float4 texcoord : TEXCOORD0; float4 texcoord1 : TEXCOORD1; #ifdef UNITY_GLOBAL_ILLUMINATION_INCLUDED #ifndef U4Imposter float4 texcoord2 : TEXCOORD2; #endif #endif fixed4 color : COLOR; };"; if (TessellationOn.On){ if (TessellationType.Type==0){ shaderCode+=@" float4 tess (appdata_min v0, appdata_min v1, appdata_min v2) { return "+TessellationQuality.Get()+@"; } "; } if (TessellationType.Type==1){ shaderCode+=@" float4 tess (appdata_min v0, appdata_min v1, appdata_min v2) { float3 pos0 = mul(_Object2World,v0.vertex).xyz; float3 pos1 = mul(_Object2World,v1.vertex).xyz; float3 pos2 = mul(_Object2World,v2.vertex).xyz; float4 tess; tess.x = distance(pos1, pos2)*"+TessellationQuality.Get()+@"; tess.y = distance(pos2, pos0)*"+TessellationQuality.Get()+@"; tess.z = distance(pos0, pos1)*"+TessellationQuality.Get()+@"; tess.w = (tess.x + tess.y + tess.z) / 3.0f; "; if (TessellationFalloff.Get()!="1") shaderCode+=" return pow(tess/50,"+TessellationFalloff.Get()+")*50;\n"; else shaderCode+=" return tess;\n"; shaderCode+=" }\n"; } if (TessellationType.Type==2){ shaderCode+=@" float4 tess (appdata_min v0, appdata_min v1, appdata_min v2) { "; if (TessellationFalloff.Get()!="1") shaderCode+=" return pow(UnityEdgeLengthBasedTess (v0.vertex, v1.vertex, v2.vertex, (51-"+TessellationQuality.Get()+")*2)/50,"+TessellationFalloff.Get()+")*50;\n"; else shaderCode+=" return UnityEdgeLengthBasedTess (v0.vertex, v1.vertex, v2.vertex, (51-"+TessellationQuality.Get()+")*2);\n"; shaderCode+=" }"; } } shaderCode+="\n"; //"void vert (inout appdata_full v, out Input o) {\n"+ if (Dist>0||ShaderLayersVertex.Count>0||ShellsOn.On||TessellationOn.On){ shaderCode+="//Generate the vertex shader\n"+ "void vert (inout appdata_min v) {\n"; //" UNITY_INITIALIZE_OUTPUT(Input, o);\n"; //if (SG.GeneralUV=="Texcoord"&&SG.UsedGenericUV){ // shaderCode+=" o.Texcoord = v.texcoord;\n"; //} shaderCode+=GCVertexInternal(SG,SP,Dist); shaderCode+="}\n"; } SG.InVertex = false; SG.UsedBases.Clear(); return shaderCode; }
internal void addPass(ShaderPass hblur) { throw new NotImplementedException(); }
public string GCLightingName(ShaderPass SP){ if (UsesShellLighting(SP)) return "CL"+ShaderUtil.CodeName(DiffuseLightingType.Names[DiffuseLightingType.Type]); else return "CLUnlit"; }
public string GCPragma(ShaderGenerate SG,ShaderPass SP) { string shaderCode = ""; if (ParallaxOn.On) shaderCode+="//Set up some Parallax Occlusion Mapping Settings\n#define LINEAR_SEARCH "+(Math.Round(ParallaxBinaryQuality.Float/2)).ToString()+"\n"+ "#define BINARY_SEARCH "+ParallaxBinaryQuality.Get()+"\n"; shaderCode+=" #pragma surface frag_surf "+GCLightingName(SP); if (ShellsOn.On||ShaderLayersVertex.Count>0||TessellationOn.On) shaderCode+=" vertex:vert "; if (!TransparencyReceive.On||!TransparencyOn.On) shaderCode+=" addshadow "; if (GCLightingName(SP)=="CLUnlit"){ #if UNITY_5 shaderCode+= " noforwardadd noambient novertexlights nolightmap nodynlightmap nodirlightmap"; #else shaderCode+= " noforwardadd noambient novertexlights nolightmap nodirlightmap"; #endif } if ((TransparencyType.Type==1&&TransparencyOn.On&&!TransparencyReceive.On&&!(ShaderPassShells(SP)&&ShellsBlendMode.Type!=0)&&!(ShaderPassStandard(SP)&&BlendMode.Type!=0))&&!SG.Wireframe){ shaderCode+= " alpha"; #if UNITY_5 if (GCLightingName(SP)!="CLPBR_Standard"||!TransparencyPBR.On) shaderCode+=":fade"; #endif } if (TransparencyReceive.On&&TransparencyOn.On) shaderCode+=" keepalpha "; if (MiscAmbient.On==false) shaderCode+=" noambient"; if (MiscVertexLights.On==false) shaderCode+=" novertexlights"; if (MiscLightmap.On==false){ #if UNITY_5 shaderCode+=" nolightmap nodynlightmap nodirlightmap"; #else shaderCode+=" nolightmap nodirlightmap"; #endif } if (MiscFullShadows.On) shaderCode+=" fullforwardshadows"; if (MiscHalfView.On) shaderCode+=" halfasview"; if (!MiscForwardAdd.On) shaderCode+=" noforwardadd"; #if UNITY_5 if (MiscInterpolateView.On) shaderCode+=" interpolateview"; if (!MiscShadows.On) shaderCode+=" noshadow"; #endif if (TessellationOn.On){ shaderCode+=" tessellate:tess"; if (TessellationSmoothingAmount.Get()!="0"){ shaderCode+=" tessphong:"+TessellationSmoothingAmount.Get(); } } shaderCode=" //Set up Unity Surface Shader Settings.\n"+shaderCode+"\n"; shaderCode+="//The Shader Target defines the maximum capabilites of the shader (Number of math operators, texture reads, etc.)\n #pragma target "+((int)TechShaderTarget.Float).ToString()+".0\n"; if (TessellationOn.On) shaderCode+="#include \"Tessellation.cginc\" //Include some Unity code for tessellation.\n"; return shaderCode; }
public string GCFragmentMask(ShaderGenerate SG, ShaderPass SP,float Depth){ return " fixed4 frag() : SV_Target {\n"+ " return fixed4(1.0,0.0,0.0,1.0);\n"+ "}\n"; }
public string GCFragment(ShaderGenerate SG, ShaderPass SP,float Depth){ string ShaderCode = ""; ShaderCode+="\n"; ShaderCode+="//Generate the fragment shader (Operates on pixels)\n"; ShaderCode+="void frag_surf (Input IN, inout CSurfaceOutput o) {\n"; #if PRE_UNITY_5 if (DiffuseLightingType.Type==4){ ShaderCode+=@" o.worldRefl = IN.worldRefl; "; } #endif if (!SG.Wireframe){ ShaderCode+=" float SSShellDepth = 1-"+Depth.ToString()+";\n"; ShaderCode+=" float SSParallaxDepth = 0;\n"; if (SG.UsedScreenPos) ShaderCode+="IN.screenPos.xy /= IN.screenPos.w;\n"; //if (SG.TooManyTexcoords){ foreach (ShaderInput SI in ShaderInputs){ if (SI.Type==0) { if (SI.UsedMapType0==true||SI.UsedMapType1==true) { if (SG.TooManyTexcoords) ShaderCode+=" float2 uv"+SI.Get()+" = IN.uvTexcoord;\n"; else ShaderCode+=" float2 uv"+SI.Get()+" = IN.uv"+SI.Get()+";\n"; } } } //} ShaderCode+=" //Set reasonable defaults for the fragment outputs.\n o.Albedo = float3(0.8,0.8,0.8);\n"+ " float4 Emission = float4(0,0,0,0);\n"; if (GCLightingName(SP)=="CLPBR_Standard"){ if (SpecularOn.On) ShaderCode+=" o.Smoothness = "+SpecularHardness.Get()+";\n"; else ShaderCode+=" o.Smoothness = 0;\n"; } else{ if (SpecularOn.On) ShaderCode+=" o.Smoothness = "+SpecularHardness.Get()+"*2;\n"; else ShaderCode+=" o.Smoothness = 0;\n"; } //if (SG.UsedNormals||SG.UsedShellsNormals) //ShaderCode+=" o.Normal = float3(0.5,0.5,1);\n"; if (SG.UsedNormals||SG.UsedShellsNormals) ShaderCode+=" o.Normal = float3(0,0,1);\n"; ShaderCode+=" o.Alpha = 1.0;\n"+ " o.Occlusion = 1.0;\n"+ " o.Specular = float3(0.3,0.3,0.3);\n"; if (SG.UsedMapGenerate==true) ShaderCode+=//" half2 UVy;\n"+ //" half2 UVx;\n"+ //" half2 UVz;\n\n"+ //" half4 TEXy;\n"+ //" half4 TEXx;\n"+ //" half4 TEXz;\n\n"+ //" half3 blend = normalize(abs(IN.worldNormal));\n"; " half3 blend = pow((abs(WorldNormalVector(IN, o.Normal))),5);\n blend /= blend.x+blend.y+blend.z;\n"; foreach(string Ty in ShaderSandwich.EffectsList){ bool IsUsed = false; foreach (ShaderLayer SL in ShaderUtil.GetAllLayers()){ foreach(ShaderEffect SE in SL.LayerEffects) { if (Ty==SE.TypeS&&SE.Visible) IsUsed = true; } } if (IsUsed){ ShaderEffect NewEffect = ShaderEffect.CreateInstance<ShaderEffect>(); NewEffect.ShaderEffectIn(Ty); if (ShaderEffect.GetMethod(NewEffect.TypeS,"GenerateStart")!=null) ShaderCode+= (string)ShaderEffect.GetMethod(NewEffect.TypeS,"GenerateStart").Invoke(null,new object[]{SG})+"\n"; } } ShaderCode+="#PARALLAX"; ShaderCode+="#GENERATEMULTIUSEDBASES\n"; foreach(ShaderLayerList SLL in ShaderLayersMasks) { if (SG.UsedMasks[SLL]>0&&!SLL.IsLighting.On){ ShaderCode+=SLL.GCVariable(); ShaderCode+=GCLayers(SG,SLL.Name.Text,SLL,SLL.CodeName,SLL.EndTag.Text,SLL.Function,false,true); } } if (ShaderPassStandard(SP)||ShaderPassMask(SP)) { ShaderCode+=GCLayers(SG,"Normals",ShaderLayersNormal,"o.Normal","rgb","",false,true); //if (SG.UsedNormals) //ShaderCode+="o.Normal = (o.Normal-0.5)*2;\n"; if (TransparencyOn.On) ShaderCode+=GCLayers(SG,"Alpha",ShaderLayersAlpha,"o.Alpha","a","",false,false); if (TransparencyOn.On&&TransparencyType.Type==0){ ShaderCode+=" clip(o.Alpha-"+TransparencyAmount.Get()+");\n"; } if (TransparencyOn.On&&TransparencyType.Type==1){ ShaderCode+=" o.Alpha *= "+TransparencyAmount.Get()+";\n"; } ShaderCode+=GCLayers(SG,"Diffuse",ShaderLayersDiffuse,"o.Albedo","rgb","",false,true); if (EmissionOn.On) ShaderCode+=GCLayers(SG,"Emission",ShaderLayersEmission,"Emission","rgba","",false,true); if (SpecularOn.On) ShaderCode+=GCLayers(SG,"Gloss",ShaderLayersSpecular,"o.Specular","rgb","",false,true); } if (ShaderPassShells(SP)) { ShaderCode+=GCLayers(SG,"Normals",ShaderLayersShellNormal,"o.Normal","rgb","",false,true); //if (SG.UsedShellsNormals) //ShaderCode+="o.Normal = (o.Normal-0.5)*2;\n"; if (TransparencyOn.On) ShaderCode+=GCLayers(SG,"Alpha",ShaderLayersShellAlpha,"o.Alpha","a","",false,true); if (TransparencyOn.On&&TransparencyType.Type==0){ ShaderCode+=" clip(o.Alpha-"+TransparencyAmount.Get()+");\n"; } if (TransparencyOn.On&&TransparencyType.Type==1){ ShaderCode+=" o.Alpha *= "+TransparencyAmount.Get()+";\n"; } ShaderCode+=GCLayers(SG,"Diffuse",ShaderLayersShellDiffuse,"o.Albedo","rgb","",false,true); if (EmissionOn.On) ShaderCode+=GCLayers(SG,"Emission",ShaderLayersShellEmission,"Emission","rgba","",false,true); if (SpecularOn.On) ShaderCode+=GCLayers(SG,"Gloss",ShaderLayersShellSpecular,"o.Specular","rgb","",false,true); } if (EmissionOn.On){ ShaderCode+=" o.Emission = Emission.rgb;\n"; if (EmissionType.Type==1) ShaderCode+=" o.Emission*=o.Albedo;\n"; if (EmissionType.Type==2){ ShaderCode+=" o.Albedo *= 1-Emission.a;\n"; //ShaderCode+=" o.Emission = float3(0,0,0);\n"; } } } ShaderCode+="}\n"; string GenMultiUseBases = ""; //int GenMultiUseBasesCount = 0; /*foreach(KeyValuePair<string, int> entry in SG.UsedBases){ if (entry.Value>=2) { GenMultiUseBasesCount+=1; GenMultiUseBases+="float4 MultiUse"+GenMultiUseBasesCount.ToString()+" = "+entry.Key+";//"+entry.Value.ToString()+"\n"; ShaderCode = ShaderCode.Replace(entry.Key,"MultiUse"+GenMultiUseBasesCount.ToString()); } }*/ ShaderCode = ShaderCode.Replace("#GENERATEMULTIUSEDBASES",GenMultiUseBases); ShaderCode = ShaderCode.Replace("#PARALLAX",GCParallax(SG)); SG.UsedBases.Clear(); return ShaderCode; }
public string GCFragmentMask(ShaderGenerate SG, ShaderPass SP){ return GCFragmentMask(SG,SP,0f); }
public string GCPassMask_Real(ShaderGenerate SG,ShaderPass SP,float Dist){ string ShaderCode = ""; //SG.Reset(); int OldTransType = TransparencyType.Type; // float OldTransAmount = TransparencyAmount.Float; // ShaderInput OldTransInput = TransparencyAmount.Input; TransparencyType.Type = 0; if (TransparencyZWriteType.Type==0) ShaderCode+="\nPass\n" +"{\n" +" Name \"ALPHAMASK\"\n" +" ColorMask 0\n"; if (ShaderPassShells(SP)) ShaderCode+=" cull "+ShellsCull.CodeNames[ShellsCull.Type]+"\n"; else ShaderCode+=" cull "+TechCull.CodeNames[TechCull.Type]+"\n"; ShaderCode+=GCLabTags(SP); ShaderCode+=" CGPROGRAM\n\n"; ShaderCode+=GCUniforms(SG); if (TransparencyZWriteType.Type==1){ ShaderCode+=GCPragma(SG,SP); ShaderCode+=GCSurfaceOutput(); ShaderCode+=GCInputs(SG); } else{ ShaderCode+=" //The Shader Target defines the maximum capabilites of the shader (Number of math operators, texture reads, etc.)\n #pragma target "+((int)TechShaderTarget.Float).ToString()+".0\n"+ " //Tell Unity which parts of the shader affect the vertexes or the pixel colors.\n"+ " #pragma vertex vert\n"+ " #pragma fragment frag\n"+ " #include \"UnityCG.cginc\" //Include some base Unity stuff.\n"; } ShaderCode+=GCFunctions(SG); if (TransparencyZWriteType.Type==1) ShaderCode+=GCLighting(SG,SP); if (TransparencyZWriteType.Type==0) ShaderCode+=GCVertexMask(SG,SP,Dist); else ShaderCode+=GCVertex(SG,SP,Dist); if (TransparencyZWriteType.Type==0) ShaderCode+=GCFragmentMask(SG,SP,Dist); else ShaderCode+=GCFragment(SG,SP,Dist); ShaderCode+=" ENDCG\n"; if ((TransparencyZWriteType.Type==0)) ShaderCode+="}\n"; //if (TransparencyZWrite.On&&TransparencyZWriteType.Type==1){ TransparencyType.Type = OldTransType; //} return ShaderCode; }
public string GCPassMask(ShaderGenerate SG,ShaderPass SP,float Dist){ if (TransparencyZWrite.On&&TransparencyOn.On&&TransparencyType.Type==1) return GCPassMask_Real(SG,SP,Dist); return ""; }
public string GCVertexMask(ShaderGenerate SG, ShaderPass SP, float Dist){ SG.InVertex = true; string shaderCode = ""; shaderCode+="float4 vert(appdata_base v) : POSITION {\n"; shaderCode+=GCVertexInternal(SG,SP,Dist); shaderCode+=" return mul (UNITY_MATRIX_MVP, v.vertex);\n"; shaderCode+="}\n"; SG.InVertex = false; SG.UsedBases.Clear(); return shaderCode; }
public string GCPass(ShaderGenerate SG,ShaderPass SP){ return GCPass_Real(SG,SP,0f); }
/// <summary> /// Parses an instance from a stream to a CGP file /// </summary> public RetroShaderPreset(Stream stream) { var content = new StreamReader(stream).ReadToEnd(); Dictionary<string, string> dict = new Dictionary<string, string>(); //parse the key-value-pair format of the file content = content.Replace("\r", ""); foreach (var _line in content.Split('\n')) { var line = _line.Trim(); if (line.StartsWith("#")) continue; //lines that are solely comments if (line == "") continue; //empty line int eq = line.IndexOf('='); var key = line.Substring(0, eq).Trim(); var value = line.Substring(eq + 1).Trim(); int quote = value.IndexOf('\"'); if (quote != -1) value = value.Substring(quote + 1, value.IndexOf('\"', quote + 1) - (quote + 1)); else { //remove comments from end of value. exclusive from above condition, since comments after quoted strings would be snipped by the quoted string extraction int hash = value.IndexOf('#'); if (hash != -1) value = value.Substring(0, hash); value = value.Trim(); } dict[key.ToLower()] = value; } //process the keys int nShaders = FetchInt(dict, "shaders", 0); for (int i = 0; i < nShaders; i++) { ShaderPass sp = new ShaderPass(); sp.Index = i; Passes.Add(sp); sp.InputFilterLinear = FetchBool(dict, "filter_linear" + i, false); //Should this value not be defined, the filtering option is implementation defined. sp.OuputFloat = FetchBool(dict, "float_framebuffer" + i, false); sp.FrameCountMod = FetchInt(dict, "frame_count_mod" + i, 1); sp.ShaderPath = FetchString(dict, "shader" + i, "?"); //todo - change extension to .cg for better compatibility? just change .cg to .glsl transparently at last second? //If no scale type is assumed, it is assumed that it is set to "source" with scaleN set to 1.0. //It is possible to set scale_type_xN and scale_type_yN to specialize the scaling type in either direction. scale_typeN however overrides both of these. sp.ScaleTypeX = (ScaleType)Enum.Parse(typeof(ScaleType), FetchString(dict, "scale_type_x" + i, "Source"), true); sp.ScaleTypeY = (ScaleType)Enum.Parse(typeof(ScaleType), FetchString(dict, "scale_type_y" + i, "Source"), true); ScaleType st = (ScaleType)Enum.Parse(typeof(ScaleType), FetchString(dict, "scale_type" + i, "NotSet"), true); if (st != ScaleType.NotSet) sp.ScaleTypeX = sp.ScaleTypeY = st; //scaleN controls both scaling type in horizontal and vertical directions. If scaleN is defined, scale_xN and scale_yN have no effect. sp.Scale.X = FetchFloat(dict, "scale_x" + i, 1); sp.Scale.Y = FetchFloat(dict, "scale_y" + i, 1); float scale = FetchFloat(dict, "scale" + i, -999); if (scale != -999) sp.Scale.X = sp.Scale.Y = FetchFloat(dict, "scale" + i, 1); //TODO - LUTs } }
public bool ShaderPassMask(ShaderPass SP){ if (SP == ShaderPass.MaskBase||SP == ShaderPass.MaskLight||SP == ShaderPass.Mask) return true; return false; }
public string GCVertexInternal(ShaderGenerate SG, ShaderPass SP, float Dist){ string shaderCode = ""; shaderCode+=" float SSShellDepth = "+Dist.ToString()+";\n"; if (Dist>0){ string Disp = ""; if (ShellsDistance.Get()==ShellsDistance.Float.ToString()){ if (ShellsEase.Get()!="1"){ if (ShellsEase.Get()==ShellsEase.Float.ToString()) Disp=(ShellsDistance.Float*Mathf.Pow(Dist,ShellsEase.Float)).ToString(); else Disp=(ShellsDistance.Float.ToString()+"*pow("+Dist.ToString()+","+ShellsEase.Get()+")"); } else Disp = (ShellsDistance.Float*Dist).ToString(); } else{ if (ShellsEase.Get()=="1") Disp=ShellsDistance.Get()+"*"+Dist.ToString(); else Disp=(ShellsDistance.Get()+"*"+"pow("+Dist.ToString().ToString()+","+ShellsEase.Get()+")"); } shaderCode+=" v.vertex.xyz += v.normal*("+Disp+");\n"; } if (SG.UsedMapGenerate==true) shaderCode+= " half3 blend = pow((abs(UnityObjectToWorldNormal(v.normal))),5);\n blend /= blend.x+blend.y+blend.z;\n"; if (ShaderLayersVertex.Count>0){ shaderCode+="\n float4 Vertex = v.vertex;\n"; foreach(ShaderLayerList SLL in ShaderLayersMasks) { if (SG.UsedMasks[SLL]>0&&!SLL.IsLighting.On){ shaderCode+=SLL.GCVariable(); shaderCode+=GCLayers(SG,SLL.Name.Text,SLL,SLL.CodeName,SLL.EndTag.Text,SLL.Function,false,true); } } shaderCode+=GCLayers(SG,"Vertex",ShaderLayersVertex,"Vertex","rgba","",false,true); shaderCode+="\n v.vertex.rgb = Vertex;\n"; } return shaderCode; }
public bool ShaderPassShells(ShaderPass SP){ if (SP == ShaderPass.ShellBase||SP == ShaderPass.ShellLight) return true; return false; }
public bool ShaderPassLight(ShaderPass SP){ if (SP == ShaderPass.Light||SP == ShaderPass.ShellLight) return true; return false; }
public string GCPass(ShaderGenerate SG,ShaderPass SP,float Dist){ return GCPass_Real(SG,SP,Dist); }
public bool ShaderPassStandard(ShaderPass SP){ if (SP == ShaderPass.Base||SP == ShaderPass.Light) return true; return false; }
public void Render(RenderFrame frame) { if (SwapChain == null) return; ///////////////////////////////////////////////// // update ///////////////////////////////////////////////// foreach (var resource in frame.Resources) { switch (resource.RenderResourceType) { case RenderResourceType.Texture: //TextureManager.Ensure(device, resource as TextureResource); break; case RenderResourceType.Sampler: //SamplerManager.Ensure(device, resource as SamplerResource); break; case RenderResourceType.Shader: m_shaderManager.Ensure(D3DDevice, resource as ShaderResource); break; case RenderResourceType.VertexBuffer: m_vertexBufferManager.Ensure(D3DDevice, resource as VertexBufferResource); break; case RenderResourceType.BlendState: //BlendStateManager.Ensure(device, resource as BlendStateResource); break; case RenderResourceType.DepthStencilState: //DepthStencilStateManager.Ensure(device, resource as DepthStencilStateResource); break; default: throw new NotImplementedException(resource.ToString()); } } ///////////////////////////////////////////////// // render ///////////////////////////////////////////////// m_pass = new ShaderPass(); using (Backbuffer = SwapChain.GetBackBuffer<SharpDX.Direct3D11.Texture2D>(0)) using (RTV = new SharpDX.Direct3D11.RenderTargetView(D3DDevice, Backbuffer)) { var context = D3DDevice.ImmediateContext; foreach (var c in frame.Commands) { switch (c.RenderCommandType) { /* case RenderCommandType.RenderTargets_Set: { var command = c as RenderTargetsSetCommand; var depthStencil = m_resources.TextureManager.Get(command.DepthStencil); var renderTargets = m_resources.TextureManager.Get(command.RenderTargets); context.OutputMerger.SetTargets( depthStencil != null ? depthStencil.DepthStencilView : null , renderTargets.Select(r => r.RenderTargetView).ToArray()); } break; case RenderCommandType.Viewport_Set: { var command = c as ViewportSetCommand; context.Rasterizer.SetViewports(new SharpDX.ViewportF[] { command.Viewport }); } break; */ case RenderCommandType.Clear_Backbuffer: { var command = c as BackbufferClearCommand; context.ClearRenderTargetView(RTV, command.Color.ToSharpDX()); context.OutputMerger.SetTargets((SharpDX.Direct3D11.DepthStencilView)null, new SharpDX.Direct3D11.RenderTargetView[] { RTV }); context.Rasterizer.SetViewports(new [] { new SharpDX.Mathematics.Interop.RawViewportF { X=0, Y=0, Width=Backbuffer.Description.Width, Height=Backbuffer.Description.Height, } }); } break; /* case RenderCommandType.Clear_Color: { var command = c as RenderTargetClearCommand; var renderTarget = m_resources.TextureManager.Get(command.ResourceID); if (renderTarget != null) { context.ClearRenderTargetView(renderTarget.RenderTargetView, command.Color); } } break; case RenderCommandType.Clear_Depth: { var command = c as DepthStencilClearCommand; var depthStencil = m_resources.TextureManager.Get(command.ResourceID); if (depthStencil != null) { context.ClearDepthStencilView(depthStencil.DepthStencilView , SharpDX.Direct3D11.DepthStencilClearFlags.Depth , command.Depth, command.Stencil); } } break; */ case RenderCommandType.VertexBuffer_Update: { var command = c as VertexBufferUpdateCommand; var vertexBuffer = m_vertexBufferManager.Get(command.ResourceID); if (vertexBuffer != null) { if (command.Ptr != IntPtr.Zero) { var data = new SharpDX.DataBox(command.Ptr); context.UpdateSubresource(data, vertexBuffer.Vertices); } } } break; case RenderCommandType.VertexBuffer_Set: { var command = c as VertexBufferSetCommand; var vertexBuffer = m_vertexBufferManager.Get(command.ResourceID); if (vertexBuffer != null) { context.InputAssembler.PrimitiveTopology = vertexBuffer.Topology; context.InputAssembler.SetVertexBuffers(0, new SharpDX.Direct3D11.VertexBufferBinding(vertexBuffer.Vertices , vertexBuffer.Stride, 0)); if (vertexBuffer.Indices != null) { context.InputAssembler.SetIndexBuffer(vertexBuffer.Indices, SharpDX.DXGI.Format.R32_UInt, 0); } m_vertexBuffer = vertexBuffer; } } break; case RenderCommandType.ShaderVriable_Set: { var command = c as ShaderVariableSetCommand; m_pass.SetConstantVariable(command); } break; /* case RenderCommandType.ShaderTexture_Set: { var command = c as ShaderTextureSetCommand; var texture = m_resources.TextureManager.Get(command.ResourceID); if (texture != null) { m_pass.SetSRV(context, command.Key, texture.ShaderResourceView); } } break; case RenderCommandType.ShaderSampler_Set: { var command = c as ShaderSamplerSetCommand; Pass.SetSampler(command); } break; */ case RenderCommandType.Shader_Set: { var command = c as ShaderSetCommand; switch (command.ShaderStage) { case ShaderStage.Vertex: { var vertexShader = m_shaderManager.Get(command.ResourceID) as VertexShaderStage; if (vertexShader != null) { context.VertexShader.Set(vertexShader.Shader); //context.InputAssembler.InputLayout = vertexShader.VertexLayout; m_pass.VertexShader = vertexShader; } } break; case ShaderStage.Geometry: { var geometryShader = m_shaderManager.Get(command.ResourceID) as GeometryShaderStage; if (geometryShader != null) { context.GeometryShader.Set(geometryShader.Shader); m_pass.GeometryShader = geometryShader; } } break; case ShaderStage.Pixel: { var pixelShader = m_shaderManager.Get(command.ResourceID) as PixelShaderStage; if (pixelShader != null) { context.PixelShader.Set(pixelShader.Shader); m_pass.PixelShader = pixelShader; } } break; default: throw new NotImplementedException(); } } break; case RenderCommandType.Shader_DrawSubMesh: { var command = c as ShaderDrawSubMeshCommand; if (m_pass.VertexShader != null) { context.InputAssembler.InputLayout = m_pass.VertexShader.VertexLayout; // 定数バッファの適用 m_pass.Apply(context); if (m_vertexBuffer != null) { if (m_vertexBuffer.Indices != null) { context.DrawIndexed(command.Count, command.Offset, 0); } else { context.Draw(command.Count, command.Offset); } } } } break; /* case RenderCommandType.BlendState_Set: { var command = c as BlendStateSetCommand; var blendState = m_resources.BlendStateManager.Get(command.ResourceID); if (blendState == null) { return; } context.OutputMerger.SetBlendState(blendState.State, SharpDX.Color4.White); } break; case RenderCommandType.DepthStencilState_Set: { var command = c as DepthStencilStateSetCommand; var depthStencilState = m_resources.DepthStencilStateManager.Get(command.ResourceID); if (depthStencilState == null) { return; } context.OutputMerger.SetDepthStencilState(depthStencilState.State); } break; */ } } context.Flush(); } Backbuffer = null; RTV = null; ///////////////////////////////////////////////// // flip ///////////////////////////////////////////////// var flags = SharpDX.DXGI.PresentFlags.None; flags|=SharpDX.DXGI.PresentFlags.DoNotWait; SwapChain.Present(0, flags, new SharpDX.DXGI.PresentParameters()); }