public Camera() { // Set up default rendering Pass worldPass = new Pass(); Pass overlayPass = new Pass(); overlayPass.MatrixMode = RenderMatrix.OrthoScreen; overlayPass.ClearFlags = ClearFlag.None; overlayPass.VisibilityMask = VisibilityFlag.AllGroups | VisibilityFlag.ScreenOverlay; this.passes.Add(worldPass); this.passes.Add(overlayPass); }
public void Close(Pass pass) { if (pass.Expired) throw new ArgumentException("You cannot close the gate with an expired gate pass", "pass"); if (pass.ClosedTheGate) return; gateControlSemaphore.WaitOne(); if (!gateClosed) { gateSemaphore.WaitOne(); // This is safe if it is reordered by the compiler because the other wait above is followed by an immediate release. gateClosed = true; } numberOfGateClosers++; pass.ClosedTheGate = true; gateControlSemaphore.Release(); }
// ******************************************************************************** /// <summary> /// /// </summary> /// <param name="resource"></param> /// <param name="checker"></param> /// <returns></returns> /// <created>UPh,29.11.2015</created> /// <changed>UPh,29.11.2015</changed> // ******************************************************************************** public override uint BeginCheckTokens(Pass.AddIn.Core.CPAIResource resource, Pass.AddIn.Core.CPAITokenCheck checker) { if (_AddInComponent == null) { _AddInComponent = AddInInstance as EasyTermAddInComponent; if (_AddInComponent == null) return 0; _TermBaseSet = _AddInComponent._TermBaseSet; if (_TermBaseSet == null) return 0; _Query = _TermBaseSet.Query; } bCheckTermUsage = false; bCheckProhibitedTerms = false; if (_Query == null) return 0; var stringlist = checker.GetStringList(); if (stringlist == null) return 0; var listinfo = stringlist.GetListInfo(); if (listinfo == null) return 0; checker.GetOption(PslConstant.TCO_CUSTOM_0, ref bCheckTermUsage); checker.GetOption(PslConstant.TCO_CUSTOM_1, ref bCheckProhibitedTerms); if (!bCheckProhibitedTerms && !bCheckTermUsage) return 0; _Query.SetLanguagePair(listinfo.Lang1, listinfo.Lang2); return 0; }
public void Execute_RewritesHtml_TagHelper() { // Arrange var document = CreateDocument(@" @addTagHelper ""*, test"" <html> <test> <head cool=""beans""> Hello, World! </head> </test> </html>"); var documentNode = Lower(document); // Act Pass.Execute(document, documentNode); // Assert var method = documentNode.FindPrimaryMethod(); Assert.Collection( method.Children, c => Assert.IsType <CSharpCodeIntermediateNode>(c), c => NodeAssert.Whitespace(c), c => Assert.IsType <DirectiveIntermediateNode>(c), c => NodeAssert.Element(c, "html")); var html = NodeAssert.Element(method.Children[3], "html"); Assert.Equal(27, html.Source.Value.AbsoluteIndex); Assert.Equal(2, html.Source.Value.LineIndex); Assert.Equal(0, html.Source.Value.CharacterIndex); Assert.Equal(95, html.Source.Value.Length); Assert.Collection( html.Children, c => NodeAssert.Whitespace(c), c => Assert.IsType <TagHelperIntermediateNode>(c), c => NodeAssert.Whitespace(c)); var body = html.Children .OfType <TagHelperIntermediateNode>().Single().Children .OfType <TagHelperBodyIntermediateNode>().Single(); Assert.Collection( body.Children, c => NodeAssert.Whitespace(c), c => NodeAssert.Element(c, "head"), c => NodeAssert.Whitespace(c)); var head = body.Children[1]; Assert.Equal(49, head.Source.Value.AbsoluteIndex); Assert.Equal(4, head.Source.Value.LineIndex); Assert.Equal(4, head.Source.Value.CharacterIndex); Assert.Equal(53, head.Source.Value.Length); Assert.Collection( head.Children, c => NodeAssert.Attribute(c, "cool", "beans"), c => NodeAssert.Content(c, "Hello, World!")); }
private void DepthPrePass(StandardFrameData frameData, DepthStencilView depthStencilView, RenderTargetView renderTargetView) { CurrentPass = Pass.DepthPrePass; // Setup targets and states GetContext.OutputMerger.SetTargets(depthStencilView, (RenderTargetView)null); SetDepthStencilState(DepthStencilStates.Greater); SetRasterizerState(RasterizerStates.SolidBackCull); GetContext.InputAssembler.InputLayout = GetSharedItems.StandardInputLayout; // Setup vertex shader SetVertexShader("ForwardPlusPosOnlyVS"); // Cleanup pixel shader SetNullPixelShader(); m_PerFrameConstBuffer = new CommonStructs.ConstBufferPerFrameStruct() { Projection = frameData.CamerasList[0].Projection, ProjectionInv = Matrix.Invert(frameData.CamerasList[0].Projection), CameraPos = frameData.CamerasList[0].Position, AlphaTest = 0.5f, WindowWidth = (uint)GetDisplay.Width, WindowHeight = (uint)GetDisplay.Height, }; GetContext.UpdateSubresource(ref m_PerFrameConstBuffer, PerFrameConstantBuffer); string MeshName = ""; string MaterialName = ""; bool IsOpaquePass = true; foreach (var rendererData in frameData.RenderersList) { if (MeshName != rendererData.MeshName) { MeshName = rendererData.MeshName; SetMesh(MeshName); } if (MaterialName != rendererData.MaterialName) { MaterialName = rendererData.MaterialName; SetMaterial(MaterialName); if (IsOpaquePass) { if (CurrentMaterialInstance.MetaMaterial.blendMode == ShaderGraph.MetaMaterial.BlendMode.Masked) { GetContext.OutputMerger.SetTargets(depthStencilView, renderTargetView); SetRasterizerState(RasterizerStates.SolidNoneCull); GetContext.PixelShader.SetSampler(0, GetSharedItems.GetSamplerState(SamplerType.AnisotropicWrap)); //if (msaa) DepthOnlyAlphaToCoverageState SetBlendState(BlendStates.DepthOnlyAlphaTest); SetVertexShader("ForwardPlusPosTexVS"); SetPixelShader("ForwardPlusPosTexPS"); GetContext.PixelShader.SetShaderResource(0, GetSharedItems.LoadTextureSRV(CurrentMaterialInstance.AlbedoMapAsset)); GetContext.PixelShader.SetSampler(0, GetSharedItems.GetSamplerState(SamplerType.BilinearClamp)); IsOpaquePass = false; } } else { GetContext.PixelShader.SetShaderResource(0, GetSharedItems.LoadTextureSRV(CurrentMaterialInstance.AlbedoMapAsset)); } if (CurrentMaterialInstance.MetaMaterial.blendMode > ShaderGraph.MetaMaterial.BlendMode.Masked) { break; // Break on translucent objects } } m_PerObjectConstBuffer.WorldMatrix = rendererData.TransformMatrix; m_PerObjectConstBuffer.WorldViewMatrix = rendererData.TransformMatrix * frameData.CamerasList[0].View; m_PerObjectConstBuffer.WorldViewProjMatrix = rendererData.TransformMatrix * frameData.CamerasList[0].ViewProjection; m_PerObjectConstBuffer.textureTiling = CurrentMaterialInstance.PropetyBlock.Tile; m_PerObjectConstBuffer.textureShift = CurrentMaterialInstance.PropetyBlock.Shift; GetContext.UpdateSubresource(ref m_PerObjectConstBuffer, PerObjConstantBuffer); DX_DrawIndexed(m_CachedMesh.IndexCount, 0, 0); } }
// ******************************************************************************** /// <summary> /// /// </summary> /// <param name="token"></param> /// <param name="resource"></param> /// <param name="checker"></param> /// <returns></returns> /// <created>UPh,29.11.2015</created> /// <changed>UPh,29.11.2015</changed> // ******************************************************************************** public override uint CheckToken(CPAIToken token, Pass.AddIn.Core.CPAIResource resource, CPAITokenCheck checker) { if (!bCheckProhibitedTerms && !bCheckTermUsage) return 0; if (_Query == null) return 0; int nTranslated = (int) token.GetProperty(enmTokenProperties.StateTranslated); if (nTranslated == 0) { // Check source string string src = token.GetProperty(enmTokenProperties.Text, PropSelectionType.Source) as string; if (bCheckProhibitedTerms) { DoCheckProhibitedTerm(src, token, checker); } } else { // Check translation string string src = token.GetProperty(enmTokenProperties.Text, PropSelectionType.Source) as string; string trn = token.GetProperty(enmTokenProperties.Text, PropSelectionType.Target) as string; if (bCheckTermUsage) { DoCheckTermUsage(src, trn, token, checker); } if (bCheckProhibitedTerms) { DoCheckProhibitedTerm(trn, token, checker); } } return 0; }
public virtual void DrawModel(GLContext control, Pass pass, Vector4 highlightColor) { }
// Just override the mandatory create scene method public override void CreateScene() { // Set ambient light sceneMgr.AmbientLight = new ColourValue(0.2f, 0.2f, 0.2f); // Create a point light Light l = sceneMgr.CreateLight("MainLight"); // Accept default settings: point light, white diffuse, just set position // NB I could attach the light to a SceneNode if I wanted it to move automatically with // other objects, but I don't l.Type = Light.LightTypes.LT_DIRECTIONAL; l.SetDirection(-0.5f, -0.5f, 0); // Create patch patchDecl = HardwareBufferManager.Singleton.CreateVertexDeclaration(); patchDecl.AddElement(0, 0, VertexElementType.VET_FLOAT3, VertexElementSemantic.VES_POSITION); patchDecl.AddElement(0, sizeof(float)*3, VertexElementType.VET_FLOAT3, VertexElementSemantic.VES_NORMAL); patchDecl.AddElement(0, sizeof(float)*6, VertexElementType.VET_FLOAT2, VertexElementSemantic.VES_TEXTURE_COORDINATES, 0); // Make a 3x3 patch for test patchCtlPoints = new PatchVertex[9]; // Patch data patchCtlPoints[0] = new PatchVertex(); patchCtlPoints[0].x = -500.0f; patchCtlPoints[0].y = 200.0f; patchCtlPoints[0].z = -500.0f; patchCtlPoints[0].nx = -0.5f; patchCtlPoints[0].ny = 0.5f; patchCtlPoints[0].nz = 0.0f; patchCtlPoints[0].u = 0.0f; patchCtlPoints[0].v = 0.0f; patchCtlPoints[1] = new PatchVertex(); patchCtlPoints[1].x = 0.0f; patchCtlPoints[1].y = 500.0f; patchCtlPoints[1].z = -750.0f; patchCtlPoints[1].nx = 0.0f; patchCtlPoints[1].ny = 0.5f; patchCtlPoints[1].nz = 0.0f; patchCtlPoints[1].u = 0.5f; patchCtlPoints[1].v = 0.0f; patchCtlPoints[2] = new PatchVertex(); patchCtlPoints[2].x = 500.0f; patchCtlPoints[2].y = 1000.0f; patchCtlPoints[2].z = -500.0f; patchCtlPoints[2].nx = 0.5f; patchCtlPoints[2].ny = 0.5f; patchCtlPoints[2].nz = 0.0f; patchCtlPoints[2].u = 1.0f; patchCtlPoints[2].v = 0.0f; patchCtlPoints[3] = new PatchVertex(); patchCtlPoints[3].x = -500.0f; patchCtlPoints[3].y = 0.0f; patchCtlPoints[3].z = 0.0f; patchCtlPoints[3].nx = -0.5f; patchCtlPoints[3].ny = 0.5f; patchCtlPoints[3].nz = 0.0f; patchCtlPoints[3].u = 0.0f; patchCtlPoints[3].v = 0.5f; patchCtlPoints[4] = new PatchVertex(); patchCtlPoints[4].x = 0.0f; patchCtlPoints[4].y = 500.0f; patchCtlPoints[4].z = 0.0f; patchCtlPoints[4].nx = 0.0f; patchCtlPoints[4].ny = 0.5f; patchCtlPoints[4].nz = 0.0f; patchCtlPoints[4].u = 0.5f; patchCtlPoints[4].v = 0.5f; patchCtlPoints[5] = new PatchVertex(); patchCtlPoints[5].x = 500.0f; patchCtlPoints[5].y = -50.0f; patchCtlPoints[5].z = 0.0f; patchCtlPoints[5].nx = 0.5f; patchCtlPoints[5].ny = 0.5f; patchCtlPoints[5].nz = 0.0f; patchCtlPoints[5].u = 1.0f; patchCtlPoints[5].v = 0.5f; patchCtlPoints[6] = new PatchVertex(); patchCtlPoints[6].x = -500.0f; patchCtlPoints[6].y = 0.0f; patchCtlPoints[6].z = 500.0f; patchCtlPoints[6].nx = -0.5f; patchCtlPoints[6].ny = 0.5f; patchCtlPoints[6].nz = 0.0f; patchCtlPoints[6].u = 0.0f; patchCtlPoints[6].v = 1.0f; patchCtlPoints[7] = new PatchVertex(); patchCtlPoints[7].x = 0.0f; patchCtlPoints[7].y = 500.0f; patchCtlPoints[7].z = 500.0f; patchCtlPoints[7].nx = 0.0f; patchCtlPoints[7].ny = 0.5f; patchCtlPoints[7].nz = 0.0f; patchCtlPoints[7].u = 0.5f; patchCtlPoints[7].v = 1.0f; patchCtlPoints[8] = new PatchVertex(); patchCtlPoints[8].x = 500.0f; patchCtlPoints[8].y = 200.0f; patchCtlPoints[8].z = 800.0f; patchCtlPoints[8].nx = 0.5f; patchCtlPoints[8].ny = 0.5f; patchCtlPoints[8].nz = 0.0f; patchCtlPoints[8].u = 1.0f; patchCtlPoints[8].v = 1.0f; patch = MeshManager.Singleton.CreateBezierPatch( "Bezier1", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, patchCtlPoints, patchDecl, 3, 3, 5, 5, PatchSurface.VisibleSide.VS_BOTH, HardwareVertexBuffer.Usage.HBU_STATIC_WRITE_ONLY, HardwareIndexBuffer.Usage.HBU_DYNAMIC_WRITE_ONLY, true, true); // Start patch at 0 detail patch.SetSubdivision(0.0f); // Create entity based on patch Entity patchEntity = sceneMgr.CreateEntity("Entity1", "Bezier1"); MaterialPtr pMat = MaterialManager.Singleton.Create("TextMat", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME); pMat.GetTechnique(0).GetPass(0).CreateTextureUnitState( "BumpyMetal.jpg" ); patchEntity.SetMaterialName("TextMat"); patchPass = pMat.GetTechnique(0).GetPass(0); // Attach the entity to the root of the scene sceneMgr.RootSceneNode.AttachObject(patchEntity); camera.SetPosition(500,500, 1500); camera.LookAt(0,200,-300); }
void SubscribePassToRenderObjectPassEvent( Pass pass ) { if( subscribedPassesForRenderObjectPass == null ) subscribedPassesForRenderObjectPass = new List<Pass>(); if( !subscribedPassesForRenderObjectPass.Contains( pass ) ) { pass.RenderObjectPass += Pass_RenderObjectPass; subscribedPassesForRenderObjectPass.Add( pass ); } }
public virtual void WriteInstance(MaterialSerializer ser, SubRenderState subRenderState, Pass srcPass, Pass dstPass) { }
private void RenderSinglePass(Rect viewportRect, Pass p) { this.drawDevice.VisibilityMask = this.visibilityMask & p.VisibilityMask; this.drawDevice.RenderMode = p.MatrixMode; this.drawDevice.Target = p.Output; this.drawDevice.ViewportRect = p.Output.IsAvailable ? new Rect(p.Output.Res.Width, p.Output.Res.Height) : viewportRect; if (p.Input == null) { // Render Scene this.drawDevice.BeginRendering(p.ClearFlags, p.ClearColor, p.ClearDepth, p.Output.IsAvailable ? false : UseViewportScaling); try { this.CollectDrawcalls(); p.NotifyCollectDrawcalls(this.drawDevice); } catch (Exception e) { Log.Core.WriteError("There was an error while {0} was collecting drawcalls: {1}", this.ToString(), Log.Exception(e)); } this.drawDevice.EndRendering(); } else { Profile.TimePostProcessing.BeginMeasure(); this.drawDevice.BeginRendering(p.ClearFlags, p.ClearColor, p.ClearDepth, !p.Output.IsAvailable && UseViewportScaling); Texture mainTex = p.Input.MainTexture.Res; Vector2 uvRatio = mainTex != null ? mainTex.UVRatio : Vector2.One; Rect targetRect = new Rect(this.drawDevice.TargetSize); IDrawDevice device = this.drawDevice; device.AddVertices(p.Input, VertexMode.Quads, new VertexC1P3T2(targetRect.MinimumX, targetRect.MinimumY, 0.0f, 0.0f, 0.0f), new VertexC1P3T2(targetRect.MaximumX, targetRect.MinimumY, 0.0f, uvRatio.X, 0.0f), new VertexC1P3T2(targetRect.MaximumX, targetRect.MaximumY, 0.0f, uvRatio.X, uvRatio.Y), new VertexC1P3T2(targetRect.MinimumX, targetRect.MaximumY, 0.0f, 0.0f, uvRatio.Y)); this.drawDevice.EndRendering(); Profile.TimePostProcessing.EndMeasure(); } }
ThisFinder(Pass parent) : base(parent) { }
public void Handle(SelectedPassEventModel message) { _getPass = message.SelectedPass; }
void Run(Pass pass) { using (Log.StartProfiler(pass.GetType())) pass.Run(); }
public void AddTransform(Pass pass) { _transforms.Add(pass); }
public void AddGenerator(Pass pass) { _generators.Add(pass); }
/// <summary> /// Loads objects from TextScene file into the currently open scene. /// </summary> public bool LoadScene(string path) { try { StreamReader fileStream = File.OpenText(path); gameObjects = new Queue<GameObject>(); gameComponents = new Queue<Component>(); SetupBuiltinMeshes(); //We're doing this in two passes - first pass simply creates all objects and //components, the second pass resolves links and assigns them (the second pass //is necessary for in-scene links, so we're just handling everything in there, //even prefab and other asset links). currentPass = Pass.CreateObjects; Deserialize(fileStream, container); fileStream.Close(); GameObject[] gameObjectArray = gameObjects.ToArray(); Component[] gameComponentArray = gameComponents.ToArray(); fileStream = File.OpenText(path); currentPass = Pass.ValueAssignment; Deserialize(fileStream, container); fileStream.Close(); //Don't let the user edit scene-in-scenes (aka prefabs), since //we currently have no way of applying changes. if (container != null) { foreach (GameObject go in gameObjectArray) go.hideFlags = HideFlags.NotEditable; foreach (Component comp in gameComponentArray) comp.hideFlags = HideFlags.NotEditable; } } catch (System.Exception e) { Debug.LogError("Exception raised when loading level: " + path + " " + e.ToString()); return false; } return true; }
public virtual SubRenderState CreateInstance(ScriptCompiler compiler, PropertyAbstractNode prop, Pass pass, SGScriptTranslator stranslator) { return(null); }
// ******************************************************************************** /// <summary> /// /// </summary> /// <param name="nIndex"></param> /// <param name="toolInfo"></param> /// <returns></returns> /// <created>UPh,29.11.2015</created> /// <changed>UPh,29.11.2015</changed> // ******************************************************************************** public override uint GetToolInfo(int nIndex, ref Pass.AddIn.Core.CPAIToolInfo toolInfo) { return 1; }
/// <summary> /// /// </summary> /// <param name="group"></param> /// <param name="entity"></param> protected ImpostorTexture(ImpostorPage group, Entity entity) { //Store scene manager and entity mSceneMgr = group.SceneManager; mEntity = entity; //Add self to list of ImpostorTexture's mEntityKey = ImpostorBatch.GenerateEntityKey(entity); mSelfList.Add(mEntityKey, this); //Calculate the entity's bounding box and it's diameter mBoundingBox = entity.BoundingBox; //Note - this radius calculation assumes the object is somewhat rounded (like trees/rocks/etc.) float tmp = 0; mEntityRadius = mBoundingBox.Maximum.x - mBoundingBox.Center.x; tmp = mBoundingBox.Maximum.y - mBoundingBox.Center.y; if (tmp > mEntityRadius) { mEntityRadius = tmp; } tmp = mBoundingBox.Maximum.z - mBoundingBox.Center.z; if (tmp > mEntityRadius) { mEntityRadius = tmp; } mEntityDiameter = 2.0f * mEntityRadius; mEntityCenter = mBoundingBox.Center; //Render impostor textures RenderTextures(false); //Set up materials for (int o = 0; o < ImpostorYawAngles; o++) { for (int i = 0; i < ImpostorPitchAngles; i++) { mMaterial[i, o] = (Material)MaterialManager.Instance.Create(GetUniqueID("ImpostorMaterial"), "Impostors"); Material m = mMaterial[i, o]; Pass p = m.GetTechnique(0).GetPass(0); TextureUnitState t = p.CreateTextureUnitState(mTexture.Name); t.TextureScrollU = (float)(o / ImpostorYawAngles); t.TextureScrollV = (float)(i / ImpostorPitchAngles); p.LightingEnabled = false; m.ReceiveShadows = false; if (group.BlendMode == ImpostorBlendMode.AlphaReject) { p.AlphaRejectFunction = CompareFunction.GreaterEqual; p.AlphaRejectValue = 128; } else if (group.BlendMode == ImpostorBlendMode.AlphaBlend) { p.SetSceneBlending(SceneBlendFactor.SourceAlpha, SceneBlendFactor.OneMinusSourceAlpha); } } } }
public override void Draw(GL_ControlModern control, Pass pass, EditorSceneBase editorScene) { if (pass == Pass.TRANSPARENT) { return; } if (!ObjectRenderState.ShouldBeDrawn(this)) { return; } bool hovered = editorScene.Hovered == this; Matrix3 rotMtx = GlobalRotation; CurrentPosition = Selected ? editorScene.CurrentAction.NewPos(Position) : Position; control.UpdateModelMatrix( Matrix4.CreateScale((Selected ? editorScene.CurrentAction.NewScale(Scale, rotMtx) : Scale) * BoxScale) * new Matrix4(Selected ? editorScene.CurrentAction.NewRot(rotMtx) : rotMtx) * Matrix4.CreateTranslation(CurrentPosition)); Vector4 blockColor; Vector4 lineColor; if (hovered && Selected) { lineColor = hoverSelectColor; } else if (Selected) { lineColor = selectColor; } else if (hovered) { lineColor = hoverColor; } else { lineColor = Color; } if (hovered && Selected) { blockColor = Color * 0.5f + hoverSelectColor * 0.5f; } else if (Selected) { blockColor = Color * 0.5f + selectColor * 0.5f; } else if (hovered) { blockColor = Color * 0.5f + hoverColor * 0.5f; } else { blockColor = Color; } Renderers.ColorBlockRenderer.Draw(control, pass, blockColor, lineColor, control.NextPickingColor()); }
private static ActiveFields GetActiveFieldsFromMasterNode(AbstractMaterialNode iMasterNode, Pass pass) { var activeFields = new ActiveFields(); var baseActiveFields = activeFields.baseInstance; HairMasterNode masterNode = iMasterNode as HairMasterNode; if (masterNode == null) { return(activeFields); } if (masterNode.doubleSidedMode != DoubleSidedMode.Disabled) { if (pass.ShaderPassName != "SHADERPASS_MOTION_VECTORS") // HACK to get around lack of a good interpolator dependency system { // we need to be able to build interpolators using multiple input structs // also: should only require isFrontFace if Normals are required... // Important: the following is used in SharedCode.template.hlsl for determining the normal flip mode baseActiveFields.Add("FragInputs.isFrontFace"); } } switch (masterNode.materialType) { case HairMasterNode.MaterialType.KajiyaKay: baseActiveFields.Add("Material.KajiyaKay"); break; default: UnityEngine.Debug.LogError("Unknown material type: " + masterNode.materialType); break; } if (masterNode.alphaTest.isOn) { int count = 0; // If alpha test shadow is enable, we use it, otherwise we use the regular test if (pass.PixelShaderUsesSlot(HairMasterNode.AlphaClipThresholdShadowSlotId) && masterNode.alphaTestShadow.isOn) { baseActiveFields.Add("AlphaTestShadow"); ++count; } else if (pass.PixelShaderUsesSlot(HairMasterNode.AlphaClipThresholdSlotId)) { baseActiveFields.Add("AlphaTest"); ++count; } // Other alpha test are suppose to be alone else if (pass.PixelShaderUsesSlot(HairMasterNode.AlphaClipThresholdDepthPrepassSlotId)) { baseActiveFields.Add("AlphaTestPrepass"); ++count; } else if (pass.PixelShaderUsesSlot(HairMasterNode.AlphaClipThresholdDepthPostpassSlotId)) { baseActiveFields.Add("AlphaTestPostpass"); ++count; } UnityEngine.Debug.Assert(count == 1, "Alpha test value not set correctly"); } if (masterNode.surfaceType != SurfaceType.Opaque) { if (masterNode.transparencyFog.isOn) { baseActiveFields.Add("AlphaFog"); } if (masterNode.transparentWritesMotionVec.isOn) { baseActiveFields.Add("TransparentWritesMotionVec"); } if (masterNode.blendPreserveSpecular.isOn) { baseActiveFields.Add("BlendMode.PreserveSpecular"); } } if (!masterNode.receiveDecals.isOn) { baseActiveFields.Add("DisableDecals"); } if (!masterNode.receiveSSR.isOn) { baseActiveFields.Add("DisableSSR"); } if (masterNode.addPrecomputedVelocity.isOn) { baseActiveFields.Add("AddPrecomputedVelocity"); } if (masterNode.specularAA.isOn && pass.PixelShaderUsesSlot(HairMasterNode.SpecularAAThresholdSlotId) && pass.PixelShaderUsesSlot(HairMasterNode.SpecularAAScreenSpaceVarianceSlotId)) { baseActiveFields.Add("Specular.AA"); } if (masterNode.IsSlotConnected(HairMasterNode.BentNormalSlotId) && pass.PixelShaderUsesSlot(HairMasterNode.BentNormalSlotId)) { baseActiveFields.Add("BentNormal"); } if (masterNode.IsSlotConnected(HairMasterNode.HairStrandDirectionSlotId) && pass.PixelShaderUsesSlot(HairMasterNode.HairStrandDirectionSlotId)) { baseActiveFields.Add("HairStrandDirection"); } if (masterNode.IsSlotConnected(HairMasterNode.TransmittanceSlotId) && pass.PixelShaderUsesSlot(HairMasterNode.TransmittanceSlotId)) { baseActiveFields.Add(HairMasterNode.TransmittanceSlotName); } if (masterNode.IsSlotConnected(HairMasterNode.RimTransmissionIntensitySlotId) && pass.PixelShaderUsesSlot(HairMasterNode.RimTransmissionIntensitySlotId)) { baseActiveFields.Add(HairMasterNode.RimTransmissionIntensitySlotName); } if (masterNode.useLightFacingNormal.isOn) { baseActiveFields.Add("UseLightFacingNormal"); } switch (masterNode.specularOcclusionMode) { case SpecularOcclusionMode.Off: break; case SpecularOcclusionMode.FromAO: baseActiveFields.Add("SpecularOcclusionFromAO"); break; case SpecularOcclusionMode.FromAOAndBentNormal: baseActiveFields.Add("SpecularOcclusionFromAOBentNormal"); break; case SpecularOcclusionMode.Custom: baseActiveFields.Add("SpecularOcclusionCustom"); break; default: break; } if (pass.PixelShaderUsesSlot(HairMasterNode.AmbientOcclusionSlotId)) { var occlusionSlot = masterNode.FindSlot <Vector1MaterialSlot>(HairMasterNode.AmbientOcclusionSlotId); bool connected = masterNode.IsSlotConnected(HairMasterNode.AmbientOcclusionSlotId); if (connected || occlusionSlot.value != occlusionSlot.defaultValue) { baseActiveFields.Add("AmbientOcclusion"); } } if (masterNode.IsSlotConnected(HairMasterNode.LightingSlotId) && pass.PixelShaderUsesSlot(HairMasterNode.LightingSlotId)) { baseActiveFields.Add("LightingGI"); } if (masterNode.IsSlotConnected(HairMasterNode.BackLightingSlotId) && pass.PixelShaderUsesSlot(HairMasterNode.LightingSlotId)) { baseActiveFields.Add("BackLightingGI"); } if (masterNode.depthOffset.isOn && pass.PixelShaderUsesSlot(HairMasterNode.DepthOffsetSlotId)) { baseActiveFields.Add("DepthOffset"); } if (masterNode.supportLodCrossFade.isOn) { baseActiveFields.AddAll("LodCrossFade"); } // custom-begin: if (masterNode.dissolveOnOcclusion.isOn) { baseActiveFields.Add("DissolveOnOcclusion"); } // custom-end return(activeFields); }
void FixedPipelineAddDiffuseMapsToPass( Pass pass ) { for( int mapIndex = 1; mapIndex <= 4; mapIndex++ ) { MapItem map = null; switch( mapIndex ) { case 1: map = diffuse1Map; break; case 2: map = diffuse2Map; break; case 3: map = diffuse3Map; break; case 4: map = diffuse4Map; break; } if( !string.IsNullOrEmpty( map.Texture ) ) { TextureUnitState state = pass.CreateTextureUnitState( map.GetTextureFullPath(), (int)map.TexCoord ); if( map.Clamp ) state.SetTextureAddressingMode( TextureAddressingMode.Clamp ); if( projectiveTexturing && map.TexCoord == TexCoordIndexes.Projective ) state.SetProjectiveTexturing( projectiveTexturingFrustum ); if( map.textureUnitStatesForFixedPipeline == null ) map.textureUnitStatesForFixedPipeline = new List<TextureUnitState>(); map.textureUnitStatesForFixedPipeline.Add( state ); UpdateMapTransformForFixedPipeline( map ); if( mapIndex > 1 && mapIndex < 5 ) { DiffuseMapItem.MapBlendingTypes mapBlending = ( (DiffuseMapItem)map ).Blending; switch( mapBlending ) { case DiffuseMapItem.MapBlendingTypes.Add: state.SetColorOperation( LayerBlendOperation.Add ); break; case DiffuseMapItem.MapBlendingTypes.Modulate: state.SetColorOperation( LayerBlendOperation.Modulate ); break; case DiffuseMapItem.MapBlendingTypes.AlphaBlend: state.SetColorOperation( LayerBlendOperation.AlphaBlend ); break; } } } } }
public Pass(Pass copyFrom, BatchInfo inputOverride) { this.input = inputOverride; this.output = copyFrom.output; this.clearColor = copyFrom.clearColor; this.clearDepth = copyFrom.clearDepth; this.clearFlags = copyFrom.clearFlags; this.matrixMode = copyFrom.matrixMode; this.visibilityMask = copyFrom.visibilityMask; this.MakeAvailable(); }
// ******************************************************************************** /// <summary> /// /// </summary> /// <param name="resource"></param> /// <param name="checker"></param> /// <returns></returns> /// <created>UPh,29.11.2015</created> /// <changed>UPh,29.11.2015</changed> // ******************************************************************************** public override uint EndCheckTokens(Pass.AddIn.Core.CPAIResource resource, Pass.AddIn.Core.CPAITokenCheck checker) { return 0; }
public override void Draw(GL_ControlModern control, Pass pass, EditorSceneBase editorScene) { if ((isHoverPickPass && IsSelected())) { return; } if (!ObjectRenderState.ShouldBeDrawn(this)) { return; } bool hovered = this.Hovered; Matrix3 rotMtx = GlobalRotation; bool positionChanged = false; var position = Position; var scale = Scale; if (editorScene.ExclusiveAction != NoAction && hovered) { position = editorScene.ExclusiveAction.NewPos(Position, out positionChanged); scale = editorScene.ExclusiveAction.NewScale(Scale, rotMtx); } else if (Selected && editorScene.CurrentAction != NoAction) { position = editorScene.CurrentAction.NewPos(Position, out positionChanged); scale = editorScene.CurrentAction.NewScale(Scale, rotMtx); } //Not necessary to update position on picking pass //That will only cause more slowdown if (positionChanged && pass != Pass.PICKING) { var newPosition = OnPositionChanged(position); if (newPosition != position) { /* if (editorScene.ExclusiveAction is TranslateAction) * ((TranslateAction)editorScene.ExclusiveAction).SetAxisXZ(); * if (editorScene.CurrentAction is TranslateAction) * ((TranslateAction)editorScene.CurrentAction).SetAxisXZ();*/ } position = newPosition; } if (position != Translate) { Translate = position; } if (hovered) { scale *= 1.2f; } if (position.Length != 0 && RenderableConnectedPath.ScaleByCamera) { scale *= 1 + ((control.CameraTarget.Length / position.Length) * RenderableConnectedPath.CameraScaleFactor); } control.UpdateModelMatrix( Matrix4.CreateScale(scale * BoxScale) * new Matrix4(Selected ? editorScene.CurrentAction.NewRot(rotMtx) : rotMtx) * Matrix4.CreateTranslation(position)); Vector4 blockColor; Vector4 lineColor; if (hovered && Selected) { lineColor = hoverSelectColor; } else if (Selected) { lineColor = selectColor; } else if (hovered) { lineColor = hoverColor; } else { lineColor = Color; } if (hovered && Selected) { blockColor = Color * 0.5f + hoverSelectColor * 0.5f; } else if (Selected) { blockColor = Color * 0.5f + selectColor * 0.5f; } else if (hovered) { blockColor = Color * 0.5f + hoverColor * 0.5f; } else { blockColor = Color; } if (IsPointOver) { blockColor = Color * 0.5f + hoverSelectColor * 0.5f; } DrawModel(control, editorScene, pass, blockColor, lineColor); }
// Just override the mandatory create scene method public override void CreateScene() { // Set ambient light sceneMgr.AmbientLight = new ColourValue(0.2f, 0.2f, 0.2f); // Create a point light Light l = sceneMgr.CreateLight("MainLight"); // Accept default settings: point light, white diffuse, just set position // NB I could attach the light to a SceneNode if I wanted it to move automatically with // other objects, but I don't l.Type = Light.LightTypes.LT_DIRECTIONAL; l.SetDirection(-0.5f, -0.5f, 0); // Create patch patchDecl = HardwareBufferManager.Singleton.CreateVertexDeclaration(); patchDecl.AddElement(0, 0, VertexElementType.VET_FLOAT3, VertexElementSemantic.VES_POSITION); patchDecl.AddElement(0, sizeof(float) * 3, VertexElementType.VET_FLOAT3, VertexElementSemantic.VES_NORMAL); patchDecl.AddElement(0, sizeof(float) * 6, VertexElementType.VET_FLOAT2, VertexElementSemantic.VES_TEXTURE_COORDINATES, 0); // Make a 3x3 patch for test patchCtlPoints = new PatchVertex[9]; // Patch data patchCtlPoints[0] = new PatchVertex(); patchCtlPoints[0].x = -500.0f; patchCtlPoints[0].y = 200.0f; patchCtlPoints[0].z = -500.0f; patchCtlPoints[0].nx = -0.5f; patchCtlPoints[0].ny = 0.5f; patchCtlPoints[0].nz = 0.0f; patchCtlPoints[0].u = 0.0f; patchCtlPoints[0].v = 0.0f; patchCtlPoints[1] = new PatchVertex(); patchCtlPoints[1].x = 0.0f; patchCtlPoints[1].y = 500.0f; patchCtlPoints[1].z = -750.0f; patchCtlPoints[1].nx = 0.0f; patchCtlPoints[1].ny = 0.5f; patchCtlPoints[1].nz = 0.0f; patchCtlPoints[1].u = 0.5f; patchCtlPoints[1].v = 0.0f; patchCtlPoints[2] = new PatchVertex(); patchCtlPoints[2].x = 500.0f; patchCtlPoints[2].y = 1000.0f; patchCtlPoints[2].z = -500.0f; patchCtlPoints[2].nx = 0.5f; patchCtlPoints[2].ny = 0.5f; patchCtlPoints[2].nz = 0.0f; patchCtlPoints[2].u = 1.0f; patchCtlPoints[2].v = 0.0f; patchCtlPoints[3] = new PatchVertex(); patchCtlPoints[3].x = -500.0f; patchCtlPoints[3].y = 0.0f; patchCtlPoints[3].z = 0.0f; patchCtlPoints[3].nx = -0.5f; patchCtlPoints[3].ny = 0.5f; patchCtlPoints[3].nz = 0.0f; patchCtlPoints[3].u = 0.0f; patchCtlPoints[3].v = 0.5f; patchCtlPoints[4] = new PatchVertex(); patchCtlPoints[4].x = 0.0f; patchCtlPoints[4].y = 500.0f; patchCtlPoints[4].z = 0.0f; patchCtlPoints[4].nx = 0.0f; patchCtlPoints[4].ny = 0.5f; patchCtlPoints[4].nz = 0.0f; patchCtlPoints[4].u = 0.5f; patchCtlPoints[4].v = 0.5f; patchCtlPoints[5] = new PatchVertex(); patchCtlPoints[5].x = 500.0f; patchCtlPoints[5].y = -50.0f; patchCtlPoints[5].z = 0.0f; patchCtlPoints[5].nx = 0.5f; patchCtlPoints[5].ny = 0.5f; patchCtlPoints[5].nz = 0.0f; patchCtlPoints[5].u = 1.0f; patchCtlPoints[5].v = 0.5f; patchCtlPoints[6] = new PatchVertex(); patchCtlPoints[6].x = -500.0f; patchCtlPoints[6].y = 0.0f; patchCtlPoints[6].z = 500.0f; patchCtlPoints[6].nx = -0.5f; patchCtlPoints[6].ny = 0.5f; patchCtlPoints[6].nz = 0.0f; patchCtlPoints[6].u = 0.0f; patchCtlPoints[6].v = 1.0f; patchCtlPoints[7] = new PatchVertex(); patchCtlPoints[7].x = 0.0f; patchCtlPoints[7].y = 500.0f; patchCtlPoints[7].z = 500.0f; patchCtlPoints[7].nx = 0.0f; patchCtlPoints[7].ny = 0.5f; patchCtlPoints[7].nz = 0.0f; patchCtlPoints[7].u = 0.5f; patchCtlPoints[7].v = 1.0f; patchCtlPoints[8] = new PatchVertex(); patchCtlPoints[8].x = 500.0f; patchCtlPoints[8].y = 200.0f; patchCtlPoints[8].z = 800.0f; patchCtlPoints[8].nx = 0.5f; patchCtlPoints[8].ny = 0.5f; patchCtlPoints[8].nz = 0.0f; patchCtlPoints[8].u = 1.0f; patchCtlPoints[8].v = 1.0f; patch = MeshManager.Singleton.CreateBezierPatch( "Bezier1", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, patchCtlPoints, patchDecl, 3, 3, 5, 5, PatchSurface.VisibleSide.VS_BOTH, HardwareVertexBuffer.Usage.HBU_STATIC_WRITE_ONLY, HardwareIndexBuffer.Usage.HBU_DYNAMIC_WRITE_ONLY, true, true); // Start patch at 0 detail patch.SetSubdivision(0.0f); // Create entity based on patch Entity patchEntity = sceneMgr.CreateEntity("Entity1", "Bezier1"); MaterialPtr pMat = MaterialManager.Singleton.Create("TextMat", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME); pMat.GetTechnique(0).GetPass(0).CreateTextureUnitState("BumpyMetal.jpg"); patchEntity.SetMaterialName("TextMat"); patchPass = pMat.GetTechnique(0).GetPass(0); // Attach the entity to the root of the scene sceneMgr.RootSceneNode.AttachObject(patchEntity); camera.SetPosition(500, 500, 1500); camera.LookAt(0, 200, -300); }
private void CreateShaderMaterials(Quake3Level q3lvl, SceneManager sm) { // NB this only works for the 'default' shaders for now // i.e. those that don't have a .shader script and thus default // to just texture + lightmap // TODO: pre-parse all .shader files and create lookup for next stage (use ROGL shader_file_t) // Material names are shadername#lightmapnumber // This is because I like to define materials up front completely // rather than combine lightmap and shader dynamically (it's // more generic). It results in more materials, but they're small // beer anyway. Texture duplication is prevented by infrastructure. // To do this I actually need to parse the faces since they have the // shader/lightmap combo (lightmap number is not in the shader since // it can be used with multiple lightmaps) string shaderName; int face = q3lvl.Faces.Length; while (face-- > 0) { // Check to see if existing material // Format shader#lightmap int shadIdx = q3lvl.Faces[face].shader; shaderName = String.Format("{0}#{1}", q3lvl.Shaders[shadIdx].name, q3lvl.Faces[face].lmTexture); Material shadMat = sm.GetMaterial(shaderName); if (shadMat == null && !bspOptions.useLightmaps) { // try the no-lightmap material shaderName = String.Format("{0}#n", q3lvl.Shaders[shadIdx].name); shadMat = sm.GetMaterial(shaderName); } if (shadMat == null) { // Colour layer // NB no extension in Q3A(doh), have to try shader, .jpg, .tga string tryName = q3lvl.Shaders[shadIdx].name; // Try shader first Quake3Shader shader = (Quake3Shader)Quake3ShaderManager.Instance.GetByName(tryName); if (shader != null) { shadMat = shader.CreateAsMaterial(sm, q3lvl.Faces[face].lmTexture); } else { // No shader script, try default type texture shadMat = sm.CreateMaterial(shaderName); Pass shadPass = shadMat.GetTechnique(0).GetPass(0); // Try jpg TextureUnitState tex = shadPass.CreateTextureUnitState(tryName + ".jpg"); tex.Load(); if (tex.IsBlank) { // Try tga tex.SetTextureName(tryName + ".tga"); } // Set replace on all first layer textures for now tex.SetColorOperation(LayerBlendOperation.Replace); tex.TextureAddressing = TextureAddressing.Wrap; // for ambient lighting tex.ColorBlendMode.source2 = LayerBlendSource.Manual; if (bspOptions.useLightmaps && q3lvl.Faces[face].lmTexture != -1) { // Add lightmap, additive blending tex = shadPass.CreateTextureUnitState(String.Format("@lightmap{0}", q3lvl.Faces[face].lmTexture)); // Blend tex.SetColorOperation(LayerBlendOperation.Modulate); // Use 2nd texture co-ordinate set tex.TextureCoordSet = 1; // Clamp tex.TextureAddressing = TextureAddressing.Clamp; } shadMat.CullingMode = CullingMode.None; shadMat.Lighting = false; } } shadMat.Load(); // Copy face data BspStaticFaceGroup dest = CopyShaderFaceData(q3lvl, face, shadMat, shadIdx); faceGroups[face] = dest; } }
/// <summary> /// Unregister cloud pass /// </summary> public void Unregister() { if (_cloudLayerPass != null) { _cloudLayerPass.Parent.RemovePass(_cloudLayerPass.Index); _cloudLayerPass = null; } }
private static ActiveFields GetActiveFieldsFromMasterNode(AbstractMaterialNode iMasterNode, Pass pass) { var activeFields = new ActiveFields(); var baseActiveFields = activeFields.baseInstance; HDUnlitMasterNode masterNode = iMasterNode as HDUnlitMasterNode; if (masterNode == null) { return(activeFields); } if (masterNode.IsSlotConnected(HDUnlitMasterNode.VertexNormalSlotId)) { baseActiveFields.Add("AttributesMesh.normalOS"); } if (masterNode.alphaTest.isOn && pass.PixelShaderUsesSlot(HDUnlitMasterNode.AlphaThresholdSlotId)) { baseActiveFields.Add("AlphaTest"); } if (masterNode.surfaceType != SurfaceType.Opaque) { if (masterNode.transparencyFog.isOn) { baseActiveFields.Add("AlphaFog"); } } if (masterNode.addPrecomputedVelocity.isOn) { baseActiveFields.Add("AddPrecomputedVelocity"); } if (masterNode.enableShadowMatte.isOn) { baseActiveFields.Add("EnableShadowMatte"); } return(activeFields); }
public virtual void DrawModel(GL_ControlModern control, EditorSceneBase editorScene, Pass pass, Vector4 blockColor, Vector4 lineColor) { bool xray = RenderableConnectedPath.XRayMode; ColorSphereRenderer.Draw(control, pass, blockColor, lineColor, xray); }
private static void AddPixelShaderSlotsForWriteNormalBufferPasses(StackLitMasterNode masterNode, ref Pass pass) { // See StackLit.hlsl:ConvertSurfaceDataToNormalData() // Note: We remove the slots we're adding as the editor will constantly regenerate the shader but // without recreating the nodes thus the passes in the subshader object. if (masterNode.coat.isOn) { // Check ConvertSurfaceDataToNormalData, in this case, we only need those: pass.PixelShaderSlots.Remove(StackLitMasterNode.CoatSmoothnessSlotId); pass.PixelShaderSlots.Add(StackLitMasterNode.CoatSmoothnessSlotId); pass.PixelShaderSlots.Remove(StackLitMasterNode.CoatNormalSlotId); pass.PixelShaderSlots.Add(StackLitMasterNode.CoatNormalSlotId); } else { pass.PixelShaderSlots.Remove(StackLitMasterNode.NormalSlotId); pass.PixelShaderSlots.Add(StackLitMasterNode.NormalSlotId); pass.PixelShaderSlots.Remove(StackLitMasterNode.LobeMixSlotId); pass.PixelShaderSlots.Add(StackLitMasterNode.LobeMixSlotId); pass.PixelShaderSlots.Remove(StackLitMasterNode.SmoothnessASlotId); pass.PixelShaderSlots.Add(StackLitMasterNode.SmoothnessASlotId); pass.PixelShaderSlots.Remove(StackLitMasterNode.SmoothnessBSlotId); pass.PixelShaderSlots.Add(StackLitMasterNode.SmoothnessBSlotId); } // Also, when geometricSpecularAA.isOn, might want to add SpecularAAScreenSpaceVarianceSlotId and SpecularAAThresholdSlotId, // since they affect smoothnesses in surfaceData directly. This is an implicit behavior for Lit, via the GBuffer pass. // Versus performance, might not be important for what it is used for, but SSR uses the roughness too so for now, // add them. if (masterNode.geometricSpecularAA.isOn) // TODOTODO || Normal Map Filtering is on { pass.PixelShaderSlots.Remove(StackLitMasterNode.SpecularAAScreenSpaceVarianceSlotId); pass.PixelShaderSlots.Add(StackLitMasterNode.SpecularAAScreenSpaceVarianceSlotId); pass.PixelShaderSlots.Remove(StackLitMasterNode.SpecularAAThresholdSlotId); pass.PixelShaderSlots.Add(StackLitMasterNode.SpecularAAThresholdSlotId); } }
internal Texture(Pass pass, ReadOnlySpan <Float4> data, Vector2I size) { Pass = pass; Data = data; Size = size; }
// // Reference for GetActiveFieldsFromMasterNode // ------------------------------------------- // // Properties (enables etc): // // ok+MFD -> material feature define: means we need a predicate, because we will transform it into a #define that match the material feature, shader_feature-defined, that the rest of the shader code uses. // // ok+MFD masterNode.baseParametrization --> even though we can just always transfer present fields (check with $SurfaceDescription.*) like specularcolor and metallic, // we need to translate this into the _MATERIAL_FEATURE_SPECULAR_COLOR define. // // ok masterNode.energyConservingSpecular // // ~~~~ ok+MFD: these are almost all material features: // masterNode.anisotropy // masterNode.coat // masterNode.coatNormal // masterNode.dualSpecularLobe // masterNode.dualSpecularLobeParametrization // masterNode.capHazinessWrtMetallic -> not a material feature define, as such, we will create a combined predicate for the HazyGlossMaxDielectricF0 slot dependency // instead of adding a #define in the template... // masterNode.iridescence // masterNode.subsurfaceScattering // masterNode.transmission // // ~~~~ ...ok+MFD: these are all material features // // ok masterNode.receiveDecals // ok masterNode.receiveSSR // ok masterNode.geometricSpecularAA --> check, a way to combine predicates and/or exclude passes: TODOTODO What about WRITE_NORMAL_BUFFER passes ? (ie smoothness) // ok masterNode.specularOcclusion --> no use for it though! see comments. // // ~~~~ ok+D: these require translation to defines also... // // masterNode.anisotropyForAreaLights // masterNode.recomputeStackPerLight // masterNode.shadeBaseUsingRefractedAngles // masterNode.debug // Inputs: Most inputs don't need a specific predicate in addition to the "present field predicate", ie the $SurfaceDescription.*, // but in some special cases we check connectivity to avoid processing the default value for nothing... // (see specular occlusion with _MASKMAP and _BENTNORMALMAP in LitData, or _TANGENTMAP, _BENTNORMALMAP, etc. which act a bit like that // although they also avoid sampling in that case, but default tiny texture map sampling isn't a big hit since they are all cached once // a default "unityTexWhite" is sampled, it is cached for everyone defaulting to white...) // // ok+ means there's a specific additional predicate // // ok masterNode.BaseColorSlotId // ok masterNode.NormalSlotId // // ok+ masterNode.BentNormalSlotId --> Dependency of the predicate on IsSlotConnected avoids processing even if the slots // ok+ masterNode.TangentSlotId are always there so any pass that declares its use in PixelShaderSlots will have the field in SurfaceDescription, // but it's not necessarily useful (if slot isnt connected, waste processing on potentially static expressions if // shader compiler cant optimize...and even then, useless to have static override value for those.) // // TODOTODO: Note you could have the same argument for NormalSlot (which we dont exclude with a predicate). // Also and anyways, the compiler is smart enough not to do the TS to WS matrix multiply on a (0,0,1) vector. // // ok+ masterNode.CoatNormalSlotId -> we already have a "material feature" coat normal map so can use that instead, although using that former, we assume the coat normal slot // will be there, but it's ok, we can #ifdef the code on the material feature define, and use the $SurfaceDescription.CoatNormal predicate // for the actual assignment, // although for that one we could again // use the "connected" condition like for tangent and bentnormal // // The following are all ok, no need beyond present field predicate, ie $SurfaceDescription.*, // except special cases where noted // // ok masterNode.SubsurfaceMaskSlotId // ok masterNode.ThicknessSlotId // ok masterNode.DiffusionProfileHashSlotId // ok masterNode.IridescenceMaskSlotId // ok masterNode.IridescenceThicknessSlotId // ok masterNode.SpecularColorSlotId // ok masterNode.DielectricIorSlotId // ok masterNode.MetallicSlotId // ok masterNode.EmissionSlotId // ok masterNode.SmoothnessASlotId // ok masterNode.SmoothnessBSlotId // ok+ masterNode.AmbientOcclusionSlotId -> defined a specific predicate, but not used, see StackLitData. // ok masterNode.AlphaSlotId // ok masterNode.AlphaClipThresholdSlotId // ok masterNode.AnisotropyASlotId // ok masterNode.AnisotropyBSlotId // ok masterNode.SpecularAAScreenSpaceVarianceSlotId // ok masterNode.SpecularAAThresholdSlotId // ok masterNode.CoatSmoothnessSlotId // ok masterNode.CoatIorSlotId // ok masterNode.CoatThicknessSlotId // ok masterNode.CoatExtinctionSlotId // ok masterNode.LobeMixSlotId // ok masterNode.HazinessSlotId // ok masterNode.HazeExtentSlotId // ok masterNode.HazyGlossMaxDielectricF0SlotId -> No need for a predicate, the needed predicate is the combined (capHazinessWrtMetallic + HazyGlossMaxDielectricF0) // "leaking case": if the 2 are true, but we're not in metallic mode, the capHazinessWrtMetallic property is wrong, // that means the master node is really misconfigured, spew an error, should never happen... // If it happens, it's because we forgot UpdateNodeAfterDeserialization() call when modifying the capHazinessWrtMetallic or baseParametrization // properties, maybe through debug etc. // // ok masterNode.DistortionSlotId -> Warning: peculiarly, instead of using $SurfaceDescription.Distortion and DistortionBlur, // ok masterNode.DistortionBlurSlotId we do an #if (SHADERPASS == SHADERPASS_DISTORTION) in the template, instead of // relying on other passed NOT to include the DistortionSlotId in their PixelShaderSlots!! // Other to deal with, and // Common between Lit and StackLit: // // doubleSidedMode, alphaTest, receiveDecals, // surfaceType, alphaMode, blendPreserveSpecular, transparencyFog, // distortion, distortionMode, distortionDepthTest, // sortPriority (int) // geometricSpecularAA, energyConservingSpecular, specularOcclusion // private static ActiveFields GetActiveFieldsFromMasterNode(AbstractMaterialNode iMasterNode, Pass pass) { var activeFields = new ActiveFields(); var baseActiveFields = activeFields.baseInstance; StackLitMasterNode masterNode = iMasterNode as StackLitMasterNode; if (masterNode == null) { return(activeFields); } if (masterNode.doubleSidedMode != DoubleSidedMode.Disabled) { if (pass.ShaderPassName != "SHADERPASS_MOTION_VECTORS") // HACK to get around lack of a good interpolator dependency system { // we need to be able to build interpolators using multiple input structs // also: should only require isFrontFace if Normals are required... // Important: the following is used in SharedCode.template.hlsl for determining the normal flip mode baseActiveFields.Add("FragInputs.isFrontFace"); } } if (masterNode.alphaTest.isOn) { if (pass.PixelShaderUsesSlot(StackLitMasterNode.AlphaClipThresholdSlotId)) { baseActiveFields.Add("AlphaTest"); } } if (masterNode.surfaceType != SurfaceType.Opaque) { if (masterNode.transparencyFog.isOn) { baseActiveFields.Add("AlphaFog"); } if (masterNode.blendPreserveSpecular.isOn) { baseActiveFields.Add("BlendMode.PreserveSpecular"); } } switch (masterNode.normalDropOffSpace) { case NormalDropOffSpace.Tangent: baseActiveFields.AddAll("NormalDropOffTS"); break; case NormalDropOffSpace.Object: baseActiveFields.AddAll("NormalDropOffOS"); break; case NormalDropOffSpace.World: baseActiveFields.AddAll("NormalDropOffWS"); break; default: UnityEngine.Debug.LogError("Unknown normal drop off space: " + masterNode.normalDropOffSpace); break; } // // Predicates to change into defines: // // Even though we can just always transfer the present (check with $SurfaceDescription.*) fields like specularcolor // and metallic, we still need to know the baseParametrization in the template to translate into the // _MATERIAL_FEATURE_SPECULAR_COLOR define: if (masterNode.baseParametrization == StackLit.BaseParametrization.SpecularColor) { baseActiveFields.Add("BaseParametrization.SpecularColor"); } if (masterNode.energyConservingSpecular.isOn) // No defines, suboption of BaseParametrization.SpecularColor { baseActiveFields.Add("EnergyConservingSpecular"); } if (masterNode.anisotropy.isOn) { baseActiveFields.Add("Material.Anisotropy"); } if (masterNode.coat.isOn) { baseActiveFields.Add("Material.Coat"); if (pass.PixelShaderUsesSlot(StackLitMasterNode.CoatMaskSlotId)) { var coatMaskSlot = masterNode.FindSlot <Vector1MaterialSlot>(StackLitMasterNode.CoatMaskSlotId); bool connected = masterNode.IsSlotConnected(StackLitMasterNode.CoatMaskSlotId); if (connected || (coatMaskSlot.value != 0.0f && coatMaskSlot.value != 1.0f)) { baseActiveFields.Add("CoatMask"); } else if (coatMaskSlot.value == 0.0f) { baseActiveFields.Add("CoatMaskZero"); } else if (coatMaskSlot.value == 1.0f) { baseActiveFields.Add("CoatMaskOne"); } } } if (masterNode.coatNormal.isOn) { baseActiveFields.Add("Material.CoatNormal"); } if (masterNode.dualSpecularLobe.isOn) { baseActiveFields.Add("Material.DualSpecularLobe"); if (masterNode.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss) { baseActiveFields.Add("DualSpecularLobeParametrization.HazyGloss"); // Option for baseParametrization == Metallic && DualSpecularLobeParametrization == HazyGloss: if (masterNode.capHazinessWrtMetallic.isOn && pass.PixelShaderUsesSlot(StackLitMasterNode.HazyGlossMaxDielectricF0SlotId)) { // check the supporting slot is there (although masternode should deal with having a consistent property config) var maxDielectricF0Slot = masterNode.FindSlot <Vector1MaterialSlot>(StackLitMasterNode.HazyGlossMaxDielectricF0SlotId); if (maxDielectricF0Slot != null) { // Again we assume masternode has HazyGlossMaxDielectricF0 which should always be the case // if capHazinessWrtMetallic.isOn. baseActiveFields.Add("CapHazinessIfNotMetallic"); } } } } if (masterNode.iridescence.isOn) { baseActiveFields.Add("Material.Iridescence"); } if (masterNode.subsurfaceScattering.isOn && masterNode.surfaceType != SurfaceType.Transparent) { baseActiveFields.Add("Material.SubsurfaceScattering"); } if (masterNode.transmission.isOn) { baseActiveFields.Add("Material.Transmission"); } // Advanced: if (masterNode.anisotropyForAreaLights.isOn) { baseActiveFields.Add("AnisotropyForAreaLights"); } if (masterNode.recomputeStackPerLight.isOn) { baseActiveFields.Add("RecomputeStackPerLight"); } if (masterNode.honorPerLightMinRoughness.isOn) { baseActiveFields.Add("HonorPerLightMinRoughness"); } if (masterNode.shadeBaseUsingRefractedAngles.isOn) { baseActiveFields.Add("ShadeBaseUsingRefractedAngles"); } if (masterNode.debug.isOn) { baseActiveFields.Add("StackLitDebug"); } // // Other property predicates: // if (!masterNode.receiveDecals.isOn) { baseActiveFields.Add("DisableDecals"); } if (!masterNode.receiveSSR.isOn) { baseActiveFields.Add("DisableSSR"); } if (masterNode.addPrecomputedVelocity.isOn) { baseActiveFields.Add("AddPrecomputedVelocity"); } // Note here we combine an "enable"-like predicate and the $SurfaceDescription.(slotname) predicate // into a single $GeometricSpecularAA pedicate. // // ($SurfaceDescription.* predicates are useful to make sure the field is present in the struct in the template. // The field will be present if both the master node and pass have the slotid, see this set intersection we make // in GenerateSurfaceDescriptionStruct(), with HDSubShaderUtilities.FindMaterialSlotsOnNode().) // // Normally, since the feature enable adds the required slots, only the $SurfaceDescription.* would be required, // but some passes might not need it and not declare the PixelShaderSlot, or, inversely, the pass might not // declare it as a way to avoid it. // // IE this has also the side effect to disable geometricSpecularAA - even if "on" - for passes that don't explicitly // advertise these slots(eg for a general feature, with separate "enable" and "field present" predicates, the // template could take a default value and process it anyway if a feature is "on"). // // (Note we can achieve the same results in the template on just single predicates by making defines out of them, // and using #if defined() && etc) bool haveSomeSpecularAA = false; // TODOTODO in prevision of normal texture filtering if (masterNode.geometricSpecularAA.isOn && pass.PixelShaderUsesSlot(StackLitMasterNode.SpecularAAThresholdSlotId) && pass.PixelShaderUsesSlot(StackLitMasterNode.SpecularAAScreenSpaceVarianceSlotId)) { haveSomeSpecularAA = true; baseActiveFields.Add("GeometricSpecularAA"); } if (haveSomeSpecularAA) { baseActiveFields.Add("SpecularAA"); } if (masterNode.screenSpaceSpecularOcclusionBaseMode != StackLitMasterNode.SpecularOcclusionBaseMode.Off || masterNode.dataBasedSpecularOcclusionBaseMode != StackLitMasterNode.SpecularOcclusionBaseMode.Off) { // activates main define baseActiveFields.Add("SpecularOcclusion"); } baseActiveFields.Add("ScreenSpaceSpecularOcclusionBaseMode." + masterNode.screenSpaceSpecularOcclusionBaseMode.ToString()); if (StackLitMasterNode.SpecularOcclusionModeUsesVisibilityCone(masterNode.screenSpaceSpecularOcclusionBaseMode)) { baseActiveFields.Add("ScreenSpaceSpecularOcclusionAOConeSize." + masterNode.screenSpaceSpecularOcclusionAOConeSize.ToString()); baseActiveFields.Add("ScreenSpaceSpecularOcclusionAOConeDir." + masterNode.screenSpaceSpecularOcclusionAOConeDir.ToString()); } baseActiveFields.Add("DataBasedSpecularOcclusionBaseMode." + masterNode.dataBasedSpecularOcclusionBaseMode.ToString()); if (StackLitMasterNode.SpecularOcclusionModeUsesVisibilityCone(masterNode.dataBasedSpecularOcclusionBaseMode)) { baseActiveFields.Add("DataBasedSpecularOcclusionAOConeSize." + masterNode.dataBasedSpecularOcclusionAOConeSize.ToString()); } // Set bent normal fixup predicate if needed: if (masterNode.SpecularOcclusionUsesBentNormal()) { baseActiveFields.Add("SpecularOcclusionConeFixupMethod." + masterNode.specularOcclusionConeFixupMethod.ToString()); } // // Input special-casing predicates: // if (masterNode.IsSlotConnected(StackLitMasterNode.BentNormalSlotId) && pass.PixelShaderUsesSlot(StackLitMasterNode.BentNormalSlotId)) { baseActiveFields.Add("BentNormal"); } if (masterNode.IsSlotConnected(StackLitMasterNode.TangentSlotId) && pass.PixelShaderUsesSlot(StackLitMasterNode.TangentSlotId)) { baseActiveFields.Add("Tangent"); } // The following idiom enables an optimization on feature ports that don't have an enable switch in the settings // view, where the default value might not produce a visual result and incur a processing cost we want to avoid. // For ambient occlusion, this is the case for the SpecularOcclusion calculations which also depend on it, // where a value of 1 will produce no results. // See SpecularOcclusion, we don't optimize out this case... if (pass.PixelShaderUsesSlot(StackLitMasterNode.AmbientOcclusionSlotId)) { bool connected = masterNode.IsSlotConnected(StackLitMasterNode.AmbientOcclusionSlotId); var ambientOcclusionSlot = masterNode.FindSlot <Vector1MaterialSlot>(StackLitMasterNode.AmbientOcclusionSlotId); // master node always has it, assert ambientOcclusionSlot != null if (connected || ambientOcclusionSlot.value != ambientOcclusionSlot.defaultValue) { baseActiveFields.Add("AmbientOcclusion"); } } if (masterNode.IsSlotConnected(StackLitMasterNode.CoatNormalSlotId) && pass.PixelShaderUsesSlot(StackLitMasterNode.CoatNormalSlotId)) { baseActiveFields.Add("CoatNormal"); } if (masterNode.IsSlotConnected(StackLitMasterNode.LightingSlotId) && pass.PixelShaderUsesSlot(StackLitMasterNode.LightingSlotId)) { baseActiveFields.Add("LightingGI"); } if (masterNode.IsSlotConnected(StackLitMasterNode.BackLightingSlotId) && pass.PixelShaderUsesSlot(StackLitMasterNode.BackLightingSlotId)) { baseActiveFields.Add("BackLightingGI"); } if (masterNode.depthOffset.isOn && pass.PixelShaderUsesSlot(StackLitMasterNode.DepthOffsetSlotId)) { baseActiveFields.Add("DepthOffset"); } if (masterNode.supportLodCrossFade.isOn) { baseActiveFields.AddAll("LodCrossFade"); } return(activeFields); }
static string GetShaderPassFromTemplate(string template, ImageEffectMasterNode masterNode, Pass pass, GenerationMode mode, SurfaceMaterialOptions materialOptions) { // ----------------------------------------------------- // // SETUP // // ----------------------------------------------------- // // ------------------------------------- // String builders var shaderProperties = new PropertyCollector(); var functionBuilder = new ShaderStringBuilder(1); var functionRegistry = new FunctionRegistry(functionBuilder); var defines = new ShaderStringBuilder(1); var graph = new ShaderStringBuilder(0); var vertexDescriptionInputStruct = new ShaderStringBuilder(1); var vertexDescriptionStruct = new ShaderStringBuilder(1); var vertexDescriptionFunction = new ShaderStringBuilder(1); var surfaceDescriptionInputStruct = new ShaderStringBuilder(1); var surfaceDescriptionStruct = new ShaderStringBuilder(1); var surfaceDescriptionFunction = new ShaderStringBuilder(1); var vertexInputStruct = new ShaderStringBuilder(1); var vertexOutputStruct = new ShaderStringBuilder(2); var vertexShader = new ShaderStringBuilder(2); var vertexShaderDescriptionInputs = new ShaderStringBuilder(2); var vertexShaderOutputs = new ShaderStringBuilder(2); var pixelShader = new ShaderStringBuilder(2); var pixelShaderSurfaceInputs = new ShaderStringBuilder(2); var pixelShaderSurfaceRemap = new ShaderStringBuilder(2); // ------------------------------------- // Get Slot and Node lists per stage var vertexSlots = pass.VertexShaderSlots.Select(masterNode.FindSlot <MaterialSlot>).ToList(); var vertexNodes = ListPool <INode> .Get(); NodeUtils.DepthFirstCollectNodesFromNode(vertexNodes, masterNode, NodeUtils.IncludeSelf.Include, pass.VertexShaderSlots); var pixelSlots = pass.PixelShaderSlots.Select(masterNode.FindSlot <MaterialSlot>).ToList(); var pixelNodes = ListPool <INode> .Get(); NodeUtils.DepthFirstCollectNodesFromNode(pixelNodes, masterNode, NodeUtils.IncludeSelf.Include, pass.PixelShaderSlots); // ------------------------------------- // Get Requirements var vertexRequirements = ShaderGraphRequirements.FromNodes(vertexNodes, ShaderStageCapability.Vertex, false); var pixelRequirements = ShaderGraphRequirements.FromNodes(pixelNodes, ShaderStageCapability.Fragment); var graphRequirements = pixelRequirements.Union(vertexRequirements); var surfaceRequirements = ShaderGraphRequirements.FromNodes(pixelNodes, ShaderStageCapability.Fragment, false); var modelRequiements = ShaderGraphRequirements.none; modelRequiements.requiresNormal |= k_PixelCoordinateSpace; modelRequiements.requiresTangent |= k_PixelCoordinateSpace; modelRequiements.requiresBitangent |= k_PixelCoordinateSpace; modelRequiements.requiresPosition |= k_PixelCoordinateSpace; modelRequiements.requiresViewDir |= k_PixelCoordinateSpace; modelRequiements.requiresMeshUVs.Add(UVChannel.UV1); // ----------------------------------------------------- // // START SHADER GENERATION // // ----------------------------------------------------- // // ------------------------------------- // Calculate material options var blendingBuilder = new ShaderStringBuilder(1); var cullingBuilder = new ShaderStringBuilder(1); var zTestBuilder = new ShaderStringBuilder(1); var zWriteBuilder = new ShaderStringBuilder(1); // Cull Off ZWrite Off ZTest Always materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Off; materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.Off; materialOptions.zTest = SurfaceMaterialOptions.ZTest.Always; materialOptions.GetBlend(blendingBuilder); materialOptions.GetCull(cullingBuilder); materialOptions.GetDepthTest(zTestBuilder); materialOptions.GetDepthWrite(zWriteBuilder); // ------------------------------------- // Generate defines //TODO // if (masterNode.IsSlotConnected(UnlitMasterNode.AlphaThresholdSlotId)) // defines.AppendLine("#define _AlphaClip 1"); if (masterNode.surfaceType == SurfaceType.Transparent && masterNode.alphaMode == AlphaMode.Premultiply) { defines.AppendLine("#define _ALPHAPREMULTIPLY_ON 1"); } if (graphRequirements.requiresDepthTexture) { defines.AppendLine("#define REQUIRE_DEPTH_TEXTURE"); } if (graphRequirements.requiresCameraOpaqueTexture) { defines.AppendLine("#define REQUIRE_OPAQUE_TEXTURE"); } // ----------------------------------------------------- // // START VERTEX DESCRIPTION // // ----------------------------------------------------- // // ------------------------------------- // Generate Input structure for Vertex Description function // TODO - Vertex Description Input requirements are needed to exclude intermediate translation spaces vertexDescriptionInputStruct.AppendLine("struct VertexDescriptionInputs"); using (vertexDescriptionInputStruct.BlockSemicolonScope()) { ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresNormal, InterpolatorType.Normal, vertexDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresTangent, InterpolatorType.Tangent, vertexDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresBitangent, InterpolatorType.BiTangent, vertexDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresViewDir, InterpolatorType.ViewDirection, vertexDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresPosition, InterpolatorType.Position, vertexDescriptionInputStruct); if (vertexRequirements.requiresVertexColor) { vertexDescriptionInputStruct.AppendLine("float4 {0};", ShaderGeneratorNames.VertexColor); } if (vertexRequirements.requiresScreenPosition) { vertexDescriptionInputStruct.AppendLine("float4 {0};", ShaderGeneratorNames.ScreenPosition); } foreach (var channel in vertexRequirements.requiresMeshUVs.Distinct()) { vertexDescriptionInputStruct.AppendLine("half4 {0};", channel.GetUVName()); } } // ------------------------------------- // Generate Output structure for Vertex Description function GraphUtil.GenerateVertexDescriptionStruct(vertexDescriptionStruct, vertexSlots); // ------------------------------------- // Generate Vertex Description function GraphUtil.GenerateVertexDescriptionFunction( masterNode.owner as AbstractMaterialGraph, vertexDescriptionFunction, functionRegistry, shaderProperties, mode, vertexNodes, vertexSlots); // ----------------------------------------------------- // // START SURFACE DESCRIPTION // // ----------------------------------------------------- // // ------------------------------------- // Generate Input structure for Surface Description function // Surface Description Input requirements are needed to exclude intermediate translation spaces surfaceDescriptionInputStruct.AppendLine("struct SurfaceDescriptionInputs"); using (surfaceDescriptionInputStruct.BlockSemicolonScope()) { ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(surfaceRequirements.requiresNormal, InterpolatorType.Normal, surfaceDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(surfaceRequirements.requiresTangent, InterpolatorType.Tangent, surfaceDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(surfaceRequirements.requiresBitangent, InterpolatorType.BiTangent, surfaceDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(surfaceRequirements.requiresViewDir, InterpolatorType.ViewDirection, surfaceDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(surfaceRequirements.requiresPosition, InterpolatorType.Position, surfaceDescriptionInputStruct); if (surfaceRequirements.requiresVertexColor) { surfaceDescriptionInputStruct.AppendLine("float4 {0};", ShaderGeneratorNames.VertexColor); } if (surfaceRequirements.requiresScreenPosition) { surfaceDescriptionInputStruct.AppendLine("float4 {0};", ShaderGeneratorNames.ScreenPosition); } if (surfaceRequirements.requiresFaceSign) { surfaceDescriptionInputStruct.AppendLine("float {0};", ShaderGeneratorNames.FaceSign); } foreach (var channel in surfaceRequirements.requiresMeshUVs.Distinct()) { surfaceDescriptionInputStruct.AppendLine("half4 {0};", channel.GetUVName()); } } // ------------------------------------- // Generate Output structure for Surface Description function GraphUtil.GenerateSurfaceDescriptionStruct(surfaceDescriptionStruct, pixelSlots, true); // ------------------------------------- // Generate Surface Description function GraphUtil.GenerateSurfaceDescriptionFunction( pixelNodes, masterNode, masterNode.owner as AbstractMaterialGraph, surfaceDescriptionFunction, functionRegistry, shaderProperties, pixelRequirements, mode, "PopulateSurfaceData", "SurfaceDescription", null, pixelSlots); // ----------------------------------------------------- // // GENERATE VERTEX > PIXEL PIPELINE // // ----------------------------------------------------- // // ------------------------------------- // Generate Input structure for Vertex shader GraphUtil.GenerateApplicationVertexInputs(vertexRequirements.Union(pixelRequirements.Union(modelRequiements)), vertexInputStruct); // ------------------------------------- // Generate standard transformations // This method ensures all required transform data is available in vertex and pixel stages ShaderGenerator.GenerateStandardTransforms( 3, 10, vertexOutputStruct, vertexShader, vertexShaderDescriptionInputs, vertexShaderOutputs, pixelShader, pixelShaderSurfaceInputs, pixelRequirements, surfaceRequirements, modelRequiements, vertexRequirements, CoordinateSpace.World); // ------------------------------------- // Generate pixel shader surface remap foreach (var slot in pixelSlots) { pixelShaderSurfaceRemap.AppendLine("{0} = surf.{0};", slot.shaderOutputName); } // ------------------------------------- // Extra pixel shader work var faceSign = new ShaderStringBuilder(); if (pixelRequirements.requiresFaceSign) { faceSign.AppendLine(", half FaceSign : VFACE"); } // ----------------------------------------------------- // // FINALIZE // // ----------------------------------------------------- // // ------------------------------------- // Combine Graph sections graph.AppendLine(shaderProperties.GetPropertiesDeclaration(1)); graph.AppendLine(vertexDescriptionInputStruct.ToString()); graph.AppendLine(surfaceDescriptionInputStruct.ToString()); graph.AppendLine(functionBuilder.ToString()); graph.AppendLine(vertexDescriptionStruct.ToString()); graph.AppendLine(vertexDescriptionFunction.ToString()); graph.AppendLine(surfaceDescriptionStruct.ToString()); graph.AppendLine(surfaceDescriptionFunction.ToString()); graph.AppendLine(vertexInputStruct.ToString()); // ------------------------------------- // Generate final subshader var resultPass = template.Replace("${Tags}", string.Empty); resultPass = resultPass.Replace("${Blending}", blendingBuilder.ToString()); resultPass = resultPass.Replace("${Culling}", cullingBuilder.ToString()); resultPass = resultPass.Replace("${ZTest}", zTestBuilder.ToString()); resultPass = resultPass.Replace("${ZWrite}", zWriteBuilder.ToString()); resultPass = resultPass.Replace("${Defines}", defines.ToString()); resultPass = resultPass.Replace("${Graph}", graph.ToString()); resultPass = resultPass.Replace("${VertexOutputStruct}", vertexOutputStruct.ToString()); resultPass = resultPass.Replace("${VertexShader}", vertexShader.ToString()); resultPass = resultPass.Replace("${VertexShaderDescriptionInputs}", vertexShaderDescriptionInputs.ToString()); resultPass = resultPass.Replace("${VertexShaderOutputs}", vertexShaderOutputs.ToString()); resultPass = resultPass.Replace("${FaceSign}", faceSign.ToString()); resultPass = resultPass.Replace("${PixelShader}", pixelShader.ToString()); resultPass = resultPass.Replace("${PixelShaderSurfaceInputs}", pixelShaderSurfaceInputs.ToString()); resultPass = resultPass.Replace("${PixelShaderSurfaceRemap}", pixelShaderSurfaceRemap.ToString()); return(resultPass); }
public override void Visit(Pass p, ExpressionUsage u) { p.Begin(ref Operand, ExpressionUsage.Operand); Operand.Visit(p, ExpressionUsage.Operand); p.End(ref Operand, ExpressionUsage.Operand); }
// ******************************************************************************** /// <summary> /// /// </summary> /// <param name="nIndex"></param> /// <param name="apptools"></param> /// <returns></returns> /// <created>UPh,29.11.2015</created> /// <changed>UPh,29.11.2015</changed> // ******************************************************************************** public override uint ExecuteTool(int nIndex, Pass.AddIn.Core.CPAIApplicationTools apptools) { return 0; }
//--------------------------------------------------------------- #endregion //--------------------------------------------------------------- //--------------------------------------------------------------- #region Methods //--------------------------------------------------------------- /// <summary> /// Addes a new <see cref="Pass"/> to the list. /// </summary> /// <param name="pass">Pass to add.</param> public void Add(Pass pass) { passes.Add(pass); }
public void OnPassRendered(Pass pass) { var handler = PassCompleted; if (handler != null) handler(this, new PassCompleteEventArgs { DrawDevice = drawDevice, Pass = pass}); }
static string GetExtraPassesFromTemplate(string template, UnlitMasterNode masterNode, Pass pass, GenerationMode mode, SurfaceMaterialOptions materialOptions) { // ----------------------------------------------------- // // SETUP // // ----------------------------------------------------- // // ------------------------------------- // String builders var dummyBuilder = new ShaderStringBuilder(0); var shaderProperties = new PropertyCollector(); var functionBuilder = new ShaderStringBuilder(1); var functionRegistry = new FunctionRegistry(functionBuilder); var defines = new ShaderStringBuilder(2); var graph = new ShaderStringBuilder(0); var vertexDescriptionInputStruct = new ShaderStringBuilder(1); var vertexDescriptionStruct = new ShaderStringBuilder(1); var vertexDescriptionFunction = new ShaderStringBuilder(1); var vertexInputStruct = new ShaderStringBuilder(1); var vertexShader = new ShaderStringBuilder(2); var vertexDescriptionInputs = new ShaderStringBuilder(2); // ------------------------------------- // Get Slot and Node lists per stage var vertexSlots = pass.VertexShaderSlots.Select(masterNode.FindSlot <MaterialSlot>).ToList(); var vertexNodes = ListPool <AbstractMaterialNode> .Get(); NodeUtils.DepthFirstCollectNodesFromNode(vertexNodes, masterNode, NodeUtils.IncludeSelf.Include, pass.VertexShaderSlots); // ------------------------------------- // Get requirements var vertexRequirements = ShaderGraphRequirements.FromNodes(vertexNodes, ShaderStageCapability.Vertex, false); var modelRequiements = ShaderGraphRequirements.none; modelRequiements.requiresNormal |= m_VertexCoordinateSpace; modelRequiements.requiresPosition |= m_VertexCoordinateSpace; modelRequiements.requiresMeshUVs.Add(UVChannel.UV1); // ----------------------------------------------------- // // START SHADER GENERATION // // ----------------------------------------------------- // // ------------------------------------- // Calculate material options var cullingBuilder = new ShaderStringBuilder(1); materialOptions.GetCull(cullingBuilder); // ------------------------------------- // Generate defines if (masterNode.IsSlotConnected(PBRMasterNode.AlphaThresholdSlotId)) { defines.AppendLine("#define _AlphaClip 1"); } // ----------------------------------------------------- // // START VERTEX DESCRIPTION // // ----------------------------------------------------- // // ------------------------------------- // Generate Input structure for Vertex Description function // TODO - Vertex Description Input requirements are needed to exclude intermediate translation spaces vertexDescriptionInputStruct.AppendLine("struct VertexDescriptionInputs"); using (vertexDescriptionInputStruct.BlockSemicolonScope()) { ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresNormal, InterpolatorType.Normal, vertexDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresTangent, InterpolatorType.Tangent, vertexDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresBitangent, InterpolatorType.BiTangent, vertexDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresViewDir, InterpolatorType.ViewDirection, vertexDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresPosition, InterpolatorType.Position, vertexDescriptionInputStruct); if (vertexRequirements.requiresVertexColor) { vertexDescriptionInputStruct.AppendLine("float4 {0};", ShaderGeneratorNames.VertexColor); } if (vertexRequirements.requiresScreenPosition) { vertexDescriptionInputStruct.AppendLine("float4 {0};", ShaderGeneratorNames.ScreenPosition); } foreach (var channel in vertexRequirements.requiresMeshUVs.Distinct()) { vertexDescriptionInputStruct.AppendLine("half4 {0};", channel.GetUVName()); } } // ------------------------------------- // Generate Output structure for Vertex Description function GraphUtil.GenerateVertexDescriptionStruct(vertexDescriptionStruct, vertexSlots); // ------------------------------------- // Generate Vertex Description function GraphUtil.GenerateVertexDescriptionFunction( masterNode.owner as AbstractMaterialGraph, vertexDescriptionFunction, functionRegistry, shaderProperties, mode, vertexNodes, vertexSlots); // ----------------------------------------------------- // // GENERATE VERTEX > PIXEL PIPELINE // // ----------------------------------------------------- // // ------------------------------------- // Generate Input structure for Vertex shader GraphUtil.GenerateApplicationVertexInputs(vertexRequirements.Union(modelRequiements), vertexInputStruct); // ------------------------------------- // Generate standard transformations // This method ensures all required transform data is available in vertex and pixel stages ShaderGenerator.GenerateStandardTransforms( 3, 10, dummyBuilder, vertexShader, vertexDescriptionInputs, dummyBuilder, dummyBuilder, dummyBuilder, ShaderGraphRequirements.none, ShaderGraphRequirements.none, modelRequiements, vertexRequirements, CoordinateSpace.World); // ----------------------------------------------------- // // FINALIZE // // ----------------------------------------------------- // // ------------------------------------- // Combine Graph sections graph.AppendLine(shaderProperties.GetPropertiesDeclaration(1)); graph.AppendLine(vertexDescriptionInputStruct.ToString()); graph.AppendLine(functionBuilder.ToString()); graph.AppendLine(vertexDescriptionStruct.ToString()); graph.AppendLine(vertexDescriptionFunction.ToString()); graph.AppendLine(vertexInputStruct.ToString()); // ------------------------------------- // Generate final subshader var resultPass = template.Replace("${Culling}", cullingBuilder.ToString()); resultPass = resultPass.Replace("${Defines}", defines.ToString()); resultPass = resultPass.Replace("${Graph}", graph.ToString()); resultPass = resultPass.Replace("${VertexShader}", vertexShader.ToString()); resultPass = resultPass.Replace("${VertexShaderDescriptionInputs}", vertexDescriptionInputs.ToString()); return(resultPass); }
void Pass_RenderObjectPass( Pass pass, Vec3 objectWorldPosition ) { //update cubemap reflection textures if( cubemapEventUnitStates != null ) { foreach( Pair<Pass, TextureUnitState> item in cubemapEventUnitStates ) if( item.First == pass ) UpdateReflectionCubemap( item.Second, objectWorldPosition ); } //update maps transform with animations if( mapsWithAnimations != null ) { foreach( MapItem map in mapsWithAnimations ) UpdateMapTransformGpuParameters( map ); } }
public override void Visit(Pass p, ExpressionUsage u) { p.VisitNullable(ref Exception); }
public void Leave(Pass pass) { if (pass.Expired) throw new ArgumentException("You cannot leave through the gate with an expired gate pass", "pass"); if (pass.ClosedTheGate) { gateControlSemaphore.WaitOne(); numberOfGateClosers--; if (numberOfGateClosers == 0) { gateClosed = false; gateSemaphore.Release(); } gateControlSemaphore.Release(); } pass.Expired = true; }
private static ActiveFields GetActiveFieldsFromMasterNode(AbstractMaterialNode iMasterNode, Pass pass) { var activeFields = new ActiveFields(); var baseActiveFields = activeFields.baseInstance; EyeMasterNode masterNode = iMasterNode as EyeMasterNode; if (masterNode == null) { return(activeFields); } if (masterNode.doubleSidedMode != DoubleSidedMode.Disabled) { if (pass.ShaderPassName != "SHADERPASS_MOTION_VECTORS") // HACK to get around lack of a good interpolator dependency system { // we need to be able to build interpolators using multiple input structs // also: should only require isFrontFace if Normals are required... // Important: the following is used in SharedCode.template.hlsl for determining the normal flip mode baseActiveFields.Add("FragInputs.isFrontFace"); } } switch (masterNode.materialType) { case EyeMasterNode.MaterialType.Eye: baseActiveFields.Add("Material.Eye"); break; case EyeMasterNode.MaterialType.EyeCinematic: baseActiveFields.Add("Material.EyeCinematic"); break; default: UnityEngine.Debug.LogError("Unknown material type: " + masterNode.materialType); break; } if (masterNode.alphaTest.isOn) { if (pass.PixelShaderUsesSlot(EyeMasterNode.AlphaClipThresholdSlotId)) { baseActiveFields.Add("AlphaTest"); } } if (masterNode.surfaceType != SurfaceType.Opaque) { if (masterNode.transparencyFog.isOn) { baseActiveFields.Add("AlphaFog"); } if (masterNode.blendPreserveSpecular.isOn) { baseActiveFields.Add("BlendMode.PreserveSpecular"); } } if (!masterNode.receiveDecals.isOn) { baseActiveFields.Add("DisableDecals"); } if (!masterNode.receiveSSR.isOn) { baseActiveFields.Add("DisableSSR"); } if (masterNode.addPrecomputedVelocity.isOn) { baseActiveFields.Add("AdditionalVelocityChange"); } if (masterNode.subsurfaceScattering.isOn && masterNode.surfaceType != SurfaceType.Transparent) { baseActiveFields.Add("Material.SubsurfaceScattering"); } if (masterNode.IsSlotConnected(EyeMasterNode.BentNormalSlotId) && pass.PixelShaderUsesSlot(EyeMasterNode.BentNormalSlotId)) { baseActiveFields.Add("BentNormal"); } switch (masterNode.specularOcclusionMode) { case SpecularOcclusionMode.Off: break; case SpecularOcclusionMode.FromAO: baseActiveFields.Add("SpecularOcclusionFromAO"); break; case SpecularOcclusionMode.FromAOAndBentNormal: baseActiveFields.Add("SpecularOcclusionFromAOBentNormal"); break; case SpecularOcclusionMode.Custom: baseActiveFields.Add("SpecularOcclusionCustom"); break; default: break; } if (pass.PixelShaderUsesSlot(EyeMasterNode.AmbientOcclusionSlotId)) { var occlusionSlot = masterNode.FindSlot <Vector1MaterialSlot>(EyeMasterNode.AmbientOcclusionSlotId); bool connected = masterNode.IsSlotConnected(EyeMasterNode.AmbientOcclusionSlotId); if (connected || occlusionSlot.value != occlusionSlot.defaultValue) { baseActiveFields.Add("AmbientOcclusion"); } } if (masterNode.IsSlotConnected(EyeMasterNode.LightingSlotId) && pass.PixelShaderUsesSlot(EyeMasterNode.LightingSlotId)) { baseActiveFields.Add("LightingGI"); } if (masterNode.IsSlotConnected(EyeMasterNode.BackLightingSlotId) && pass.PixelShaderUsesSlot(EyeMasterNode.BackLightingSlotId)) { baseActiveFields.Add("BackLightingGI"); } if (masterNode.depthOffset.isOn && pass.PixelShaderUsesSlot(EyeMasterNode.DepthOffsetSlotId)) { baseActiveFields.Add("DepthOffset"); } return(activeFields); }
public bool drawSceene(Pass currentPass, ViewInfo curView) { GL.Enable(EnableCap.DepthTest); GL.Enable(EnableCap.CullFace); GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha); if (currentPass == Pass.diffuse) { GL.Disable(EnableCap.Blend); foreach (Drawable curDrawable in drawables) { if ((curDrawable.renderlayer == RenderLayer.Solid) || (curDrawable.renderlayer == RenderLayer.Both)) { curDrawable.draw(curView, false); } } } if (currentPass == Pass.transparent) { GL.Enable(EnableCap.Blend); /* for (int i = drawables.Count - 1; i >= 0; i--) { if ((drawables[i].renderlayer == RenderLayer.Transparent)|| (drawables[i].renderlayer == RenderLayer.Both)) { drawables[i].draw(curView, true); } } * */ foreach (Drawable curDrawable in drawables) { if ((curDrawable.renderlayer == RenderLayer.Transparent) || (curDrawable.renderlayer == RenderLayer.Both)) { curDrawable.draw(curView, true); } } GL.Disable(EnableCap.Blend); } if (currentPass == Pass.shadow) { foreach (Drawable curDrawable in drawables) { curDrawable.drawShadow(curView); } } if (currentPass == Pass.selection) { bool hasSelection = false; foreach (Drawable curDrawable in drawables) { if (curDrawable.selectedSmooth > 0.01) { curDrawable.drawSelection(curView); hasSelection = true; } } return hasSelection; } if (currentPass == Pass.normal) { GL.Disable(EnableCap.Blend); foreach (Drawable curDrawable in drawables) { curDrawable.drawNormal(curView); } } if (currentPass == Pass.defInfo) { GL.Disable(EnableCap.Blend); foreach (Drawable curDrawable in drawables) { curDrawable.drawDefInfo(curView); } } GL.DepthMask(true); GL.Disable(EnableCap.DepthTest); GL.Disable(EnableCap.CullFace); GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha); return false; }
/// <summary> /// Add ground pass (Use for atmospheric scattering effect on the terrain) /// </summary> /// <param name="groundPass">Ground pass</param> public void AddGroundPass(Pass groundPass) { AddGroundPass(groundPass, 0, SceneBlendType.SBT_ADD); }
void Pass_RenderObjectPass( Pass pass, Vec3 objectWorldPosition ) { //update cubemap reflection textures if( cubemapEventUnitStates != null ) { for( int n = 0; n < cubemapEventUnitStates.Count; n++ ) { Pair<Pass, TextureUnitState> item = cubemapEventUnitStates[ n ]; if( item.First == pass ) UpdateReflectionCubemap( item.Second, objectWorldPosition ); } } //update maps transform with animations if( mapsWithAnimations != null ) { for( int n = 0; n < mapsWithAnimations.Count; n++ ) UpdateMapTransformGpuParameters( mapsWithAnimations[ n ] ); } //set the matrix for projective texturing if( projectiveTexturing ) { Mat4 clipSpaceToImageSpaceMatrix = new Mat4( 0.5f, 0, 0, 0, 0, -0.5f, 0, 0, 0, 0, 1, 0, 0.5f, 0.5f, 0, 1 ); Mat4 matrix = clipSpaceToImageSpaceMatrix * projectiveTexturingFrustum.GetProjectionMatrix() * projectiveTexturingFrustum.GetViewMatrix(); matrix.Transpose(); SetCustomGpuParameter( GpuParameters.texViewProjImageMatrix0, matrix.Item0, true, false, false ); SetCustomGpuParameter( GpuParameters.texViewProjImageMatrix1, matrix.Item1, true, false, false ); SetCustomGpuParameter( GpuParameters.texViewProjImageMatrix2, matrix.Item2, true, false, false ); SetCustomGpuParameter( GpuParameters.texViewProjImageMatrix3, matrix.Item3, true, false, false ); } }
/// <summary> /// Add ground pass (Use for atmospheric scattering effect on the terrain) /// </summary> /// <param name="groundPass">Ground pass</param> /// <param name="atmosphereRadius">Atmosphere radius (far carmera clip plane, or needed)</param> public void AddGroundPass(Pass groundPass, float atmosphereRadius) { AddGroundPass(groundPass, 0, SceneBlendType.SBT_ADD); }
/// <summary> /// Opponent p has passed. Not much to do here, just log it to some kind of text status window/control. /// </summary> /// <param name="t"></param> /// <param name="p"></param> private void DrawOpponentTurn(Pass t, Player p) { StatusBar.Text = string.Format("Player {0} has passed...", p.Name); }
/// <summary> /// Add ground pass (Use for atmospheric scattering effect on the terrain) /// </summary> /// <param name="groundPass">Ground pass</param> /// <param name="atmosphereRadius">Atmosphere radius (far carmera clip plane, or needed)</param> /// <param name="sbt">Scene blend type</param> public void AddGroundPass(Pass groundPass, float atmosphereRadius, SceneBlendType sbt) { groundPass.SetVertexProgram("SkyX_Ground_VP"); if (this.SkyX.LightingMode == LightingMode.Ldr) { groundPass.SetFragmentProgram("SkyX_Ground_LDR_FP"); } else { groundPass.SetFragmentProgram("SkyX_Ground_HDR_FP"); } groundPass.GetVertexProgramParameters().SetNamedConstant("uSkydomeRadius", ((atmosphereRadius == 0) ? this.SkyX.MeshManager.SkydomeRadius : atmosphereRadius) * 10); groundPass.LightingEnabled = false; groundPass.DepthCheckEnabled = true; groundPass.DepthWriteEnabled = false; groundPass.SetSceneBlending(sbt); ///TODO _groundPasses.Add(groundPass); this.SkyX.AtmosphereManager.Update(this.SkyX.AtmosphereManager.Options, true); }
/// <summary> /// Opponent p has passed. Not much to do here, just log it to some kind of text status window/control. /// </summary> /// <param name="t"></param> /// <param name="p"></param> private void DrawOpponentTurn(Pass t, Player p) { throw new NotImplementedException(); }
public override void Draw(GL_ControlModern control, Pass pass) { if (pass == Pass.TRANSPARENT) { return; } bool buffersWereInitialized = vbo_position != 0; if (!buffersWereInitialized) { UpdateVertexData(); } if (!Runtime.OpenTKInitialized) { return; } control.CurrentShader = ProbeSHShaderProgram; control.UpdateModelMatrix(Matrix4.Identity); Matrix4 previewScale = Utils.TransformValues(Vector3.Zero, Vector3.Zero, Runtime.previewScale); ProbeSHShaderProgram.SetMatrix4x4("previewScale", ref previewScale); foreach (var entry in Entries) { if (!entry.IsVisable) { continue; } Vector3[] vertices = GetBoundingVertices((int)entry.Index).ToArray(); Vector3 Max = entry.Grid.AABB_Max_Position; Vector3 Min = entry.Grid.AABB_Min_Position; Vector3 Step = entry.Grid.Voxel_Step_Position; float gridHeight = Min.Y + Max.Y; float gridWidth = Min.X + Max.X; float gridDepth = Min.Z + Max.Z; //Draw bounding box GL.Color3(entry.Grid.GridColor); GL.Begin(PrimitiveType.LineLoop); GL.Vertex3(vertices[0]); GL.Vertex3(vertices[1]); GL.Vertex3(vertices[3]); GL.Vertex3(vertices[2]); GL.End(); GL.Begin(PrimitiveType.LineLoop); GL.Vertex3(vertices[4]); GL.Vertex3(vertices[5]); GL.Vertex3(vertices[7]); GL.Vertex3(vertices[6]); GL.End(); GL.Begin(PrimitiveType.Lines); GL.Vertex3(vertices[0]); GL.Vertex3(vertices[4]); GL.Vertex3(vertices[1]); GL.Vertex3(vertices[5]); GL.Vertex3(vertices[3]); GL.Vertex3(vertices[7]); GL.Vertex3(vertices[2]); GL.Vertex3(vertices[6]); GL.End(); ProbeSHShaderProgram.EnableVertexAttributes(); Draw(ProbeSHShaderProgram); ProbeSHShaderProgram.DisableVertexAttributes(); } GL.UseProgram(0); }
internal static stmt Convert(Statement stmt) { stmt ast; if (stmt is FunctionDefinition) ast = new FunctionDef((FunctionDefinition)stmt); else if (stmt is ReturnStatement) ast = new Return((ReturnStatement)stmt); else if (stmt is AssignmentStatement) ast = new Assign((AssignmentStatement)stmt); else if (stmt is AugmentedAssignStatement) ast = new AugAssign((AugmentedAssignStatement)stmt); else if (stmt is DelStatement) ast = new Delete((DelStatement)stmt); else if (stmt is PrintStatement) ast = new Print((PrintStatement)stmt); else if (stmt is ExpressionStatement) ast = new Expr((ExpressionStatement)stmt); else if (stmt is ForStatement) ast = new For((ForStatement)stmt); else if (stmt is WhileStatement) ast = new While((WhileStatement)stmt); else if (stmt is IfStatement) ast = new If((IfStatement)stmt); else if (stmt is WithStatement) ast = new With((WithStatement)stmt); else if (stmt is RaiseStatement) ast = new Raise((RaiseStatement)stmt); else if (stmt is TryStatement) ast = Convert((TryStatement)stmt); else if (stmt is AssertStatement) ast = new Assert((AssertStatement)stmt); else if (stmt is ImportStatement) ast = new Import((ImportStatement)stmt); else if (stmt is FromImportStatement) ast = new ImportFrom((FromImportStatement)stmt); else if (stmt is ExecStatement) ast = new Exec((ExecStatement)stmt); else if (stmt is GlobalStatement) ast = new Global((GlobalStatement)stmt); else if (stmt is ClassDefinition) ast = new ClassDef((ClassDefinition)stmt); else if (stmt is BreakStatement) ast = new Break(); else if (stmt is ContinueStatement) ast = new Continue(); else if (stmt is EmptyStatement) ast = new Pass(); else throw new ArgumentTypeException("Unexpected statement type: " + stmt.GetType()); ast.GetSourceLocation(stmt); return ast; }
public override void Draw(GL_ControlLegacy control, Pass pass) { }
private void RenderSinglePass(Rect viewportRect, Pass p) { this.drawDevice.VisibilityMask = this.visibilityMask & p.VisibilityMask; this.drawDevice.RenderMode = p.MatrixMode; this.drawDevice.Target = p.Output; this.drawDevice.ViewportRect = p.Output.IsAvailable ? new Rect(p.Output.Res.Width, p.Output.Res.Height) : viewportRect; if (p.Input == null) { // Render Scene this.drawDevice.PrepareForDrawcalls(); try { this.CollectDrawcalls(); p.NotifyCollectDrawcalls(this.drawDevice); } catch (Exception e) { Log.Core.WriteError("There was an error while {0} was collecting drawcalls: {1}", this.ToString(), Log.Exception(e)); } this.drawDevice.Render(p.ClearFlags, p.ClearColor, p.ClearDepth); } else { Profile.TimePostProcessing.BeginMeasure(); this.drawDevice.PrepareForDrawcalls(); Texture mainTex = p.Input.MainTexture.Res; Vector2 uvRatio = mainTex != null ? mainTex.UVRatio : Vector2.One; Vector2 inputSize = mainTex != null ? new Vector2(mainTex.PixelWidth, mainTex.PixelHeight) : Vector2.One; Rect targetRect; if (DualityApp.ExecEnvironment == DualityApp.ExecutionEnvironment.Editor && !this.drawDevice.Target.IsAvailable) targetRect = Rect.Align(Alignment.Center, this.drawDevice.TargetSize.X * 0.5f, this.drawDevice.TargetSize.Y * 0.5f, inputSize.X, inputSize.Y); else targetRect = new Rect(this.drawDevice.TargetSize); IDrawDevice device = this.drawDevice; { VertexC1P3T2[] vertices = new VertexC1P3T2[4]; vertices[0].Pos = new Vector3(targetRect.LeftX, targetRect.TopY, 0.0f); vertices[1].Pos = new Vector3(targetRect.RightX, targetRect.TopY, 0.0f); vertices[2].Pos = new Vector3(targetRect.RightX, targetRect.BottomY, 0.0f); vertices[3].Pos = new Vector3(targetRect.LeftX, targetRect.BottomY, 0.0f); vertices[0].TexCoord = new Vector2(0.0f, 0.0f); vertices[1].TexCoord = new Vector2(uvRatio.X, 0.0f); vertices[2].TexCoord = new Vector2(uvRatio.X, uvRatio.Y); vertices[3].TexCoord = new Vector2(0.0f, uvRatio.Y); vertices[0].Color = ColorRgba.White; vertices[1].Color = ColorRgba.White; vertices[2].Color = ColorRgba.White; vertices[3].Color = ColorRgba.White; device.AddVertices(p.Input, VertexMode.Quads, vertices); } this.drawDevice.Render(p.ClearFlags, p.ClearColor, p.ClearDepth); Profile.TimePostProcessing.EndMeasure(); } }
public DynamicTexture(Entity entity, RenderPipeline pipeline, PerspectiveCamera viewPoint, GBuffer gBuffer, TextureCube skybox, Pass pass, string label) { this.Entity = entity; this.Pipeline = pipeline; this.ViewPoint = viewPoint; this.GBuffer = gBuffer; this.Pass = pass; this.Label = label; this.Skybox = skybox; this.Input = new RenderPipelineInput(); }
private void RenderSinglePass(Pass p) { this.drawDevice.VisibilityMask = this.visibilityMask & p.VisibilityMask; this.drawDevice.RenderMode = p.MatrixMode; this.drawDevice.Target = p.Output; if (p.Input == null) { // Render Scene this.drawDevice.BeginRendering(p.ClearFlags, p.ClearColor, p.ClearDepth); try { this.CollectDrawcalls(); p.NotifyCollectDrawcalls(this.drawDevice); } catch (Exception e) { Log.Core.WriteError("There was an error while {0} was collecting drawcalls: {1}", this.ToString(), Log.Exception(e)); } this.drawDevice.EndRendering(); } else { Profile.TimePostProcessing.BeginMeasure(); this.drawDevice.BeginRendering(p.ClearFlags, p.ClearColor, p.ClearDepth); Texture mainTex = p.Input.MainTexture.Res; Vector2 uvRatio = mainTex != null ? mainTex.UVRatio : Vector2.One; Vector2 inputSize = mainTex != null ? new Vector2(mainTex.PixelWidth, mainTex.PixelHeight) : Vector2.One; Rect targetRect; if (DualityApp.ExecEnvironment == DualityApp.ExecutionEnvironment.Editor && !this.drawDevice.Target.IsAvailable) targetRect = Rect.AlignCenter(this.drawDevice.TargetSize.X * 0.5f, this.drawDevice.TargetSize.Y * 0.5f, inputSize.X, inputSize.Y); else targetRect = new Rect(this.drawDevice.TargetSize); IDrawDevice device = this.drawDevice; device.AddVertices(p.Input, VertexMode.Quads, new VertexC1P3T2(targetRect.MinimumX, targetRect.MinimumY, 0.0f, 0.0f, 0.0f), new VertexC1P3T2(targetRect.MaximumX, targetRect.MinimumY, 0.0f, uvRatio.X, 0.0f), new VertexC1P3T2(targetRect.MaximumX, targetRect.MaximumY, 0.0f, uvRatio.X, uvRatio.Y), new VertexC1P3T2(targetRect.MinimumX, targetRect.MaximumY, 0.0f, 0.0f, uvRatio.Y)); this.drawDevice.EndRendering(); Profile.TimePostProcessing.EndMeasure(); } }
/// <summary> /// Register layer /// </summary> /// <param name="cloudLayerPass">Pass where register the cloud layer</param> public void RegisterCloudLayer(Pass cloudLayerPass) { Unregister(); cloudLayerPass.SetSceneBlending(SceneBlendType.SBT_TRANSPARENT_ALPHA); cloudLayerPass.CullingMode = CullingMode.CULL_NONE; cloudLayerPass.LightingEnabled = false; cloudLayerPass.DepthWriteEnabled = false; cloudLayerPass.SetVertexProgram("SkyX_Clouds_VP"); if (this.SkyX.LightingMode == LightingMode.Ldr) { cloudLayerPass.SetFragmentProgram("SkyX_Clouds_LDR_FP"); } else { cloudLayerPass.SetFragmentProgram("SkyX_Clouds_HDR_FP"); } //TODO //cloudLayerPass.CreateTextureUnitState("Cloud1.png").TextureAddressing = TextureUnitState.TextureAddressingMode.TAM_WRAP; //cloudLayerPass.CreateTextureUnitState("c22n.png").TextureAddressing = TextureUnitState.TextureAddressingMode.TAM_WRAP; //cloudLayerPass.CreateTextureUnitState("c22.png").TextureAddressing = TextureUnitState.TextureAddressingMode.TAM_WRAP; cloudLayerPass.CreateTextureUnitState("Cloud1.png").SetTextureAddressingMode(TextureUnitState.TextureAddressingMode.TAM_WRAP ); cloudLayerPass.CreateTextureUnitState("c22n.png").SetTextureAddressingMode( TextureUnitState.TextureAddressingMode.TAM_WRAP); cloudLayerPass.CreateTextureUnitState("c22.png").SetTextureAddressingMode( TextureUnitState.TextureAddressingMode.TAM_WRAP); _cloudLayerPass = cloudLayerPass; UpdatePassParameters(); }