Пример #1
0
 internal static void EnqueueMessage(MyRenderMessageBase message, bool limitMaxQueueSize)
 {
     if (MyRenderProxy.RenderThread != null && Thread.CurrentThread == MyRenderProxy.RenderThread.SystemThread)
     {
         SharedData.MessagesForNextFrame.Enqueue(message);
     }
     else
         SharedData.CurrentUpdateFrame.Enqueue(message);
 }
Пример #2
0
 internal static void EnqueueMessage(MyRenderMessageBase message, bool limitMaxQueueSize)
 {
     if (MyRenderProxy.RenderThread != null && Thread.CurrentThread == MyRenderProxy.RenderThread.SystemThread)
     {
         SharedData.MessagesForNextFrame.Enqueue(message);
     }
     else
     {
         SharedData.CurrentUpdateFrame.Enqueue(message);
     }
 }
Пример #3
0
 public void Enqueue(MyRenderMessageBase message)
 {
     //RenderInput.Add(message);
     if (message.MessageType != MyRenderMessageEnum.DebugDrawAABB)
     {
         RenderInput.Add(message);
     }
     else
     {
         RenderInput.Insert(0, message);
     }
 }
Пример #4
0
 public void Enqueue(MyRenderMessageBase message)
 {
     //RenderInput.Add(message);
     if (message.MessageType != MyRenderMessageEnum.DebugDrawAABB)
     {
         RenderInput.Add(message);
     }
     else
     {
         RenderInput.Insert(0, message);
     }
 }
        private static void ProcessMessage(MyRenderMessageBase message)
        {
#if DEBUG
            ProcessMessageInternal(message);
#else
            try
            {
                ProcessMessageInternal(message);
            }
            catch
            {
                if (message != null)
                {
                    MyLog.Default.WriteLine("Error processing message: " + message.MessageType);
                }
                throw;
            }
#endif
        }
 private static void ProcessMessage(MyRenderMessageBase message)
 {
     try
     {
         MyRender.GetRenderProfiler().StartProfilingBlock(MyEnum<MyRenderMessageType>.GetName(message.MessageClass));
         MyRender.GetRenderProfiler().StartProfilingBlock(Partition.Select(MyEnum<MyRenderMessageEnum>.GetName(message.MessageType).GetHashCode(), "A", "B", "C", "D", "E", "F", "G", "H", "I"));
         MyRender.GetRenderProfiler().StartProfilingBlock(MyEnum<MyRenderMessageEnum>.GetName(message.MessageType));
         ProcessMessageInternal(message);
         MyRender.GetRenderProfiler().EndProfilingBlock();
         MyRender.GetRenderProfiler().EndProfilingBlock();
         MyRender.GetRenderProfiler().EndProfilingBlock();
     }
     catch
     {
         if (message != null)
         {
             MyLog.Default.WriteLine("Error processing message: " + message.MessageType);
             MyLog.Default.WriteLine("Details: " + message.ToString());
         }
         throw;
     }
 }
        private static void ProcessMessageInternal(MyRenderMessageBase message)
        {
            switch (message.MessageType)
            {
                #region Sprites
                case MyRenderMessageEnum.DrawSprite:
                case MyRenderMessageEnum.DrawSpriteNormalized:
                case MyRenderMessageEnum.DrawSpriteAtlas:
                case MyRenderMessageEnum.SpriteScissorPush:
                case MyRenderMessageEnum.SpriteScissorPop:
                    {
                        EnqueueDrawMessage(message);
                        break;
                    }

                #endregion

                #region Textures

                case MyRenderMessageEnum.PreloadTextures:
                    {
                        var preloadMsg = message as MyRenderMessagePreloadTextures;

                        MyTextureManager.PreloadTextures(preloadMsg.InDirectory, preloadMsg.Recursive);

                        break;
                    }

                case MyRenderMessageEnum.UnloadTexture:
                    {
                        var texMessage = (MyRenderMessageUnloadTexture)message;

                        MyTextureManager.UnloadTexture(texMessage.Texture);



                        break;
                    }

                #endregion

                #region Profiler

                case MyRenderMessageEnum.RenderProfiler:
                    {
                        var profMessage = (MyRenderMessageRenderProfiler)message;

                        MyRenderProfiler.HandleInput(profMessage.Command, profMessage.Index);

                        break;
                    }

                #endregion

                #region Render objects

                case MyRenderMessageEnum.CreateRenderEntity:
                    {
                        var rMessage = (MyRenderMessageCreateRenderEntity)message;

                        MyRenderEntity renderEntity;

                        // AlesR : refactor
                        if (string.IsNullOrEmpty(rMessage.Model))
                        {
                            ProfilerShort.Begin("CreateRenderEntity-NoModel");
                            renderEntity = new MyRenderEntity(
                                rMessage.ID,
                                rMessage.DebugName,
                                rMessage.WorldMatrix,
                                rMessage.Technique,
                                rMessage.Flags
                            );
                            ProfilerShort.BeginNextBlock("SetMaxDist");
                            renderEntity.MaxViewDistance = rMessage.MaxViewDistance;
                            ProfilerShort.End();
                        }
                        else
                        {
                            ProfilerShort.Begin("CreateRenderEntity-Model");
                            renderEntity = new MyRenderEntity(
                                rMessage.ID,
                                rMessage.DebugName,
                                rMessage.Model,
                                rMessage.WorldMatrix,
                                rMessage.Technique,
                                rMessage.Flags
                            );
                            ProfilerShort.End();

                            if (renderEntity.Lods.Count == 0)
                                return;

                            ProfilerShort.Begin("SetMaxDist");
                            renderEntity.MaxViewDistance = rMessage.MaxViewDistance;
                            ProfilerShort.End();
                            ProfilerShort.Begin("renderEntity.LoadContent");
                            renderEntity.LoadContent();
                            ProfilerShort.End();
                        }

                        ProfilerShort.Begin("AddRenderObjectFromProxy");
                        AddRenderObjectFromProxy(renderEntity);
                        ProfilerShort.End();

                        break;
                    }

                case MyRenderMessageEnum.CreateRenderEntityAtmosphere:
                    {
                        var rMessage = (MyRenderMessageCreateRenderEntityAtmosphere)message;

                        MyRenderEntity renderEntity;


                        ProfilerShort.Begin("CreateRenderEntity-Atmosphere");
                        renderEntity = new MyRenderAtmosphere(
                            rMessage.ID,
                            rMessage.DebugName,
                            rMessage.Model,
                            rMessage.WorldMatrix,
                            rMessage.Technique,
                            rMessage.Flags,
                            rMessage.AtmosphereRadius,
                            rMessage.PlanetRadius,
                            rMessage.AtmosphereWavelengths
                        );
                        ProfilerShort.End();

                        if (renderEntity.Lods.Count == 0)
                            return;

                        ProfilerShort.Begin("SetMaxDist");
                        renderEntity.MaxViewDistance = rMessage.MaxViewDistance;
                        ProfilerShort.End();
                        ProfilerShort.Begin("renderEntity.LoadContent");
                        renderEntity.LoadContent();
                        ProfilerShort.End();

                        ProfilerShort.Begin("AddRenderObjectFromProxy");
                        AddRenderObjectFromProxy(renderEntity);
                        ProfilerShort.End();

                        break;
                    }

                case MyRenderMessageEnum.AddRuntimeModel:
                    {
                        var rMessage = (MyRenderMessageAddRuntimeModel)message;
                        var model = new MyRenderModel(MyMeshDrawTechnique.MESH);
                        ProfilerShort.Begin("LoadBuffers");
                        model.LoadBuffers(rMessage.ModelData);
                        ProfilerShort.End();
                        MyRenderModels.AddRuntimeModel(rMessage.Name, model);
                        break;
                    }

                case MyRenderMessageEnum.PreloadModel:
                    {
                        var rMessage = (MyRenderMessagePreloadModel)message;
                        MyRenderModels.GetModel(rMessage.Name);
                        break;
                    }


                case MyRenderMessageEnum.UnloadModel:
                    {
                        var rMessage = (MyRenderMessageUnloadModel)message;

                        MyRenderModels.UnloadModel(rMessage.Name);

                        break;
                    }
                case MyRenderMessageEnum.PreloadMaterials:
                    {
                        var rMessage = (MyRenderMessagePreloadMaterials)message;
                        MyRenderModels.GetMaterials(rMessage.Name);
                        break;
                    }

                case MyRenderMessageEnum.SetRenderEntityData:
                    {
                        var rMessage = (MyRenderMessageSetRenderEntityData)message;
                        var entity = (MyRenderEntity)GetRenderObject(rMessage.ID);

                        if (entity != null)
                            entity.AddData(rMessage);

                        break;
                    }


                case MyRenderMessageEnum.SetRenderEntityLOD:
                    {
                        var rMessage = (MyRenderMessageSetRenderEntityLOD)message;

                        var entity = (MyRenderEntity)GetRenderObject(rMessage.ID);
                        if (entity != null)
                        {
                            entity.AddLOD(rMessage.Distance, rMessage.Model);
                        }

                        break;
                    }

                case MyRenderMessageEnum.CreateRenderBatch:
                    {
                        var rMessage = (MyRenderMessageCreateRenderBatch)message;

                        MyRenderBatch renderBatch = new MyRenderBatch(
                            rMessage.ID,
                            rMessage.DebugName,
                            (MatrixD)rMessage.WorldMatrix,
                            rMessage.Flags,
                            rMessage.RenderBatchParts
                            );

                        renderBatch.LoadContent();
                        AddRenderObjectFromProxy(renderBatch);



                        break;
                    }

                case MyRenderMessageEnum.CreateRenderInstanceBuffer:
                    {
                        var rMessage = (MyRenderMessageCreateRenderInstanceBuffer)message;

                        MyRenderInstanceBuffer renderBatch = new MyRenderInstanceBuffer(rMessage.ID, rMessage.DebugName, rMessage.Type);

                        renderBatch.LoadContent();
                        AddRenderObjectFromProxy(renderBatch);



                        break;
                    }

                case MyRenderMessageEnum.CreateLineBasedObject:
                    {
                        var rMessage = (MyRenderMessageCreateLineBasedObject)message;

                        var lineBasedObj = new MyRenderLineBasedObject(rMessage.ID, rMessage.DebugName);
                        lineBasedObj.LoadContent();
                        AddRenderObjectFromProxy(lineBasedObj);

                        break;
                    }

                case MyRenderMessageEnum.UpdateLineBasedObject:
                    {
                        var rMessage = (MyRenderMessageUpdateLineBasedObject)message;

                        var obj = (MyRenderLineBasedObject)GetRenderObject(rMessage.ID);
                        if (obj != null)
                        {
                            obj.SetWorldPoints(ref rMessage.WorldPointA, ref rMessage.WorldPointB);
                            UpdateRenderObject(obj);
                        }

                        break;
                    }

                case MyRenderMessageEnum.UpdateRenderCubeInstanceBuffer:
                    {
                        var rMessage = (MyRenderMessageUpdateRenderCubeInstanceBuffer)message;

                        var obj = (MyRenderInstanceBuffer)GetRenderObject(rMessage.ID);
                        obj.UpdateCube(rMessage.InstanceData, rMessage.Capacity);

                        rMessage.InstanceData.Clear();


                        break;
                    }

                case MyRenderMessageEnum.UpdateRenderInstanceBuffer:
                    {
                        var rMessage = (MyRenderMessageUpdateRenderInstanceBuffer)message;

                        var obj = (MyRenderInstanceBuffer)GetRenderObject(rMessage.ID);
                        obj.Update(rMessage.InstanceData, rMessage.Capacity);

                        rMessage.InstanceData.Clear();


                        break;
                    }


                case MyRenderMessageEnum.SetInstanceBuffer:
                    {
                        var rMessage = (MyRenderMessageSetInstanceBuffer)message;

                        var entity = (MyRenderEntity)GetRenderObject(rMessage.ID);
                        if (entity != null)
                        {
                            //RemoveRenderObject(entity);
                            var buffer = rMessage.InstanceBufferId == MyRenderProxy.RENDER_ID_UNASSIGNED ? null : (MyRenderInstanceBuffer)GetRenderObject(rMessage.InstanceBufferId);
                            entity.SetInstanceData(buffer, rMessage.InstanceStart, rMessage.InstanceCount, (BoundingBoxD)rMessage.LocalAabb);
                            MoveRenderObject(entity);
                        }


                        break;
                    }

                case MyRenderMessageEnum.CreateManualCullObject:
                    {
                        var rMessage = (MyRenderMessageCreateManualCullObject)message;

                        MyManualCullableRenderObject manualCullObject = new MyManualCullableRenderObject(rMessage.ID, (MatrixD)rMessage.WorldMatrix);
                        manualCullObject.DebugName = rMessage.DebugName;
                        manualCullObject.WorldMatrix = (MatrixD)rMessage.WorldMatrix;

                        AddRenderObjectFromProxy(manualCullObject, false);



                        break;
                    }

                case MyRenderMessageEnum.SetParentCullObject:
                    {
                        var rMessage = (MyRenderMessageSetParentCullObject)message;

                        MyRenderObject renderObject = GetRenderObject(rMessage.ID);
                        RemoveRenderObject(renderObject);
                        //m_renderObjects.Remove(rMessage.ID);

                        MyManualCullableRenderObject manualCullObject = GetRenderObject(rMessage.CullObjectID) as MyManualCullableRenderObject;
                        if (manualCullObject != null)
                        {
                            RemoveRenderObject(manualCullObject);

                            manualCullObject.AddRenderObject(renderObject, (MatrixD?)rMessage.ChildToParent);

                            AddRenderObject(manualCullObject);
                        }
                        else
                        { 
                        }
                        break;
                    }

                case MyRenderMessageEnum.SetCameraViewMatrix:
                    {
                        var rMessage = (MyRenderMessageSetCameraViewMatrix)message;
                        rMessage.UpdateTime = MyRender.CurrentUpdateTime;

                        // EnqueueDrawMessage(rMessage);

                        // var rMessage = (MyRenderMessageSetCameraViewMatrix)drawMessage;

                        MyRenderCamera.ProjectionMatrix = rMessage.ProjectionMatrix;
                        MyRenderCamera.ProjectionMatrixForNearObjects = rMessage.NearProjectionMatrix;
                        MyRenderCamera.SetViewMatrix(rMessage.ViewMatrix, rMessage.UpdateTime);

                        MyRenderCamera.SafeNearForForward = rMessage.SafeNear;
                        MyRenderCamera.FieldOfView = rMessage.FOV;
                        MyRenderCamera.FieldOfViewForNearObjects = rMessage.NearFOV;

                        if ((MyRenderCamera.NEAR_PLANE_DISTANCE != rMessage.NearPlane) ||
                            (MyRenderCamera.FAR_PLANE_DISTANCE != rMessage.FarPlane) ||
                            (MyRenderCamera.NEAR_PLANE_FOR_NEAR_OBJECTS != rMessage.NearObjectsNearPlane) ||
                            (MyRenderCamera.FAR_PLANE_FOR_NEAR_OBJECTS != rMessage.NearObjectsFarPlane))
                        {
                            MyRenderCamera.NEAR_PLANE_DISTANCE = rMessage.NearPlane;
                            MyRenderCamera.FAR_PLANE_DISTANCE = rMessage.FarPlane;
                            MyRenderCamera.NEAR_PLANE_FOR_NEAR_OBJECTS = rMessage.NearObjectsNearPlane;
                            MyRenderCamera.FAR_PLANE_FOR_NEAR_OBJECTS = rMessage.NearObjectsFarPlane;

                            foreach (var effect in m_effects)
                            {
                                if (effect != null)
                                {
                                    effect.SetNearPlane(MyRenderCamera.NEAR_PLANE_DISTANCE);
                                    effect.SetFarPlane(MyRenderCamera.FAR_PLANE_DISTANCE);
                                }
                            }
                        }

                        MyRenderCamera.UpdateCamera();

                        break;
                    }

                case MyRenderMessageEnum.DrawScene:
                    {
                        var rMessage = (MyRenderMessageBase)message;
                        EnqueueDrawMessage(rMessage);

                        break;
                    }

                case MyRenderMessageEnum.UpdateRenderObject:
                    {
                        var rMessage = (MyRenderMessageUpdateRenderObject)message;

                        MyRenderObject renderObject;
                        if (m_renderObjects.TryGetValue(rMessage.ID, out renderObject))
                        {
                            //System.Diagnostics.Debug.Assert(renderObject.ParentCullObject == null);
                            if (renderObject.ParentCullObject != null)
                            {
                                MyRenderTransformObject transformObject = renderObject as MyRenderTransformObject;
                                if (transformObject != null)
                                {
                                    //System.Diagnostics.Debug.Assert(Vector3D.IsZero(transformObject.WorldMatrix.Translation - rMessage.WorldMatrix.Translation, 0.01f));
                                }
                            }

                            {
                                MyRenderCharacter characterObject = renderObject as MyRenderCharacter;
                                if (characterObject != null)
                                {
                                    if (rMessage.AABB.HasValue)
                                        characterObject.ActualWorldAABB = rMessage.AABB.Value;
                                }
                                MyRenderTransformObject transformObject = renderObject as MyRenderTransformObject;
                                if (transformObject != null)
                                {
                                    transformObject.WorldMatrix = rMessage.WorldMatrix;
                                    UpdateRenderObject(transformObject, rMessage.SortIntoCulling);
                                }
                                MyRenderClipmap clipmap = renderObject as MyRenderClipmap;
                                if (clipmap != null)
                                {
                                    clipmap.UpdateWorldMatrix(ref rMessage.WorldMatrix, rMessage.SortIntoCulling);
                                    UpdateRenderObject(clipmap, rMessage.SortIntoCulling);
                                }
                                MyManualCullableRenderObject manualCullableRenderObject = renderObject as MyManualCullableRenderObject;
                                if (manualCullableRenderObject != null)
                                {
                                    manualCullableRenderObject.WorldMatrix = rMessage.WorldMatrix;
                                    UpdateRenderObject(manualCullableRenderObject, rMessage.SortIntoCulling);
                                }
                            }
                        }



                        break;
                    }

                case MyRenderMessageEnum.UpdateRenderObjectVisibility:
                    {
                        var rMessage = (MyRenderMessageUpdateRenderObjectVisibility)message;

                        MyRenderObject renderObject;
                        if (m_renderObjects.TryGetValue(rMessage.ID, out renderObject))
                        {
                            MyRenderTransformObject transformObject = renderObject as MyRenderTransformObject;
                            if (transformObject != null)
                            {
                                transformObject.ClearInterpolator();
                            }
                            MyManualCullableRenderObject manualCullableRenderObject = renderObject as MyManualCullableRenderObject;
                            if (manualCullableRenderObject != null)
                            {
                                manualCullableRenderObject.ClearInterpolator();
                            }

                            if (renderObject.NearFlag != rMessage.NearFlag)
                            {
                                var parentCullObject = renderObject.ParentCullObject;
                                if (parentCullObject != null)
                                {
                                    parentCullObject.RemoveRenderObject(renderObject);
                                }

                                RemoveRenderObject(renderObject, true);

                                renderObject.NearFlag = rMessage.NearFlag;

                                if (parentCullObject != null)
                                {
                                    RemoveRenderObject(parentCullObject);
                                    parentCullObject.AddRenderObject(renderObject);
                                    AddRenderObject(parentCullObject);

                                    if (renderObject.NearFlag && !m_nearObjects.Contains(renderObject))
                                    {
                                        m_nearObjects.Add(renderObject);
                                    }
                                }
                                else
                                {
                                    AddRenderObject(renderObject);
                                }
                            }
                            else
                            {
                                renderObject.Visible = rMessage.Visible;
                            }
                        }



                        break;
                    }

                case MyRenderMessageEnum.RemoveRenderObject:
                    {
                        var rMessage = (MyRenderMessageRemoveRenderObject)message;

                        MyRenderObject renderObject;
                        if (m_renderObjects.TryGetValue(rMessage.ID, out renderObject))
                        {
                            RemoveRenderObject(renderObject);
                            m_renderObjects.Remove(rMessage.ID);
                            renderObject.UnloadContent();
                        }
                        else
                        {
                        } // Put breakpoint here



                        break;
                    }


                case MyRenderMessageEnum.UpdateRenderEntity:
                    {
                        var rMessage = (MyRenderMessageUpdateRenderEntity)message;

                        MyRenderObject renderObject;
                        if (m_renderObjects.TryGetValue(rMessage.ID, out renderObject))
                        {
                            MyRenderEntity renderEntity = (MyRenderEntity)renderObject;
                            if (rMessage.DiffuseColor.HasValue)
                            {
                                renderEntity.EntityColor = rMessage.DiffuseColor.Value;
                            }
                            if (rMessage.ColorMaskHSV.HasValue)
                            {
                                renderEntity.EntityColorMaskHSV = rMessage.ColorMaskHSV.Value;
                            }
                            renderEntity.EntityDithering = rMessage.Dithering;
                        }



                        break;
                    }

                case MyRenderMessageEnum.EnableRenderModule:
                    {
                        var rMessage = (MyRenderMessageEnableRenderModule)message;

                        EnableRenderModule((MyRenderModuleEnum)rMessage.ID, rMessage.Enable);

                        break;
                    }

                case MyRenderMessageEnum.UseCustomDrawMatrix:
                    {
                        var rMessage = (MyRenderMessageUseCustomDrawMatrix)message;

                        MyRenderObject renderObject;
                        if (m_renderObjects.TryGetValue(rMessage.ID, out renderObject))
                        {
                            MyRenderEntity renderEntity = (MyRenderEntity)renderObject;

                            renderEntity.UseCustomDrawMatrix = rMessage.Enable;
                            renderEntity.DrawMatrix = (MatrixD)rMessage.DrawMatrix;
                        }

                        break;
                    }

                case MyRenderMessageEnum.CreateClipmap:
                    {
                        var rMessage = (MyRenderMessageCreateClipmap)message;

                        var clipmap = new MyRenderClipmap(rMessage);

                        AddRenderObjectFromProxy(clipmap);
                        clipmap.LoadContent();

                        break;
                    }

                case MyRenderMessageEnum.UpdateClipmapCell:
                    {
                        var rMessage = (MyRenderMessageUpdateClipmapCell)message;

                        MyRenderObject renderObject;
                        if (m_renderObjects.TryGetValue(rMessage.ClipmapId, out renderObject))
                        {
                            var clipmap = (MyRenderClipmap)renderObject;
                            clipmap.UpdateCell(rMessage);
                        }

                        break;
                    }

                case MyRenderMessageEnum.InvalidateClipmapRange:
                    {
                        var rMessage = (MyRenderMessageInvalidateClipmapRange)message;

                        MyRenderObject renderObject;
                        if (m_renderObjects.TryGetValue(rMessage.ClipmapId, out renderObject))
                        {
                            var clipmap = (MyRenderClipmap)renderObject;
                            clipmap.InvalidateRange(rMessage.MinCellLod0, rMessage.MaxCellLod0);
                        }
                        break;
                    }


                case MyRenderMessageEnum.RebuildCullingStructure:
                    {
                        MyRender.RebuildCullingStructure();

                        break;
                    }

                case MyRenderMessageEnum.ReloadGrass:
                case MyRenderMessageEnum.ReloadEffects:
                    {
                        MyRender.RootDirectoryEffects = MyRender.RootDirectoryDebug;
                        //MyRender.RootDirectoryEffects = MyRender.RootDirectory;
                        MyRender.LoadEffects();



                        break;
                    }


                case MyRenderMessageEnum.ReloadModels:
                    {
                        MyRenderModels.ReloadModels();



                        break;
                    }

                case MyRenderMessageEnum.ReloadTextures:
                    {
                        MyTextureManager.ReloadTextures(false);



                        break;
                    }

                case MyRenderMessageEnum.CreateRenderVoxelMaterials:
                    {
                        MyRenderVoxelMaterials.Clear();

                        var rMessage = (MyRenderMessageCreateRenderVoxelMaterials)message;

                        for (int i = 0; i < rMessage.Materials.Length; ++i)
                            MyRenderVoxelMaterials.Add(ref rMessage.Materials[i]);

                        rMessage.Materials = null;


                        break;
                    }

                case MyRenderMessageEnum.UpdateRenderVoxelMaterials:
                    {
                        MyRenderVoxelMaterials.Clear();

                        var rMessage = (MyRenderMessageUpdateRenderVoxelMaterials)message;

                        MyRenderVoxelMaterials.Add(ref rMessage.Materials[0]);

                        rMessage.Materials = null;


                        break;
                    }

                case MyRenderMessageEnum.CreateRenderVoxelDebris:
                    {
                        var rMessage = (MyRenderMessageCreateRenderVoxelDebris)message;

                        MyRenderVoxelDebris renderVoxelDebris = new MyRenderVoxelDebris(
                            rMessage.ID,
                            rMessage.DebugName,
                            rMessage.Model,
                            (MatrixD)rMessage.WorldMatrix,
                            rMessage.TextureCoordOffset,
                            rMessage.TextureCoordScale,
                            rMessage.TextureColorMultiplier,
                            rMessage.VoxelMaterialIndex
                            );

                        AddRenderObjectFromProxy(renderVoxelDebris);



                        break;
                    }


                case MyRenderMessageEnum.CreateRenderCharacter:
                    {
                        var rMessage = (MyRenderMessageCreateRenderCharacter)message;

                        MyRenderCharacter renderCharacter = new MyRenderCharacter(
                            rMessage.ID,
                            rMessage.DebugName,
                            rMessage.Model,
                            (MatrixD)rMessage.WorldMatrix,
                            rMessage.Flags
                            );

                        AddRenderObjectFromProxy(renderCharacter);



                        break;
                    }

                case MyRenderMessageEnum.UpdateModelProperties:
                    {
                        var rMessage = (MyRenderMessageUpdateModelProperties)message;

                        if (rMessage.ID == MyRenderProxy.RENDER_ID_UNASSIGNED)
                        {
                            MyRenderModel model = MyRenderModels.GetModel(rMessage.Model);
                            MyRenderMesh mesh = null;

                            if (rMessage.MaterialName != null)
                            {
                                foreach (var rMesh in model.GetMeshList())
                                {
                                    if (rMesh.Material.MaterialName == rMessage.MaterialName)
                                    {
                                        mesh = rMesh;
                                        break;
                                    }
                                }
                            }
                            else
                                mesh = model.GetMeshList()[rMessage.MeshIndex];

                            if (mesh != null)
                            {
                                MyRenderMeshMaterial material = mesh.Material;

                                if (rMessage.Enabled.HasValue)
                                    material.Enabled = rMessage.Enabled.Value;

                                if (rMessage.DiffuseColor.HasValue)
                                    material.DiffuseColor = rMessage.DiffuseColor.Value.ToVector3();

                                if (rMessage.SpecularIntensity.HasValue)
                                    material.SpecularIntensity = rMessage.SpecularIntensity.Value;

                                if (rMessage.SpecularPower.HasValue)
                                    material.SpecularPower = rMessage.SpecularPower.Value;

                                if (rMessage.Emissivity.HasValue)
                                    material.Emissivity = rMessage.Emissivity.Value;
                            }

                            model.HasSharedMaterials = true;
                        }
                        else
                        {
                            MyRenderObject renderObject;
                            if (m_renderObjects.TryGetValue(rMessage.ID, out renderObject))
                            {
                                MyRenderEntity renderEntity = renderObject as MyRenderEntity;
                                List<MyRenderMeshMaterial> materials = renderEntity.Lods[rMessage.LOD].MeshMaterials;
                                MyRenderModel model = renderEntity.Lods[rMessage.LOD].Model;
                                MyRenderMeshMaterial material = null;

                                model.HasSharedMaterials = false;

                                if (rMessage.MaterialName != null)
                                {
                                    foreach (var rMaterial in materials)
                                    {
                                        if (rMaterial.MaterialName == rMessage.MaterialName)
                                        {
                                            material = rMaterial;
                                            break;
                                        }
                                    }
                                }
                                else
                                    material = materials[rMessage.MeshIndex];

                                if (material != null)
                                {
                                    if (rMessage.Enabled.HasValue)
                                        material.Enabled = rMessage.Enabled.Value;

                                    if (rMessage.DiffuseColor.HasValue)
                                        material.DiffuseColor = rMessage.DiffuseColor.Value.ToVector3();

                                    if (rMessage.SpecularIntensity.HasValue)
                                        material.SpecularIntensity = rMessage.SpecularIntensity.Value;

                                    if (rMessage.SpecularPower.HasValue)
                                        material.SpecularPower = rMessage.SpecularPower.Value;

                                    if (rMessage.Emissivity.HasValue)
                                        material.Emissivity = rMessage.Emissivity.Value;
                                }
                            }
                        }



                        break;
                    }
                case MyRenderMessageEnum.UpdateColorEmissivity:
                    {
                        var rMessage = (MyRenderMessageUpdateColorEmissivity)message;

                        MyRenderObject renderObject;
                        if (m_renderObjects.TryGetValue(rMessage.ID, out renderObject))
                        {
                            MyRenderEntity renderEntity = renderObject as MyRenderEntity;
                            List<MyRenderMeshMaterial> materials = renderEntity.Lods[rMessage.LOD].MeshMaterials;
                            MyRenderModel model = renderEntity.Lods[rMessage.LOD].Model;
                            MyRenderMeshMaterial material = null;

                            model.HasSharedMaterials = false;

                            if (rMessage.MaterialName != null)
                            {
                                foreach (var rMaterial in materials)
                                {
                                    if (rMaterial.MaterialName == rMessage.MaterialName)
                                    {
                                        material = rMaterial;
                                        break;
                                    }
                                }
                            }

                            if (material != null)
                            {
                                material.DiffuseColor = rMessage.DiffuseColor.ToVector3();
                                material.Emissivity = rMessage.Emissivity;
                            }
                        }

                        break;
                    }

                case MyRenderMessageEnum.ChangeModel:
                    {
                        var rMessage = (MyRenderMessageChangeModel)message;

                        MyRenderObject renderObject;
                        if (m_renderObjects.TryGetValue(rMessage.ID, out renderObject))
                        {
                            MyRenderEntity entity = renderObject as MyRenderEntity;
                            if (rMessage.UseForShadow)
                            {
                                entity.ChangeShadowModels(rMessage.LOD, rMessage.Model);
                                entity.ChangeModels(rMessage.LOD, rMessage.Model);
                            }
                            else
                            {
                                entity.ChangeShadowModels(rMessage.LOD, entity.Lods[rMessage.LOD].Model.AssetName);
                                entity.ChangeModels(rMessage.LOD, rMessage.Model);
                            }
                        }




                        break;
                    }

                case MyRenderMessageEnum.UpdateGameplayFrame:
                    {
                        var rMessage = (MyRenderMessageUpdateGameplayFrame)message;

                        Settings.GameplayFrame = rMessage.GameplayFrame;

                        break;
                    }

                case MyRenderMessageEnum.UpdateVoxelMaterialsProperties:
                    {
                        var rMessage = (MyRenderMessageUpdateVoxelMaterialsProperties)message;

                        var material = MyRenderVoxelMaterials.Get(rMessage.MaterialIndex);

                        material.SpecularIntensity = rMessage.SpecularIntensity;
                        material.SpecularPower = rMessage.SpecularPower;



                        break;
                    }

                case MyRenderMessageEnum.ChangeMaterialTexture:
                    {
                        var rMessage = (MyRenderMessageChangeMaterialTexture)message;
                        MyRenderMeshMaterial material = GetMeshMaterial(rMessage.RenderObjectID, rMessage.MaterialName);
                        if (material != null)
                        {
                            material.DiffuseTexture = MyTextureManager.GetTexture<MyTexture2D>(rMessage.Changes[0].TextureName, "", null, LoadingMode.Immediate);
                        }
                        rMessage.Changes.Clear();

                        break;
                    }

                case MyRenderMessageEnum.DrawTextToMaterial:
                    {
                        var rMessage = (MyRenderMessageDrawTextToMaterial)message;
                        MyRenderMeshMaterial material = GetMeshMaterial(rMessage.RenderObjectID, rMessage.MaterialName);
                        if (material != null)
                        {
                            var id = new MyRenderTextureId();
                            id.EntityId = rMessage.EntityId;
                            id.RenderObjectId = rMessage.RenderObjectID;

                            material.DiffuseTexture = MyRender.RenderTextToTexture(id, rMessage.Text, rMessage.TextScale , rMessage.FontColor, rMessage.BackgroundColor, rMessage.TextureResolution, rMessage.TextureAspectRatio);
                            if (material.DiffuseTexture == null)
                            {
                                MyRenderProxy.TextNotDrawnToTexture(rMessage.EntityId);
                            }
                        }
                        break;
                    }
                case MyRenderMessageEnum.ReleaseRenderTexture:
                    {
                        var rMessage = (MyRenderMessageReleaseRenderTexture)message;
                        var id = new MyRenderTextureId();
                        id.EntityId = rMessage.EntityId;
                        id.RenderObjectId = rMessage.RenderObjectID;
                        if (MyRenderTexturePool.ReleaseRenderTexture(id))
                        {
                            MyRenderProxy.RenderTextureFreed(MyRenderTexturePool.FreeResourcesCount());
                        }
                        break;
                    }
                #endregion

                #region Lights

                case MyRenderMessageEnum.CreateRenderLight:
                    {
                        var rMessage = (MyRenderMessageCreateRenderLight)message;

                        MyRenderLight renderLight = new MyRenderLight(
                            rMessage.ID
                            );

                        AddRenderObjectFromProxy(renderLight);



                        break;
                    }

                case MyRenderMessageEnum.UpdateRenderLight:
                    {
                        var rMessage = (MyRenderMessageUpdateRenderLight)message;

                        MyRenderObject renderObject;
                        if (m_renderObjects.TryGetValue(rMessage.ID, out renderObject))
                        {
                            MyRenderLight renderLight = renderObject as MyRenderLight;
                            if (renderLight != null)
                            {
                                bool dirtyAABB = false;
                                if (renderLight.m_parentID != rMessage.ParentID)
                                    dirtyAABB = true;

                                if (renderLight.m_position != rMessage.Position)
                                    dirtyAABB = true;

                                renderLight.UpdateParameters(
                                    rMessage.Type,
                                    rMessage.Position,
                                    rMessage.ParentID,
                                    rMessage.Offset,
                                    rMessage.Color,
                                    rMessage.SpecularColor,
                                    rMessage.Falloff,
                                    rMessage.Range,
                                    rMessage.Intensity,
                                    rMessage.LightOn,
                                    rMessage.UseInForwardRender,
                                    rMessage.ReflectorIntensity,
                                    rMessage.ReflectorOn,
                                    rMessage.ReflectorDirection,
                                    rMessage.ReflectorUp,
                                    rMessage.ReflectorConeMaxAngleCos,
                                    rMessage.ReflectorColor,
                                    rMessage.ReflectorRange,
                                    rMessage.ReflectorFalloff,
                                    rMessage.ReflectorTexture,
                                    rMessage.ShadowDistance,
                                    rMessage.CastShadows,
                                    rMessage.GlareOn,
                                    rMessage.GlareType,
                                    rMessage.GlareSize,
                                    rMessage.GlareQuerySize,
                                    rMessage.GlareIntensity,
                                    rMessage.GlareMaterial,
                                    rMessage.GlareMaxDistance
                                    );

                                if (dirtyAABB)
                                    UpdateRenderObject(renderLight, false);
                            }
                        }



                        break;
                    }


                case MyRenderMessageEnum.SetLightShadowIgnore:
                    {
                        var rMessage = (MyRenderMessageSetLightShadowIgnore)message;

                        MyRenderObject renderObject;
                        if (m_renderObjects.TryGetValue(rMessage.ID, out renderObject))
                        {
                            MyRenderLight renderLight = (MyRenderLight)renderObject;
                            renderLight.ShadowIgnoreObjects.Add(rMessage.ID2);
                        }



                        break;
                    }


                case MyRenderMessageEnum.ClearLightShadowIgnore:
                    {
                        var rMessage = (MyRenderMessageClearLightShadowIgnore)message;

                        MyRenderObject renderObject;
                        if (m_renderObjects.TryGetValue(rMessage.ID, out renderObject))
                        {
                            MyRenderLight renderLight = (MyRenderLight)renderObject;
                            renderLight.ShadowIgnoreObjects.Clear();
                        }



                        break;
                    }

                case MyRenderMessageEnum.UpdateRenderEnvironment:
                    {
                        var rMessage = (MyRenderMessageUpdateRenderEnvironment)message;

                        float DX9Rescaling = 0.1195f;

                        Sun.Direction = rMessage.SunDirection;
                        Sun.Color = rMessage.SunColor;
                        Sun.BackColor = rMessage.AdditionalSunColors[0];
                        Sun.BackIntensity = rMessage.AdditionalSunIntensities[0] * DX9Rescaling;
                        Sun.Intensity = rMessage.SunIntensity;
                        Sun.LightOn = rMessage.SunLightOn;
                        Sun.SpecularColor = rMessage.SunSpecularColor;
                        Sun.SunSizeMultiplier = rMessage.SunSizeMultiplier;
                        Sun.DistanceToSun = rMessage.DistanceToSun;

                        MyRender.AmbientColor = rMessage.AmbientColor;
                        MyRender.AmbientMultiplier = rMessage.AmbientMultiplier;
                        MyRender.EnvAmbientIntensity = rMessage.EnvAmbientIntensity;

                        MyBackgroundCube.Filename = rMessage.BackgroundTexture;
                        MyBackgroundCube.BackgroundColor = rMessage.BackgroundColor;
                        MyBackgroundCube.BackgroundOrientation = rMessage.BackgroundOrientation;
                        Sun.SunMaterial = rMessage.SunMaterial;

                        MyBackgroundCube.Static.ReloadContent();

                        break;
                    }
                #endregion

                #region Post processes

                case MyRenderMessageEnum.UpdateHDRSettings:
                    {
                        var rMessage = (MyRenderMessageUpdateHDRSettings)message;

                        MyPostProcessHDR postProcessHDR = MyRender.GetPostProcess(MyPostProcessEnum.HDR) as MyPostProcessHDR;

                        postProcessHDR.Enabled = rMessage.Enabled;
                        postProcessHDR.Exposure = rMessage.Exposure;
                        postProcessHDR.Threshold = rMessage.Threshold;
                        postProcessHDR.BloomIntensity = rMessage.BloomIntensity;
                        postProcessHDR.BloomIntensityBackground = rMessage.BloomIntensityBackground;
                        postProcessHDR.VerticalBlurAmount = rMessage.VerticalBlurAmount;
                        postProcessHDR.HorizontalBlurAmount = rMessage.HorizontalBlurAmount;
                        postProcessHDR.NumberOfBlurPasses = rMessage.NumberOfBlurPasses;



                        break;
                    }

                case MyRenderMessageEnum.UpdateAntiAliasSettings:
                    {
                        var rMessage = (MyRenderMessageUpdateAntiAliasSettings)message;

                        var postProcess = MyRender.GetPostProcess(MyPostProcessEnum.FXAA) as MyPostProcessAntiAlias;

                        postProcess.Enabled = rMessage.Enabled;



                        break;
                    }

                case MyRenderMessageEnum.UpdateVignettingSettings:
                    {
                        var rMessage = (MyRenderMessageUpdateVignettingSettings)message;

                        var postProcess = MyRender.GetPostProcess(MyPostProcessEnum.Vignetting) as MyPostProcessVignetting;

                        postProcess.Enabled = rMessage.Enabled;
                        postProcess.VignettingPower = rMessage.VignettingPower;



                        break;
                    }

                case MyRenderMessageEnum.UpdateColorMappingSettings:
                    {
                        var rMessage = (MyRenderMessageUpdateColorMappingSettings)message;

                        var postProcess = MyRender.GetPostProcess(MyPostProcessEnum.ColorMapping) as MyPostProcessColorMapping;

                        postProcess.Enabled = rMessage.Enabled;



                        break;
                    }

                case MyRenderMessageEnum.UpdateContrastSettings:
                    {
                        var rMessage = (MyRenderMessageUpdateContrastSettings)message;
                        var postProcess = MyRender.GetPostProcess(MyPostProcessEnum.Contrast) as MyPostProcessContrast;

                        postProcess.Enabled = rMessage.Enabled;
                        postProcess.Contrast = rMessage.Contrast;
                        postProcess.Hue = rMessage.Hue;
                        postProcess.Saturation = rMessage.Saturation;



                        break;
                    }

                case MyRenderMessageEnum.UpdateChromaticAberrationSettings:
                    {
                        var rMessage = (MyRenderMessageUpdateChromaticAberrationSettings)message;
                        var postProcess = MyRender.GetPostProcess(MyPostProcessEnum.ChromaticAberration) as MyPostProcessChromaticAberration;

                        postProcess.Enabled = rMessage.Enabled;
                        postProcess.DistortionLens = rMessage.DistortionLens;
                        postProcess.DistortionCubic = rMessage.DistortionCubic;
                        postProcess.DistortionWeights = rMessage.DistortionWeights;



                        break;
                    }

                case MyRenderMessageEnum.UpdateSSAOSettings:
                    {
                        var rMessage = (MyRenderMessageUpdateSSAOSettings)message;

                        var postProcess = MyRender.GetPostProcess(MyPostProcessEnum.VolumetricSSAO2) as MyPostProcessVolumetricSSAO2;

                        postProcess.Enabled = rMessage.Enabled;

                        postProcess.ShowOnlySSAO = rMessage.ShowOnlySSAO;
                        postProcess.UseBlur = rMessage.UseBlur;

                        postProcess.MinRadius = rMessage.MinRadius;
                        postProcess.MaxRadius = rMessage.MaxRadius;
                        postProcess.RadiusGrowZScale = rMessage.RadiusGrowZScale;
                        postProcess.CameraZFar = rMessage.CameraZFar;

                        postProcess.Bias = rMessage.Bias;
                        postProcess.Falloff = rMessage.Falloff;
                        postProcess.NormValue = rMessage.NormValue;
                        postProcess.Contrast = rMessage.Contrast;



                        break;
                    }

                case MyRenderMessageEnum.UpdateFogSettings:
                    {
                        var rMessage = (MyRenderMessageUpdateFogSettings)message;

                        var postProcess = MyRender.GetPostProcess(MyPostProcessEnum.VolumetricFog) as MyPostProcessVolumetricFog;

                        postProcess.Enabled = rMessage.Settings.Enabled;
                        FogProperties.FogNear = rMessage.Settings.FogNear;
                        FogProperties.FogFar = rMessage.Settings.FogFar;
                        FogProperties.FogMultiplier = rMessage.Settings.FogMultiplier;
                        FogProperties.FogBacklightMultiplier = rMessage.Settings.FogBacklightMultiplier;
                        FogProperties.FogColor = rMessage.Settings.FogColor;



                        break;
                    }

                case MyRenderMessageEnum.UpdateGodRaysSettings:
                    {
                        var rMessage = (MyRenderMessageUpdateGodRaysSettings)message;

                        var postProcess = MyRender.GetPostProcess(MyPostProcessEnum.GodRays) as MyPostProcessGodRays;

                        postProcess.Enabled = rMessage.Enabled;
                        postProcess.Density = rMessage.Density;
                        postProcess.Weight = rMessage.Weight;
                        postProcess.Decay = rMessage.Decay;
                        postProcess.Exposition = rMessage.Exposition;
                        postProcess.ApplyBlur = rMessage.ApplyBlur;



                        break;
                    }

                #endregion

                #region Environment

                case MyRenderMessageEnum.UpdateEnvironmentMap:
                    {
                        EnqueueDrawMessage(message);
                        break;
                    }

                #endregion

                #region Video

                case MyRenderMessageEnum.PlayVideo:
                    {
                        var rMessage = (MyRenderMessagePlayVideo)message;

                        MyRender.PlayVideo(rMessage.ID, rMessage.VideoFile, rMessage.Volume);



                        break;
                    }

                case MyRenderMessageEnum.UpdateVideo:
                    {
                        var rMessage = (MyRenderMessageUpdateVideo)message;

                        MyRender.UpdateVideo(rMessage.ID);



                        break;
                    }

                case MyRenderMessageEnum.DrawVideo:
                    {
                        var rMessage = (MyRenderMessageDrawVideo)message;

                        EnqueueDrawMessage(rMessage);

                        break;
                    }

                case MyRenderMessageEnum.CloseVideo:
                    {
                        var rMessage = (MyRenderMessageCloseVideo)message;

                        MyRender.CloseVideo(rMessage.ID);



                        break;
                    }

                case MyRenderMessageEnum.SetVideoVolume:
                    {
                        var rMessage = (MyRenderMessageSetVideoVolume)message;

                        MyRender.SetVideoVolume(rMessage.ID, rMessage.Volume);



                        break;
                    }


                #endregion

                #region Secondary camera

                case MyRenderMessageEnum.DrawSecondaryCamera:
                    {
                        var rMessage = (MyRenderMessageDrawSecondaryCamera)message;

                        EnqueueDrawMessage(rMessage);

                        break;
                    }

                case MyRenderMessageEnum.DrawSecondaryCameraSprite:
                    {
                        var rMessage = (MyRenderMessageDrawSecondaryCameraSprite)message;
                        EnqueueDrawMessage(rMessage);
                        break;
                    }

                #endregion

                #region Decals

                case MyRenderMessageEnum.CreateDecal:
                    {
                        var rMessage = (MyRenderMessageCreateDecal)message;

                        MyRenderObject renderObject;
                        if (m_renderObjects.TryGetValue(rMessage.ID, out renderObject))
                        {
                            MyDecals.AddDecal(
                                renderObject,
                                ref rMessage.Triangle,
                                rMessage.TrianglesToAdd,
                                rMessage.Texture,
                                (Vector3D)rMessage.Position,
                                rMessage.LightSize,
                                rMessage.Emissivity
                               );
                        }



                        break;
                    }


                case MyRenderMessageEnum.HideDecals:
                    {
                        var rMessage = (MyRenderMessageHideDecals)message;

                        MyRenderObject renderObject;
                        if (m_renderObjects.TryGetValue(rMessage.ID, out renderObject))
                        {
                            if (rMessage.Radius == 0 && renderObject is MyRenderTransformObject)
                            {
                                MyDecals.RemoveModelDecals(renderObject as MyRenderTransformObject);
                            }
                            else
                            {
                                if (renderObject is MyRenderVoxelCell)
                                {
                                    VRageMath.BoundingSphere bs = new VRageMath.BoundingSphere(rMessage.Center, rMessage.Radius);
                                    MyDecals.HideTrianglesAfterExplosion(renderObject as MyRenderVoxelCell, ref bs);
                                }
                            }
                        }



                        break;
                    }



                #endregion

                #region Cockpit

                case MyRenderMessageEnum.UpdateCockpitGlass:
                    {
                        var rMessage = (MyRenderMessageUpdateCockpitGlass)message;

                        MyCockpitGlass.Visible = rMessage.Visible;
                        MyCockpitGlass.PlayerHeadForCockpitInteriorWorldMatrix = (MatrixD)rMessage.WorldMatrix;
                        MyCockpitGlass.GlassDirtAlpha = rMessage.DirtAlpha;
                        MyCockpitGlass.Model = rMessage.Model;



                        break;
                    }

                #endregion

                #region Billboards and quality

                case MyRenderMessageEnum.UpdateBillboardsColorize:
                    {
                        var rMessage = (MyRenderMessageUpdateBillboardsColorize)message;

                        EnqueueDrawMessage(rMessage);

                        break;
                    }

                case MyRenderMessageEnum.AddLineBillboardLocal:
                    {
                        var rMessage = (MyRenderMessageAddLineBillboardLocal)message;

                        MyRenderObject renderObject;
                        if (m_renderObjects.TryGetValue(rMessage.RenderObjectID, out renderObject))
                        {
                            renderObject.Billboards.Add(rMessage);
                        }

                        break;
                    }

                case MyRenderMessageEnum.AddPointBillboardLocal:
                    {
                        var rMessage = (MyRenderMessageAddPointBillboardLocal)message;

                        MyRenderObject renderObject;
                        if (m_renderObjects.TryGetValue(rMessage.RenderObjectID, out renderObject))
                        {
                            renderObject.Billboards.Add(rMessage);
                        }

                        break;
                    }

                case MyRenderMessageEnum.UpdateDistantImpostors:
                    {
                        var rMessage = (MyRenderMessageUpdateDistantImpostors)message;

                        MyDistantImpostors.ImpostorProperties = rMessage.ImpostorProperties;
                        MyDistantImpostors.Static.ReloadContent();



                        break;
                    }

                case MyRenderMessageEnum.SetTextureIgnoreQuality:
                    {
                        var rMessage = (MyRenderMessageSetTextureIgnoreQuality)message;

                        MyTextureManager.TexturesWithIgnoredQuality.Add(rMessage.Path);
                        MyTextureManager.UnloadTexture(rMessage.Path);



                        break;
                    }

                case MyRenderMessageEnum.UpdateRenderQuality:
                    {
                        var rMessage = (MyRenderMessageUpdateRenderQuality)message;

                        MyRenderQualityProfile profile = MyRenderConstants.m_renderQualityProfiles[(int)rMessage.RenderQuality];

                        profile.EnableCascadeBlending = rMessage.EnableCascadeBlending;

                        MyRenderTexturePool.RenderQualityChanged(rMessage.RenderQuality);

                        break;
                    }

                case MyRenderMessageEnum.TakeScreenshot:
                    {
                        var rMessage = (MyRenderMessageTakeScreenshot)message;

                        m_screenshot = new MyScreenshot(rMessage.SizeMultiplier, rMessage.PathToSave, rMessage.IgnoreSprites, rMessage.ShowNotification);
                        ScreenshotOnlyFinal = !rMessage.Debug;

                        //Will do before draw
                        //UpdateScreenSize();
                        //MyEnvironmentMap.Reset();



                        break;
                    }
                case MyRenderMessageEnum.RenderColoredTexture:
                    {
                        var rMessage = (MyRenderMessageRenderColoredTexture)message;
                        m_texturesToRender.AddRange(rMessage.texturesToRender);
                        break;
                    }

                #endregion

                #region Characters

                case MyRenderMessageEnum.SetCharacterSkeleton:
                    {
                        var rMessage = (MyRenderMessageSetCharacterSkeleton)message;

                        MyRenderObject renderCharacterObject;
                        if (m_renderObjects.TryGetValue(rMessage.CharacterID, out renderCharacterObject))
                        {
                            MyRenderCharacter renderCharacter = (MyRenderCharacter)renderCharacterObject;
                            renderCharacter.SetSkeleton(rMessage.SkeletonBones, rMessage.SkeletonIndices);
                        }

                        break;
                    }

                case MyRenderMessageEnum.SetCharacterTransforms:
                    {
                        var rMessage = (MyRenderMessageSetCharacterTransforms)message;

                        MyRenderObject renderCharacterObject;
                        if (m_renderObjects.TryGetValue(rMessage.CharacterID, out renderCharacterObject))
                        {
                            MyRenderCharacter renderCharacter = (MyRenderCharacter)renderCharacterObject;
                            renderCharacter.SetAnimationBones(rMessage.RelativeBoneTransforms);
                        }



                        break;
                    }


                #endregion

                #region Debug draw

                case MyRenderMessageEnum.DebugDrawLine3D:
                case MyRenderMessageEnum.DebugDrawLine2D:
                case MyRenderMessageEnum.DebugDrawSphere:
                case MyRenderMessageEnum.DebugDrawAABB:
                case MyRenderMessageEnum.DebugDrawAxis:
                case MyRenderMessageEnum.DebugDrawOBB:
                case MyRenderMessageEnum.DebugDrawTriangle:
                case MyRenderMessageEnum.DebugDrawCapsule:
                case MyRenderMessageEnum.DebugDrawText2D:
                case MyRenderMessageEnum.DebugDrawText3D:
                case MyRenderMessageEnum.DebugDrawModel:
                case MyRenderMessageEnum.DebugDrawTriangles:
                case MyRenderMessageEnum.DebugDrawPlane:
                case MyRenderMessageEnum.DebugDrawCylinder:
                case MyRenderMessageEnum.DebugWaitForPresent:
                    {
                        EnqueueDebugDrawMessage(message);
                    }
                    break;

                case MyRenderMessageEnum.DebugCrashRenderThread:
                    {
                        throw new InvalidOperationException("Forced exception");
                    }
                #endregion

                #region Fonts and text

                case MyRenderMessageEnum.CreateFont:
                    {
                        var createFontMessage = message as MyRenderMessageCreateFont;
                        Debug.Assert(createFontMessage != null);

                        var renderFont = new MyRenderFont(createFontMessage.FontPath);
                        renderFont.LoadContent();
                        AddFont(createFontMessage.FontId, renderFont, createFontMessage.IsDebugFont);

                        break;
                    }

                case MyRenderMessageEnum.DrawString:
                    {
                        EnqueueDrawMessage(message);
                        break;
                    }

                #endregion

                case MyRenderMessageEnum.VideoAdaptersRequest:
                    {
                        MyRenderProxy.SendVideoAdapters(GetAdaptersList());
                        break;
                    }

                case MyRenderMessageEnum.SwitchDeviceSettings:
                    {
                        MyRenderProxy.RenderThread.SwitchSettings((message as MyRenderMessageSwitchDeviceSettings).Settings);
                        break;
                    }

                case MyRenderMessageEnum.SwitchRenderSettings:
                    {
                        // Dx9 Only understands interpolation and render quality.
                        var rMessage = (MyRenderMessageSwitchRenderSettings)message;
                        MyRenderProxy.Settings.EnableObjectInterpolation = rMessage.Settings.InterpolationEnabled;
                        MyRenderProxy.Settings.EnableCameraInterpolation = rMessage.Settings.InterpolationEnabled;
                        MyRenderProxy.RenderThread.SwitchQuality(rMessage.Settings.Dx9Quality);
                        break;
                    }

                case MyRenderMessageEnum.UnloadData:
                    {
                        MyRender.UnloadData();



                        break;
                    }

                case MyRenderMessageEnum.CollectGarbage:
                    {
                        GC.Collect();
                        break;
                    }

                case MyRenderMessageEnum.UpdatePostprocessSettings:
                    {
                        break;
                    }

                default:
                  //  System.Diagnostics.Debug.Assert(false, "Unknown message");
                    break;
            }
        }
 public void Enqueue(MyRenderMessageBase message)
 {
     using (m_lock.Acquire())
         RenderInput.Add(message);
 }
Пример #9
0
 internal static void EnqueueOutputMessage(MyRenderMessageBase message)
 {
     SharedData.RenderOutputMessageQueue.Enqueue(message);
 }
Пример #10
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);
            }
        }
Пример #11
0
 internal static void EnqueueMessage(MyRenderMessageBase message, bool limitMaxQueueSize)
 {
     SharedData.CurrentUpdateFrame.RenderInput.Add(message);
 }
Пример #12
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;

                MyFileTextureManager texManager = MyManagers.FileTextures;
                MySpritesRenderer.AddSingleSprite(texManager.GetTexture(sprite.Texture, MyFileTextureEnum.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 = MyManagers.FileTextures.GetTexture(sprite.Texture, MyFileTextureEnum.GUI, true);

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

                Vector2 sizeInPixels       = tex.Size;
                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);

                MyFileTextureManager texManager = MyManagers.FileTextures;
                MySpritesRenderer.AddSingleSprite(texManager.GetTexture(sprite.Texture, MyFileTextureEnum.GUI, waitTillLoaded: sprite.WaitTillLoaded), sprite.Color, origin, rightVector, null, rect);

                break;
            }


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

                MyFileTextureManager texManager = MyManagers.FileTextures;
                var tex         = texManager.GetTexture(sprite.Texture, MyFileTextureEnum.GUI, true);
                var textureSize = tex.Size;

                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(texManager.GetTexture(sprite.Texture, MyFileTextureEnum.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;
            }

            default:
                throw new Exception();
            }
        }
Пример #13
0
 internal static void EnqueueMessage(MyRenderMessageBase message, bool limitMaxQueueSize)
 {
     SharedData.CurrentUpdateFrame.RenderInput.Add(message);
 }
Пример #14
0
 public void EnqueueMessage(MyRenderMessageBase message, bool limitMaxQueueSize)
 {
     MyRender.EnqueueMessage(message, limitMaxQueueSize);
 }
        private static void DrawDebugMessages()
        {
            //DepthStencilState.None.Apply();
            DepthStencilState.DepthRead.Apply();
            BlendState.NonPremultiplied.Apply();

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

                MyRenderMessageEnum messageType = debugDrawMessage.MessageType;

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

                    MyDebugDraw.DrawLine3D(
                        message.PointFrom,
                        message.PointTo,
                        message.ColorFrom,
                        message.ColorTo,
                        message.DepthRead);

                    break;
                }

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

                    MyDebugDraw.DrawLine2D(
                        message.PointFrom,
                        message.PointTo,
                        message.ColorFrom,
                        message.ColorTo,
                        message.Projection);

                    break;
                }

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

                    MyDebugDraw.DrawSphere(
                        message.Position,
                        message.Radius,
                        message.Color,
                        message.Alpha,
                        message.DepthRead,
                        message.Smooth,
                        message.Cull);

                    break;
                }

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

                    Color color = new Color(message.Color, message.Alpha);
                    var   aabb  = new BoundingBoxD(message.AABB.Min, message.AABB.Max);
                    MyDebugDraw.DrawAABBLine(
                        ref aabb,
                        ref color,
                        message.Scale,
                        message.DepthRead);

                    break;
                }

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

                    MyDebugDraw.DrawAxis(
                        (MatrixD)message.Matrix,
                        message.AxisLength,
                        1,
                        message.DepthRead);

                    break;
                }

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

                    if (message.Smooth)
                    {
                        MyDebugDraw.DrawLowresBoxSmooth(
                            message.Matrix,
                            message.Color,
                            message.Alpha,
                            message.DepthRead,
                            message.Cull);
                    }
                    else
                    {
                        MyDebugDraw.DrawOBBLine(
                            new MyOrientedBoundingBoxD(message.Matrix),
                            message.Color,
                            message.Alpha,
                            message.DepthRead);

                        //BoundingBoxD bd = new BoundingBoxD(message.Matrix.Translation - new Vector3(100),message.Matrix.Translation + new Vector3(100));

                        //Vector4 c = new Vector4(message.Color.X, message.Color.Y, message.Color.Z, message.Alpha);
                        //MyDebugDraw.DrawAABBLine(ref bd, ref c, 1, false);
                    }
                    break;
                }

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

                    if (message.Smooth)
                    {
                        MyDebugDraw.DrawLowresCylinderSmooth(
                            (MatrixD)message.Matrix,
                            message.Color,
                            message.Alpha,
                            message.DepthRead);
                    }
                    else
                    {
                        MyDebugDraw.DrawLowresCylinderWireframe(
                            (MatrixD)message.Matrix,
                            message.Color,
                            message.Alpha,
                            message.DepthRead);
                    }
                    break;
                }

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

                    MyDebugDraw.DrawTriangle((Vector3D)message.Vertex0, (Vector3D)message.Vertex1, (Vector3D)message.Vertex2, message.Color, message.Color, message.Color, message.Smooth, message.DepthRead);

                    break;
                }

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

                    MyDebugDraw.DrawTriangles(message.WorldMatrix, message.Vertices, message.Indices, message.Color,
                                              message.DepthRead, message.Shaded);
                    break;
                }

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

                    if (message.Shaded)
                    {
                        MyDebugDraw.DrawCapsuleShaded(message.P0, message.P1, message.Radius, message.Color, message.DepthRead);
                    }
                    else
                    {
                        MyDebugDraw.DrawCapsule(message.P0, message.P1, message.Radius, message.Color, message.DepthRead);
                    }

                    break;
                }

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

                    MyDebugDraw.DrawText(
                        message.Coord,
                        new StringBuilder(message.Text),
                        message.Color,
                        message.Scale,
                        false,
                        message.Align);

                    break;
                }

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

                    MyDebugDraw.DrawText(
                        (Vector3D)message.Coord,
                        new StringBuilder(message.Text),
                        message.Color,
                        message.Scale,
                        message.DepthRead,
                        message.Align,
                        message.CustomViewProjection);

                    break;
                }

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

                    MyDebugDraw.DrawModel(MyRenderModels.GetModel(message.Model), message.WorldMatrix, message.Color,
                                          message.DepthRead);

                    break;
                }

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

                    MyDebugDraw.DrawPlane((Vector3D)message.Position, message.Normal, message.Color, message.DepthRead);

                    break;
                }

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

                default:
                {
                    System.Diagnostics.Debug.Assert(false, "Unknown debug draw message");
                    break;
                }
                }
            }
        }
Пример #16
0
 public void Enqueue(MyRenderMessageBase message)
 {
     using (m_lock.Acquire())
         RenderInput.Add(message);
 }
 internal static void EnqueueDebugDrawMessage(MyRenderMessageBase drawMessage)
 {
     Debug.Assert(drawMessage.MessageClass == MyRenderMessageType.DebugDraw, "Enqueuing non-draw message");
     m_debugDrawMessages.Enqueue(drawMessage);
 }
        internal static void DrawMessageQueue()
        {
            if (m_spriteBatch == null)
            {
                return;
            }



            BeginSpriteBatch();

            /*
             * if (m_drawMessages.Count == 0)
             * {
             *  GraphicsDevice.Clear(ClearFlags.All, new SharpDX.ColorBGRA(1.0f, 1, 0, 1), 1, 0);
             *  DrawText(new Vector2(0, 300), new StringBuilder("No draw input"), Color.White, 1);
             * } */


            while (m_drawMessages.Count > 0)
            {
                MyRenderMessageBase drawMessage = m_drawMessages.Dequeue();

                MyRenderMessageEnum messageType = drawMessage.MessageType;
                switch (messageType)
                {
                case MyRenderMessageEnum.SpriteScissorPush:
                {
                    var msg = drawMessage as MyRenderMessageSpriteScissorPush;
                    m_spriteBatch.ScissorStack.Push(msg.ScreenRectangle);
                    break;
                }

                case MyRenderMessageEnum.SpriteScissorPop:
                {
                    m_spriteBatch.ScissorStack.Pop();
                    break;
                }

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

                    ProcessSpriteMessage(sprite);
                    break;
                }

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

                    ProcessNormalizedSpriteMessage(sprite);

                    break;
                }

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

                    ProcessAtlasSprite(sprite);

                    break;
                }

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

                    var font = MyRender.GetFont(message.FontIndex);
                    font.DrawString(
                        message.ScreenCoord * m_sizeMultiplierForStrings,
                        message.ColorMask,
                        message.Text,
                        message.ScreenScale * m_sizeMultiplierForStrings.X,
                        message.ScreenMaxWidth * m_sizeMultiplierForStrings.X);

                    break;
                }

                case MyRenderMessageEnum.DrawScene:
                {
                    EndSpriteBatch();

                    MyRenderCamera.UpdateCamera();
                    MyRender.SetDeviceViewport(MyRenderCamera.Viewport);

                    Draw3D();

                    DrawDebugMessages();

                    BeginSpriteBatch();

                    break;
                }

                case MyRenderMessageEnum.DrawVideo:
                {
                    var rMessage = (MyRenderMessageDrawVideo)drawMessage;
                    MyRender.DrawVideo(rMessage.ID, rMessage.Rectangle, rMessage.Color, rMessage.FitMode);

                    break;
                }

                case MyRenderMessageEnum.UpdateEnvironmentMap:
                {
                    MyRender.GetRenderProfiler().StartProfilingBlock("MyEnvironmentMap.Update");
                    MyEnvironmentMap.Update();
                    MyRender.GetRenderProfiler().EndProfilingBlock();

                    break;
                }

                case MyRenderMessageEnum.DrawSecondaryCamera:
                {
                    var rMessage = (MyRenderMessageDrawSecondaryCamera)drawMessage;

                    MySecondaryCameraRenderer.Instance.ViewMatrix = (MatrixD)rMessage.ViewMatrix;
                    MySecondaryCameraRenderer.Instance.Render();

                    break;
                }

                case MyRenderMessageEnum.DrawSecondaryCameraSprite:
                {
                    MyRenderMessageDrawSecondaryCameraSprite sprite = (MyRenderMessageDrawSecondaryCameraSprite)drawMessage;

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

                    DrawSpriteMain(
                        MySecondaryCameraRenderer.Instance.GetRenderedTexture(),
                        null,
                        ref sprite.DestinationRectangle,
                        sprite.ScaleDestination,
                        sprite.SourceRectangle,
                        sprite.Color,
                        rightVector,
                        ref sprite.Origin,
                        sprite.Effects,
                        sprite.Depth
                        );

                    break;
                }

                case MyRenderMessageEnum.UpdateBillboardsColorize:
                {
                    var rMessage = (MyRenderMessageUpdateBillboardsColorize)drawMessage;

                    MyTransparentGeometry.EnableColorize        = rMessage.Enable;
                    MyTransparentGeometry.ColorizeColor         = rMessage.Color;
                    MyTransparentGeometry.ColorizePlaneDistance = rMessage.Distance;
                    MyTransparentGeometry.ColorizePlaneNormal   = rMessage.Normal;

                    break;
                }

                default:
                {
                    System.Diagnostics.Debug.Assert(false, "Unknown draw message");
                    break;
                }
                }
            }

            GetRenderProfiler().StartProfilingBlock("SpriteBatchRestart");
            EndSpriteBatch();
            BeginSpriteBatch();
            GetRenderProfiler().EndProfilingBlock();

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

            if (MyRenderProxy.DRAW_RENDER_STATS)
            {
                MyRenderStatsDraw.Draw(MyRenderStats.m_stats, 0.6f, Color.Yellow);
            }

            if (MyRender.Settings.TearingTest)
            {
                DrawTearingTest();
            }

            if (MyRender.Settings.MultimonTest)
            {
                // Middle screen
                var from = new Vector2(GraphicsDevice.Viewport.Width / 2.0f, 0);
                var to   = new Vector2(GraphicsDevice.Viewport.Width / 2.0f, GraphicsDevice.Viewport.Height);
                VRageRender.MyRenderProxy.DebugDrawLine2D(from, to, Color.Orange, Color.Orange);

                from = new Vector2(GraphicsDevice.Viewport.Width / 3.0f, 0);
                to   = new Vector2(GraphicsDevice.Viewport.Width / 3.0f, GraphicsDevice.Viewport.Height);
                VRageRender.MyRenderProxy.DebugDrawLine2D(from, to, Color.Yellow, Color.Yellow);
                from = new Vector2(GraphicsDevice.Viewport.Width / 3.0f * 2.0f, 0);
                to   = new Vector2(GraphicsDevice.Viewport.Width / 3.0f * 2.0f, GraphicsDevice.Viewport.Height);
                VRageRender.MyRenderProxy.DebugDrawLine2D(from, to, Color.Yellow, Color.Yellow);
            }

            GetRenderProfiler().StartProfilingBlock("SpriteBatchEnd");
            EndSpriteBatch();
            GetRenderProfiler().EndProfilingBlock();


            System.Diagnostics.Debug.Assert(m_spriteBatchUsageCount == 0);
        }
Пример #19
0
 public void EnqueueOutputMessage(MyRenderMessageBase message)
 {
     MyRender.EnqueueOutputMessage(message);
 }
        private static void ProcessMessageInternal(MyRenderMessageBase message)
        {
            switch (message.MessageType)
            {
                case MyRenderMessageEnum.SetCameraViewMatrix:
                {
                    var rMessage = (MyRenderMessageSetCameraViewMatrix)message;

                    SetupCameraMatrices(rMessage);

                    break;
                }

                case MyRenderMessageEnum.DrawScene:
                {
                    var rMessage = (MyRenderMessageBase)message;

                    m_drawQueue.Enqueue(rMessage);

                    m_messageTracker.Clear();

                    break;
                }

                case MyRenderMessageEnum.RebuildCullingStructure:
                {

                    break;
                }

                #region Profiler

                case MyRenderMessageEnum.RenderProfiler:
                {
                    var profMessage = (MyRenderMessageRenderProfiler)message;

                    MyRenderProfiler.HandleInput(profMessage.Command, profMessage.Index);

                    break;
                }

                #endregion

                #region Characters

                case MyRenderMessageEnum.CreateRenderCharacter:
                {
                    var rMessage = (MyRenderMessageCreateRenderCharacter)message;

                    var actor = MyActorFactory.CreateCharacter();
                    var renderable = actor.GetRenderable();
                    renderable.SetModel(MyMeshes.GetMeshId(MyStringId.GetOrCompute(rMessage.Model)));
                    actor.SetMatrix(ref rMessage.WorldMatrix);

                    if (rMessage.ColorMaskHSV.HasValue)
                    {
                        var color = ColorFromMask(rMessage.ColorMaskHSV.Value);
                        renderable.SetKeyColor(new Vector4(color, 1));
                    }

                    actor.SetID(rMessage.ID);
					renderable.m_additionalFlags |= MyProxiesFactory.GetRenderableProxyFlags(rMessage.Flags);
                    renderable.m_drawFlags = MyDrawSubmesh.MySubmeshFlags.Gbuffer | MyDrawSubmesh.MySubmeshFlags.Depth;

                    break;
                }

                case MyRenderMessageEnum.SetCharacterSkeleton:
                {
                    var rMessage = (MyRenderMessageSetCharacterSkeleton)message;

                    var actor = MyIDTracker<MyActor>.FindByID(rMessage.CharacterID);
                    if (actor != null)
                    {
                        actor.GetSkinning().SetSkeleton(rMessage.SkeletonBones, rMessage.SkeletonIndices);
                    }

                    //var entity = MyComponents.GetEntity(rMessage.CharacterID);
                    //MyComponents.SetSkeleton(entity, rMessage.SkeletonBones, rMessage.SkeletonIndices);

                    break;
                };

                case MyRenderMessageEnum.SetCharacterTransforms:
                {
                    var rMessage = (MyRenderMessageSetCharacterTransforms)message;

                    var actor = MyIDTracker<MyActor>.FindByID(rMessage.CharacterID);
                    if (actor != null)
                    {
                        actor.GetSkinning().SetAnimationBones(rMessage.RelativeBoneTransforms);
                    }
                    //var entity = MyComponents.GetEntity(rMessage.CharacterID);
                    //MyComponents.SetAnimation(entity, rMessage.RelativeBoneTransforms);

                    break;
                }

                case MyRenderMessageEnum.UpdateRenderEntity:
                {
                    var rMessage = (MyRenderMessageUpdateRenderEntity)message;

                    var actor = MyIDTracker<MyActor>.FindByID(rMessage.ID);
                    if (actor == null)
                        break;

                    var renderableComponent = actor.GetRenderable();
                    if (renderableComponent == null)
                        break;

                    if (rMessage.ColorMaskHSV.HasValue)
                    {
                        actor.GetRenderable().SetKeyColor(new Vector4(ColorFromMask(rMessage.ColorMaskHSV.Value), 0));
                    }
                    actor.GetRenderable().SetDithering(rMessage.Dithering);

                    break;
                }

                case MyRenderMessageEnum.ChangeModel:
                {
                    var rMessage = (MyRenderMessageChangeModel)message;

                    var actor = MyIDTracker<MyActor>.FindByID(rMessage.ID);
                    if (actor != null && actor.GetRenderable() != null)
                    {
                        var r = actor.GetRenderable();

                        var modelId = MyMeshes.GetMeshId(X.TEXT_(rMessage.Model));
                        if(r.GetModel() != modelId)
                        {
                            r.SetModel(modelId);
                        }
                    }

                    break;
                }

                case MyRenderMessageEnum.ChangeModelMaterial:
                {
                    var rMessage = (MyRenderMessageChangeModelMaterial)message;

                    

                    //var matId = MyMeshMaterialId.NULL;
                    //if (rMessage.Material.ToLower().Contains("debug"))
                    //{
                    //    matId = MyMeshMaterials1.DebugMaterialId;
                    //}
                    //else
                    //{
                    //    matId = MyMeshMaterials1.GetMaterialId(rMessage.Material);
                    //}

                    //MyAssetsLoader.GetModel(rMessage.Model).SetMaterial_SLOW(MyMeshMaterials1.GetProxyId(matId));

                    break;
                }
          
                #endregion

                #region Render objects

                case MyRenderMessageEnum.UpdateCockpitGlass:
                {
                    var rMessage = (MyRenderMessageUpdateCockpitGlass)message;

                    //if (MyEnvironment.CockpitGlass == null)
                    //{
                    //    MyEnvironment.CockpitGlass = MyActorFactory.CreateSceneObject();
                    //}

                    //MyEnvironment.CockpitGlass.GetRenderable().SetModel(MyMeshes.GetMeshId(X.TEXT(rMessage.Model)));
                    //MyEnvironment.CockpitGlass.SetVisibility(rMessage.Visible);
                    //MyEnvironment.CockpitGlass.MarkRenderDirty();

                    //var matrix = (Matrix)rMessage.WorldMatrix;
                    //MyEnvironment.CockpitGlass.SetMatrix(ref matrix);


                    break;
                }

                case MyRenderMessageEnum.CreateRenderVoxelDebris:
                {
                    var rMessage = (MyRenderMessageCreateRenderVoxelDebris)message;

                    Matrix m = (Matrix)rMessage.WorldMatrix;

                    var actor = MyActorFactory.CreateSceneObject();
                    if (rMessage.Model != null)
                    {
                        actor.GetRenderable().SetModel(MyMeshes.GetMeshId(X.TEXT_(rMessage.Model)));
                    }

                    actor.SetID(rMessage.ID);
                    actor.SetMatrix(ref rMessage.WorldMatrix);

                    MyRenderableComponent.DebrisEntityVoxelMaterial[rMessage.ID] = rMessage.VoxelMaterialIndex;

                    break;
                }

                case MyRenderMessageEnum.CreateScreenDecal:
                {
                    var rMessage = (MyRenderMessageCreateScreenDecal)message;

                    MyScreenDecals.AddDecal(rMessage.ID, rMessage.ParentID, rMessage.LocalOBB, rMessage.DecalMaterial);

                    break;
                }

				case MyRenderMessageEnum.CreateRenderEntity:
				{
					var rMessage = (MyRenderMessageCreateRenderEntity)message;

					Matrix m = (Matrix)rMessage.WorldMatrix;

					var actor = MyActorFactory.CreateSceneObject();
					if (rMessage.Model != null)
					{
						var model = MyAssetsLoader.ModelRemap.Get(rMessage.Model, rMessage.Model);

						actor.GetRenderable().SetModel(MyMeshes.GetMeshId(X.TEXT_(model)));
					}

					actor.SetID(rMessage.ID);
					actor.SetMatrix(ref rMessage.WorldMatrix);
                    var renderable = actor.GetRenderable();

					renderable.m_additionalFlags |= MyProxiesFactory.GetRenderableProxyFlags(rMessage.Flags);
                    renderable.m_depthBias = rMessage.DepthBias;

					break;
				}

				case MyRenderMessageEnum.CreateRenderEntityClouds:
				{
					var rMessage = (MyRenderMessageCreateRenderEntityClouds)message;

					if (rMessage.Technique == VRage.Import.MyMeshDrawTechnique.CLOUD_LAYER)
					{
						MyCloudRenderer.CreateCloudLayer(
							rMessage.ID,
							rMessage.CenterPoint,
							rMessage.Altitude,
							rMessage.MinScaledAltitude,
							rMessage.ScalingEnabled,
							rMessage.FadeOutRelativeAltitudeStart,
							rMessage.FadeOutRelativeAltitudeEnd,
							rMessage.ApplyFogRelativeDistance,
							rMessage.MaxPlanetHillRadius,
							rMessage.Model,
                            rMessage.Textures,
							rMessage.RotationAxis,
							rMessage.AngularVelocity,
							rMessage.InitialRotation);
					}

					break;
				}

                case MyRenderMessageEnum.CreateRenderEntityAtmosphere:
                {
                    var rMessage = (MyRenderMessageCreateRenderEntityAtmosphere)message;

                    if (rMessage.Technique == VRage.Import.MyMeshDrawTechnique.ATMOSPHERE) {


                        float earthPlanetRadius = 6360000f;
                        float earthAtmosphereRadius = 6420000f;

                        float earthAtmosphereToPlanetRatio = earthAtmosphereRadius / earthPlanetRadius;
                        float targetAtmosphereToPlanetRatio = rMessage.AtmosphereRadius / rMessage.PlanetRadius;
                        float targetToEarthRatio = (targetAtmosphereToPlanetRatio - 1) / (earthAtmosphereToPlanetRatio - 1);
                        earthAtmosphereRadius = earthPlanetRadius * targetAtmosphereToPlanetRatio;

                        float planetScaleFactor = (rMessage.PlanetRadius) / earthPlanetRadius;
                        float atmosphereScaleFactor = (rMessage.AtmosphereRadius - rMessage.PlanetRadius) / (rMessage.PlanetRadius * 0.5f);
                        
                        Vector3 rayleighScattering = new Vector3(5.8e-6f, 13.5e-6f, 33.1e-6f);
                        Vector3 mieScattering = new Vector3(2e-5f, 2e-5f, 2e-5f);
                        float rayleighHeightScale = 8000f;
                        float mieHeightScale = 1200f;

                        MyAtmosphereRenderer.CreateAtmosphere(rMessage.ID, rMessage.WorldMatrix, earthPlanetRadius, earthAtmosphereRadius, 
                            rayleighScattering, rayleighHeightScale, mieScattering, mieHeightScale,
                            planetScaleFactor, atmosphereScaleFactor);
                    }

                    break;
                }

                case MyRenderMessageEnum.RemoveDecal:
                {
                    var rMessage = (MyRenderMessageRemoveDecal)message;

                    MyScreenDecals.RemoveDecal(rMessage.ID);

                    break;
                }

                case MyRenderMessageEnum.SetDecalGlobals:
                {
                    var rMessage = (MyRenderMessageSetDecalGlobals)message;

                    MyScreenDecals.SetDecalGlobals(rMessage.Globals);

                    break;
                }

                case MyRenderMessageEnum.RegisterDecalsMaterials:
                {
                    var rMessage = (MyRenderMessageRegisterScreenDecalsMaterials)message;

                    MyScreenDecals.RegisterMaterials(rMessage.MaterialsNames, rMessage.MaterialsDescriptions);


                    break;
                }

                case MyRenderMessageEnum.UpdateRenderObject:
                { 
                    var rMessage = (MyRenderMessageUpdateRenderObject)message;

                    var actor = MyIDTracker<MyActor>.FindByID(rMessage.ID);
                    if (actor != null)
                    {
                        actor.SetMatrix(ref rMessage.WorldMatrix);
                        if(rMessage.AABB.HasValue)
                        { 
                            actor.SetAabb(rMessage.AABB.Value);
                        }
                        
                    }
                    else
                        //if (MyLights.Get(rMessage.ID) != LightId.NULL)
                        //{
                        //    var light = MyLights.Get(rMessage.ID);
                        //    var lightInfo = new MyLightInfo
                        //    {
                        //        Position = rMessage.WorldMatrix.Translation,
                        //        PositionWithOffset = rMessage.WorldMatrix.Translation,
                        //        CastsShadows = light.CastsShadows,
                        //        ShadowsDistance = light.ShadowDistance,
                        //        ParentGID = light.ParentGID,
                        //        UsedInForward = true
                        //    };

                        //    MyLights.UpdateEntity(light, ref lightInfo);
                        //}
                        //else
                        {
                            if (MyClipmapFactory.ClipmapByID.ContainsKey(rMessage.ID))
                            {
                                MyClipmapFactory.ClipmapByID[rMessage.ID].UpdateWorldMatrix(ref rMessage.WorldMatrix);
                            }
                        }

                    //var entity = MyComponents.GetEntity(rMessage.ID);
                    //if(entity != EntityId.NULL)
                    //{
                    //    MyComponents.SetMatrix(entity, ref rMessage.WorldMatrix);
                    //    if (rMessage.AABB.HasValue)
                    //    {
                    //        var aabb = rMessage.AABB.Value;
                    //        MyComponents.SetAabb(entity, ref aabb);
                    //    }
                    //}

                    break;
                }

                case MyRenderMessageEnum.RemoveRenderObject:
                {
                    var rMessage = (MyRenderMessageRemoveRenderObject)message;

                    var actor = MyIDTracker<MyActor>.FindByID(rMessage.ID);
                    if (actor != null)
                    {
                        if (actor.GetRenderable() != null && actor.GetRenderable().GetModel().Info.Dynamic)
                        {
                            MyMeshes.RemoveMesh(actor.GetRenderable().GetModel());
                        }

                        actor.Destruct();
                        MyScreenDecals.RemoveEntityDecals(rMessage.ID);

                        break;
                    }

                    var instancing = MyInstancing.Get(rMessage.ID);
                    if(instancing != InstancingId.NULL)
                    {
                        MyInstancing.Remove(rMessage.ID, instancing);
                        break;
                    }

                    var light = MyLights.Get(rMessage.ID);
                    if (light != LightId.NULL)
                    {
                        MyLights.Remove(rMessage.ID, light);
                        break;
                    }

                    var clipmap = MyClipmapFactory.ClipmapByID.Get(rMessage.ID);
                    if(clipmap != null)
                    {
                        clipmap.RemoveFromUpdate();
                        break;
                    }

                    if (rMessage.ID != MyRenderProxy.RENDER_ID_UNASSIGNED)
                    {
                        MyGPUEmitters.Remove(rMessage.ID);
                        MyAtmosphereRenderer.RemoveAtmosphere(rMessage.ID);
                        MyCloudRenderer.RemoveCloud(rMessage.ID);

                        MyPrimitivesRenderer.RemoveDebugMesh(rMessage.ID);
                    }

                    break;
                }

                case MyRenderMessageEnum.UpdateRenderObjectVisibility:
                {
                    var rMessage = (MyRenderMessageUpdateRenderObjectVisibility)message;

                    var actor = MyIDTracker<MyActor>.FindByID(rMessage.ID);
                    if (actor != null)
                    {
                        actor.SetVisibility(rMessage.Visible);

                        //if(rMessage.NearFlag)
                        //{
                        //    actor.GetRenderable().m_additionalFlags = MyRenderableProxyFlags.InvertFaceCulling;
                        //    actor.MarkRenderDirty();
                        //}
                        //else
                        //{
                        //    actor.GetRenderable().m_additionalFlags = 0;
                        //    actor.MarkRenderDirty();
                        //}
                    }

                    break;
                }


                case MyRenderMessageEnum.CreateRenderInstanceBuffer:
                {
                    var rMessage = (MyRenderMessageCreateRenderInstanceBuffer)message;

                    //var instancing = MyComponentFactory<MyInstancingComponent>.Create();
                    //instancing.SetID(rMessage.ID);
                    //instancing.Init(rMessage.Type);
                    //instancing.SetDebugName(rMessage.DebugName);

                    MyInstancing.Create(rMessage.ID, rMessage.Type, rMessage.DebugName);

                    break;
                }

                case MyRenderMessageEnum.UpdateRenderInstanceBuffer:
                {
                    var rMessage = (MyRenderMessageUpdateRenderInstanceBuffer)message;

                    //var instancing = MyIDTracker<MyInstancingComponent>.FindByID(rMessage.ID);
                    //if(instancing != null)
                    //{
                    //    instancing.UpdateGeneric(rMessage.InstanceData, rMessage.Capacity);
                    //}

                    var handle = MyInstancing.Get(rMessage.ID);

                    if (handle != InstancingId.NULL)
                    {
                        MyInstancing.UpdateGeneric(handle, rMessage.InstanceData, rMessage.Capacity);
                    }
                    else
                    {
                       // Debug.Assert(handle != InstancingId.NULL, "No instance buffer with ID " + rMessage.ID);
                    }

                    break;
                }

                case MyRenderMessageEnum.UpdateRenderCubeInstanceBuffer:
                {
                    var rMessage = (MyRenderMessageUpdateRenderCubeInstanceBuffer)message;

                    //var instancing = MyIDTracker<MyInstancingComponent>.FindByID(rMessage.ID);
                    //if (instancing != null)
                    //{
                    //    instancing.UpdateCube(rMessage.InstanceData, rMessage.Capacity);
                    //}

                    var handle = MyInstancing.Get(rMessage.ID);

                    if (handle != InstancingId.NULL)
                    {
                        MyInstancing.UpdateCube(MyInstancing.Get(rMessage.ID), rMessage.InstanceData, rMessage.Capacity);
                    }
                    else
                        Debug.Fail("No instance buffer with ID " + rMessage.ID);

                    break;
                }

                case MyRenderMessageEnum.SetInstanceBuffer:
                {
                    var rMessage = (MyRenderMessageSetInstanceBuffer)message;

                    var actor = MyIDTracker<MyActor>.FindByID(rMessage.ID);
                    //var instancing = MyIDTracker<MyInstancingComponent>.FindByID(rMessage.InstanceBufferId);

                    if (actor != null)
                    {
                        //if (actor.GetComponent(MyActorComponentEnum.Instancing) != instancing)
                        //{
                        //    actor.AddComponent(instancing);
                        //}
                        //actor.SetLocalAabb(rMessage.LocalAabb);
                        //actor.GetRenderable().SetInstancingCounters(rMessage.InstanceCount, rMessage.InstanceStart);

                        actor.GetRenderable().SetInstancing(MyInstancing.Get(rMessage.InstanceBufferId));
                        actor.SetLocalAabb(rMessage.LocalAabb);
                        actor.GetRenderable().SetInstancingCounters(rMessage.InstanceCount, rMessage.InstanceStart);
                    }

                    break;
                }

                   
                case MyRenderMessageEnum.CreateManualCullObject:
                {
                    var rMessage = (MyRenderMessageCreateManualCullObject)message;

                    var actor = MyActorFactory.CreateGroup();
                    actor.SetID(rMessage.ID);
                    Matrix m = (Matrix)rMessage.WorldMatrix;
                    actor.SetMatrix(ref rMessage.WorldMatrix);

                    break;
                }

                case MyRenderMessageEnum.SetParentCullObject:
                {
                    var rMessage = (MyRenderMessageSetParentCullObject)message;

                    var child = MyIDTracker<MyActor>.FindByID(rMessage.ID);
                    var parent = MyIDTracker<MyActor>.FindByID(rMessage.CullObjectID);
                    if (child != null && parent != null && parent.GetGroupRoot() != null && child.GetGroupLeaf() == null)
                    {
                        child.SetRelativeTransform(rMessage.ChildToParent);
                        parent.GetGroupRoot().Add(child);
                    }

                    break;
                }

                case MyRenderMessageEnum.CreateLineBasedObject:
                {
                    var rMessage = (MyRenderMessageCreateLineBasedObject)message;

                    var actor = MyActorFactory.CreateSceneObject();
                    //actor.GetRenderable().SetModel(new MyDynamicMesh());

                    actor.SetID(rMessage.ID);
                    actor.SetMatrix(ref MatrixD.Identity);

                    MyMeshMaterials1.GetMaterialId("__ROPE_MATERIAL", null, rMessage.ColorMetalTexture, rMessage.NormalGlossTexture, rMessage.ExtensionTexture, MyMesh.DEFAULT_MESH_TECHNIQUE);
                    actor.GetRenderable().SetModel(MyMeshes.CreateRuntimeMesh(X.TEXT_("LINE" + rMessage.ID), 1, true));

                    break;
                }

                case MyRenderMessageEnum.UpdateLineBasedObject:
                {
                    var rMessage = (MyRenderMessageUpdateLineBasedObject)message;

                    var actor = MyIDTracker<MyActor>.FindByID(rMessage.ID);
                    if (actor != null)
                    {
                        //var mesh = actor.GetRenderable().GetMesh() as MyDynamicMesh;

                        MyVertexFormatPositionH4 [] stream0;
                        MyVertexFormatTexcoordNormalTangent [] stream1;

                        MyLineHelpers.GenerateVertexData(ref rMessage.WorldPointA, ref rMessage.WorldPointB, 
                            out stream0, out stream1);

                        var indices = MyLineHelpers.GenerateIndices(stream0.Length);
                        var sections = new MySectionInfo[] 
                        { 
                            new MySectionInfo { TriCount = indices.Length / 3, IndexStart = 0, MaterialName = "__ROPE_MATERIAL" } 
                        };

                        MyMeshes.UpdateRuntimeMesh(MyMeshes.GetMeshId(X.TEXT_("LINE" + rMessage.ID)), 
                            indices, 
                            stream0, 
                            stream1, 
                            sections,
                            (BoundingBox)MyLineHelpers.GetBoundingBox(ref rMessage.WorldPointA, ref rMessage.WorldPointB));

                        //actor.SetAabb((BoundingBox)MyLineHelpers.GetBoundingBox(ref rMessage.WorldPointA, ref rMessage.WorldPointB));
                        actor.MarkRenderDirty();

                        var matrix = MatrixD.CreateTranslation((Vector3)(rMessage.WorldPointA + rMessage.WorldPointB) * 0.5f);
                        actor.SetMatrix(ref matrix);
                    }

                    break;
                }

                case MyRenderMessageEnum.SetRenderEntityData:
                {
                    var rMessage = (MyRenderMessageSetRenderEntityData)message;

                    Debug.Assert(false, "MyRenderMessageSetRenderEntityData is deprecated!");

                    break;
                }

                case MyRenderMessageEnum.AddRuntimeModel:
                {
                    var rMessage = (MyRenderMessageAddRuntimeModel)message;

                    //MyDestructionMesh mesh = MyDestructionMesh.ModelsDictionary.Get(rMessage.Name);
                    //if (mesh == null)
                    //{
                        //mesh = new MyDestructionMesh(rMessage.Name);

                        //ProfilerShort.Begin("LoadBuffers");
                        //mesh.Fill(rMessage.ModelData.Indices, rMessage.ModelData.Positions, rMessage.ModelData.Normals, rMessage.ModelData.Tangents, rMessage.ModelData.TexCoords, rMessage.ModelData.Sections, rMessage.ModelData.AABB);
                        //ProfilerShort.End();

                    if(!MyMeshes.Exists(rMessage.Name))
                    {
                        {
                            ushort[] indices = new ushort[rMessage.ModelData.Indices.Count];
                            for (int i = 0; i < rMessage.ModelData.Indices.Count; i++)
                            {
                                indices[i] = (ushort)rMessage.ModelData.Indices[i];
                            }
                            var verticesNum = rMessage.ModelData.Positions.Count;
                            MyVertexFormatPositionH4[] stream0 = new MyVertexFormatPositionH4[verticesNum];
                            MyVertexFormatTexcoordNormalTangent[] stream1 = new MyVertexFormatTexcoordNormalTangent[verticesNum];
                            for (int i = 0; i < verticesNum; i++)
                            {
                                stream0[i] = new MyVertexFormatPositionH4(rMessage.ModelData.Positions[i]);
                                stream1[i] = new MyVertexFormatTexcoordNormalTangent(
                                    rMessage.ModelData.TexCoords[i], rMessage.ModelData.Normals[i], rMessage.ModelData.Tangents[i]);
                            }
                            var id = MyMeshes.CreateRuntimeMesh(X.TEXT_(rMessage.Name), rMessage.ModelData.Sections.Count, false);
                            MyMeshes.UpdateRuntimeMesh(id, indices, stream0, stream1, rMessage.ModelData.Sections.ToArray(), rMessage.ModelData.AABB);
                        }

                        if (rMessage.ReplacedModel != null)
                        {
                            //MyAssetsLoader.ModelRemap[rMessage.ReplacedModel] = rMessage.Name;
                            MyAssetsLoader.ModelRemap[rMessage.Name] = rMessage.ReplacedModel;
                        }

                        //if (MyAssetsLoader.LOG_MESH_STATISTICS)
                        //{
                        //    mesh.DebugWriteInfo();
                        //}
                    }
                    
                    break;
                }

                case MyRenderMessageEnum.UpdateModelProperties:
                {
                    var rMessage = (MyRenderMessageUpdateModelProperties)message;

                    var actor = MyIDTracker<MyActor>.FindByID(rMessage.ID);
                    if (actor != null)
                    {
                        // careful, lod is ignored after all (properties apply to all lods)
                        var key = new MyEntityMaterialKey { LOD = rMessage.LOD, Material = X.TEXT_(rMessage.MaterialName) };

                        if(rMessage.Enabled.HasValue)
                        {
                            if (!MyScene.EntityDisabledMaterials.ContainsKey(rMessage.ID))
                            {
                                MyScene.EntityDisabledMaterials.Add(rMessage.ID, new HashSet<MyEntityMaterialKey>());
                            }

                            if (!rMessage.Enabled.Value)
                            {
                                MyScene.EntityDisabledMaterials[rMessage.ID].Add(key);
                            }
                            else
                            {
                                MyScene.EntityDisabledMaterials[rMessage.ID].Remove(key);
                            }
                        }

                        var renderableComponent = actor.GetRenderable();

                        if ((rMessage.Emissivity.HasValue || rMessage.DiffuseColor.HasValue) && !renderableComponent.ModelProperties.ContainsKey(key))
                        {
                            renderableComponent.ModelProperties[key] = new MyModelProperties();
                        }

                        if(rMessage.Emissivity.HasValue)
                        {
                            renderableComponent.ModelProperties[key].Emissivity = rMessage.Emissivity.Value;
                        }

                        if(rMessage.DiffuseColor.HasValue)
                        {
                            renderableComponent.ModelProperties[key].ColorMul = rMessage.DiffuseColor.Value;
                        }

                        actor.MarkRenderDirty();

                        MyOutline.HandleOutline(rMessage.ID, rMessage.MeshIndex, rMessage.OutlineColor, rMessage.OutlineThickness, rMessage.PulseTimeInFrames);
                    }

                    break;
                }

                case MyRenderMessageEnum.UpdateModelHighlight:
                {
                    var rMessage = (MyRenderMessageUpdateModelHighlight)message;
                    MyOutline.HandleOutline(rMessage.ID, rMessage.SectionIndices, rMessage.OutlineColor, rMessage.Thickness, rMessage.PulseTimeInFrames);

                    if (rMessage.SubpartIndices != null)
                    {
                        foreach (uint index in rMessage.SubpartIndices)
                            MyOutline.HandleOutline(index, null, rMessage.OutlineColor, rMessage.Thickness, rMessage.PulseTimeInFrames);
                    }

                    break;
                }

                case MyRenderMessageEnum.UpdateColorEmissivity:
                {
                    var rMessage = (MyRenderMessageUpdateColorEmissivity)message;
                    var actor = MyIDTracker<MyActor>.FindByID(rMessage.ID);
                    if (actor != null)
                    {
                        actor.GetRenderable().UpdateColorEmissivity(rMessage.LOD, rMessage.MaterialName, rMessage.DiffuseColor, rMessage.Emissivity);
                    }

                    break;
                }

                case MyRenderMessageEnum.PreloadModel:
                {
                    var rMessage = (MyRenderMessagePreloadModel) message;

                    //MyAssetsLoader.GetModel(rMessage.Name);
                    MyMeshes.GetMeshId(X.TEXT_(rMessage.Name));

                    break;
                }

                case MyRenderMessageEnum.ChangeMaterialTexture:
                {
                    var rMessage = (MyRenderMessageChangeMaterialTexture)message;

                    var actor = MyIDTracker<MyActor>.FindByID(rMessage.RenderObjectID);
                    if (actor != null)
                    {
                        var r = actor.GetRenderable();
                        var key = new MyEntityMaterialKey { LOD = 0, Material = X.TEXT_(rMessage.MaterialName) };

                        if (!r.ModelProperties.ContainsKey(key))
                        {
                            r.ModelProperties[key] = new MyModelProperties();
                        }

                        if (r.ModelProperties[key].TextureSwaps == null)
                        {
                            r.ModelProperties[key].TextureSwaps = new List<MyMaterialTextureSwap>();

                            foreach(var s in rMessage.Changes)
                            {
                                r.ModelProperties[key].TextureSwaps.Add(new MyMaterialTextureSwap { 
                                    TextureName = X.TEXT_(s.TextureName), 
                                    MaterialSlot = s.MaterialSlot
                                });
                            }
                        }
                        else
                        {
                            foreach (var s in rMessage.Changes)
                            {
                                bool swapped = false;
                                for(int i=0; i<r.ModelProperties[key].TextureSwaps.Count; ++i)
                                {
                                    if(r.ModelProperties[key].TextureSwaps[i].MaterialSlot == s.MaterialSlot)
                                    {
                                        r.ModelProperties[key].TextureSwaps[i] = new MyMaterialTextureSwap
                                        {
                                            TextureName = X.TEXT_(s.TextureName),
                                            MaterialSlot = s.MaterialSlot
                                        };
                                        swapped = true;
                                        break;
                                    }
                                }

                                if(!swapped)
                                {
                                    r.ModelProperties[key].TextureSwaps.Add(new MyMaterialTextureSwap
                                        {
                                            TextureName = X.TEXT_(s.TextureName),
                                            MaterialSlot = s.MaterialSlot
                                        });
                                }
                            }
                        }

                        r.FreeCustomRenderTextures(key);

                        actor.MarkRenderDirty();
                    }

                    rMessage.Changes.Clear();
                   
                    break;
                }

                case MyRenderMessageEnum.RequestScreenData:
                {
                    var renderMessage = (MyRenderMessageRequestScreenData)message;

                    var screenData = GetScreenData((Vector2I)renderMessage.Resolution, renderMessage.PreallocatedBuffer);

                    MyRenderProxy.SendReadyScreenData(renderMessage.Id, screenData, renderMessage.Resolution);

                    break;
                }

                case MyRenderMessageEnum.DrawTextToMaterial:
                {
                    var rMessage = (MyRenderMessageDrawTextToMaterial)message;

                    //rMessage.EntityId
                    //rMessage.FontColor
                    //rMessage.MaterialName
                    //rMessage.Text;
                    //rMessage.TextScale;

                    var actor = MyIDTracker<MyActor>.FindByID(rMessage.RenderObjectID);
                    if (actor != null)
                    {
                        var renderableComponent = actor.GetRenderable();
                        var key = new MyEntityMaterialKey { LOD = 0, Material = X.TEXT_(rMessage.MaterialName) };

                        if (!renderableComponent.ModelProperties.ContainsKey(key))
                            renderableComponent.ModelProperties[key] = new MyModelProperties();
                        else
                            renderableComponent.ModelProperties[key].TextureSwaps = null;

                        RwTexId handle = renderableComponent.ModelProperties[key].CustomRenderedTexture;
                        if (handle == RwTexId.NULL && MyModelProperties.CustomTextures < MyModelProperties.MaxCustomTextures)
                        {
                           handle = MyRwTextures.CreateRenderTarget(rMessage.TextureResolution * rMessage.TextureAspectRatio, rMessage.TextureResolution, SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb, true);
                           renderableComponent.ModelProperties[key].CustomRenderedTexture = handle;
                           ++MyModelProperties.CustomTextures;
                        }

                        if (handle != RwTexId.NULL)
                        {
                            var clearColor = new SharpDX.Color4(rMessage.BackgroundColor.PackedValue);
                            clearColor.Alpha = 0;
                            MyRender11.DeviceContext.ClearRenderTargetView(handle.Rtv, clearColor);

                            // my sprites renderer -> push state
                            MySpritesRenderer.PushState(new Vector2(rMessage.TextureResolution * rMessage.TextureAspectRatio, rMessage.TextureResolution));


                            MySpritesRenderer.DrawText(Vector2.Zero, new StringBuilder(rMessage.Text), rMessage.FontColor, rMessage.TextScale);
                            // render text with fonts to rt
                            // update texture of proxy
                            MySpritesRenderer.Draw(handle.Rtv, new MyViewport(rMessage.TextureResolution * rMessage.TextureAspectRatio, rMessage.TextureResolution));

                            // render to rt
                            // my sprites renderer -> pop state
                            MySpritesRenderer.PopState();
                            

                            MyRender11.DeviceContext.GenerateMips(handle.SRV);

                            actor.MarkRenderDirty();
                        }
                        else
                        {
                            MyRenderProxy.TextNotDrawnToTexture(rMessage.EntityId);
                        }
                    }
                    else
                    {
                        MyRenderProxy.TextNotDrawnToTexture(rMessage.EntityId);
                    }

                    break;
                }

                case MyRenderMessageEnum.PreloadMaterials:
                {
                    var rMessage = (MyRenderMessagePreloadMaterials)message;

                    //MyAssetsLoader.GetMaterials(rMessage.Name);
                    MyMeshes.GetMeshId(X.TEXT_(rMessage.Name));

                    break;
                }

                #endregion

                #region Voxels

                case MyRenderMessageEnum.CreateClipmap:
                {
                    var rMessage = (MyRenderMessageCreateClipmap)message;

                    var clipmap = new MyClipmapHandler(rMessage.ClipmapId, rMessage.ScaleGroup, rMessage.WorldMatrix, rMessage.SizeLod0, rMessage.Position, rMessage.PlanetRadius, rMessage.SpherizeWithDistance, rMessage.AdditionalRenderFlags, rMessage.PrunningFunc);
                    MyClipmapFactory.ClipmapByID[rMessage.ClipmapId] = clipmap;
                    clipmap.Base.LoadContent();

                    break;
                }

                case MyRenderMessageEnum.UpdateClipmapCell:
                {
                    var rMessage = (MyRenderMessageUpdateClipmapCell)message;

                    var clipmap = MyClipmapFactory.ClipmapByID.Get(rMessage.ClipmapId);

                    Debug.Assert(clipmap != null);

                    if (clipmap != null)
                    {
                        clipmap.Base.UpdateCell(rMessage);
                    }
                    break;
                }

                case MyRenderMessageEnum.UpdateMergedVoxelMesh:
                {
                    var rMessage = (MyRenderMessageUpdateMergedVoxelMesh)message;

                    MyClipmapHandler clipmap = MyClipmapFactory.ClipmapByID.Get(rMessage.ClipmapId);
                        if (clipmap != null)
                            clipmap.UpdateMergedMesh(rMessage);
                        break;
                    }

                case MyRenderMessageEnum.ResetMergedVoxels:
                    {
                        var rMessage = (MyRenderMessageResetMergedVoxels)message;

                        foreach(var clipmapHandler in MyClipmapFactory.ClipmapByID.Values)
                        {
                            if (clipmapHandler != null)
                                clipmapHandler.ResetMergedMeshes();
                        }
                        break;
                    }

                case MyRenderMessageEnum.InvalidateClipmapRange:
                {
                    var rMessage = (MyRenderMessageInvalidateClipmapRange)message;

                    var clipmap = MyClipmapFactory.ClipmapByID.Get(rMessage.ClipmapId);
                    if (clipmap != null)
                    {
                        clipmap.Base.InvalidateRange(rMessage.MinCellLod0, rMessage.MaxCellLod0);
                    }

                    break;
                }

                case MyRenderMessageEnum.CreateRenderVoxelMaterials:
                {
                    var rMessage = (MyRenderMessageCreateRenderVoxelMaterials)message;

                    Debug.Assert(MyVoxelMaterials1.CheckIndices(rMessage.Materials));
                    MyVoxelMaterials1.Set(rMessage.Materials);

                    rMessage.Materials = null;

                    break;
                }


                case MyRenderMessageEnum.UpdateRenderVoxelMaterials:
                {
                    var rMessage = (MyRenderMessageUpdateRenderVoxelMaterials)message;

                    MyVoxelMaterials1.Set(rMessage.Materials, true);

                    rMessage.Materials = null;

                    break;
                }

                #endregion

                #region Lights

                case MyRenderMessageEnum.CreateRenderLight:
                {
                    var rMessage = (MyRenderMessageCreateRenderLight)message;

                    //MyLight.Create(rMessage.ID);

                    MyLights.Create(rMessage.ID);

                    break;
                }

                case MyRenderMessageEnum.UpdateRenderLight:
                {
                    var rMessage = (MyRenderMessageUpdateRenderLight)message;

                    var light = MyLights.Get(rMessage.ID);

                    if(light != LightId.NULL)
                    {
                        var lightInfo = new MyLightInfo
                        {
                            SpotPosition = rMessage.ReflectorPosition,
                            PointPosition = rMessage.ReflectorPosition + rMessage.PointPositionOffset * rMessage.Range * rMessage.ReflectorDirection,
                            CastsShadows = rMessage.CastShadows,
                            ShadowsDistance = rMessage.ShadowDistance,
                            ParentGID = rMessage.ParentID,
                            UsedInForward = rMessage.UseInForwardRender
                        };

                        MyLights.UpdateEntity(light, ref lightInfo);

                        if ((rMessage.Type & LightTypeEnum.PointLight) > 0)
                        {
                            MyLights.UpdatePointlight(light, rMessage.LightOn, rMessage.Range, 
                                new Vector3(rMessage.Color.R, rMessage.Color.G, rMessage.Color.B) / 255.0f * rMessage.Intensity, rMessage.Falloff, rMessage.GlossFactor);
                        }
                        if ((rMessage.Type & LightTypeEnum.Hemisphere) > 0)
                        {
                            //rMessage.Color;
                            //rMessage.Falloff;
                            //rMessage.Intensity;
                            //rMessage.LightOn;
                            //rMessage.ReflectorDirection;
                            //rMessage.ReflectorUp;
                        }
                        if ((rMessage.Type & LightTypeEnum.Spotlight) > 0)
                        {
                            // because it's so in dx9...
                            float coneMaxAngleCos = 1 - rMessage.ReflectorConeMaxAngleCos;
                            coneMaxAngleCos = (float)Math.Min(Math.Max(coneMaxAngleCos, 0.01), 0.99f);
                            MyLights.UpdateSpotlight(light, rMessage.ReflectorOn,
                                rMessage.ReflectorDirection, rMessage.ReflectorRange, coneMaxAngleCos, rMessage.ReflectorUp,
                                new Vector3(rMessage.ReflectorColor.R, rMessage.ReflectorColor.G, rMessage.ReflectorColor.B) / 255.0f * rMessage.ReflectorIntensity,
                                rMessage.ReflectorFalloff, rMessage.ReflectorGlossFactor,
                                MyTextures.GetTexture(rMessage.ReflectorTexture, MyTextureEnum.CUSTOM));
                        }

                        MyLights.UpdateGlare(light, new MyGlareDesc
                            {
                                Enabled = rMessage.GlareOn,
                                Material = X.TEXT_(rMessage.GlareMaterial),
                                Intensity = rMessage.GlareIntensity,
                                QuerySize = rMessage.GlareQuerySize,
                                Type = rMessage.GlareType,
                                Size = rMessage.GlareSize,
                                MaxDistance = rMessage.GlareMaxDistance,
                                Color = rMessage.Color,
                                Direction = rMessage.ReflectorDirection,
                                Range = rMessage.Range
                            });
                    }

                    break;
                }

                case MyRenderMessageEnum.SetLightShadowIgnore:
                {
                    var rMessage = (MyRenderMessageSetLightShadowIgnore)message;

                    var light = MyLights.Get(rMessage.ID);
                    var actor = MyIDTracker<MyActor>.FindByID(rMessage.ID2);

                    if(light != LightId.NULL && actor != null)
                    {
                        if(!MyLights.IgnoredEntitites.ContainsKey(light))
                        {
                            MyLights.IgnoredEntitites[light] = new HashSet<uint>();
                        }
                        MyLights.IgnoredEntitites[light].Add(rMessage.ID2);
                    }

                    break;
                }


                case MyRenderMessageEnum.ClearLightShadowIgnore:
                {
                    var rMessage = (MyRenderMessageClearLightShadowIgnore)message;

                    var light = MyLights.Get(rMessage.ID);
                    if(light != LightId.NULL)
                    {
                        MyLights.IgnoredEntitites.Remove(light);
                    }

                    break;
                }

                case MyRenderMessageEnum.UpdateFogSettings:
                {
                    var rMessage = (MyRenderMessageUpdateFogSettings)message;

                    if (m_debugOverrides.Fog)
                        MyEnvironment.FogSettings = rMessage.Settings;
                    else MyEnvironment.FogSettings.FogDensity = 0;

                    break;
                }


                case MyRenderMessageEnum.UpdateAtmosphereSettings:
                {
                    var rMessage = (MyRenderMessageUpdateAtmosphereSettings)message;

                    MyAtmosphereRenderer.UpdateSettings(rMessage.ID, rMessage.Settings);

                    break;
                }

                case MyRenderMessageEnum.EnableAtmosphere:
                {
                    var rMessage = (MyRenderMessageEnableAtmosphere)message;
                    MyAtmosphereRenderer.Enabled = rMessage.Enabled;
                    break;
                }

                case MyRenderMessageEnum.UpdatePlanetBlurSettings:
                {
                    var rMessage = (MyRenderMessageUpdatePlanetBlurSettings)message;
                    MyPlanetBlur.Settings = rMessage.Settings;
                    break;
                }

				case MyRenderMessageEnum.UpdateCloudLayerFogFlag:
				{
					var rMessage = (MyRenderMessageUpdateCloudLayerFogFlag)message;
					MyCloudRenderer.DrawFog = rMessage.ShouldDrawFog;
					break;
				}

                case MyRenderMessageEnum.UpdateRenderEnvironment:
                {
                    var rMessage = (MyRenderMessageUpdateRenderEnvironment)message;

                    if (!m_debugOverrides.AdditionalSuns)
                        rMessage.AdditionalSunCount = 0;

                    if (MyEnvironment.AdditionalSunIntensities == null || MyEnvironment.AdditionalSunIntensities.Length != rMessage.AdditionalSunCount)
                        MyEnvironment.AdditionalSunIntensities = new float[rMessage.AdditionalSunCount];
                    if (MyEnvironment.AdditionalSunColors == null || MyEnvironment.AdditionalSunColors.Length != rMessage.AdditionalSunCount)
                        MyEnvironment.AdditionalSunColors = new Vector3[rMessage.AdditionalSunCount];
                    if (MyEnvironment.AdditionalSunDirections == null || MyEnvironment.AdditionalSunDirections.Length != rMessage.AdditionalSunCount)
                        MyEnvironment.AdditionalSunDirections = new Vector2[rMessage.AdditionalSunCount];

                    MyEnvironment.DirectionalLightDir = VRageMath.Vector3.Normalize(rMessage.SunDirection);
                    if (rMessage.SunLightOn && m_debugOverrides.Sun)
                        MyEnvironment.DirectionalLightIntensity = rMessage.SunIntensity*rMessage.SunColor.ToVector3();
                    else MyEnvironment.DirectionalLightIntensity = new Vector3(0, 0, 0);

                    for (int lightIndex = 0; lightIndex < MyEnvironment.AdditionalSunIntensities.Length; ++lightIndex)
                    {
                        MyEnvironment.AdditionalSunIntensities[lightIndex] = rMessage.AdditionalSunIntensities[lightIndex];
                        MyEnvironment.AdditionalSunColors[lightIndex] = rMessage.AdditionalSunColors[lightIndex];
                        MyEnvironment.AdditionalSunDirections[lightIndex] = rMessage.AdditionalSunDirections[lightIndex];
                    }

                    MyEnvironment.DayTime = (float)(rMessage.DayTime - Math.Truncate(rMessage.DayTime));
                    MyEnvironment.SunDistance = rMessage.DistanceToSun;
                    MyEnvironment.SunColor = rMessage.SunColor;
                    MyEnvironment.SunMaterial = rMessage.SunMaterial;
                    MyEnvironment.SunSizeMultiplier = rMessage.SunSizeMultiplier;
                    MyEnvironment.SunBillboardEnabled = rMessage.SunBillboardEnabled;
                    MyEnvironment.PlanetFactor = rMessage.PlanetFactor;
                    MyEnvironment.DaySkybox = rMessage.DayBackgroundTexture;
                    MyEnvironment.NightSkybox = rMessage.NightBackgroundTexture;
                    MyEnvironment.NightSkyboxPrefiltered = rMessage.NightBackgroundPrefilteredTexture;
                    MyEnvironment.BackgroundOrientation = rMessage.BackgroundOrientation;
					MyEnvironment.BackgroundColor = rMessage.BackgroundColor;

                    m_resetEyeAdaptation = m_resetEyeAdaptation || rMessage.ResetEyeAdaptation;

                    break;
                }

                case MyRenderMessageEnum.UpdateEnvironmentMap:
                {   
                    break;
                }

                case MyRenderMessageEnum.UpdateDebugOverrides:
                {
                    var rMessage = (MyRenderMessageUpdateDebugOverrides)message;
                    m_debugOverrides = rMessage.Overrides;
                    break;
                }
                case MyRenderMessageEnum.UpdatePostprocessSettings:
                {
                    var rMessage = (MyRenderMessageUpdatePostprocessSettings)message;

                    m_postprocessSettings = rMessage.Settings;

                    if (m_postprocessSettings.EnableEyeAdaptation != rMessage.Settings.EnableEyeAdaptation)
                        m_resetEyeAdaptation = true;

                    break;
                }

                case MyRenderMessageEnum.UpdateSSAOSettings:
                {
                    var rMessage = (MyRenderMessageUpdateSSAOSettings)message;

                    MyRender11.Postprocess.EnableSsao = rMessage.Enabled;

                    MySSAO.Params.MinRadius = rMessage.MinRadius;
                    MySSAO.Params.MaxRadius = rMessage.MaxRadius;
                    MySSAO.Params.RadiusGrow = rMessage.RadiusGrowZScale;

                    MySSAO.Params.RadiusBias = rMessage.Bias;
                    MySSAO.Params.Falloff = rMessage.Falloff;
                    MySSAO.Params.Normalization = rMessage.NormValue;
                    MySSAO.Params.Contrast = rMessage.Contrast;

                    MySSAO.UseBlur = rMessage.UseBlur;

                    break;
                }

                #endregion

                #region Sprites
                case MyRenderMessageEnum.DrawSprite:
                case MyRenderMessageEnum.DrawSpriteNormalized:
                case MyRenderMessageEnum.DrawSpriteAtlas:
                case MyRenderMessageEnum.SpriteScissorPush:
                case MyRenderMessageEnum.SpriteScissorPop:
                {
                    m_drawQueue.Enqueue(message);
                    break;
                }

                #endregion

                #region Fonts and text

                case MyRenderMessageEnum.CreateFont:
                {
                    var createFontMessage = message as MyRenderMessageCreateFont;
                    Debug.Assert(createFontMessage != null);

                    var renderFont = new MyRenderFont(createFontMessage.FontPath);
                    renderFont.LoadContent();
                    AddFont(createFontMessage.FontId, renderFont, createFontMessage.IsDebugFont);

                    break;
                }

                case MyRenderMessageEnum.DrawString:
                {
                    m_drawQueue.Enqueue(message);
                    break;
                }

                #endregion

                #region Textures

                case MyRenderMessageEnum.PreloadTextures:
                    {
                        var preloadMsg = message as MyRenderMessagePreloadTextures;

                        //MyTextureManager.PreloadTextures(preloadMsg.InDirectory, preloadMsg.Recursive);
                        //MyTextures.UnloadTexture(texMessage.Texture);

                        break;
                    }

                case MyRenderMessageEnum.UnloadTexture:
                    {
                        var texMessage = (MyRenderMessageUnloadTexture)message;

                        //MyTextureManager.UnloadTexture(texMessage.Texture);
                        MyTextures.UnloadTexture(texMessage.Texture);

                        break;
                    }

                case MyRenderMessageEnum.ReloadTextures:
                    {
                        var reloadMsg = (MyRenderMessageReloadTextures)message;

                        MyVoxelMaterials1.InvalidateMaterials();
                        MyMeshMaterials1.InvalidateMaterials();
                        MyTextures.ReloadAssetTextures();

                        //MyTextureManager.UnloadTextures();
                        //MyMaterialProxyFactory.ReloadTextures();

                        break;
                    }

                case MyRenderMessageEnum.ReloadModels:
                    {
                        var reloadMsg = (MyRenderMessageReloadModels)message;

                        //MyMaterials.Clear();
                        MyAssetsLoader.ReloadMeshes();
                        MyRenderableComponent.MarkAllDirty();

                        break;
                    }

                #endregion

                case MyRenderMessageEnum.TakeScreenshot:
                {
                    var rMessage = (MyRenderMessageTakeScreenshot)message;

                    m_screenshot = new MyScreenshot(rMessage.PathToSave, rMessage.SizeMultiplier, rMessage.IgnoreSprites, rMessage.ShowNotification);

                    break;
                }

                case MyRenderMessageEnum.ReloadEffects:
                {
                    m_reloadShaders = true;

                    //MyShaderBundleFactory.ClearCache();
                    //MyShaderMaterial.ClearCache();
                    //MyShaderPass.ClearCache();

                    MyShaders.Recompile();
                    MyMaterialShaders.Recompile();

                    MyAtmosphereRenderer.RecomputeAtmospheres();

                    MyRenderableComponent.MarkAllDirty();

                    foreach (var f in MyComponentFactory<MyFoliageComponent>.GetAll())
                    {
                        f.Dispose();
                    }

                    break;
                }

                case MyRenderMessageEnum.ReloadGrass:
                {
                    MyRenderProxy.ReloadEffects();  // Need some delay
                    break;
                }

                case MyRenderMessageEnum.PlayVideo:
                {
                    var rMessage = (MyRenderMessagePlayVideo)message;

                    MyVideoFactory.Create(rMessage.ID, rMessage.VideoFile);
                    var video = MyVideoFactory.Videos.Get(rMessage.ID);
                    if (video != null)
                    {
                        video.Volume = rMessage.Volume;
                    }

                    break;
                }

                case MyRenderMessageEnum.CloseVideo:
                {
                    var rMessage = (MyRenderMessageCloseVideo)message;

                    var video = MyVideoFactory.Videos.Get(rMessage.ID);
                    if (video != null)
                    {
                        video.Stop();
                        video.Dispose();
                        MyVideoFactory.Videos.Remove(rMessage.ID);
                    }

                    break;
                }

                case MyRenderMessageEnum.UpdateGameplayFrame:
                {
                    var rMessage = (MyRenderMessageUpdateGameplayFrame)message;

                    Settings.GameplayFrame = rMessage.GameplayFrame;

                    break;
                }

                case MyRenderMessageEnum.DrawVideo:
                {
                    var rMessage = (MyRenderMessageDrawVideo)message;

                    var video = MyVideoFactory.Videos.Get(rMessage.ID);
                    if (video != null)
                    {
                        video.Draw(rMessage.Rectangle, rMessage.Color, rMessage.FitMode);
                    }

                    break;
                }

                case MyRenderMessageEnum.UpdateVideo:
                {
                    var rMessage = (MyRenderMessageUpdateVideo)message;

                    var video = MyVideoFactory.Videos.Get(rMessage.ID);
                    if(video != null)
                    {
                        video.Update();
                    }

                    break;
                }

                case MyRenderMessageEnum.SetVideoVolume:
                {
                    var rMessage = (MyRenderMessageSetVideoVolume)message;

                    var video = MyVideoFactory.Videos.Get(rMessage.ID);
                    if (video != null)
                    {
                        video.Volume = rMessage.Volume;
                    }

                    break;
                }

                case MyRenderMessageEnum.VideoAdaptersRequest:
                {
                    MyRenderProxy.SendVideoAdapters(GetAdaptersList());
                    break;
                }

                case MyRenderMessageEnum.SwitchDeviceSettings:
                {
                    MyRenderProxy.RenderThread.SwitchSettings((message as MyRenderMessageSwitchDeviceSettings).Settings);
                    break;
                }

                case MyRenderMessageEnum.SwitchRenderSettings:
                {
                    UpdateRenderSettings((message as MyRenderMessageSwitchRenderSettings).Settings);
                    break;
                }

                case MyRenderMessageEnum.SetMouseCapture:
                {
                    var umc = message as MyRenderMessageSetMouseCapture;

                    MyRenderProxy.RenderThread.SetMouseCapture(umc.Capture);
                    break;
                }

                case MyRenderMessageEnum.UnloadData:
                {
                    MyRender11.UnloadData();
                    break;
                }

                case MyRenderMessageEnum.CollectGarbage:
                {
                    GC.Collect();
                    break;
                }

                case MyRenderMessageEnum.RenderColoredTexture:
                {
                    var rMessage = (MyRenderMessageRenderColoredTexture)message;
                    m_texturesToRender.AddRange(rMessage.texturesToRender);
                    break;
                }

                case MyRenderMessageEnum.CreateGPUEmitter:
                {
                    var rMessage = (MyRenderMessageCreateGPUEmitter)message;

                    //MyLight.Create(rMessage.ID);

                    MyGPUEmitters.Create(rMessage.ID);

                    break;
                }
                case MyRenderMessageEnum.UpdateGPUEmitters:
                {
                    var rMessage = (MyRenderMessageUpdateGPUEmitters)message;
                    MyGPUEmitters.UpdateEmitters(rMessage.Emitters);
                    break;
                }
                case MyRenderMessageEnum.UpdateGPUEmittersPosition:
                {
                    var rMessage = (MyRenderMessageUpdateGPUEmittersPosition)message;
                    MyGPUEmitters.UpdateEmittersPosition(rMessage.GIDs, rMessage.WorldPositions);
                    break;
                }
                case MyRenderMessageEnum.RemoveGPUEmitter:
                {
                    var rMessage = (MyRenderMessageRemoveGPUEmitter)message;
                    MyGPUEmitters.Remove(rMessage.GID, rMessage.Instant);
                    break;
                }

                #region Debug draw

                case MyRenderMessageEnum.DebugDrawPoint:
                case MyRenderMessageEnum.DebugDrawLine3D:
                case MyRenderMessageEnum.DebugDrawLine2D:
                case MyRenderMessageEnum.DebugDrawSphere:
                case MyRenderMessageEnum.DebugDrawAABB:
                case MyRenderMessageEnum.DebugDrawAxis:
                case MyRenderMessageEnum.DebugDrawOBB:
                case MyRenderMessageEnum.DebugDraw6FaceConvex:
                case MyRenderMessageEnum.DebugDrawCone:
                case MyRenderMessageEnum.DebugDrawTriangle:
                case MyRenderMessageEnum.DebugDrawCapsule:
                case MyRenderMessageEnum.DebugDrawText2D:
                case MyRenderMessageEnum.DebugDrawText3D:
                case MyRenderMessageEnum.DebugDrawModel:
                case MyRenderMessageEnum.DebugDrawTriangles:
                case MyRenderMessageEnum.DebugDrawPlane:
                case MyRenderMessageEnum.DebugDrawCylinder:
                case MyRenderMessageEnum.DebugDrawFrustrum:
                case MyRenderMessageEnum.DebugDrawMesh:
                case MyRenderMessageEnum.DebugWaitForPresent:
                {
                    m_debugDrawMessages.Enqueue(message);
                }
                break;

                case MyRenderMessageEnum.DebugCrashRenderThread:
                {
                    throw new InvalidOperationException("Forced exception");
                }
                #endregion
            }
        }
Пример #21
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;
            }
            }
        }
 public void EnqueueMessage(MyRenderMessageBase message, bool limitMaxQueueSize)
 {
     MyRender11.EnqueueMessage(message, limitMaxQueueSize);
 }
Пример #23
0
 internal static void EnqueueOutputMessage(MyRenderMessageBase message)
 {
     SharedData.RenderOutputMessageQueue.Enqueue(message);
 }
 public void EnqueueOutputMessage(MyRenderMessageBase message)
 {
     MyRender11.EnqueueOutputMessage(message);
 }
        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:
                    {
                        AddDebugQueueMessage("Frame render start");

                        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();
                        }

                        AddDebugQueueMessage("Frame render end");
                        ProcessDebugOutput();
                        break;
                    }
            }
        }
 internal static void EnqueueDebugDrawMessage(MyRenderMessageBase drawMessage)
 {
     Debug.Assert(drawMessage.MessageClass == MyRenderMessageType.DebugDraw, "Enqueuing non-draw message");
     m_debugDrawMessages.Enqueue(drawMessage);
 }