Пример #1
0
        internal static void Draw(bool draw = true)
        {
            try
            {
                MyGpuProfiler.IC_BeginBlock("Draw");
                GetRenderProfiler().StartProfilingBlock("ProcessMessages");
                MyGpuProfiler.IC_BeginBlock("ProcessMessageQueue");
                TransferLocalMessages();
                ProcessMessageQueue();
                MyGpuProfiler.IC_EndBlock();
                GetRenderProfiler().EndProfilingBlock();

                if (draw)
                {
                    m_drawScene = false;
                    DispatchDrawQueue();

                    if (m_drawScene)
                    {
                        DrawScene();
                    }

                    if (!(MyRender11.Settings.OffscreenSpritesRendering && m_drawScene))
                    {
                        ProcessDrawQueue();
                        DrawSprites(MyRender11.Backbuffer);
                    }

                    MyFileTextureManager texManager = MyManagers.FileTextures;
                    texManager.LoadAllRequested();

                    if (m_texturesToRender.Count > 0)
                    {
                        VRage.Render11.PostprocessStage.MySaveExportedTextures.RenderColoredTextures(m_texturesToRender);
                    }
                }

                MyLinesRenderer.Clear();
                MySpritesRenderer.Clear();

                m_drawQueue.Clear();
                MyGpuProfiler.IC_EndBlock();
            }
            catch (SharpDXException e)
            {
                MyRender11.Log.IncreaseIndent();
                MyRender11.Log.WriteLine(" " + e);
                if (e.Descriptor == SharpDX.DXGI.ResultCode.DeviceRemoved)
                {
                    MyRender11.Log.WriteLine("Reason: " + Device.DeviceRemovedReason);
                }
                MyRender11.Log.DecreaseIndent();

                throw;
            }
        }
Пример #2
0
        internal static void Draw(bool draw = true)
        {
            //if (false) Debug.Assert(MyClipmap.LodLevel.DrewLastFrame);
            //MyClipmap.LodLevel.DrewLastFrame = false;

            try
            {
                GetRenderProfiler().StartProfilingBlock("ProcessMessages");
                TransferLocalMessages();
                ProcessMessageQueue();
                GetRenderProfiler().EndProfilingBlock();

                if (draw)
                {
                    MyImmediateRC.RC.Clear();
                    GetRenderProfiler().StartProfilingBlock("ProcessDrawQueue");
                    ProcessDrawQueue();
                    GetRenderProfiler().EndProfilingBlock();

                    /*GetRenderProfiler().StartProfilingBlock("ProcessDebugMessages");
                     * ProcessDebugMessages();
                     * GetRenderProfiler().EndProfilingBlock();*/

                    GetRenderProfiler().StartProfilingBlock("MySpritesRenderer.Draw");
                    //MyCommon.UpdateFrameConstants();
                    MySpritesRenderer.Draw(MyRender11.Backbuffer.m_RTV, new MyViewport(MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y));
                    GetRenderProfiler().EndProfilingBlock();

                    MyTextures.Load();
                }

                if (m_profilingStarted)
                {
                    MyGpuProfiler.IC_BeginBlock("Waiting for present");
                }

                MyLinesRenderer.Clear();
                MySpritesRenderer.Clear();

                m_drawQueue.Clear();
                m_debugDrawMessages.Clear();
            }
            catch (SharpDXException e)
            {
                MyRender11.Log.IncreaseIndent();
                MyRender11.Log.WriteLine(" " + e);
                if (e.Descriptor == SharpDX.DXGI.ResultCode.DeviceRemoved)
                {
                    MyRender11.Log.WriteLine("Reason: " + Device.DeviceRemovedReason);
                }
                MyRender11.Log.DecreaseIndent();

                throw;
            }
        }
Пример #3
0
        internal static unsafe void InitSubsystems()
        {
            InitializeBlendStates();
            InitializeRasterizerStates();
            InitilizeSamplerStates();

            MyCommon.Init();
            MyPipelineStates.Init();
            MyTextures.Init();
            MyVertexLayouts.Init();
            MyShaders.Init();
            MyRwTextures.Init();
            MyHwBuffers.Init();
            MyMeshes.Init();
            MyMeshTableSRV.Init();
            MyMergeInstancing.Init();
            MyGeometryRenderer.Init();
            MyLightRendering.Init();
            MyShadows.Init();
            MyLinesRenderer.Init();
            MySpritesRenderer.Init();
            MyPrimitivesRenderer.Init();
            MyFoliageRenderer.Init();
            MyOutline.Init();

            MyComponents.Init();

            MyBillboardRenderer.Init(); // hardcoded limits
            MyDebugRenderer.Init();
            MyGPUFoliageGenerating.Init();

            MyScreenDecals.Init();
            MyEnvProbeProcessing.Init();
            MyShadowsResolve.Init();
            MyAtmosphereRenderer.Init();
            MyAAEdgeMarking.Init();
            MyScreenPass.Init();
            MyCopyToRT.Init();
            MyBlendTargets.Init();
            MyFXAA.Init();
            MyDepthResolve.Init();
            MyBloom.Init();
            MyLuminanceAverage.Init();
            MyToneMapping.Init();
            MySSAO.Init();
            MyHdrDebugTools.Init();

            MySceneMaterials.Init();
            MyMaterials1.Init();
            MyVoxelMaterials1.Init();
            MyMeshMaterials1.Init();

            //MyShaderFactory.RunCompilation(); // rebuild
        }
Пример #4
0
        internal static unsafe void InitSubsystems()
        {
            MyRwTextures.Init();
            MyHwBuffers.Init();
            MyPipelineStates.Init();
            ResetShadows(MyRenderProxy.Settings.ShadowCascadeCount, RenderSettings.ShadowQuality.ShadowCascadeResolution());
            MyRender11.Init();
            MyCommon.Init();
            SamplerStates.Init();
            MyDepthStencilState.Init();
            MyTextures.Init();
            MyVertexLayouts.Init();
            MyShaders.Init();
            MyMeshes.Init();
            MyMeshTableSRV.Init();
            MyLightRendering.Init();
            MyLinesRenderer.Init();
            MySpritesRenderer.Init();
            MyPrimitivesRenderer.Init();
            MyOutline.Init();
            MyBlur.Init();
            MyTransparentRendering.Init();

            MyFoliageComponents.Init();

            MyBillboardRenderer.Init(); // hardcoded limits
            MyDebugRenderer.Init();

            MyScreenDecals.Init();
            MyEnvProbeProcessing.Init();
            MyAtmosphereRenderer.Init();
            MyCloudRenderer.Init();
            MyAAEdgeMarking.Init();
            MyScreenPass.Init();
            MyCopyToRT.Init();
            MyBlendTargets.Init();
            MyFXAA.Init();
            MyDepthResolve.Init();
            MyBloom.Init();
            MyLuminanceAverage.Init();
            MyToneMapping.Init();
            MySSAO.Init();
            MyPlanetBlur.Init();
            MyHdrDebugTools.Init();

            MySceneMaterials.Init();
            MyMaterials1.Init();
            MyVoxelMaterials1.Init();
            MyMeshMaterials1.Init();
        }
Пример #5
0
        private void DebugDrawFrozenViewFrustrum(int nCascade)
        {
            var oldInvView = MatrixD.Invert(Matrix.CreateTranslation(MyRender11.Environment.CameraPosition) * m_debugFrozenMatrixView[nCascade]);

            Vector3D.Transform(m_blockOS, ref oldInvView, m_tmpDebugFrozen8D);

            for (int i = 0; i < 8; i++)
            {
                m_tmpDebugFrozen8[i] = m_tmpDebugFrozen8D[i];
            }

            var batch = MyLinesRenderer.CreateBatch();

            batch.Add6FacedConvex(m_tmpDebugFrozen8, Color.Blue);

            batch.Commit();
        }
Пример #6
0
        // can be on another job
        internal static void Draw()
        {
            // calculate box ()
            var cubeVertices = new Vector3[8] {
                new Vector3(-0.5f, -0.5f, -0.5f),
                new Vector3(-0.5f, 0.5f, -0.5f),
                new Vector3(0.5f, 0.5f, -0.5f),
                new Vector3(0.5f, -0.5f, -0.5f),

                new Vector3(-0.5f, -0.5f, 0.5f),
                new Vector3(-0.5f, 0.5f, 0.5f),
                new Vector3(0.5f, 0.5f, 0.5f),
                new Vector3(0.5f, -0.5f, 0.5f)
            };

            var worldVertices = new Vector3[8];

            var decals = IdIndex.Values.ToArray();

            // sort visible decals by material
            Array.Sort(decals, DecalsMaterialComparer);

            ///
            // copy gbuffer with normals for read (uhoh)
            // bind copy and depth for read
            // bind gbuffer for write

            var batch = MyLinesRenderer.CreateBatch();

            for (int i = 0; i < decals.Length; ++i)
            {
                var index = decals[i];

                var parentMatrix = MyIDTracker <MyActor> .FindByID(Decals.Data[index].ParentID).WorldMatrix;

                var volumeMatrix    = Decals.Data[index].LocalOBB * parentMatrix;
                var invVolumeMatrix = Matrix.Invert(volumeMatrix);

                Vector3.Transform(cubeVertices, ref volumeMatrix, worldVertices);

                batch.Add6FacedConvex(worldVertices, Color.Red);
            }

            batch.Commit();
        }
Пример #7
0
        private void DebugDrawFrozenCascadeFrustrum(int nCascade)
        {
            var lineBatch = MyLinesRenderer.CreateBatch();

            MatrixD inverseViewProj = MatrixD.Invert(Matrix.CreateTranslation(MyRender11.Environment.CameraPosition) * m_cascadeInfo[nCascade].WorldToProjection);

            Vector3D.Transform(m_blockOS, ref inverseViewProj, m_tmpDebugFrozen8D);

            for (int vertexIndex = 0; vertexIndex < 8; ++vertexIndex)
            {
                m_tmpDebugFrozen8[vertexIndex] = m_tmpDebugFrozen8D[vertexIndex];
            }

            MyPrimitivesRenderer.Draw6FacedConvexZ(m_tmpDebugFrozen8, m_debugCascadeColor[nCascade], 0.2f);
            lineBatch.Add6FacedConvex(m_tmpDebugFrozen8, Color.Pink);

            lineBatch.Commit();
        }
Пример #8
0
        private unsafe void DebugDrawFrozen(MatrixD *cascadesMatrices)
        {
            Vector3D *verticesWS = stackalloc Vector3D[8];

            Color[] cascadeColor = null;

            cascadeColor = new[]
            {
                Color.Red,
                Color.Green,
                Color.Blue,
                Color.Yellow,
                Color.Gray,
                Color.Orange
            };
            var lineBatch = MyLinesRenderer.CreateBatch();

            Vector3 *tmpFloatVertices = stackalloc Vector3[8];

            for (int c = 0; c < m_initializedShadowCascadesCount; c++)
            {
                if (MyRenderProxy.Settings.ShadowCascadeFrozen[c])
                {
                    var inverseViewProj = MatrixD.Invert(cascadesMatrices[c]);
                    Vector3D.Transform(m_cornersCS, ref inverseViewProj, verticesWS);

                    for (int vertexIndex = 0; vertexIndex < 8; ++vertexIndex)
                    {
                        verticesWS[vertexIndex] += MyEnvironment.CameraPosition;
                    }

                    for (int vertexIndex = 0; vertexIndex < 8; ++vertexIndex)
                    {
                        tmpFloatVertices[vertexIndex] = verticesWS[vertexIndex];
                    }

                    MyPrimitivesRenderer.Draw6FacedConvexZ(tmpFloatVertices, cascadeColor[c], 0.2f);
                    lineBatch.Add6FacedConvex(tmpFloatVertices, Color.Pink);
                }
            }

            lineBatch.Commit();
        }
Пример #9
0
        internal static unsafe void InitSubsystems()
        {
            MyManagers.OnDeviceInit();
            //MyRwTextures.Init();
            MyHwBuffers.Init();
            ResetShadows(MyShadowCascades.Settings.NewData.CascadesCount, RenderSettings.ShadowQuality.ShadowCascadeResolution());
            MyRender11.Init();
            MyCommon.Init();
            MyVertexLayouts.Init();
            MyShaders.Init();
            MyMeshes.Init();
            MyMeshTableSrv.Init();
            MyLightRendering.Init();
            MyLinesRenderer.Init();
            MySpritesRenderer.Init();
            MyPrimitivesRenderer.Init();
            MyOutline.Init();
            MyBlur.Init();
            MyTransparentRendering.Init();

            MyFoliageComponents.Init();

            MyBillboardRenderer.Init(); // hardcoded limits
            MyDebugRenderer.Init();

            MyScreenDecals.Init();
            MyEnvProbeProcessing.Init();
            MyAtmosphereRenderer.Init();
            MyCloudRenderer.Init();
            MyAAEdgeMarking.Init();
            MyScreenPass.Init();
            MyCopyToRT.Init();
            MyBlendTargets.Init();
            MyFXAA.Init();
            MyDepthResolve.Init();
            MyBloom.Init();
            MyLuminanceAverage.Init();
            MyToneMapping.Init();
            MySSAO.Init();
            MyHdrDebugTools.Init();

            MySceneMaterials.Init();
            MyMaterials1.Init();
            MyVoxelMaterials1.Init();
            MyMeshMaterials1.Init();

            MyHBAO.Init();

            try
            {
                if (m_settings.UseStereoRendering)
                {
                    var openVR = new MyOpenVR();
                    MyStereoStencilMask.InitUsingOpenVR();
                }
            }
            catch (System.Exception e)
            {
                if (!VRage.MyCompilationSymbols.DX11ForceStereo)
                {
                    throw;
                }
                MyStereoStencilMask.InitUsingUndefinedMask();
            }
        }
Пример #10
0
        static void PrepareCascades()
        {
            MyImmediateRC.RC.BeginProfilingBlock("PrepareCascades");
            MyImmediateRC.RC.Context.CopyResource(m_cascadeShadowmapArray.Resource, m_cascadeShadowmapBackup.Resource);

            bool        stabilize = true;
            const float DirectionDifferenceThreshold = 0.02f;

            for (int cascadeIndex = 0; cascadeIndex < m_initializedShadowCascadesCount; ++cascadeIndex)
            {
                ++m_shadowCascadeFramesSinceUpdate[cascadeIndex];

                if (m_shadowCascadeFramesSinceUpdate[cascadeIndex] > cascadeIndex * 60 ||
                    MyEnvironment.DirectionalLightDir.Dot(m_shadowCascadeLightDirections[cascadeIndex]) < (1 - DirectionDifferenceThreshold))
                {
                    m_shadowCascadeLightDirections[cascadeIndex]   = MyEnvironment.DirectionalLightDir;
                    m_shadowCascadeFramesSinceUpdate[cascadeIndex] = 0;
                }
            }

            var globalMatrix = CreateGlobalMatrix();

            MatrixD[] cascadesMatrices = new MatrixD[8];

            var cascadeFrozen = MyRender11.Settings.ShadowCascadeFrozen.Any(x => x == true);

            if (!cascadeFrozen)
            {
                m_oldView = MyEnvironment.View;
            }

            float cascadesNearClip = 1f;

            float cascadesFarClip = MyRender11.RenderSettings.ShadowQuality.ShadowCascadeSplit(m_initializedShadowCascadesCount);
            float backOffset      = MyRender11.RenderSettings.ShadowQuality.BackOffset();
            float shadowmapSize   = MyRender11.RenderSettings.ShadowQuality.ShadowCascadeResolution();

            var  oldCascadeSplit = 0.0f;
            bool useFarShadows   = MyRenderProxy.Settings.FarShadowDistanceOverride > MyRender11.Settings.ShadowCascadeMaxDistance;

            if (useFarShadows)
            {
                oldCascadeSplit = MyRender11.Settings.ShadowCascadeMaxDistance;

                MyRender11.Settings.ShadowCascadeMaxDistance = MyRenderProxy.Settings.FarShadowDistanceOverride;
            }

            for (int cascadeIndex = 0; cascadeIndex < ShadowCascadeSplitDepths.Length; ++cascadeIndex)
            {
                ShadowCascadeSplitDepths[cascadeIndex] = MyRender11.RenderSettings.ShadowQuality.ShadowCascadeSplit(cascadeIndex);
            }

            if (useFarShadows)
            {
                MyRender11.Settings.ShadowCascadeMaxDistance = oldCascadeSplit;
            }

            double unitWidth  = 1.0 / MyEnvironment.Projection.M11;
            double unitHeight = 1.0 / MyEnvironment.Projection.M22;
            var    vertices   = new Vector3D[]
            {
                new Vector3D(-unitWidth, -unitHeight, -1),
                new Vector3D(-unitWidth, unitHeight, -1),
                new Vector3D(unitWidth, unitHeight, -1),
                new Vector3D(unitWidth, -unitHeight, -1),
            };
            var frustumVerticesWS = new Vector3D[8];

            for (int cascadeIndex = 0; cascadeIndex < m_initializedShadowCascadesCount; ++cascadeIndex)
            {
                for (int i = 0; i < 4; i++)
                {
                    frustumVerticesWS[i]     = vertices[i] * ShadowCascadeSplitDepths[cascadeIndex];
                    frustumVerticesWS[i + 4] = vertices[i] * ShadowCascadeSplitDepths[cascadeIndex + 1];
                }

                if (MyRender11.Settings.ShadowCascadeFrozen[cascadeIndex])
                {
                    // draw cascade bounding primtiive
                    if (VisualizeDebug)
                    {
                        var oldInvView = MatrixD.Invert(m_oldView);
                        Vector3D.Transform(frustumVerticesWS, ref oldInvView, frustumVerticesWS);

                        var verticesF = new Vector3[8];
                        for (int i = 0; i < 8; i++)
                        {
                            verticesF[i] = frustumVerticesWS[i];
                        }
                        var batch = MyLinesRenderer.CreateBatch();
                        batch.Add6FacedConvex(verticesF, Color.Blue);

                        var bs = BoundingSphere.CreateFromPoints(verticesF);
                        var bb = BoundingBox.CreateFromSphere(bs);
                        batch.AddBoundingBox(bb, Color.OrangeRed);

                        batch.Commit();
                    }

                    continue;
                }


                /*
                 * Cascades update scheme:
                 *    1 2 3 4 5 6 7
                 * 0: 1 1 1 1 1 1 1
                 * 1: 1 0 1 0 1 0 1
                 * 2: 0 1 0 0 1 0 0
                 * 3: 0 0 0 1 0 0 0
                 * 4: 0 0 0 0 0 1 0
                 * 5: 0 0 0 0 0 0 1
                 */

                bool skipCascade  = false; // TODO: properly
                bool skipCascade1 = cascadeIndex == 1 && (MyCommon.FrameCounter % 2) != 0;
                bool skipCascade2 = cascadeIndex == 2 && (MyCommon.FrameCounter % 4) != 1;
                bool skipCascade3 = cascadeIndex == 3 && (MyCommon.FrameCounter % 4) != 3;
                bool skipCascade4 = cascadeIndex == 4 && (MyCommon.FrameCounter % 8) != 5;
                bool skipCascade5 = cascadeIndex == 5 && (MyCommon.FrameCounter % 8) != 7;
                skipCascade = skipCascade1 || skipCascade2 || skipCascade3 || skipCascade4 || skipCascade5;
                //
                if (skipCascade && !MyRender11.Settings.UpdateCascadesEveryFrame)
                {
                    continue;
                }

                MatrixD invView = MyEnvironment.InvView;
                Vector3D.Transform(frustumVerticesWS, ref invView, frustumVerticesWS);

                var bSphere = BoundingSphereD.CreateFromPoints((IEnumerable <Vector3D>)frustumVerticesWS);
                if (stabilize)
                {
                    bSphere.Center = bSphere.Center.Round();
                    bSphere.Radius = Math.Ceiling(bSphere.Radius);
                }

                var shadowCameraPosWS = bSphere.Center + m_shadowCascadeLightDirections[cascadeIndex] * (bSphere.Radius + cascadesNearClip);

                var lightView     = VRageMath.MatrixD.CreateLookAt(shadowCameraPosWS, shadowCameraPosWS - m_shadowCascadeLightDirections[cascadeIndex], Math.Abs(Vector3.UnitY.Dot(m_shadowCascadeLightDirections[cascadeIndex])) < 0.99f ? Vector3.UnitY : Vector3.UnitX);
                var longestShadow = MyRenderProxy.Settings.LongShadowFactor;
                var offset        = bSphere.Radius + cascadesNearClip + backOffset + (longestShadow < 0 ? 0.0 : longestShadow);

                Vector3D vMin = new Vector3D(-bSphere.Radius, -bSphere.Radius, cascadesNearClip);
                Vector3D vMax = new Vector3D(bSphere.Radius, bSphere.Radius, offset + bSphere.Radius);

                var cascadeProjection = MatrixD.CreateOrthographicOffCenter(vMin.X, vMax.X, vMin.Y, vMax.Y, vMax.Z, vMin.Z);
                cascadesMatrices[cascadeIndex] = lightView * cascadeProjection;

                var transformed = Vector3D.Transform(Vector3D.Zero, cascadesMatrices[cascadeIndex]) * shadowmapSize / 2;
                var smOffset    = (transformed.Round() - transformed) * 2 / shadowmapSize;

                // stabilize 1st cascade only
                if (stabilize)
                {
                    cascadeProjection.M41         += smOffset.X;
                    cascadeProjection.M42         += smOffset.Y;
                    cascadesMatrices[cascadeIndex] = lightView * cascadeProjection;
                }

                var inverseCascadeMatrix = MatrixD.Invert(cascadesMatrices[cascadeIndex]);
                var corner0 = Vector3D.Transform(Vector3D.Transform(new Vector3D(-1, -1, 0), inverseCascadeMatrix), globalMatrix);
                var corner1 = Vector3D.Transform(Vector3D.Transform(new Vector3D(1, 1, 1), inverseCascadeMatrix), globalMatrix);

                var d = corner1 - corner0;

                var cascadeScale = 1f / (corner1 - corner0);
                ShadowCascadeScales[cascadeIndex] = new Vector4D(cascadeScale, 0);

                var query = new MyShadowmapQuery();
                query.DepthBuffer = m_cascadeShadowmapArray.SubresourceDsv(cascadeIndex);
                query.Viewport    = new MyViewport(shadowmapSize, shadowmapSize);

                m_cascadeInfo[cascadeIndex].WorldCameraOffsetPosition = MyEnvironment.CameraPosition;
                m_cascadeInfo[cascadeIndex].WorldToProjection         = cascadesMatrices[cascadeIndex];
                // todo: skip translation, recalculate matrix in local space, keep world space matrix only for bounding frustum
                m_cascadeInfo[cascadeIndex].LocalToProjection = Matrix.CreateTranslation(MyEnvironment.CameraPosition) * cascadesMatrices[cascadeIndex];

                query.ProjectionInfo   = m_cascadeInfo[cascadeIndex];
                query.ProjectionDir    = m_shadowCascadeLightDirections[cascadeIndex];
                query.ProjectionFactor = (float)(shadowmapSize * shadowmapSize / (bSphere.Radius * bSphere.Radius * 4));

                query.QueryType    = MyFrustumEnum.ShadowCascade;
                query.CascadeIndex = cascadeIndex;

                m_shadowmapQueries.Add(query);
            }

            if (true)
            {
                var verticesWS = new Vector3D[8];

                var batch = MyLinesRenderer.CreateBatch();

                var cascadeColor = new[]
                {
                    Color.Red,
                    Color.Green,
                    Color.Blue,
                    Color.Yellow
                };

                for (int c = 0; c < m_initializedShadowCascadesCount; c++)
                {
                    if (MyRender11.Settings.ShadowCascadeFrozen[c])
                    {
                        if (VisualizeDebug)
                        {
                            var inverseViewProj = MatrixD.Invert(cascadesMatrices[c]);
                            Vector3D.Transform(m_cornersCS, ref inverseViewProj, verticesWS);

                            for (int i = 0; i < verticesWS.Length; i++)
                            {
                                verticesWS[i] += MyEnvironment.CameraPosition;
                            }

                            var verticesF = new Vector3[8];
                            for (int i = 0; i < 8; i++)
                            {
                                verticesF[i] = verticesWS[i];
                            }

                            MyPrimitivesRenderer.Draw6FacedConvex(verticesF, cascadeColor[c], 0.2f);
                            batch.Add6FacedConvex(verticesF, Color.Pink);
                        }
                    }
                }

                batch.Commit();
            }

            var mapping = MyMapping.MapDiscard(m_csmConstants);

            for (int c = 0; c < m_initializedShadowCascadesCount; c++)
            {
                mapping.stream.Write(Matrix.Transpose(m_cascadeInfo[c].CurrentLocalToProjection * MyMatrixHelpers.ClipspaceToTexture));
            }
            for (int i = m_initializedShadowCascadesCount; i < 8; i++)
            {
                mapping.stream.Write(Matrix.Zero);
            }

            for (int i = 0; i < ShadowCascadeSplitDepths.Length; i++)
            {
                mapping.stream.Write(ShadowCascadeSplitDepths[i]);
            }
            for (int i = ShadowCascadeSplitDepths.Length; i < 8; i++)
            {
                mapping.stream.Write(0.0f);
            }

            for (int i = 0; i < m_initializedShadowCascadesCount; i++)
            {
                mapping.stream.Write(ShadowCascadeScales[i] / ShadowCascadeScales[0]);
            }

            mapping.Unmap();

            MyImmediateRC.RC.EndProfilingBlock();
        }
Пример #11
0
        static void ProcessDebugMessages()
        {
            bool clearPersistent = false;

            m_persistentDebugMessagesTemp.Clear();
            var linesBatch        = MyLinesRenderer.CreateBatch();
            var noDepthLinesBatch = MyLinesRenderer.CreateBatch();

            noDepthLinesBatch.IgnoreDepth = true;
            var lines2D = MyLinesRenderer.CreateBatch();

            lines2D.IgnoreDepth = true;

            while (m_debugDrawMessages.Count > 0)
            {
                MyRenderMessageBase debugDrawMessage = m_debugDrawMessages.Dequeue();
                if (debugDrawMessage.IsPersistent)
                {
                    m_persistentDebugMessagesTemp.Add(debugDrawMessage);
                }

                MyRenderMessageEnum messageType = debugDrawMessage.MessageType;

                switch (messageType)
                {
                case MyRenderMessageEnum.DebugDrawLine3D:
                {
                    MyRenderMessageDebugDrawLine3D message = (MyRenderMessageDebugDrawLine3D)debugDrawMessage;

                    if (message.DepthRead)
                    {
                        linesBatch.Add(message.PointFrom - MyRender11.Environment.Matrices.CameraPosition, message.PointTo - MyRender11.Environment.Matrices.CameraPosition, message.ColorFrom, message.ColorTo);
                    }
                    else
                    {
                        noDepthLinesBatch.Add(message.PointFrom - MyRender11.Environment.Matrices.CameraPosition, message.PointTo - MyRender11.Environment.Matrices.CameraPosition, message.ColorFrom, message.ColorTo);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawLine2D:
                {
                    MyRenderMessageDebugDrawLine2D message = (MyRenderMessageDebugDrawLine2D)debugDrawMessage;

                    var matrix = message.Projection ?? Matrix.CreateOrthographicOffCenter(0, MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y, 0, 0, -1);

                    if (!lines2D.CustomViewProjection.HasValue || (lines2D.CustomViewProjection.HasValue && lines2D.CustomViewProjection.Value != matrix))
                    {
                        lines2D.Commit();
                        lines2D                      = MyLinesRenderer.CreateBatch();
                        lines2D.IgnoreDepth          = true;
                        lines2D.CustomViewProjection = matrix;
                    }

                    var p0 = new Vector3(message.PointFrom.X, message.PointFrom.Y, 0);
                    var p1 = new Vector3(message.PointTo.X, message.PointTo.Y, 0);
                    lines2D.Add(p0, p1, message.ColorFrom, message.ColorTo);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawPoint:
                {
                    MyRenderMessageDebugDrawPoint message = (MyRenderMessageDebugDrawPoint)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    var scale = 0.125f;

                    var borderDepth = MyRender11.UseComplementaryDepthBuffer ? 0.0f : 1.0f;
                    borderDepth = message.ClipDistance.HasValue ? Vector3.Transform(new Vector3(0, 0, -message.ClipDistance.Value), MyRender11.Environment.Matrices.Projection).Z : borderDepth;

                    var clipPosition = Vector3D.Transform(message.Position, MyRender11.Environment.Matrices.ViewProjectionAt0);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;

                    //Debug.Assert(MyRender11.UseComplementaryDepthBuffer);

                    Vector3 position = (Vector3)(message.Position - MyRender11.Environment.Matrices.CameraPosition);

                    bool drawCondition =
                        MyRender11.UseComplementaryDepthBuffer
                                ? clipPosition.Z > borderDepth && clipPosition.Z < 1
                                : clipPosition.Z < borderDepth && clipPosition.Z > 0;

                    if (drawCondition)
                    {
                        batch.Add(position + Vector3.UnitX * scale, position - Vector3.UnitX * scale, message.Color);
                        batch.Add(position + Vector3.UnitY * scale, position - Vector3.UnitY * scale, message.Color);
                        batch.Add(position + Vector3.UnitZ * scale, position - Vector3.UnitZ * scale, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawSphere:
                {
                    MyRenderMessageDebugDrawSphere message = (MyRenderMessageDebugDrawSphere)debugDrawMessage;

                    var borderDepth = MyRender11.UseComplementaryDepthBuffer ? 0.0f : 1.0f;
                    borderDepth = message.ClipDistance.HasValue ? Vector3.Transform(new Vector3(0, 0, -message.ClipDistance.Value), MyRender11.Environment.Matrices.Projection).Z : borderDepth;

                    Vector3D position = message.Position - MyRender11.Environment.Matrices.CameraPosition;

                    var clipPosition = Vector3D.Transform(position, MyRender11.Environment.Matrices.ViewProjectionAt0);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;

                    bool drawCondition =
                        MyRender11.UseComplementaryDepthBuffer
                                ? clipPosition.Z > borderDepth && clipPosition.Z < 1
                                : clipPosition.Z < borderDepth && clipPosition.Z > 0;

                    if (drawCondition)
                    {
                        var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                        batch.AddSphereRing(new BoundingSphere(position, message.Radius), message.Color, Matrix.Identity);
                        batch.AddSphereRing(new BoundingSphere(position, message.Radius), message.Color, Matrix.CreateRotationX(MathHelper.PiOver2));
                        batch.AddSphereRing(new BoundingSphere(position, message.Radius), message.Color, Matrix.CreateRotationZ(MathHelper.PiOver2));
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawAABB:
                {
                    MyRenderMessageDebugDrawAABB message = (MyRenderMessageDebugDrawAABB)debugDrawMessage;

                    BoundingBox aabb = (BoundingBox)message.AABB;
                    aabb.Translate(-MyRender11.Environment.Matrices.CameraPosition);

                    if (message.DepthRead)
                    {
                        linesBatch.AddBoundingBox(aabb, message.Color);
                    }
                    else
                    {
                        noDepthLinesBatch.AddBoundingBox(aabb, message.Color);
                    }

                    if (message.Shaded)
                    {
                        unsafe
                        {
                            Vector3 *points = stackalloc Vector3[8];

                            aabb.GetCornersUnsafe(points);

                            MyPrimitivesRenderer.Draw6FacedConvexZ(points, message.Color, message.Alpha);
                        }
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDraw6FaceConvex:
                {
                    MyRenderMessageDebugDraw6FaceConvex convex = (MyRenderMessageDebugDraw6FaceConvex)debugDrawMessage;

                    if (convex.Fill)
                    {
                        MyPrimitivesRenderer.Draw6FacedConvex(convex.Vertices, convex.Color, convex.Alpha);
                    }
                    else
                    {
                        if (convex.DepthRead)
                        {
                            linesBatch.Add6FacedConvexWorld(convex.Vertices, convex.Color);
                        }
                        else
                        {
                            noDepthLinesBatch.Add6FacedConvexWorld(convex.Vertices, convex.Color);
                        }
                    }
                    break;
                }


                case MyRenderMessageEnum.DebugDrawCone:
                {
                    MyRenderMessageDebugDrawCone message = (MyRenderMessageDebugDrawCone)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    var axis = message.DirectionVector;
                    axis.Normalize();

                    var apex = message.Translation + message.DirectionVector;

                    var steps    = 32;
                    var stepsRcp = (float)(Math.PI * 2 / steps);
                    for (int i = 0; i < 32; i++)
                    {
                        float a0 = i * stepsRcp;
                        float a1 = (i + 1) * stepsRcp;

                        var A = message.Translation + Vector3D.Transform(message.BaseVector, MatrixD.CreateFromAxisAngle(axis, a0)) - MyRender11.Environment.Matrices.CameraPosition;
                        var B = message.Translation + Vector3D.Transform(message.BaseVector, MatrixD.CreateFromAxisAngle(axis, a1)) - MyRender11.Environment.Matrices.CameraPosition;

                        batch.Add(A, B, message.Color);
                        batch.Add(A, apex, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawAxis:
                {
                    MyRenderMessageDebugDrawAxis message = (MyRenderMessageDebugDrawAxis)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    Vector3 position = message.Matrix.Translation - MyRender11.Environment.Matrices.CameraPosition;

                    if (message.SkipScale)
                    {
                        batch.Add(position, position + Vector3.Normalize(message.Matrix.Right) * message.AxisLength, Color.Red);
                        batch.Add(position, position + Vector3.Normalize(message.Matrix.Up) * message.AxisLength, Color.Green);
                        batch.Add(position, position + Vector3.Normalize(message.Matrix.Forward) * message.AxisLength, Color.Blue);
                    }
                    else
                    {
                        batch.Add(position, position + message.Matrix.Right * message.AxisLength, Color.Red);
                        batch.Add(position, position + message.Matrix.Up * message.AxisLength, Color.Green);
                        batch.Add(position, position + message.Matrix.Forward * message.AxisLength, Color.Blue);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawOBB:
                {
                    MyRenderMessageDebugDrawOBB message = (MyRenderMessageDebugDrawOBB)debugDrawMessage;

                    Vector3D[] cornersD = new Vector3D[8];
                    MatrixD    matrix   = (MatrixD)message.Matrix;
                    new MyOrientedBoundingBoxD(matrix).GetCorners(cornersD, 0);

                    Vector3[] corners = new Vector3[8];
                    for (int i = 0; i < 8; i++)
                    {
                        corners[i] = (cornersD[i] - MyRender11.Environment.Matrices.CameraPosition);
                    }

                    if (message.DepthRead)
                    {
                        linesBatch.Add6FacedConvex(corners, message.Color);
                    }
                    else
                    {
                        noDepthLinesBatch.Add6FacedConvex(corners, message.Color);
                    }

                    MyPrimitivesRenderer.Draw6FacedConvexZ(corners, message.Color, message.Alpha);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawFrustrum:
                {
                    MyRenderMessageDebugDrawFrustrum message = (MyRenderMessageDebugDrawFrustrum)debugDrawMessage;

                    Vector3[] corners = new Vector3[8];

                    Matrix m = message.Frustrum.Matrix;

                    m.Translation -= MyRender11.Environment.Matrices.CameraPosition;

                    message.Frustrum.Matrix = m;

                    message.Frustrum.GetCorners(corners);

                    if (message.DepthRead)
                    {
                        linesBatch.Add6FacedConvex(corners, message.Color);
                    }
                    else
                    {
                        noDepthLinesBatch.Add6FacedConvex(corners, message.Color);
                    }

                    MyPrimitivesRenderer.Draw6FacedConvexZ(corners, message.Color, message.Alpha);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawCylinder:
                {
                    MyRenderMessageDebugDrawCylinder message = (MyRenderMessageDebugDrawCylinder)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    var steps    = 32;
                    var stepsRcp = (float)(Math.PI * 2 / steps);
                    for (int i = 0; i < 32; i++)
                    {
                        float a0 = i * stepsRcp;
                        float a1 = (i + 1) * stepsRcp;

                        Vector3D A = new Vector3D(Math.Cos(a0), 1.0f, Math.Sin(a0)) * 0.5f;
                        Vector3D B = new Vector3D(Math.Cos(a1), 1.0f, Math.Sin(a1)) * 0.5f;
                        Vector3D C = A - Vector3D.UnitY;
                        Vector3D D = B - Vector3D.UnitY;

                        A = Vector3D.Transform(A, message.Matrix);
                        B = Vector3D.Transform(B, message.Matrix);
                        C = Vector3D.Transform(C, message.Matrix);
                        D = Vector3D.Transform(D, message.Matrix);

                        A -= MyRender11.Environment.Matrices.CameraPosition;
                        B -= MyRender11.Environment.Matrices.CameraPosition;
                        C -= MyRender11.Environment.Matrices.CameraPosition;
                        D -= MyRender11.Environment.Matrices.CameraPosition;

                        batch.Add(A, B, message.Color);
                        batch.Add(A, C, message.Color);
                        batch.Add(C, D, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawTriangle:
                {
                    MyRenderMessageDebugDrawTriangle message = (MyRenderMessageDebugDrawTriangle)debugDrawMessage;

                    MyPrimitivesRenderer.DrawTriangle(message.Vertex0 - MyRender11.Environment.Matrices.CameraPosition,
                                                      message.Vertex1 - MyRender11.Environment.Matrices.CameraPosition,
                                                      message.Vertex2 - MyRender11.Environment.Matrices.CameraPosition, message.Color);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawTriangles:
                {
                    MyRenderMessageDebugDrawTriangles message = (MyRenderMessageDebugDrawTriangles)debugDrawMessage;

                    for (int i = 0; i < message.Indices.Count; i += 3)
                    {
                        var v0 = Vector3D.Transform(message.Vertices[message.Indices[i + 0]], message.WorldMatrix) - MyRender11.Environment.Matrices.CameraPosition;
                        var v1 = Vector3D.Transform(message.Vertices[message.Indices[i + 1]], message.WorldMatrix) - MyRender11.Environment.Matrices.CameraPosition;
                        var v2 = Vector3D.Transform(message.Vertices[message.Indices[i + 2]], message.WorldMatrix) - MyRender11.Environment.Matrices.CameraPosition;

                        MyPrimitivesRenderer.DrawTriangle(v0, v1, v2, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawMesh:
                {
                    MyPrimitivesRenderer.DebugMesh(debugDrawMessage as MyRenderMessageDebugDrawMesh);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawCapsule:
                {
                    MyRenderMessageDebugDrawCapsule message = (MyRenderMessageDebugDrawCapsule)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    batch.AddSphereRing(new BoundingSphere(message.P0 - MyRender11.Environment.Matrices.CameraPosition, message.Radius), message.Color, Matrix.Identity);
                    batch.AddSphereRing(new BoundingSphere(message.P0 - MyRender11.Environment.Matrices.CameraPosition, message.Radius), message.Color, Matrix.CreateRotationX(MathHelper.PiOver2));
                    batch.AddSphereRing(new BoundingSphere(message.P1 - MyRender11.Environment.Matrices.CameraPosition, message.Radius), message.Color, Matrix.Identity);
                    batch.AddSphereRing(new BoundingSphere(message.P1 - MyRender11.Environment.Matrices.CameraPosition, message.Radius), message.Color, Matrix.CreateRotationX(MathHelper.PiOver2));

                    batch.Add(message.P0 - MyRender11.Environment.Matrices.CameraPosition, message.P1 - MyRender11.Environment.Matrices.CameraPosition, message.Color);


                    break;
                }

                case MyRenderMessageEnum.DebugDrawText2D:
                {
                    MyRenderMessageDebugDrawText2D message = (MyRenderMessageDebugDrawText2D)debugDrawMessage;

                    var text = new StringBuilder(message.Text);

                    MySpritesRenderer.DrawText(message.Coord, text, message.Color, message.Scale, message.Align);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawText3D:
                {
                    MyRenderMessageDebugDrawText3D message = (MyRenderMessageDebugDrawText3D)debugDrawMessage;

                    Vector3D position = message.Coord;

                    var worldToClip = MyRender11.Environment.Matrices.ViewProjectionD;
                    if (message.CustomViewProjection != -1)
                    {
                        if (!MyRenderProxy.BillboardsViewProjectionRead.ContainsKey(message.CustomViewProjection))
                        {
                            break;
                        }

                        var i = message.CustomViewProjection;

                        var scaleX  = MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.Width / (float)MyRender11.ViewportResolution.X;
                        var scaleY  = MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.Height / (float)MyRender11.ViewportResolution.Y;
                        var offsetX = MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.OffsetX / (float)MyRender11.ViewportResolution.X;
                        var offsetY = (MyRender11.ViewportResolution.Y - MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.OffsetY - MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.Height)
                                      / (float)MyRender11.ViewportResolution.Y;

                        var viewportTransformation = new Matrix(
                            scaleX, 0, 0, 0,
                            0, scaleY, 0, 0,
                            0, 0, 1, 0,
                            offsetX, offsetY, 0, 1
                            );

                        worldToClip = MyRenderProxy.BillboardsViewProjectionRead[message.CustomViewProjection].ViewAtZero * MyRenderProxy.BillboardsViewProjectionRead[message.CustomViewProjection].Projection * viewportTransformation;
                    }

                    var clipPosition = Vector3D.Transform(position, ref worldToClip);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;

                    var borderDepth = MyRender11.UseComplementaryDepthBuffer ? 0.0f : 1.0f;
                    borderDepth = message.ClipDistance.HasValue ? Vector3.Transform(new Vector3(0, 0, -message.ClipDistance.Value), MyRender11.Environment.Matrices.Projection).Z : borderDepth;

                    bool drawCondition =
                        MyRender11.UseComplementaryDepthBuffer
                                ? clipPosition.Z > borderDepth && clipPosition.Z < 1
                                : clipPosition.Z < borderDepth && clipPosition.Z > 0;

                    if (drawCondition)
                    {
                        MySpritesRenderer.DrawText(new Vector2((float)clipPosition.X, (float)clipPosition.Y) * MyRender11.ViewportResolution,
                                                   new StringBuilder(message.Text), message.Color, message.Scale, message.Align);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawModel:
                {
                    MyRenderMessageDebugDrawModel message = (MyRenderMessageDebugDrawModel)debugDrawMessage;


                    break;
                }

                case MyRenderMessageEnum.DebugDrawPlane:
                {
                    MyRenderMessageDebugDrawPlane message = (MyRenderMessageDebugDrawPlane)debugDrawMessage;


                    break;
                }

                case MyRenderMessageEnum.DebugWaitForPresent:
                {
                    MyRenderMessageDebugWaitForPresent rMessage = (MyRenderMessageDebugWaitForPresent)debugDrawMessage;
                    MyRenderProxy.RenderThread.DebugAddWaitingForPresent(rMessage.WaitHandle);
                    break;
                }

                case MyRenderMessageEnum.DebugClearPersistentMessages:
                {
                    MyRenderMessageDebugClearPersistentMessages rMessage = (MyRenderMessageDebugClearPersistentMessages)debugDrawMessage;
                    clearPersistent = true;
                    break;
                }

                default:
                {
                    break;
                }
                }
            }

            linesBatch.Commit();
            noDepthLinesBatch.Commit();
            lines2D.Commit();

            foreach (var message in m_persistentDebugMessagesTemp)
            {
                if (clearPersistent && m_currentPersistentDebugMessages.Remove(message))
                {
                    continue;
                }

                m_debugDrawMessages.Enqueue(message);
                m_currentPersistentDebugMessages.Add(message);
            }
        }
Пример #12
0
        internal static void DrawSceneDebug()
        {
            //ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            //ImmediateContext.Rasterizer.SetViewport(0, 0, m_settings.BackBufferWidth, m_settings.BackBufferHeight);
            //ImmediateContext.OutputMerger.ResetTargets();
            //ShaderResourceView[] shaderViews = m_gbuffer.ShaderViews;
            //ImmediateContext.OutputMerger.SetTargets(Backbuffer.RenderTarget);
            //ImmediateContext.PixelShader.SetConstantBuffer(0, m_frameCB.Buffer);
            //ImmediateContext.PixelShader.SetConstantBuffer(2, m_shadowsCB.Buffer);
            //ImmediateContext.PixelShader.SetShaderResources(0, shaderViews);

            //if (Settings.ShowGbufferDepth)
            //{
            //    ImmediateContext.PixelShader.Set(m_debugGbufferDepth.GetShader());
            //    DrawFullscreen();
            //}
            //else if (Settings.ShowGbufferAlbedo)
            //{
            //    ImmediateContext.PixelShader.Set(m_debugGbufferAlbedo.GetShader());
            //    DrawFullscreen();
            //}
            //else if (Settings.ShowGbufferNormals)
            //{
            //    ImmediateContext.PixelShader.Set(m_debugGbufferNormals.GetShader());
            //    DrawFullscreen();
            //}
            //else if (Settings.ShowCascadesRange)
            //{
            //    ImmediateContext.PixelShader.Set(m_debugContainingCascade.GetShader());
            //    DrawFullscreen();
            //}
            //if (Settings.ShowCascadesDepth)
            //{
            //    /*
            //    SetupSpritePipeline();
            //    ImmediateContext.PixelShader.Set(m_debugCascadeDepth.GetShader());
            //    ImmediateContext.PixelShader.SetConstantBuffer(3, m_debugCB.Buffer);
            //    ImmediateContext.PixelShader.SetShaderResource(7, m_cascadesTexture.ShaderView);

            //    const int horizontalCutoff = (MyRenderConstants.CASCADES_NUM + 1) / 2;
            //    var size = Math.Min(ViewportResolution.X / horizontalCutoff, ViewportResolution.Y / 2) - 3;

            //    for (int i = 0; i < MyRenderConstants.CASCADES_NUM; i++)
            //    {
            //        var stream = MapCB(m_debugCB);
            //        stream.Write(i);
            //        UnmapCB(m_debugCB);

            //        var gridX = i % horizontalCutoff;
            //        var gridY = i / horizontalCutoff;

            //        Vector2 csScale;
            //        Vector2 csOffset;
            //        CalculateSpriteClipspace(new RectangleF(new Vector2I(gridX * size + gridX, gridY * size + gridY), new Vector2I(size, size)), ViewportResolution, out csOffset, out csScale);

            //        DrawSprite(null, csOffset, csScale, Vector2.Zero, Vector2.One);
            //    }
            //     * */
            //}
            if (false)
            {
                /*
                 * var linesBatch = CreateLinesBatch();
                 *
                 * int objectsNum = MyRenderObjectPool.Size();
                 * for (int i = 0; i < objectsNum; i++)
                 * {
                 *  var bb = MyRenderObjectPool.m_cullinfos[i].worldAABB;
                 *
                 *  var v0 = bb.Center - bb.HalfExtents;
                 *  var v1 = v0 + new Vector3(bb.HalfExtents.X *2, 0, 0);
                 *  var v2 = v0 + new Vector3(bb.HalfExtents.X * 2, bb.HalfExtents.Y * 2, 0);
                 *  var v3 = v0 + new Vector3(0, bb.HalfExtents.Y * 2, 0);
                 *
                 *  var v4 = v0 + new Vector3(0, 0, bb.HalfExtents.Z * 2);
                 *  var v5 = v4 + new Vector3(bb.HalfExtents.X * 2, 0, 0);
                 *  var v6 = v4 + new Vector3(bb.HalfExtents.X * 2, bb.HalfExtents.Y * 2, 0);
                 *  var v7 = v4 + new Vector3(0, bb.HalfExtents.Y * 2, 0);
                 *
                 *  var color = new Byte4(255, 255, 255, 0);
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 * }
                 *
                 * linesBatch.Commit();
                 * */
                /*
                 * var linesBatch = CreateLinesBatch();
                 *
                 * int objectsNum = MyRenderObjectPool.Size();
                 * for (int i = 0; i < objectsNum; i++)
                 * {
                 *  var bb = MyRenderObjectPool.m_cullinfos[i].worldAABB;
                 *
                 *  var v0 = bb.Center - bb.HalfExtents;
                 *  var v1 = v0 + new Vector3(bb.HalfExtents.X *2, 0, 0);
                 *  var v2 = v0 + new Vector3(bb.HalfExtents.X * 2, bb.HalfExtents.Y * 2, 0);
                 *  var v3 = v0 + new Vector3(0, bb.HalfExtents.Y * 2, 0);
                 *
                 *  var v4 = v0 + new Vector3(0, 0, bb.HalfExtents.Z * 2);
                 *  var v5 = v4 + new Vector3(bb.HalfExtents.X * 2, 0, 0);
                 *  var v6 = v4 + new Vector3(bb.HalfExtents.X * 2, bb.HalfExtents.Y * 2, 0);
                 *  var v7 = v4 + new Vector3(0, bb.HalfExtents.Y * 2, 0);
                 *
                 *  var color = new Byte4(255, 255, 255, 0);
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 * }
                 *
                 * linesBatch.Commit();
                 * */
                /*
                 * var linesBatch = CreateLinesBatch();
                 *
                 * int objectsNum = MyRenderObjectPool.Size();
                 * for (int i = 0; i < objectsNum; i++)
                 * {
                 *  var bb = MyRenderObjectPool.m_cullinfos[i].worldAABB;
                 *
                 *  var v0 = bb.Center - bb.HalfExtents;
                 *  var v1 = v0 + new Vector3(bb.HalfExtents.X *2, 0, 0);
                 *  var v2 = v0 + new Vector3(bb.HalfExtents.X * 2, bb.HalfExtents.Y * 2, 0);
                 *  var v3 = v0 + new Vector3(0, bb.HalfExtents.Y * 2, 0);
                 *
                 *  var v4 = v0 + new Vector3(0, 0, bb.HalfExtents.Z * 2);
                 *  var v5 = v4 + new Vector3(bb.HalfExtents.X * 2, 0, 0);
                 *  var v6 = v4 + new Vector3(bb.HalfExtents.X * 2, bb.HalfExtents.Y * 2, 0);
                 *  var v7 = v4 + new Vector3(0, bb.HalfExtents.Y * 2, 0);
                 *
                 *  var color = new Byte4(255, 255, 255, 0);
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 * }
                 *
                 * linesBatch.Commit();
                 * */
            }

            //if(true)
            //{
            //    /*
            //    var linesBatch = MyRender.CreateLinesBatch();

            //    var list = new List<MySpatialObject>();
            //    var bsphere = new BoundingSphere(Vector3.Zero, 25.0f);
            //    MySpatialManager.Tree.OverlapAllBoundingSphere<MySpatialObject>(ref bsphere, list);
            //    var inIDs = new Dictionary<uint, object>();
            //    foreach(var item in list)
            //    {
            //        inIDs[item.ID] = null;
            //    }

            //    foreach (var item in MySpatialManager.AllValues())
            //    {
            //        var bb = item.m_aabb;

            //        var v0 = bb.Center - bb.HalfExtents;
            //        var v1 = v0 + new Vector3(bb.HalfExtents.X * 2, 0, 0);
            //        var v2 = v0 + new Vector3(bb.HalfExtents.X * 2, bb.HalfExtents.Y * 2, 0);
            //        var v3 = v0 + new Vector3(0, bb.HalfExtents.Y * 2, 0);

            //        var v4 = v0 + new Vector3(0, 0, bb.HalfExtents.Z * 2);
            //        var v5 = v4 + new Vector3(bb.HalfExtents.X * 2, 0, 0);
            //        var v6 = v4 + new Vector3(bb.HalfExtents.X * 2, bb.HalfExtents.Y * 2, 0);
            //        var v7 = v4 + new Vector3(0, bb.HalfExtents.Y * 2, 0);

            //        var color = new Byte4(255, 0, 0, 0);
            //        if (inIDs.ContainsKey(item.ID))
            //        {
            //            color = new Byte4(0, 255, 0, 0);
            //        }

            //        linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v3, color));

            //        linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v7, color));

            //        linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
            //    }

            //    linesBatch.Commit();
            //     * */
            //}

            // draw culling structure
            if (false)
            {
                var linesBatch = MyLinesRenderer.CreateLinesBatch();

                List <MyRenderObjectProxy> list = new List <MyRenderObjectProxy>();

                foreach (var obj in MySceneObject.Collection)
                {
                    linesBatch.AddBoundingBox(obj.AABB, Color.AntiqueWhite);
                }



                linesBatch.Commit();
            }

            if (false)
            {
                var linesBatch = MyLinesRenderer.CreateLinesBatch();

                var worldToClip = m_viewMatrix * m_projectionMatrix;

                var displayString = new StringBuilder();

                var screenPositions = new List <Vector2>(10000);
                var display         = new List <bool>(10000);
                foreach (var obj in MySceneObject.Collection)
                {
                    var position     = obj.m_spatial.m_worldMatrix.Translation;
                    var clipPosition = Vector3.Transform(position, ref worldToClip);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;
                    screenPositions.Add(new Vector2(clipPosition.X, clipPosition.Y) * ViewportResolution);
                    display.Add(clipPosition.Z > 0 && clipPosition.Z < 1);
                }

                int i = 0;
                foreach (var obj in MySceneObject.Collection)
                {
                    if (display[i])
                    {
                        //displayString.AppendFormat("ID: {0}, proxy ID: {1}", obj.ID, obj.m_spatial.proxyID);

                        var v  = obj.m_spatial.m_aabb.Center;
                        var vv = obj.m_spatial.m_aabb.HalfExtents;

                        //var vv = obj.m_spatial.m_localAabb.HasValue ? obj.m_spatial.m_localAabb.Value.Center : Vector3.Zero;
                        displayString.AppendFormat("<{0}, {1}, {2}> <{3}, {4}, {5}>", v.X, v.Y, v.Z, vv.X, vv.Y, vv.Z);
                        if (obj.m_spatial.m_localAabb.HasValue)
                        {
                            v  = obj.m_spatial.m_localAabb.Value.Center;
                            vv = obj.m_spatial.m_localAabb.Value.HalfExtents;
                            displayString.AppendFormat("local: <{0}, {1}, {2}> <{3}, {4}, {5}>", v.X, v.Y, v.Z, vv.X, vv.Y, vv.Z);
                        }

                        //if (v.X != 0 && v.Y != 0 && v.Z != 0)
                        {
                            if (obj.m_spatial.m_parent != null)
                            {
                                MySpritesRenderer.DrawText(screenPositions[i], displayString, Color.DarkCyan, 0.5f);
                            }
                            else
                            {
                                MySpritesRenderer.DrawText(screenPositions[i] + new Vector2(0, -25.0f), displayString, Color.LightSkyBlue, 1);
                            }
                        }
                    }

                    if (obj.m_spatial.m_parent != null)
                    {
                        linesBatch.Add(new MyVertexFormatPositionColor(obj.m_spatial.m_parent.m_worldMatrix.Translation, new Byte4(0, 0, 128, 25)));
                        linesBatch.Add(new MyVertexFormatPositionColor(obj.m_spatial.m_worldMatrix.Translation, new Byte4(0, 0, 128, 25)));
                    }

                    displayString.Clear();

                    i++;
                }

                linesBatch.Commit();
            }

            //UpdateDepthBias();

            //ImmediateContext.ClearState();
        }
Пример #13
0
        private static void DrawScene()
        {
            AddDebugQueueMessage("Frame render start");

            MyGpuProfiler.IC_BeginBlock("UpdateSceneFrame");
            UpdateSceneFrame();
            MyGpuProfiler.IC_EndBlock();

            var testingDepth = MyRender11.MultisamplingEnabled ? MyScreenDependants.m_resolvedDepth : MyGBuffer.Main.DepthStencil;

            MyGpuProfiler.IC_BeginBlock("Clear");
            MyGBuffer.Main.Clear(VRageMath.Color.Black);
            MyGpuProfiler.IC_EndBlock();

            if (MyOpenVR.Static != null)
            {
                ProfilerShort.Begin("OpenVR.WaitForNextStart");
                MyOpenVR.WaitForNextStart();
                ProfilerShort.End();
            }

            ProfilerShort.Begin("DrawGameScene");
            DrawGameScene(Backbuffer);
            ProfilerShort.End();
            if (MyOpenVR.Static != null)
            {
                ProfilerShort.Begin("OpenVR.DisplayEye");
                MyGpuProfiler.IC_BeginBlock("OpenVR.DisplayEye");
                MyGBuffer.Main.Clear(VRageMath.Color.Black);//image is in HMD now, lets draw the rest for overlay
                MyOpenVR.Static.DisplayEye(MyRender11.Backbuffer.Resource.NativePointer);
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();
            }

            ProfilerShort.Begin("Draw scene debug");
            MyGpuProfiler.IC_BeginBlock("Draw scene debug");
            DrawSceneDebug();
            ProfilerShort.End();

            ProfilerShort.Begin("ProcessDebugMessages");
            ProcessDebugMessages();
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            ProfilerShort.Begin("MyDebugRenderer.Draw");
            MyGpuProfiler.IC_BeginBlock("MyDebugRenderer.Draw");
            MyDebugRenderer.Draw(MyRender11.Backbuffer);
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            ProfilerShort.Begin("MyPrimitivesRenderer.Draw");
            MyGpuProfiler.IC_BeginBlock("MyPrimitivesRenderer.Draw");
            MyPrimitivesRenderer.Draw(MyRender11.Backbuffer, testingDepth);
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            ProfilerShort.Begin("MyLinesRenderer.Draw");
            MyGpuProfiler.IC_BeginBlock("MyLinesRenderer.Draw");
            MyLinesRenderer.Draw(MyRender11.Backbuffer, testingDepth);
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            if (m_screenshot.HasValue && m_screenshot.Value.IgnoreSprites)
            {
                ProfilerShort.Begin("Screenshot");
                if (m_screenshot.Value.SizeMult == Vector2.One)
                {
                    SaveScreenshotFromResource(Backbuffer.Resource);
                }
                else
                {
                    TakeCustomSizedScreenshot(m_screenshot.Value.SizeMult);
                }
                ProfilerShort.End();
            }

            ProfilerShort.Begin("ProcessDebugOutput");
            AddDebugQueueMessage("Frame render end");
            ProcessDebugOutput();
            ProfilerShort.End();
        }
Пример #14
0
        /// <summary>
        /// Creates shadowmap queries and appends them to the provided list
        /// </summary>
        internal unsafe void PrepareQueries(List <MyShadowmapQuery> appendShadowmapQueries)
        {
            Debug.Assert(appendShadowmapQueries != null, "Shadowmap query list cannot be null!");
            if (!MyRenderProxy.Settings.EnableShadows)
            {
                return;
            }

            MyImmediateRC.RC.BeginProfilingBlock("PrepareCascades");
            MyImmediateRC.RC.DeviceContext.CopyResource(m_cascadeShadowmapArray.Resource, m_cascadeShadowmapBackup.Resource);

            bool        stabilize = true;
            const float DirectionDifferenceThreshold = 0.0175f;

            float shadowChangeDelayMultiplier = 180;

            for (int cascadeIndex = 0; cascadeIndex < m_initializedShadowCascadesCount; ++cascadeIndex)
            {
                ++m_shadowCascadeFramesSinceLightUpdate[cascadeIndex];

                if (m_shadowCascadeFramesSinceLightUpdate[cascadeIndex] > cascadeIndex * shadowChangeDelayMultiplier ||
                    MyEnvironment.DirectionalLightDir.Dot(m_shadowCascadeLightDirections[cascadeIndex]) < (1 - DirectionDifferenceThreshold))
                {
                    m_shadowCascadeLightDirections[cascadeIndex]        = MyEnvironment.DirectionalLightDir;
                    m_shadowCascadeFramesSinceLightUpdate[cascadeIndex] = 0;
                }
            }

            var globalMatrix = CreateGlobalMatrix();

            var cascadeFrozen = MyRenderProxy.Settings.ShadowCascadeFrozen.Any(x => x == true);

            if (!cascadeFrozen)
            {
                m_oldView = MyEnvironment.View;
            }

            float cascadesNearClip = 1f;

            float backOffset    = MyRender11.RenderSettings.ShadowQuality.BackOffset();
            float shadowmapSize = MyRender11.RenderSettings.ShadowQuality.ShadowCascadeResolution();

            for (int cascadeIndex = 0; cascadeIndex < ShadowCascadeSplitDepths.Length; ++cascadeIndex)
            {
                ShadowCascadeSplitDepths[cascadeIndex] = MyRender11.RenderSettings.ShadowQuality.ShadowCascadeSplit(cascadeIndex);
            }

            double unitWidth  = 1.0 / MyEnvironment.Projection.M11;
            double unitHeight = 1.0 / MyEnvironment.Projection.M22;

            Vector3D *untransformedVertices = stackalloc Vector3D[4];

            untransformedVertices[0] = new Vector3D(-unitWidth, -unitHeight, -1);
            untransformedVertices[1] = new Vector3D(-unitWidth, unitHeight, -1);
            untransformedVertices[2] = new Vector3D(unitWidth, unitHeight, -1);
            untransformedVertices[3] = new Vector3D(unitWidth, -unitHeight, -1);

            MatrixD *cascadesMatrices = stackalloc MatrixD[MaxShadowCascades];

            for (int cascadeIndex = 0; cascadeIndex < m_initializedShadowCascadesCount; ++cascadeIndex)
            {
                for (int vertexIndex = 0; vertexIndex < 4; ++vertexIndex)
                {
                    m_frustumVerticesWS[vertexIndex]     = untransformedVertices[vertexIndex] * ShadowCascadeSplitDepths[cascadeIndex];
                    m_frustumVerticesWS[vertexIndex + 4] = untransformedVertices[vertexIndex] * ShadowCascadeSplitDepths[cascadeIndex + 1];
                }

                if (MyRender11.Settings.ShadowCascadeFrozen[cascadeIndex])
                {
                    // draw cascade bounding primtiive
                    if (VISUALIZE_DEBUG)
                    {
                        var oldInvView = MatrixD.Invert(m_oldView);
                        Vector3D.Transform(m_frustumVerticesWS, ref oldInvView, m_frustumVerticesWS);

                        var verticesF = new Vector3[8];
                        for (int i = 0; i < 8; i++)
                        {
                            verticesF[i] = m_frustumVerticesWS[i];
                        }
                        var batch = MyLinesRenderer.CreateBatch();
                        batch.Add6FacedConvex(verticesF, Color.Blue);

                        var bs = BoundingSphere.CreateFromPoints(verticesF);
                        var bb = BoundingBox.CreateFromSphere(bs);
                        batch.AddBoundingBox(bb, Color.OrangeRed);

                        batch.Commit();
                    }

                    continue;
                }

                bool skipCascade = MyCommon.FrameCounter % (ulong)m_shadowCascadeUpdateIntervals[cascadeIndex].Item1 != (ulong)m_shadowCascadeUpdateIntervals[cascadeIndex].Item2;
                bool forceUpdate = ShadowCascadeSplitDepths[cascadeIndex] > 1000f && Vector3D.DistanceSquared(m_shadowCascadeUpdatePositions[cascadeIndex], MyEnvironment.CameraPosition) > Math.Pow(1000, 2);
                //
                if (!forceUpdate && skipCascade && !MyRenderProxy.Settings.UpdateCascadesEveryFrame)
                {
                    continue;
                }

                m_shadowCascadeUpdatePositions[cascadeIndex] = MyEnvironment.CameraPosition;

                MatrixD invView = MyEnvironment.InvView;
                Vector3D.Transform(m_frustumVerticesWS, ref invView, m_frustumVerticesWS);

                var bSphere = BoundingSphereD.CreateFromPoints(m_frustumVerticesWS);
                if (stabilize)
                {
                    bSphere.Center = bSphere.Center.Round();
                    bSphere.Radius = Math.Ceiling(bSphere.Radius);
                }

                var shadowCameraPosWS = bSphere.Center + m_shadowCascadeLightDirections[cascadeIndex] * (bSphere.Radius + cascadesNearClip);

                var lightView = VRageMath.MatrixD.CreateLookAt(shadowCameraPosWS, shadowCameraPosWS - m_shadowCascadeLightDirections[cascadeIndex], Math.Abs(Vector3.UnitY.Dot(m_shadowCascadeLightDirections[cascadeIndex])) < 0.99f ? Vector3.UnitY : Vector3.UnitX);
                var offset    = bSphere.Radius + cascadesNearClip + backOffset;

                Vector3D vMin = new Vector3D(-bSphere.Radius, -bSphere.Radius, cascadesNearClip);
                Vector3D vMax = new Vector3D(bSphere.Radius, bSphere.Radius, offset + bSphere.Radius);

                var cascadeProjection = MatrixD.CreateOrthographicOffCenter(vMin.X, vMax.X, vMin.Y, vMax.Y, vMax.Z, vMin.Z);
                cascadesMatrices[cascadeIndex] = lightView * cascadeProjection;

                var transformed = Vector3D.Transform(Vector3D.Zero, cascadesMatrices[cascadeIndex]) * shadowmapSize / 2;
                var smOffset    = (transformed.Round() - transformed) * 2 / shadowmapSize;

                // stabilize 1st cascade only
                if (stabilize)
                {
                    cascadeProjection.M41         += smOffset.X;
                    cascadeProjection.M42         += smOffset.Y;
                    cascadesMatrices[cascadeIndex] = lightView * cascadeProjection;
                }

                var inverseCascadeMatrix = MatrixD.Invert(cascadesMatrices[cascadeIndex]);
                var corner0 = Vector3D.Transform(Vector3D.Transform(new Vector3D(-1, -1, 0), inverseCascadeMatrix), globalMatrix);
                var corner1 = Vector3D.Transform(Vector3D.Transform(new Vector3D(1, 1, 1), inverseCascadeMatrix), globalMatrix);

                var diameter = corner1 - corner0;

                var cascadeScale = 1f / diameter;
                ShadowCascadeScales[cascadeIndex] = new Vector4D(cascadeScale, 0);

                var query = new MyShadowmapQuery();
                query.DepthBuffer = m_cascadeShadowmapArray.SubresourceDsv(cascadeIndex);
                query.Viewport    = new MyViewport(shadowmapSize, shadowmapSize);

                m_cascadeInfo[cascadeIndex].WorldCameraOffsetPosition = MyEnvironment.CameraPosition;
                m_cascadeInfo[cascadeIndex].WorldToProjection         = cascadesMatrices[cascadeIndex];
                // todo: skip translation, recalculate matrix in local space, keep world space matrix only for bounding frustum
                m_cascadeInfo[cascadeIndex].LocalToProjection = Matrix.CreateTranslation(MyEnvironment.CameraPosition) * cascadesMatrices[cascadeIndex];

                query.ProjectionInfo   = m_cascadeInfo[cascadeIndex];
                query.ProjectionDir    = m_shadowCascadeLightDirections[cascadeIndex];
                query.ProjectionFactor = (float)(shadowmapSize * shadowmapSize / (bSphere.Radius * bSphere.Radius * 4));

                query.QueryType    = MyFrustumEnum.ShadowCascade;
                query.CascadeIndex = cascadeIndex;

                appendShadowmapQueries.Add(query);
            }

            if (VISUALIZE_DEBUG)
            {
                DebugDrawFrozen(cascadesMatrices);
            }

            FillConstantBuffer(m_csmConstants);

            MyImmediateRC.RC.EndProfilingBlock();
        }
Пример #15
0
        private static void ProcessDrawMessage(MyRenderMessageBase drawMessage)
        {
            switch (drawMessage.MessageType)
            {
            case MyRenderMessageEnum.SpriteScissorPush:
            {
                var msg = drawMessage as MyRenderMessageSpriteScissorPush;

                MySpritesRenderer.ScissorStackPush(msg.ScreenRectangle);

                break;
            }

            case MyRenderMessageEnum.SpriteScissorPop:
            {
                MySpritesRenderer.ScissorStackPop();

                break;
            }

            case MyRenderMessageEnum.DrawSprite:
            {
                MyRenderMessageDrawSprite sprite = (MyRenderMessageDrawSprite)drawMessage;

                MySpritesRenderer.AddSingleSprite(MyTextures.GetTexture(sprite.Texture, MyTextureEnum.GUI, waitTillLoaded: sprite.WaitTillLoaded), sprite.Color, sprite.Origin, sprite.RightVector, sprite.SourceRectangle, sprite.DestinationRectangle);

                break;
            }

            case MyRenderMessageEnum.DrawSpriteNormalized:
            {
                MyRenderMessageDrawSpriteNormalized sprite = (MyRenderMessageDrawSpriteNormalized)drawMessage;

                var rotation = sprite.Rotation;
                if (sprite.RotationSpeed != 0)
                {
                    rotation += sprite.RotationSpeed * (float)(MyRender11.CurrentDrawTime - MyRender11.CurrentUpdateTime).Seconds;
                }

                Vector2 rightVector = rotation != 0f ? new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)) : sprite.RightVector;

                int safeGuiSizeY = MyRender11.ResolutionI.Y;
                int safeGuiSizeX = (int)(safeGuiSizeY * 1.3333f);             //  This will mantain same aspect ratio for GUI elements

                var   safeGuiRectangle = new VRageMath.Rectangle(MyRender11.ResolutionI.X / 2 - safeGuiSizeX / 2, 0, safeGuiSizeX, safeGuiSizeY);
                var   safeScreenScale  = (float)safeGuiSizeY / MyRenderGuiConstants.REFERENCE_SCREEN_HEIGHT;
                float fixedScale       = sprite.Scale * safeScreenScale;

                var tex = MyTextures.GetTexture(sprite.Texture, MyTextureEnum.GUI, true);

                var normalizedCoord = sprite.NormalizedCoord;
                var screenCoord     = new Vector2(safeGuiRectangle.Left + safeGuiRectangle.Width * normalizedCoord.X,
                                                  safeGuiRectangle.Top + safeGuiRectangle.Height * normalizedCoord.Y);

                var sizeInPixels       = MyTextures.GetSize(tex);
                var sizeInPixelsScaled = sizeInPixels * fixedScale;

                Vector2 alignedScreenCoord = screenCoord;
                var     drawAlign          = sprite.DrawAlign;

                if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP)
                {
                    //  Nothing to do as position is already at this point
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER)
                {
                    //  Move position to the texture center
                    alignedScreenCoord -= sizeInPixelsScaled / 2.0f;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_TOP)
                {
                    alignedScreenCoord.X -= sizeInPixelsScaled.X / 2.0f;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_BOTTOM)
                {
                    alignedScreenCoord.X -= sizeInPixelsScaled.X / 2.0f;
                    alignedScreenCoord.Y -= sizeInPixelsScaled.Y;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_BOTTOM)
                {
                    alignedScreenCoord -= sizeInPixelsScaled;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER)
                {
                    alignedScreenCoord.Y -= sizeInPixelsScaled.Y / 2.0f;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_CENTER)
                {
                    alignedScreenCoord.X -= sizeInPixelsScaled.X;
                    alignedScreenCoord.Y -= sizeInPixelsScaled.Y / 2.0f;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_BOTTOM)
                {
                    alignedScreenCoord.Y -= sizeInPixelsScaled.Y;        // *0.75f;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_TOP)
                {
                    alignedScreenCoord.X -= sizeInPixelsScaled.X;
                }

                screenCoord = alignedScreenCoord;

                var     rect = new RectangleF(screenCoord.X, screenCoord.Y, fixedScale * sizeInPixels.X, fixedScale * sizeInPixels.Y);
                Vector2 origin;
                if (sprite.OriginNormalized.HasValue)
                {
                    origin = sprite.OriginNormalized.Value * sizeInPixels;
                }
                else
                {
                    origin = sizeInPixels / 2;
                }

                sprite.OriginNormalized = sprite.OriginNormalized ?? new Vector2(0.5f);

                MySpritesRenderer.AddSingleSprite(MyTextures.GetTexture(sprite.Texture, MyTextureEnum.GUI, waitTillLoaded: sprite.WaitTillLoaded), sprite.Color, origin, rightVector, null, rect);

                break;
            }


            case MyRenderMessageEnum.DrawSpriteAtlas:
            {
                MyRenderMessageDrawSpriteAtlas sprite = (MyRenderMessageDrawSpriteAtlas)drawMessage;

                var tex         = MyTextures.GetTexture(sprite.Texture, MyTextureEnum.GUI, true);
                var textureSize = MyTextures.GetSize(tex);

                Rectangle?sourceRect = new Rectangle(
                    (int)(textureSize.X * sprite.TextureOffset.X),
                    (int)(textureSize.Y * sprite.TextureOffset.Y),
                    (int)(textureSize.X * sprite.TextureSize.X),
                    (int)(textureSize.Y * sprite.TextureSize.Y));

                VRageMath.RectangleF destRect = new VRageMath.RectangleF(
                    (sprite.Position.X) * sprite.Scale.X,
                    (sprite.Position.Y) * sprite.Scale.Y,
                    sprite.HalfSize.X * sprite.Scale.X * 2,
                    sprite.HalfSize.Y * sprite.Scale.Y * 2);

                Vector2 origin = new Vector2(textureSize.X * sprite.TextureSize.X * 0.5f, textureSize.Y * sprite.TextureSize.Y * 0.5f);

                MySpritesRenderer.AddSingleSprite(MyTextures.GetTexture(sprite.Texture, MyTextureEnum.GUI, true), sprite.Color, origin, sprite.RightVector, sourceRect, destRect);

                break;
            }

            case MyRenderMessageEnum.DrawString:
            {
                var message = drawMessage as MyRenderMessageDrawString;

                var font = MyRender11.GetFont(message.FontIndex);
                font.DrawString(
                    message.ScreenCoord,
                    message.ColorMask,
                    message.Text,
                    message.ScreenScale,
                    message.ScreenMaxWidth);

                break;
            }

            case MyRenderMessageEnum.DrawScene:
            {
                UpdateSceneFrame();

                ProfilerShort.Begin("DrawScene");
                DrawGameScene(Backbuffer);
                ProfilerShort.Begin("TransferPerformanceStats");
                TransferPerformanceStats();
                ProfilerShort.End();
                ProfilerShort.End();

                ProfilerShort.Begin("Draw scene debug");
                MyGpuProfiler.IC_BeginBlock("Draw scene debug");
                DrawSceneDebug();
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();

                ProfilerShort.Begin("ProcessDebugMessages");
                ProcessDebugMessages();
                ProfilerShort.End();

                ProfilerShort.Begin("MyDebugRenderer.Draw");
                MyGpuProfiler.IC_BeginBlock("MyDebugRenderer.Draw");
                MyDebugRenderer.Draw(MyRender11.Backbuffer);
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();

                var testingDepth = MyRender11.MultisamplingEnabled ? MyScreenDependants.m_resolvedDepth : MyGBuffer.Main.DepthStencil;

                ProfilerShort.Begin("MyPrimitivesRenderer.Draw");
                MyGpuProfiler.IC_BeginBlock("MyPrimitivesRenderer.Draw");
                MyPrimitivesRenderer.Draw(MyRender11.Backbuffer, testingDepth);
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();

                ProfilerShort.Begin("MyLinesRenderer.Draw");
                MyGpuProfiler.IC_BeginBlock("MyLinesRenderer.Draw");
                MyLinesRenderer.Draw(MyRender11.Backbuffer, testingDepth);
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();

                if (m_screenshot.HasValue && m_screenshot.Value.IgnoreSprites)
                {
                    if (m_screenshot.Value.SizeMult == Vector2.One)
                    {
                        SaveScreenshotFromResource(Backbuffer.m_resource);
                    }
                    else
                    {
                        TakeCustomSizedScreenshot(m_screenshot.Value.SizeMult);
                    }
                }

                ProfilerShort.Begin("MySpritesRenderer.Draw");
                MyGpuProfiler.IC_BeginBlock("MySpritesRenderer.Draw");
                MySpritesRenderer.Draw(MyRender11.Backbuffer.m_RTV, new MyViewport(MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y));
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();

                if (MyRenderProxy.DRAW_RENDER_STATS)
                {
                    MyRender11.GetRenderProfiler().StartProfilingBlock("MyRenderStatsDraw.Draw");
                    MyRenderStatsDraw.Draw(MyRenderStats.m_stats, 0.6f, VRageMath.Color.Yellow);
                    ProfilerShort.End();
                }

                break;
            }
            }
        }
Пример #16
0
        internal static void Draw(bool draw = true)
        {
            try
            {
                GetRenderProfiler().StartProfilingBlock("ProcessMessages");
                ProcessMessageQueue();
                GetRenderProfiler().EndProfilingBlock();


                GetRenderProfiler().StartProfilingBlock("RebuildShaders");

                //

                //MyShaderCache.CompilePending();
                //MyShaderFactory.RunCompilation();

                GetRenderProfiler().EndProfilingBlock();

                if (draw)
                {
                    MyImmediateRC.RC.Clear();
                    GetRenderProfiler().StartProfilingBlock("ProcessDrawQueue");
                    ProcessDrawQueue();
                    GetRenderProfiler().EndProfilingBlock();

                    GetRenderProfiler().StartProfilingBlock("ProcessDebugMessages");
                    ProcessDebugMessages();
                    GetRenderProfiler().EndProfilingBlock();

                    GetRenderProfiler().StartProfilingBlock("MySpritesRenderer.Draw");
                    MyCommon.UpdateFrameConstants();
                    MySpritesRenderer.Draw(MyRender11.Backbuffer.m_RTV, new MyViewport(MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y));
                    GetRenderProfiler().EndProfilingBlock();

                    MyTextures.Load();
                }

                if (m_profilingStarted)
                {
                    MyGpuProfiler.IC_BeginBlock("Waiting for present");
                }

                MyLinesRenderer.Clear();
                MySpritesRenderer.Clear();

                m_drawQueue.Clear();
                m_debugDrawMessages.Clear();
            }
            catch (SharpDXException e)
            {
                MyRender11.Log.IncreaseIndent();
                MyRender11.Log.WriteLine(" " + e);
                if (e.Descriptor == SharpDX.DXGI.ResultCode.DeviceRemoved)
                {
                    MyRender11.Log.WriteLine("Reason: " + Device.DeviceRemovedReason);
                }
                MyRender11.Log.DecreaseIndent();

                throw e;
            }
        }
Пример #17
0
        internal static void DrawHierarchyDebug()
        {
            var worldToClip   = MyEnvironment.ViewProjection;
            var displayString = new StringBuilder();

            var batch = MyLinesRenderer.CreateBatch();

            if (MyRender11.Settings.DisplayIDs)
            {
                foreach (var actor in MyActorFactory.GetAll())
                {
                    var h = actor.GetGroupLeaf();
                    var r = actor.GetRenderable();

                    Vector3 position;
                    uint    ID;

                    if (r != null)
                    {
                        position = r.Owner.WorldMatrix.Translation;
                        ID       = r.Owner.ID;
                    }
                    else if (h != null)
                    {
                        position = h.Owner.WorldMatrix.Translation;
                        ID       = h.Owner.ID;
                    }
                    else
                    {
                        continue;
                    }

                    var clipPosition = Vector3.Transform(position, ref worldToClip);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;

                    if (clipPosition.Z > 0 && clipPosition.Z < 1)
                    {
                        displayString.AppendFormat("{0}", ID);
                        MySpritesRenderer.DrawText(new Vector2(clipPosition.X, clipPosition.Y) * MyRender11.ViewportResolution,
                                                   displayString, Color.DarkCyan, 0.5f);
                    }

                    displayString.Clear();
                }
            }

            if (MyRender11.Settings.DisplayAabbs)
            {
                foreach (var actor in MyActorFactory.GetAll())
                {
                    var h = actor.GetGroupRoot();
                    var r = actor.GetRenderable();

                    if (h != null)
                    {
                        var bb = BoundingBoxD.CreateInvalid();

                        foreach (var child in h.m_children)
                        {
                            if (child.IsVisible)
                            {
                                bb.Include(child.Aabb);
                            }
                        }

                        batch.AddBoundingBox((BoundingBox)bb, Color.Red);
                        MyPrimitivesRenderer.Draw6FacedConvexZ(bb.GetCorners().Select(x => (Vector3)x).ToArray(), Color.Red, 0.1f);
                    }
                    else if (r != null && actor.GetGroupLeaf() == null)
                    {
                        batch.AddBoundingBox((BoundingBox)r.Owner.Aabb, Color.Green);
                    }
                }
            }

            batch.Commit();
        }
Пример #18
0
 internal void Commit()
 {
     MyLinesRenderer.Commit(this);
 }
Пример #19
0
        internal static void Draw(IRtvBindable renderTarget, IRtvTexture ambientOcclusion)
        {
            RC.SetPrimitiveTopology(PrimitiveTopology.TriangleList);
            RC.SetViewport(0, 0, MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y);
            RC.PixelShader.SetConstantBuffer(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);

            RC.SetRtv(renderTarget);
            RC.PixelShader.SetSrvs(0, MyGBuffer.Main);

            RC.SetBlendState(null);

            if (MyRender11.Settings.DisplayGbufferColor)
            {
                RC.PixelShader.Set(m_baseColorShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayGbufferAlbedo)
            {
                RC.PixelShader.Set(m_albedoShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayGbufferNormal)
            {
                RC.PixelShader.Set(m_normalShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayGbufferNormalView)
            {
                RC.PixelShader.Set(m_normalViewShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayGbufferGlossiness)
            {
                RC.PixelShader.Set(m_glossinessShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayGbufferMetalness)
            {
                RC.PixelShader.Set(m_metalnessShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayGbufferAO)
            {
                RC.PixelShader.Set(m_aoShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayEmissive)
            {
                RC.PixelShader.Set(m_emissiveShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayAmbientDiffuse)
            {
                RC.PixelShader.Set(m_ambientDiffuseShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayAmbientSpecular)
            {
                RC.PixelShader.Set(m_ambientSpecularShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayEdgeMask)
            {
                RC.PixelShader.Set(m_edgeDebugShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayShadowsWithDebug)
            {
                RC.PixelShader.Set(m_shadowsDebugShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayNDotL)
            {
                RC.PixelShader.Set(m_NDotLShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayGbufferLOD)
            {
                RC.PixelShader.Set(m_LODShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayMipmap)
            {
                RC.PixelShader.Set(m_baseColorShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayDepth)
            {
                RC.PixelShader.Set(m_depthShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayReprojectedDepth)
            {
                var dst = MyManagers.RwTexturesPool.BorrowUav("DebugRender.DepthReprojection", Format.R32_Float);
                MyRender11.RC.ClearUav(dst, SharpDX.Int4.Zero);

                RC.ComputeShader.SetConstantBuffer(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);
                RC.ComputeShader.SetSrv(0, MyGBuffer.Main.DepthStencil.SrvDepth);
                RC.ComputeShader.SetUav(0, dst);
                RC.ComputeShader.Set(m_depthReprojectionShader);
                int numThreadGroupsX = align(MyRender11.ResolutionI.X, 32) / 32;
                int numThreadGroupsY = align(MyRender11.ResolutionI.Y, 32) / 32;
                RC.Dispatch(numThreadGroupsX, numThreadGroupsY, 1);
                RC.ComputeShader.SetSrv(0, null);
                RC.ComputeShader.SetUav(0, null);

                RC.PixelShader.SetSrv(0, dst);
                RC.PixelShader.Set(m_depthShader);
                MyScreenPass.DrawFullscreenQuad();

                RC.PixelShader.SetSrv(0, MyGBuffer.Main.DepthStencil.SrvDepth);
            }
            else if (MyRender11.Settings.DisplayStencil)
            {
                RC.PixelShader.Set(m_stencilShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayAO)
            {
                RC.PixelShader.SetSrv(0, ambientOcclusion);
                RC.PixelShader.SetSampler(0, MySamplerStateManager.Linear);
                RC.PixelShader.Set(m_rtShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayEnvProbe)
            {
                DrawEnvProbe();
            }

            //DrawEnvProbe();
            //DrawAtmosphereTransmittance(MyAtmosphereRenderer.AtmosphereLUT.Keys.ToArray()[0]);
            //DrawAtmosphereInscatter(MyAtmosphereRenderer.AtmosphereLUT.Keys.ToArray()[0]);

            if (MyRender11.Settings.DrawCascadeTextures)
            {
                //DrawDepthArrayTexture(MyManagers.Shadow.GetCsmForGbuffer(), 100, 100, 200);
                DrawDepthArrayTexture(MyRender11.DynamicShadows.ShadowCascades.CascadeShadowmapArray, 100, 100, 200);
                if (MyScene.SeparateGeometry)
                {
                    DrawDepthArrayTexture(MyRender11.StaticShadows.ShadowCascades.CascadeShadowmapArray, 100, 300, 200);
                    DrawDepthArrayTexture(MyShadowCascades.CombineShadowmapArray, 100, 500, 200);
                }
            }

            if (MyRender11.Settings.DisplayIDs || MyRender11.Settings.DisplayAabbs)
            {
                DrawHierarchyDebug();
            }

            if (false)
            {
                var batch = MyLinesRenderer.CreateBatch();

                foreach (var light in MyLightsRendering.VisiblePointlights)
                {
                    batch.AddSphereRing(new BoundingSphere(light.PointPosition, 0.5f), Color.White, Matrix.Identity);
                }
                batch.Commit();
            }

            // draw terrain lods
            if (MyRender11.Settings.DebugRenderClipmapCells)
            {
                //var batch = MyLinesRenderer.CreateBatch();

                //foreach (var renderable in MyComponentFactory<MyRenderableComponent>.GetAll().Where(x => (MyMeshes.IsVoxelMesh(x.Mesh))))
                //{
                //    if (renderable.IsVisible)
                //    {
                //        if (renderable.m_lod >= LOD_COLORS.Length)
                //            return;

                //        BoundingBox bb = new BoundingBox(renderable.m_owner.Aabb.Min - MyRender11.Environment.CameraPosition,renderable.m_owner.Aabb.Max - MyRender11.Environment.CameraPosition);

                //        batch.AddBoundingBox(bb, new Color(LOD_COLORS[renderable.m_voxelLod]));


                //        if (renderable.m_lods != null && renderable.m_voxelLod != renderable.m_lods[0].RenderableProxies[0].ObjectData.CustomAlpha)
                //        {

                //        }
                //    }
                //}

                //batch.Commit();

                MyClipmap.DebugDrawClipmaps();
            }

            //if(true)
            //{
            //    var batch = MyLinesRenderer.CreateBatch();

            //    foreach(var id in MyLights.DirtySpotlights)
            //    {
            //        var info = MyLights.Spotlights[id.Index];

            //        if(info.ApertureCos > 0)
            //        {
            //            var D = info.Direction * info.Range;
            //            //batch.AddCone(MyLights.Lights.Data[id.Index].Position + D, -D, info.Up.Cross(info.Direction) * info.BaseRatio * info.Range, 32, Color.OrangeRed);

            //            //var bb = MyLights.AabbFromCone(info.Direction, info.ApertureCos, info.Range).Transform(Matrix.CreateLookAt(MyLights.Lights.Data[id.Index].Position, info.Direction, info.Up));


            //            //batch.AddBoundingBox(bb, Color.Green);

            //            batch.AddCone(MyLights.Lights.Data[id.Index].Position + D, -D, info.Up.Cross(info.Direction) * info.BaseRatio * info.Range, 32, Color.OrangeRed);

            //            var bb = MyLights.AabbFromCone(info.Direction, info.ApertureCos, info.Range, MyLights.Lights.Data[id.Index].Position, info.Up);
            //            batch.AddBoundingBox(bb, Color.Green);
            //        }
            //    }



            //    batch.Commit();
            //}

            // draw lods
            if (false)
            {
                var batch = MyLinesRenderer.CreateBatch();

                //foreach (var renderable in MyComponentFactory<MyRenderableComponent>.GetAll().Where(x => ((x.GetMesh() as MyVoxelMesh) == null)))
                //{

                //    if (renderable.CurrentLodNum >= LOD_COLORS.Length || renderable.m_lods.Length == 1)
                //        continue;

                //    batch.AddBoundingBox(renderable.m_owner.Aabb, new Color(LOD_COLORS[renderable.CurrentLodNum]));
                //}

                batch.Commit();
            }
        }
Пример #20
0
        private static void DrawScene()
        {
            AddDebugQueueMessage("Frame render start");

            MyGpuProfiler.IC_BeginBlock("UpdateSceneFrame");
            UpdateSceneFrame();
            MyGpuProfiler.IC_EndBlock();

            MyGpuProfiler.IC_BeginBlock("Clear");
            MyGBuffer.Main.Clear(VRageMath.Color.Black);
            MyGpuProfiler.IC_EndBlock();

            if (MyOpenVR.Static != null)
            {
                ProfilerShort.Begin("OpenVR.WaitForNextStart");
                MyOpenVR.WaitForNextStart();
                ProfilerShort.End();
            }

            IBorrowedRtvTexture debugAmbientOcclusion; // TODO: Think of another way to get this texture to the DebugRenderer...

            ProfilerShort.Begin("DrawGameScene");
            DrawGameScene(Backbuffer, out debugAmbientOcclusion);
            ProfilerShort.End();
            if (MyOpenVR.Static != null)
            {
                ProfilerShort.Begin("OpenVR.DisplayEye");
                MyGpuProfiler.IC_BeginBlock("OpenVR.DisplayEye");
                MyGBuffer.Main.Clear(VRageMath.Color.Black);//image is in HMD now, lets draw the rest for overlay
                MyOpenVR.Static.DisplayEye(MyRender11.Backbuffer.Resource.NativePointer);
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();
            }

            ProfilerShort.Begin("Draw scene debug");
            MyGpuProfiler.IC_BeginBlock("Draw scene debug");
            DrawSceneDebug();
            ProfilerShort.End();

            ProfilerShort.Begin("ProcessDebugMessages");
            ProcessDebugMessages();
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            ProfilerShort.Begin("MyDebugRenderer.Draw");
            MyGpuProfiler.IC_BeginBlock("MyDebugRenderer.Draw");
            MyDebugRenderer.Draw(MyRender11.Backbuffer, debugAmbientOcclusion);
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            debugAmbientOcclusion.Release();

            ProfilerShort.Begin("MyPrimitivesRenderer.Draw");
            MyGpuProfiler.IC_BeginBlock("MyPrimitivesRenderer.Draw");
            MyPrimitivesRenderer.Draw(MyRender11.Backbuffer);
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            ProfilerShort.Begin("MyLinesRenderer.Draw");
            MyGpuProfiler.IC_BeginBlock("MyLinesRenderer.Draw");
            MyLinesRenderer.Draw(MyRender11.Backbuffer);
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            if (m_screenshot.HasValue && m_screenshot.Value.IgnoreSprites)
            {
                ProfilerShort.Begin("Screenshot");
                if (m_screenshot.Value.SizeMult == Vector2.One)
                {
                    SaveScreenshotFromResource(Backbuffer);
                }
                else
                {
                    TakeCustomSizedScreenshot(m_screenshot.Value.SizeMult);
                }
                ProfilerShort.End();
            }

            ProfilerShort.Begin("ProcessDebugOutput");
            AddDebugQueueMessage("Frame render end");
            ProcessDebugOutput();
            ProfilerShort.End();
        }
Пример #21
0
        internal static void Draw(bool draw = true)
        {
            //if (false) Debug.Assert(MyClipmap.LodLevel.DrewLastFrame);
            //MyClipmap.LodLevel.DrewLastFrame = false;

            try
            {
                MyGpuProfiler.IC_BeginBlock("Draw");
                GetRenderProfiler().StartProfilingBlock("ProcessMessages");
                MyGpuProfiler.IC_BeginBlock("ProcessMessageQueue");
                TransferLocalMessages();
                ProcessMessageQueue();
                MyGpuProfiler.IC_EndBlock();
                GetRenderProfiler().EndProfilingBlock();

                if (draw)
                {
                    //MyLog.Default.WriteLine("Draw");
                    //MyOpenVR.ReadPoses();
                    MyRender11.ClearBackbuffer(MyRender11.Environment.BackgroundColor);
                    MyImmediateRC.RC.Clear();

                    GetRenderProfiler().StartProfilingBlock("ProcessDrawQueue");
                    ProcessDrawQueue();
                    GetRenderProfiler().EndProfilingBlock();

                    /*GetRenderProfiler().StartProfilingBlock("ProcessDebugMessages");
                     * ProcessDebugMessages();
                     * GetRenderProfiler().EndProfilingBlock();*/

                    GetRenderProfiler().StartProfilingBlock("MySpritesRenderer.Draw");
                    MyGpuProfiler.IC_BeginBlock("SpriteRenderer");
                    //MyCommon.UpdateFrameConstants();
                    MySpritesRenderer.Draw(MyRender11.Backbuffer.m_RTV, new MyViewport(MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y));
                    MyGpuProfiler.IC_EndBlock();

                    GetRenderProfiler().EndProfilingBlock();

                    MyTextures.Load();

                    if (m_texturesToRender.Count > 0)
                    {
                        VRage.Render11.PostprocessStage.MySaveExportedTextures.RenderColoredTextures(m_texturesToRender);
                    }
                }

                MyLinesRenderer.Clear();
                MySpritesRenderer.Clear();

                m_drawQueue.Clear();
                MyGpuProfiler.IC_EndBlock();
            }
            catch (SharpDXException e)
            {
                MyRender11.Log.IncreaseIndent();
                MyRender11.Log.WriteLine(" " + e);
                if (e.Descriptor == SharpDX.DXGI.ResultCode.DeviceRemoved)
                {
                    MyRender11.Log.WriteLine("Reason: " + Device.DeviceRemovedReason);
                }
                MyRender11.Log.DecreaseIndent();

                throw;
            }
        }
Пример #22
0
        internal static void Draw(MyBindableResource renderTarget)
        {
            var context = RC.DeviceContext;

            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.Rasterizer.SetViewport(0, 0, MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y);
            context.PixelShader.SetConstantBuffer(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);

            RC.BindDepthRT(null, DepthStencilAccess.ReadWrite, renderTarget);
            RC.BindGBufferForRead(0, MyGBuffer.Main);

            //context.OutputMerger.SetTargets(null as DepthStencilView, MyRender.Backbuffer.RenderTarget);

            //context.PixelShader.SetShaderResources(0, MyRender.MainGbuffer.DepthGbufferViews);

            context.OutputMerger.BlendState = null;

            RC.SetVS(null);
            RC.DeviceContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding());
            RC.DeviceContext.InputAssembler.InputLayout = null;

            if (MyRender11.Settings.DisplayGbufferColor)
            {
                context.PixelShader.Set(m_baseColorShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            if (MyRender11.Settings.DisplayGbufferColorLinear)
            {
                context.PixelShader.Set(m_baseColorLinearShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayGbufferNormal)
            {
                context.PixelShader.Set(m_normalShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayGbufferGlossiness)
            {
                context.PixelShader.Set(m_glossinessShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayGbufferMetalness)
            {
                context.PixelShader.Set(m_metalnessShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayGbufferMaterialID)
            {
                context.PixelShader.Set(m_matIDShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayGbufferAO)
            {
                context.PixelShader.Set(m_aoShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayEmissive)
            {
                context.PixelShader.Set(m_emissiveShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayAmbientDiffuse)
            {
                context.PixelShader.Set(m_ambientDiffuseShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayAmbientSpecular)
            {
                context.PixelShader.Set(m_ambientSpecularShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayEdgeMask)
            {
                context.PixelShader.Set(m_edgeDebugShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayShadowsWithDebug)
            {
                context.PixelShader.Set(m_shadowsDebugShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayNDotL)
            {
                context.PixelShader.Set(m_NDotLShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            else if (MyRender11.Settings.DisplayStencil)
            {
                context.PixelShader.SetShaderResource(4, MyGBuffer.Main.DepthStencil.m_SRV_stencil);
                context.PixelShader.Set(m_stencilShader);
                MyScreenPass.DrawFullscreenQuad();
            }
            //DrawEnvProbe();
            //DrawAtmosphereTransmittance(MyAtmosphereRenderer.AtmosphereLUT.Keys.ToArray()[0]);
            //DrawAtmosphereInscatter(MyAtmosphereRenderer.AtmosphereLUT.Keys.ToArray()[0]);

            if (MyRender11.Settings.DrawCascadeTextures)
            {
                DrawCascades(MyRender11.DynamicShadows.ShadowCascades, 100, 100, 200);
                if (MyScene.SeparateGeometry)
                {
                    DrawCascades(MyRender11.StaticShadows.ShadowCascades, 100, 300, 200);
                    DrawCombinedCascades(100, 500, 200);
                }
            }

            if (MyRender11.Settings.DisplayIDs || MyRender11.Settings.DisplayAabbs)
            {
                DrawHierarchyDebug();
            }

            if (false)
            {
                var batch = MyLinesRenderer.CreateBatch();

                foreach (var light in MyLightRendering.VisiblePointlights)
                {
                    batch.AddSphereRing(new BoundingSphere(light.Position, 0.5f), Color.White, Matrix.Identity);
                }
                batch.Commit();
            }

            // draw terrain lods
            if (MyRender11.Settings.DebugRenderClipmapCells)
            {
                //var batch = MyLinesRenderer.CreateBatch();

                //foreach (var renderable in MyComponentFactory<MyRenderableComponent>.GetAll().Where(x => (MyMeshes.IsVoxelMesh(x.Mesh))))
                //{
                //    if (renderable.IsVisible)
                //    {
                //        if (renderable.m_lod >= LOD_COLORS.Length)
                //            return;

                //        BoundingBox bb = new BoundingBox(renderable.m_owner.Aabb.Min - MyEnvironment.CameraPosition,renderable.m_owner.Aabb.Max - MyEnvironment.CameraPosition);

                //        batch.AddBoundingBox(bb, new Color(LOD_COLORS[renderable.m_voxelLod]));


                //        if (renderable.m_lods != null && renderable.m_voxelLod != renderable.m_lods[0].RenderableProxies[0].ObjectData.CustomAlpha)
                //        {

                //        }
                //    }
                //}

                //batch.Commit();

                MyClipmap.DebugDrawClipmaps();
            }

            if (MyRender11.Settings.EnableVoxelMerging && MyRender11.Settings.DebugRenderMergedCells)
            {
                MyClipmap.DebugDrawMergedCells();
            }

            //if(true)
            //{
            //    var batch = MyLinesRenderer.CreateBatch();

            //    foreach(var id in MyLights.DirtySpotlights)
            //    {
            //        var info = MyLights.Spotlights[id.Index];

            //        if(info.ApertureCos > 0)
            //        {
            //            var D = info.Direction * info.Range;
            //            //batch.AddCone(MyLights.Lights.Data[id.Index].Position + D, -D, info.Up.Cross(info.Direction) * info.BaseRatio * info.Range, 32, Color.OrangeRed);

            //            //var bb = MyLights.AabbFromCone(info.Direction, info.ApertureCos, info.Range).Transform(Matrix.CreateLookAt(MyLights.Lights.Data[id.Index].Position, info.Direction, info.Up));


            //            //batch.AddBoundingBox(bb, Color.Green);

            //            batch.AddCone(MyLights.Lights.Data[id.Index].Position + D, -D, info.Up.Cross(info.Direction) * info.BaseRatio * info.Range, 32, Color.OrangeRed);

            //            var bb = MyLights.AabbFromCone(info.Direction, info.ApertureCos, info.Range, MyLights.Lights.Data[id.Index].Position, info.Up);
            //            batch.AddBoundingBox(bb, Color.Green);
            //        }
            //    }



            //    batch.Commit();
            //}

            // draw lods
            if (false)
            {
                var batch = MyLinesRenderer.CreateBatch();

                //foreach (var renderable in MyComponentFactory<MyRenderableComponent>.GetAll().Where(x => ((x.GetMesh() as MyVoxelMesh) == null)))
                //{

                //    if (renderable.CurrentLodNum >= LOD_COLORS.Length || renderable.m_lods.Length == 1)
                //        continue;

                //    batch.AddBoundingBox(renderable.m_owner.Aabb, new Color(LOD_COLORS[renderable.CurrentLodNum]));
                //}

                batch.Commit();
            }
        }
Пример #23
0
        static void PrepareCascades()
        {
            MyImmediateRC.RC.Context.CopyResource(m_cascadeShadowmapArray.Resource, m_cascadeShadowmapBackup.Resource);

            bool stabilize = true;

            for (int i = 0; i < 4; i++)
            {
                ++FramesSinceUpdate[i];
            }

            CascadeLightDirection[0] = MyEnvironment.DirectionalLightDir;
            CascadeLightDirection[1] = MyEnvironment.DirectionalLightDir;

            const float DirectionDifferenceThreshold = 0.02f;


            if (FramesSinceUpdate[2] > 180 || MyEnvironment.DirectionalLightDir.Dot(CascadeLightDirection[2]) < (1 - DirectionDifferenceThreshold))
            {
                FramesSinceUpdate[2]     = 0;
                CascadeLightDirection[2] = MyEnvironment.DirectionalLightDir;
            }
            if (FramesSinceUpdate[3] > 180 || MyEnvironment.DirectionalLightDir.Dot(CascadeLightDirection[3]) < (1 - DirectionDifferenceThreshold))
            {
                FramesSinceUpdate[3]     = 0;
                CascadeLightDirection[3] = MyEnvironment.DirectionalLightDir;
            }

            var globalMatrix = CreateGlobalMatrix();

            Matrix[] cascadesMatrices = new Matrix[8];

            var cascadeFrozen = MyRender11.Settings.FreezeCascade.Any(x => x == true);

            if (!cascadeFrozen)
            {
                m_oldView = MyEnvironment.View;
            }

            float cascadesNearClip = 1f;
            float cascadesFarClip  = 1000f;
            float backOffset       = 100f; // more and fit projection to objects inside
            float shadowmapSize    = m_cascadeResolution;

            m_splitDepth[0] = cascadesNearClip;
            m_splitDepth[1] = MyRender11.Settings.CascadesSplit0;
            m_splitDepth[2] = MyRender11.Settings.CascadesSplit1;
            m_splitDepth[3] = MyRender11.Settings.CascadesSplit2;
            m_splitDepth[4] = MyRender11.Settings.CascadesSplit3;

            float unitWidth  = 1 / MyEnvironment.Projection.M11;
            float unitHeight = 1 / MyEnvironment.Projection.M22;
            var   vertices   = new Vector3[]
            {
                new Vector3(-unitWidth, -unitHeight, -1),
                new Vector3(-unitWidth, unitHeight, -1),
                new Vector3(unitWidth, unitHeight, -1),
                new Vector3(unitWidth, -unitHeight, -1),
            };
            var frustumVerticesWS = new Vector3[8];

            for (int c = 0; c < m_cascadesNum; c++)
            {
                for (int i = 0; i < 4; i++)
                {
                    frustumVerticesWS[i]     = vertices[i] * m_splitDepth[c];
                    frustumVerticesWS[i + 4] = vertices[i] * m_splitDepth[c + 1];
                }

                if (MyRender11.Settings.FreezeCascade[c])
                {
                    // draw cascade bounding primtiive
                    if (VisualizeDebug)
                    {
                        var invView = Matrix.Invert(m_oldView);
                        Vector3.Transform(frustumVerticesWS, ref invView, frustumVerticesWS);
                        var batch = MyLinesRenderer.CreateBatch();
                        batch.Add6FacedConvex(frustumVerticesWS, Color.Blue);

                        var bs = BoundingSphere.CreateFromPoints(frustumVerticesWS);
                        var bb = BoundingBox.CreateFromSphere(bs);
                        batch.AddBoundingBox(bb, Color.OrangeRed);

                        batch.Commit();
                    }

                    continue;
                }


                /*
                 * Cascades update scheme:
                 * 0: 1 1 1 1
                 * 1: 1 0 1 0
                 * 2: 0 1 0 0
                 * 3: 0 0 0 1
                 */

                bool skipCascade1 = c == 1 && (MyCommon.FrameCounter % 2) != 0;
                bool skipCascade2 = c == 2 && (MyCommon.FrameCounter % 4) != 1;
                bool skipCascade3 = c == 3 && (MyCommon.FrameCounter % 4) != 3;
                //
                if (skipCascade1 || skipCascade2 || skipCascade3)
                {
                    if (!MyRender11.Settings.UpdateCascadesEveryFrame)
                    {
                        continue;
                    }
                }

                Vector3.Transform(frustumVerticesWS, ref MyEnvironment.InvView, frustumVerticesWS);

                var bSphere = BoundingSphere.CreateFromPoints(frustumVerticesWS);
                if (stabilize)
                {
                    bSphere.Center = bSphere.Center.Round();
                    bSphere.Radius = (float)Math.Ceiling(bSphere.Radius);
                }

                var offset            = bSphere.Radius + cascadesNearClip + backOffset;
                var shadowCameraPosWS = bSphere.Center + CascadeLightDirection[c] * (bSphere.Radius + cascadesNearClip);

                var lightView = VRageMath.Matrix.CreateLookAt(shadowCameraPosWS, shadowCameraPosWS - CascadeLightDirection[c], Math.Abs(Vector3.UnitY.Dot(CascadeLightDirection[c])) < 0.99f ? Vector3.UnitY : Vector3.UnitX);

                Vector3 vMin = new Vector3(-bSphere.Radius, -bSphere.Radius, cascadesNearClip);
                Vector3 vMax = new Vector3(bSphere.Radius, bSphere.Radius, offset + bSphere.Radius);

                var cascadeProjection = Matrix.CreateOrthographicOffCenter(vMin.X, vMax.X, vMin.Y, vMax.Y, vMax.Z, vMin.Z);
                cascadesMatrices[c] = lightView * cascadeProjection;

                var transformed = Vector3.Transform(Vector3.Zero, ref cascadesMatrices[c]) * shadowmapSize / 2;
                var smOffset    = (transformed.Round() - transformed) * 2 / shadowmapSize;

                // stabilize 1st cascade only
                if (stabilize)
                {
                    cascadeProjection.M41 += smOffset.X;
                    cascadeProjection.M42 += smOffset.Y;
                    cascadesMatrices[c]    = lightView * cascadeProjection;
                }

                var inverseCascadeMatrix = Matrix.Invert(cascadesMatrices[c]);
                var corner0 = Vector3.Transform(Vector3.Transform(new Vector3(-1, -1, 0), inverseCascadeMatrix), globalMatrix);
                var corner1 = Vector3.Transform(Vector3.Transform(new Vector3(1, 1, 1), inverseCascadeMatrix), globalMatrix);

                var d = corner1 - corner0;

                var cascadeScale = 1f / (corner1 - corner0);
                m_cascadeScale[c] = new Vector4(cascadeScale, 0);

                var query = new MyShadowmapQuery();
                query.DepthBuffer = m_cascadeShadowmapArray.SubresourceDsv(c);
                query.Viewport    = new MyViewport(shadowmapSize, shadowmapSize);

                m_cascadeInfo[c].WorldCameraOffsetPosition = MyEnvironment.CameraPosition;
                m_cascadeInfo[c].WorldToProjection         = cascadesMatrices[c];
                // todo: skip translation, recalculate matrix in local space, keep world space matrix only for bounding frustum
                m_cascadeInfo[c].LocalToProjection = Matrix.CreateTranslation(MyEnvironment.CameraPosition) * cascadesMatrices[c];

                query.ProjectionInfo   = m_cascadeInfo[c];
                query.ProjectionDir    = CascadeLightDirection[c];
                query.ProjectionFactor = shadowmapSize * shadowmapSize / (bSphere.Radius * bSphere.Radius * 4);

                if (c == 0)
                {
                    query.QueryType = MyFrustumEnum.Cascade0;
                }
                if (c == 1)
                {
                    query.QueryType = MyFrustumEnum.Cascade1;
                }
                if (c == 2)
                {
                    query.QueryType = MyFrustumEnum.Cascade2;
                }
                if (c == 3)
                {
                    query.QueryType = MyFrustumEnum.Cascade3;
                }

                m_shadowmapQueries.Add(query);
            }

            if (true)
            {
                var verticesWS = new Vector3[8];

                var batch = MyLinesRenderer.CreateBatch();

                var cascadeColor = new[]
                {
                    Color.Red,
                    Color.Green,
                    Color.Blue,
                    Color.Yellow
                };

                for (int c = 0; c < m_cascadesNum; c++)
                {
                    if (MyRender11.Settings.FreezeCascade[c])
                    {
                        if (VisualizeDebug)
                        {
                            var inverseViewProj = Matrix.Invert(cascadesMatrices[c]);
                            Vector3.Transform(m_cornersCS, ref inverseViewProj, verticesWS);

                            for (int i = 0; i < verticesWS.Length; i++)
                            {
                                verticesWS[i] += MyEnvironment.CameraPosition;
                            }

                            MyPrimitivesRenderer.Draw6FacedConvex(verticesWS, cascadeColor[c], 0.2f);

                            batch.Add6FacedConvex(verticesWS, Color.Pink);
                        }
                    }
                }

                batch.Commit();
            }

            var mapping = MyMapping.MapDiscard(m_csmConstants);

            for (int c = 0; c < m_cascadesNum; c++)
            {
                mapping.stream.Write(Matrix.Transpose(m_cascadeInfo[c].CurrentLocalToProjection * MyMatrixHelpers.ClipspaceToTexture));
            }
            for (int i = m_cascadesNum; i < 8; i++)
            {
                mapping.stream.Write(Matrix.Zero);
            }

            for (int i = 0; i < m_splitDepth.Length; i++)
            {
                mapping.stream.Write(m_splitDepth[i]);
            }
            for (int i = m_splitDepth.Length; i < 8; i++)
            {
                mapping.stream.Write(0.0f);
            }

            for (int i = 0; i < 4; i++)
            {
                mapping.stream.Write(m_cascadeScale[i] / m_cascadeScale[0]);
            }

            mapping.Unmap();
        }
Пример #24
0
        internal static void DrawSceneDebug()
        {
            //if(true)
            //{
            //    //m_proj = MyEnvironment.Projection;
            //    //m_vp = MyEnvironment.ViewProjection;
            //    //m_invvp = MyEnvironment.InvViewProjection;

            //    Vector2 groupDim = new Vector2(256, 256);
            //    Vector2 tileScale = new Vector2(1600, 900) / (2 * groupDim);
            //    Vector2 tileBias = tileScale - new Vector2(1, 1);


            //    //Vector4 c1 = new Vector4(m_proj.M11 * tileScale.X, 0, tileBias.X, 0);
            //    //Vector4 c2 = new Vector4(0, -m_proj.M22 * tileScale.Y, tileBias.Y, 0);
            //    Vector4 c1 = new Vector4(m_proj.M11, 0, 0, 0);
            //    Vector4 c2 = new Vector4(0, m_proj.M22, 0, 0);
            //    Vector4 c4 = new Vector4(0, 0, 1, 0);

            //    var frustumPlane0 = new VRageMath.Plane(c4 - c1);
            //    var frustumPlane1 = new VRageMath.Plane(c4 + c1);
            //    var frustumPlane2 = new VRageMath.Plane(c4 - c2);
            //    var frustumPlane3 = new VRageMath.Plane(c4 + c2);
            //    frustumPlane0.Normalize();
            //    frustumPlane1.Normalize();
            //    frustumPlane2.Normalize();
            //    frustumPlane3.Normalize();


            //    var ray0 = ComputeIntersectionLine(ref frustumPlane2, ref frustumPlane0);
            //    var ray1 = ComputeIntersectionLine(ref frustumPlane1, ref frustumPlane2);
            //    var ray2 = ComputeIntersectionLine(ref frustumPlane3, ref frustumPlane1);
            //    var ray3 = ComputeIntersectionLine(ref frustumPlane0, ref frustumPlane3);


            //    TransformRay(ref ray0, ref m_invvp);
            //    TransformRay(ref ray1, ref m_invvp);
            //    TransformRay(ref ray2, ref m_invvp);
            //    TransformRay(ref ray3, ref m_invvp);


            //    var batch = MyLinesRenderer.CreateBatch();

            //    batch.Add(ray0.Position, ray0.Position + ray0.Direction * 100, Color.Red);
            //    batch.Add(ray1.Position, ray1.Position + ray1.Direction * 100, Color.Red);
            //    batch.Add(ray2.Position, ray2.Position + ray2.Direction * 100, Color.Red);
            //    batch.Add(ray3.Position, ray3.Position + ray3.Direction * 100, Color.Red);

            //    batch.AddFrustum(new BoundingFrustum(m_vp), Color.Green);

            //    batch.Commit();

            //}

            // draw lights
            //if(false)
            //{
            //    MyLinesBatch batch = MyLinesRenderer.CreateBatch();

            //    foreach (var light in MyLight.Collection)
            //    {
            //        if (light.PointLightEnabled)
            //        {
            //            var position = light.GetPosition();
            //            //batch.AddBoundingBox(new BoundingBox(position - light.Pointlight.Range, position + light.Pointlight.Range), Color.Red);

            //            batch.AddSphereRing(new BoundingSphere(position, light.Pointlight.Range), new Color(light.Pointlight.Color), Matrix.Identity);
            //            batch.AddSphereRing(new BoundingSphere(position, light.Pointlight.Range), new Color(light.Pointlight.Color), Matrix.CreateRotationX((float)Math.PI * 0.5f));
            //            batch.AddSphereRing(new BoundingSphere(position, light.Pointlight.Range), new Color(light.Pointlight.Color), Matrix.CreateRotationZ((float)Math.PI * 0.5f));

            //            batch.AddSphereRing(new BoundingSphere(position, light.Pointlight.Radius), new Color(light.Pointlight.Color), Matrix.Identity);
            //            batch.AddSphereRing(new BoundingSphere(position, light.Pointlight.Radius), new Color(light.Pointlight.Color), Matrix.CreateRotationX((float)Math.PI * 0.5f));
            //        }
            //    }

            //    batch.Commit();
            //}

            //
            if (false)
            {
                MyLinesBatch batch = MyLinesRenderer.CreateBatch();

                foreach (var r in MyComponentFactory <MyRenderableComponent> .GetAll())
                {
                    if (r.Owner.GetInstanceLod() != null)
                    {
                        batch.AddBoundingBox((BoundingBox)r.Owner.Aabb, Color.Blue);
                    }
                }

                batch.Commit();
            }

            if (false)
            {
                MyLinesBatch batch = MyLinesRenderer.CreateBatch();
                //var radius = new [] { 0, 40, 72, 128, 256 , 512 };
                var   radius   = new[] { 0, 50, 80, 128, 256, 512 };
                float cellSize = 8;

                var colors = new[] { Color.Red, Color.Green, Color.Blue, Color.Yellow, Color.Pink, Color.MediumVioletRed };

                var prevPositionG = Vector3.PositiveInfinity;
                for (int i = 0; i < 4; i++)
                {
                    float levelCellSize = cellSize * (float)Math.Pow(2, i);
                    var   position      = MyEnvironment.CameraPosition;
                    //var position = Vector3.Zero;
                    position.Y = 0;
                    var positionG = position.Snap(levelCellSize * 2);

                    float radiusMin = radius[i];
                    float radiusMax = radius[i + 1];

                    // naive

                    var pmin = (positionG - radiusMax - levelCellSize * 2).Snap(levelCellSize * 2);
                    var pmax = (positionG + radiusMax + levelCellSize * 2).Snap(levelCellSize * 2);

                    //if(i==0)
                    //{
                    //    for (var x = pmin.X; x < pmax.X; x += levelCellSize)
                    //    {
                    //        for (var y = pmin.Y; y < pmax.Y; y += levelCellSize)
                    //        {
                    //            for (var z = pmin.Z; z < pmax.Z; z += levelCellSize)
                    //            {
                    //                var cell = new Vector3(x, y, z);
                    //                var rep = cell.Snap(levelCellSize * 2);

                    //                var inLevelGrid = (rep - positionG).Length() < radiusMax;
                    //                if(inLevelGrid)
                    //                {
                    //                    batch.AddBoundingBox(new BoundingBox(cell, cell + levelCellSize), colors[i]);
                    //                }
                    //            }
                    //        }
                    //    }
                    //}
                    //else
                    {
                        for (var x = pmin.X; x < pmax.X; x += levelCellSize)
                        {
                            for (var z = pmin.Z; z < pmax.Z; z += levelCellSize)
                            {
                                var cell = new Vector3(x, positionG.Y, z);
                                var rep  = cell.Snap(levelCellSize * 2);

                                var inPrevLevelGrid = (cell - prevPositionG).Length() < radiusMin;
                                var inLevelGrid     = (rep - positionG).Length() < radiusMax;

                                if (inLevelGrid && !inPrevLevelGrid)
                                {
                                    batch.AddBoundingBox(new BoundingBox(cell, cell + levelCellSize), colors[i]);
                                }
                            }
                        }
                    }

                    prevPositionG = positionG;
                }


                batch.Commit();
            }
        }
        static void ProcessDebugMessages()
        {
            var linesBatch        = MyLinesRenderer.CreateBatch();
            var noDepthLinesBatch = MyLinesRenderer.CreateBatch();

            noDepthLinesBatch.IgnoreDepth = true;
            var lines2D = MyLinesRenderer.CreateBatch();

            lines2D.IgnoreDepth = true;


            while (m_debugDrawMessages.Count > 0)
            {
                IMyRenderMessage debugDrawMessage = m_debugDrawMessages.Dequeue();

                MyRenderMessageEnum messageType = debugDrawMessage.MessageType;

                switch (messageType)
                {
                case MyRenderMessageEnum.DebugDrawLine3D:
                {
                    MyRenderMessageDebugDrawLine3D message = (MyRenderMessageDebugDrawLine3D)debugDrawMessage;

                    if (message.DepthRead)
                    {
                        linesBatch.Add(message.PointFrom, message.PointTo, message.ColorFrom, message.ColorTo);
                    }
                    else
                    {
                        noDepthLinesBatch.Add(message.PointFrom, message.PointTo, message.ColorFrom, message.ColorTo);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawLine2D:
                {
                    MyRenderMessageDebugDrawLine2D message = (MyRenderMessageDebugDrawLine2D)debugDrawMessage;

                    var matrix = message.Projection ?? Matrix.CreateOrthographicOffCenter(0, MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y, 0, 0, -1);

                    if (!lines2D.CustomViewProjection.HasValue || (lines2D.CustomViewProjection.HasValue && lines2D.CustomViewProjection.Value != matrix))
                    {
                        lines2D.Commit();
                        lines2D                      = MyLinesRenderer.CreateBatch();
                        lines2D.IgnoreDepth          = true;
                        lines2D.CustomViewProjection = matrix;
                    }

                    var p0 = new Vector3(message.PointFrom.X, message.PointFrom.Y, 0);
                    var p1 = new Vector3(message.PointTo.X, message.PointTo.Y, 0);
                    lines2D.Add(p0, p1, message.ColorFrom, message.ColorTo);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawPoint:
                {
                    MyRenderMessageDebugDrawPoint message = (MyRenderMessageDebugDrawPoint)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    var scale = 0.125f;

                    var borderDepth = MyRender11.UseComplementaryDepthBuffer ? 0.0f : 1.0f;
                    borderDepth = message.ClipDistance.HasValue ? Vector3.Transform(new Vector3(0, 0, -message.ClipDistance.Value), MyEnvironment.Projection).Z : borderDepth;

                    var clipPosition = Vector3.Transform((Vector3)message.Position, ref MyEnvironment.ViewProjection);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;

                    //Debug.Assert(MyRender11.UseComplementaryDepthBuffer);

                    bool drawCondition =
                        MyRender11.UseComplementaryDepthBuffer
                                ? clipPosition.Z > borderDepth && clipPosition.Z < 1
                                : clipPosition.Z < borderDepth && clipPosition.Z > 0;

                    if (drawCondition)
                    {
                        batch.Add(message.Position + Vector3.UnitX * scale, message.Position - Vector3.UnitX * scale, message.Color);
                        batch.Add(message.Position + Vector3.UnitY * scale, message.Position - Vector3.UnitY * scale, message.Color);
                        batch.Add(message.Position + Vector3.UnitZ * scale, message.Position - Vector3.UnitZ * scale, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawSphere:
                {
                    MyRenderMessageDebugDrawSphere message = (MyRenderMessageDebugDrawSphere)debugDrawMessage;

                    var borderDepth = MyRender11.UseComplementaryDepthBuffer ? 0.0f : 1.0f;
                    borderDepth = message.ClipDistance.HasValue ? Vector3.Transform(new Vector3(0, 0, -message.ClipDistance.Value), MyEnvironment.Projection).Z : borderDepth;

                    var clipPosition = Vector3.Transform((Vector3)message.Position, ref MyEnvironment.ViewProjection);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;

                    bool drawCondition =
                        MyRender11.UseComplementaryDepthBuffer
                                ? clipPosition.Z > borderDepth && clipPosition.Z < 1
                                : clipPosition.Z < borderDepth && clipPosition.Z > 0;

                    if (drawCondition)
                    {
                        var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                        batch.AddSphereRing(new BoundingSphere(message.Position, message.Radius), message.Color, Matrix.Identity);
                        batch.AddSphereRing(new BoundingSphere(message.Position, message.Radius), message.Color, Matrix.CreateRotationX(MathHelper.PiOver2));
                        batch.AddSphereRing(new BoundingSphere(message.Position, message.Radius), message.Color, Matrix.CreateRotationZ(MathHelper.PiOver2));
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawAABB:
                {
                    MyRenderMessageDebugDrawAABB message = (MyRenderMessageDebugDrawAABB)debugDrawMessage;

                    if (message.DepthRead)
                    {
                        linesBatch.AddBoundingBox((BoundingBox)message.AABB, message.Color);
                    }
                    else
                    {
                        noDepthLinesBatch.AddBoundingBox((BoundingBox)message.AABB, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawCone:
                {
                    MyRenderMessageDebugDrawCone message = (MyRenderMessageDebugDrawCone)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    var axis = message.DirectionVector;
                    axis.Normalize();

                    var apex = message.Translation + message.DirectionVector;

                    var steps    = 32;
                    var stepsRcp = (float)(Math.PI * 2 / steps);
                    for (int i = 0; i < 32; i++)
                    {
                        float a0 = i * stepsRcp;
                        float a1 = (i + 1) * stepsRcp;

                        var A = message.Translation + Vector3.Transform(message.BaseVector, Matrix.CreateFromAxisAngle(axis, a0));
                        var B = message.Translation + Vector3.Transform(message.BaseVector, Matrix.CreateFromAxisAngle(axis, a1));

                        batch.Add(A, B, message.Color);
                        batch.Add(A, apex, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawAxis:
                {
                    MyRenderMessageDebugDrawAxis message = (MyRenderMessageDebugDrawAxis)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    batch.Add(message.Matrix.Translation, message.Matrix.Translation + message.Matrix.Right * message.AxisLength, Color.Red);
                    batch.Add(message.Matrix.Translation, message.Matrix.Translation + message.Matrix.Up * message.AxisLength, Color.Green);
                    batch.Add(message.Matrix.Translation, message.Matrix.Translation + message.Matrix.Forward * message.AxisLength, Color.Blue);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawOBB:
                {
                    MyRenderMessageDebugDrawOBB message = (MyRenderMessageDebugDrawOBB)debugDrawMessage;

                    Vector3 [] corners = new Vector3[8];
                    Matrix     matrix  = (Matrix)message.Matrix;
                    new MyOrientedBoundingBox(ref matrix).GetCorners(corners, 0);

                    if (message.DepthRead)
                    {
                        linesBatch.Add6FacedConvex(corners, message.Color);
                    }
                    else
                    {
                        noDepthLinesBatch.Add6FacedConvex(corners, message.Color);
                    }

                    MyPrimitivesRenderer.Draw6FacedConvex(corners, message.Color, message.Alpha);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawCylinder:
                {
                    MyRenderMessageDebugDrawCylinder message = (MyRenderMessageDebugDrawCylinder)debugDrawMessage;

                    var steps    = 32;
                    var stepsRcp = (float)(Math.PI * 2 / steps);
                    for (int i = 0; i < 32; i++)
                    {
                        float a0 = i * stepsRcp;
                        float a1 = (i + 1) * stepsRcp;

                        Vector3 A = new Vector3(Math.Cos(a0), 1.0f, Math.Sin(a0)) * 0.5f;
                        Vector3 B = new Vector3(Math.Cos(a1), 1.0f, Math.Sin(a1)) * 0.5f;
                        Vector3 C = A - Vector3.UnitY;
                        Vector3 D = B - Vector3.UnitY;

                        A = Vector3.Transform(A, message.Matrix);
                        B = Vector3.Transform(B, message.Matrix);
                        C = Vector3.Transform(C, message.Matrix);
                        D = Vector3.Transform(D, message.Matrix);

                        linesBatch.Add(A, B, message.Color);
                        linesBatch.Add(A, C, message.Color);
                        linesBatch.Add(C, D, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawTriangle:
                {
                    MyRenderMessageDebugDrawTriangle message = (MyRenderMessageDebugDrawTriangle)debugDrawMessage;

                    MyPrimitivesRenderer.DrawTriangle(message.Vertex0, message.Vertex1, message.Vertex2, message.Color);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawTriangles:
                {
                    MyRenderMessageDebugDrawTriangles message = (MyRenderMessageDebugDrawTriangles)debugDrawMessage;

                    for (int i = 0; i < message.Indices.Count; i += 3)
                    {
                        var v0 = Vector3.Transform(message.Vertices[message.Indices[i + 0]], message.WorldMatrix);
                        var v1 = Vector3.Transform(message.Vertices[message.Indices[i + 1]], message.WorldMatrix);
                        var v2 = Vector3.Transform(message.Vertices[message.Indices[i + 2]], message.WorldMatrix);

                        MyPrimitivesRenderer.DrawTriangle(v0, v1, v2, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawCapsule:
                {
                    MyRenderMessageDebugDrawCapsule message = (MyRenderMessageDebugDrawCapsule)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    batch.AddSphereRing(new BoundingSphere(message.P0, message.Radius), message.Color, Matrix.Identity);
                    batch.AddSphereRing(new BoundingSphere(message.P0, message.Radius), message.Color, Matrix.CreateRotationX(MathHelper.PiOver2));
                    batch.AddSphereRing(new BoundingSphere(message.P1, message.Radius), message.Color, Matrix.Identity);
                    batch.AddSphereRing(new BoundingSphere(message.P1, message.Radius), message.Color, Matrix.CreateRotationX(MathHelper.PiOver2));

                    batch.Add(message.P0, message.P1, message.Color);


                    break;
                }

                case MyRenderMessageEnum.DebugDrawText2D:
                {
                    MyRenderMessageDebugDrawText2D message = (MyRenderMessageDebugDrawText2D)debugDrawMessage;

                    var text = new StringBuilder(message.Text);

                    MySpritesRenderer.DrawText(message.Coord, text, message.Color, message.Scale, message.Align);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawText3D:
                {
                    MyRenderMessageDebugDrawText3D message = (MyRenderMessageDebugDrawText3D)debugDrawMessage;

                    Vector3 position = (Vector3)message.Coord;

                    var worldToClip = MyEnvironment.ViewProjection;
                    if (message.CustomViewProjection != -1)
                    {
                        if (!MyRenderProxy.BillboardsViewProjectionRead.ContainsKey(message.CustomViewProjection))
                        {
                            break;
                        }

                        var i = message.CustomViewProjection;

                        var scaleX  = MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.Width / (float)MyRender11.ViewportResolution.X;
                        var scaleY  = MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.Height / (float)MyRender11.ViewportResolution.Y;
                        var offsetX = MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.OffsetX / (float)MyRender11.ViewportResolution.X;
                        var offsetY = (MyRender11.ViewportResolution.Y - MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.OffsetY - MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.Height)
                                      / (float)MyRender11.ViewportResolution.Y;

                        var viewportTransformation = new Matrix(
                            scaleX, 0, 0, 0,
                            0, scaleY, 0, 0,
                            0, 0, 1, 0,
                            offsetX, offsetY, 0, 1
                            );

                        worldToClip = MyRenderProxy.BillboardsViewProjectionRead[message.CustomViewProjection].View * MyRenderProxy.BillboardsViewProjectionRead[message.CustomViewProjection].Projection * viewportTransformation;
                    }

                    var clipPosition = Vector3.Transform(position, ref worldToClip);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;

                    var borderDepth = MyRender11.UseComplementaryDepthBuffer ? 0.0f : 1.0f;
                    borderDepth = message.ClipDistance.HasValue ? Vector3.Transform(new Vector3(0, 0, -message.ClipDistance.Value), MyEnvironment.Projection).Z : borderDepth;

                    bool drawCondition =
                        MyRender11.UseComplementaryDepthBuffer
                                ? clipPosition.Z > borderDepth && clipPosition.Z < 1
                                : clipPosition.Z < borderDepth && clipPosition.Z > 0;

                    if (drawCondition)
                    {
                        MySpritesRenderer.DrawText(new Vector2(clipPosition.X, clipPosition.Y) * MyRender11.ViewportResolution,
                                                   new StringBuilder(message.Text), message.Color, message.Scale, message.Align);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawModel:
                {
                    MyRenderMessageDebugDrawModel message = (MyRenderMessageDebugDrawModel)debugDrawMessage;


                    break;
                }

                case MyRenderMessageEnum.DebugDrawPlane:
                {
                    MyRenderMessageDebugDrawPlane message = (MyRenderMessageDebugDrawPlane)debugDrawMessage;


                    break;
                }

                default:
                {
                    break;
                }
                }
            }

            linesBatch.Commit();
            noDepthLinesBatch.Commit();
            lines2D.Commit();
        }