public void DebugDraw()
        {
            if (!m_simulationDataPrepared)
            {
                return;
            }

            SlidingOffset += 0.005f;

            if (MyPetaInputComponent.DEBUG_DRAW_PATHS)
            {
                var selcolor = Color.Aqua;
                DrawCube(m_grid.GridSize, SelectedCube, ref selcolor, null);

                if (m_finishedData.All.ContainsKey(SelectedCube))
                {
                    var node = m_finishedData.All[SelectedCube];

                    float spacing   = 0.2f;
                    float offset    = -spacing * node.Paths.Count / 2.0f;
                    float increment = spacing;

                    //    if (drawOutgoing)
                    {
                        int   p        = 0;
                        float ratioSum = 0;
                        foreach (var path in node.Paths)
                        {
                            DebugDrawPath(path.Value, offset, p);
                            offset += increment;
                            p++;
                            ratioSum += path.Value.Ratio;

                            if (path.Value.Parents.Count > 1)
                            {
                                foreach (var ppath in path.Value.Parents)
                                {
                                    DebugDrawPath(ppath, offset, p);
                                }
                            }
                        }

                        //foreach (var outg in node.OutgoingNodeswWithWeights)
                        //{
                        //    if (outg.Count > 0)
                        //    {
                        //        string s = "";
                        //        foreach (var outNode in outg)
                        //        {
                        //            s += outNode.Item2.ToString() + " + ";
                        //        }

                        //        Vector3 delta = outg[0].Item1.Pos - node.Pos;

                        //        Vector3D pos = Vector3D.Transform((node.Pos + delta * 0.4f) * m_grid.GridSize, m_grid.WorldMatrix);
                        //        MyRenderProxy.DebugDrawText3D(pos, s, Color.White, 0.5f, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER);

                        //    }
                        //}

                        Vector3D selpos = Vector3D.Transform(node.Pos * m_grid.GridSize, m_grid.WorldMatrix);
                        MyRenderProxy.DebugDrawText3D(selpos + Vector3D.Up / 2, SelectedCube.ToString(), Color.White, 0.5f, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER);

                        //foreach (var nodesSup in node.SupportingNodeswWithWeights)
                        //{
                        //    if (nodesSup.Count > 0)
                        //    {
                        //        string s = "";
                        //        foreach (var outNode in nodesSup)
                        //        {
                        //            s += outNode.Item2.ToString() + " + ";
                        //        }

                        //        Vector3 delta = nodesSup[0].Item1.Pos - node.Pos;

                        //        Vector3D pos = Vector3D.Transform((node.Pos + delta * 0.4f) * m_grid.GridSize, m_grid.WorldMatrix);
                        //        MyRenderProxy.DebugDrawText3D(pos, s, Color.White, 0.5f, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER);

                        //    }
                        //}
                    }
                }
            }

            //MyRenderProxy.DebugDrawAABB(m_grid.PositionComp.WorldAABB, Color.White, 1, 1, false);


            if (MyPetaInputComponent.DEBUG_DRAW_TENSIONS)
            {
                bool drawTensions = true;

                var size = m_grid.GridSize;

                if (drawTensions)
                {
                    foreach (var c in m_finishedData.All)
                    {
                        Color color   = Color.Gray;
                        float tension = 0;

                        if (c.Value.IsDynamicWeight)
                        {
                            continue;
                        }

                        if (!c.Value.IsStatic)
                        {
                            //1kg cube can hold 10kg
                            //0.5kg - 5kg
                            //etc.
                            //Max. supported weight <0..1> is then TotalSupportingWeight / (mass * MaxSupportedWeight)

                            float MaxSupportedWeight = 10;
                            //tension = c.Value.TotalSupportingWeight / (c.Value.Mass * MaxSupportedWeight);
                            tension = c.Value.TotalSupportingWeight / (c.Value.Mass * c.Value.PhysicalMaterial.SupportMultiplier);
                            //tension = c.Value.TotalSupportingWeight;

                            color = GetTension(tension, MaxSupportedWeight);
                        }

                        string text = tension.ToString("0.00");
                        //string text = c.Key.ToString();
                        DrawCube(size, c.Key, ref color, text);
                    }
                }
                else
                {   //Draw weights
                    foreach (var c in m_finishedData.All)
                    {
                        Color color = GetTension(c.Value.Mass, 4);

                        string text = c.Value.Mass.ToString("0.00");
                        DrawCube(size, c.Key, ref color, text);
                    }
                }
            }
        }
Beispiel #2
0
        public override void AddRenderObjects()
        {
            var minCorner = m_planet.PositionLeftBottomCorner;

            m_renderObjectIDs = new uint[16];

            for (int index = 0; index < 16; ++index)
            {
                m_renderObjectIDs[index] = MyRenderProxy.RENDER_ID_UNASSIGNED;
            }

            int runningRenderObjectIndex = 0;

            Debug.Assert((m_planet.Size % MyVoxelCoordSystems.RenderCellSizeInLodVoxels(0)) == Vector3I.Zero);
            var clipmapSizeLod0 = m_planet.Size / MyVoxelCoordSystems.RenderCellSizeInLodVoxels(0);

            Vector3 atmosphereWavelengths = new Vector3();

            atmosphereWavelengths.X = 1.0f / (float)Math.Pow(m_planet.AtmosphereWavelengths.X, 4.0);
            atmosphereWavelengths.Y = 1.0f / (float)Math.Pow(m_planet.AtmosphereWavelengths.Y, 4.0);
            atmosphereWavelengths.Z = 1.0f / (float)Math.Pow(m_planet.AtmosphereWavelengths.Z, 4.0);

            var voxel = (Entity as MyVoxelBase);

            SetRenderObjectID(runningRenderObjectIndex++,
                              MyRenderProxy.CreateClipmap(
                                  MatrixD.CreateTranslation(minCorner),
                                  clipmapSizeLod0,
                                  m_planet.ScaleGroup,
                                  m_planet.PositionComp.GetPosition(),
                                  m_planet.AtmosphereRadius,
                                  m_planet.AverageRadius,
                                  m_planet.HasAtmosphere,
                                  atmosphereWavelengths,
                                  m_planet.SpherizeWithDistance,
                                  RenderFlags.Visible | RenderFlags.DrawOutsideViewDistance | RenderFlags.CastShadows,
                                  IntersectStorage));

            if (m_planet.HasAtmosphere)
            {
                MatrixD matrix = MatrixD.Identity * m_planet.AtmosphereRadius;
                matrix.M44         = 1;
                matrix.Translation = Entity.PositionComp.GetPosition();

                m_atmosphereRenderIndex = runningRenderObjectIndex;

                SetRenderObjectID(runningRenderObjectIndex++, MyRenderProxy.CreateRenderEntityAtmosphere(this.Entity.GetFriendlyName() + " " + this.Entity.EntityId.ToString(),
                                                                                                         "Models\\Environment\\Atmosphere_sphere.mwm",
                                                                                                         matrix,
                                                                                                         MyMeshDrawTechnique.ATMOSPHERE,
                                                                                                         RenderFlags.Visible | RenderFlags.DrawOutsideViewDistance,
                                                                                                         GetRenderCullingOptions(),
                                                                                                         m_planet.AtmosphereRadius,
                                                                                                         m_planet.AverageRadius,
                                                                                                         atmosphereWavelengths));

                SetRenderObjectID(runningRenderObjectIndex++, MyRenderProxy.CreateRenderEntityAtmosphere(this.Entity.GetFriendlyName() + " " + this.Entity.EntityId.ToString(),
                                                                                                         "Models\\Environment\\Atmosphere_sphere.mwm",
                                                                                                         matrix,
                                                                                                         MyMeshDrawTechnique.PLANET_SURFACE,
                                                                                                         RenderFlags.Visible | RenderFlags.DrawOutsideViewDistance,
                                                                                                         GetRenderCullingOptions(),
                                                                                                         m_planet.AtmosphereRadius,
                                                                                                         m_planet.AverageRadius,
                                                                                                         atmosphereWavelengths));

                UpdateAtmosphereSettings(m_planet.AtmosphereSettings);
            }

            m_shadowHelperRenderObjectIndex = runningRenderObjectIndex;
            MatrixD shadowHelperWorldMatrix = MatrixD.CreateScale(m_planet.MinimumRadius);

            shadowHelperWorldMatrix.Translation = m_planet.WorldMatrix.Translation;
            SetRenderObjectID(runningRenderObjectIndex++, MyRenderProxy.CreateRenderEntity("Shadow helper", "Models\\Environment\\Sky\\ShadowHelperSphere.mwm",
                                                                                           shadowHelperWorldMatrix,
                                                                                           MyMeshDrawTechnique.MESH,
                                                                                           RenderFlags.Visible | RenderFlags.CastShadows | RenderFlags.DrawOutsideViewDistance | RenderFlags.NoBackFaceCulling | RenderFlags.SkipInMainView,
                                                                                           CullingOptions.Default,
                                                                                           Color.White, new Vector3(1, 1, 1)));

            MyPlanetGeneratorDefinition definition = m_planet.Generator;

            if (!MyFakes.ENABLE_PLANETARY_CLOUDS || definition == null || definition.CloudLayers == null)
            {
                return;
            }

            foreach (var cloudLayer in definition.CloudLayers)
            {
                double   minScaledAltitude = (m_planet.AverageRadius + m_planet.MaximumRadius) / 2.0;
                double   layerAltitude     = minScaledAltitude + (m_planet.MaximumRadius - minScaledAltitude) * cloudLayer.RelativeAltitude;
                Vector3D rotationAxis      = Vector3D.Normalize(cloudLayer.RotationAxis == Vector3D.Zero ? Vector3D.Up : cloudLayer.RotationAxis);

                int index = runningRenderObjectIndex + m_cloudLayerRenderObjectIndexList.Count;
                SetRenderObjectID(index,
                                  MyRenderProxy.CreateRenderEntityCloudLayer(this.Entity.GetFriendlyName() + " " + this.Entity.EntityId.ToString(),
                                                                             cloudLayer.Model,
                                                                             cloudLayer.Textures,
                                                                             Entity.PositionComp.GetPosition(),
                                                                             layerAltitude,
                                                                             minScaledAltitude,
                                                                             cloudLayer.ScalingEnabled,
                                                                             cloudLayer.FadeOutRelativeAltitudeStart,
                                                                             cloudLayer.FadeOutRelativeAltitudeEnd,
                                                                             cloudLayer.ApplyFogRelativeDistance,
                                                                             m_planet.MaximumRadius,
                                                                             MyMeshDrawTechnique.CLOUD_LAYER,
                                                                             RenderFlags.Visible | RenderFlags.DrawOutsideViewDistance,
                                                                             GetRenderCullingOptions(),
                                                                             rotationAxis,
                                                                             cloudLayer.AngularVelocity,
                                                                             cloudLayer.InitialRotation));
                m_cloudLayerRenderObjectIndexList.Add(index);
            }
            runningRenderObjectIndex += definition.CloudLayers.Count;
        }
        private static void PrepareMaterialBatches(MyRenderContext RC, List <MyScreenDecal> decals, uint sinceStartTs)
        {
            if (decals.Count == 0)
            {
                return;
            }

            List <uint> decalsToRemove = new List <uint>();

            foreach (MyScreenDecal decal in decals)
            {
                var parent = MyIDTracker <MyActor> .FindByID(decal.ParentID);

                bool world = decal.Flags.HasFlag(MyDecalFlags.World);
                if (parent == null && !world)
                {
                    decalsToRemove.Add(decal.ID);
                    continue;
                }

                Matrix volumeMatrix;
                if (world)
                {
                    volumeMatrix = decal.OBBox;
                    Vector3D translation = decal.Data.Position - MyRender11.Environment.CameraPosition;
                    volumeMatrix.Translation = translation;
                }
                else
                {
                    MatrixD transform = decal.OBBox * parent.WorldMatrix;
                    transform.Translation = transform.Translation - MyRender11.Environment.CameraPosition;
                    volumeMatrix          = transform;
                }

                uint  fadeDiff  = decal.FadeTimestamp - sinceStartTs;
                float fadeAlpha = decal.FadeTimestamp - sinceStartTs >= DECAL_FADE_DURATION ? 1 : fadeDiff / (float)DECAL_FADE_DURATION;
                m_jobs.Add(new MyDecalJob()
                {
                    WorldMatrix = volumeMatrix, FadeAlpha = fadeAlpha
                });

                if (MyRenderProxy.Settings.DebugDrawDecals)
                {
                    MatrixD worldMatrix;
                    if (parent == null)
                    {
                        worldMatrix             = decal.OBBox;
                        worldMatrix.Translation = decal.Data.Position;
                    }
                    else
                    {
                        worldMatrix = decal.OBBox * parent.WorldMatrix;
                    }

                    MyRenderProxy.DebugDrawAxis(worldMatrix, 0.2f, false, true);
                    MyRenderProxy.DebugDrawOBB(worldMatrix, Color.Blue, 0.1f, false, false);

                    Vector3 position = worldMatrix.Translation;
                    MyRenderProxy.DebugDrawText3D(position, decal.SourceTarget, Color.White, 1, false);
                }
            }

            foreach (uint id in decalsToRemove)
            {
                DecalNode node = m_nodeMap[id];
                RemoveDecalByNode(node);
            }
        }
Beispiel #4
0
 public void DebugDraw()
 {
     MyRenderProxy.DebugDrawSphere(this.m_center, this.m_innerRadius, Color.RoyalBlue, 0.4f, true, false, true, false);
     MyRenderProxy.DebugDrawSphere(this.m_center, this.m_outerRadius, Color.Aqua, 0.4f, true, false, true, false);
 }
Beispiel #5
0
        public void Draw(List <VRageRender.MyBillboard> collectedBillboards)
        {
            VRage.Profiler.ProfilerShort.Begin("GPU_Draw");
            if (m_renderId == MyRenderProxy.RENDER_ID_UNASSIGNED)
            {
                ProfilerShort.Begin("GPU_Create");
                m_renderId = MyRenderProxy.CreateGPUEmitter();
                ProfilerShort.End();
            }

            if (IsDirty)
            {
                ProfilerShort.Begin("GPU_FillDataComplete");
                m_emitter = new MyGPUEmitter();
                FillDataComplete(ref m_emitter);
                m_lastFramePPS = m_emitter.ParticlesPerSecond;
                MyParticlesManager.GPUEmitters.Add(m_emitter);
                ProfilerShort.End();
                m_dirty = m_animDirty = m_positionDirty = false;
            }
            else if (m_animatedTimeValues || m_animDirty)
            {
                ProfilerShort.Begin("GPU_FillData");
                FillData(ref m_emitter);
                m_lastFramePPS = m_emitter.ParticlesPerSecond;
                MyParticlesManager.GPUEmitters.Add(m_emitter);
                ProfilerShort.End();
                m_animDirty = false;
            }
            else if (IsPositionDirty)
            {
                ProfilerShort.Begin("GPU_FillPosition");
                var pps = GetParticlesPerSecond();
                m_lastFramePPS = pps;
                var transform = new MyGPUEmitterTransformUpdate()
                {
                    GID                = m_renderId,
                    Transform          = CalculateWorldMatrix(),
                    Scale              = m_effect.GetEmitterScale(),
                    Gravity            = m_effect.Gravity * Gravity,
                    ParticlesPerSecond = pps
                };
                MyParticlesManager.GPUEmitterTransforms.Add(transform);
                ProfilerShort.End();

                m_positionDirty = false;
            }
            else if (ParticlesPerSecond.GetKeysCount() > 1)
            {
                ProfilerShort.Begin("GPU_FillLight");
                var pps = GetParticlesPerSecond();
                if (Math.Abs(m_lastFramePPS - pps) > 0.5f)
                {
                    m_lastFramePPS = pps;
                    MyParticlesManager.GPUEmittersLight.Add(new MyGPUEmitterLight()
                    {
                        GID = m_renderId,
                        ParticlesPerSecond = pps
                    });
                }
                ProfilerShort.End();
            }
            ProfilerShort.End();
        }
Beispiel #6
0
 public void OnDeviceInit()
 {
     MyRenderProxy.Assert(m_textures.Count == 0);
     RegisterDefaultTextures();
     LoadAllRequested();
 }
        private void UpdateRenderInstanceData(Dictionary <ModelId, Tuple <List <MyCubeInstanceMergedData>, MyInstanceInfo> > instanceParts, RenderFlags renderFlags)
        {
            if (m_parentCullObject == MyRenderProxy.RENDER_ID_UNASSIGNED)
            {
                m_parentCullObject = MyRenderProxy.CreateManualCullObject(m_gridRenderComponent.Container.Entity.GetFriendlyName() + " " + m_gridRenderComponent.Container.Entity.EntityId.ToString() + ", cull object", m_gridRenderComponent.Container.Entity.PositionComp.WorldMatrix);
                AddRenderObjectId(m_parentCullObject, true);
            }

            if (m_instanceBufferId == MyRenderProxy.RENDER_ID_UNASSIGNED)
            {
                m_instanceBufferId = MyRenderProxy.CreateRenderInstanceBuffer(
                    m_gridRenderComponent.Container.Entity.GetFriendlyName() + " "
                    + m_gridRenderComponent.Container.Entity.EntityId.ToString()
                    + ", instance buffer " + DebugName, MyRenderInstanceBufferType.Cube,
                    m_gridRenderComponent.GetRenderObjectID());
                AddRenderObjectId(m_instanceBufferId, false);
            }

            ProfilerShort.Begin("Merge render parts");

            // Merge data into one buffer
            Debug.Assert(InstanceData.Count == 0, "Instance data is not cleared");
            m_instanceInfo.Clear();
            m_tmpDecalData.Clear();
            int instaceDataIndex = -1;

            foreach (var pair in instanceParts)
            {
                var modeId = pair.Key;
                var tuple  = pair.Value;
                m_instanceInfo.Add(modeId, new MyRenderInstanceInfo(m_instanceBufferId, InstanceData.Count, tuple.Item1.Count, tuple.Item2.MaxViewDistance, tuple.Item2.Flags));

                var instaceDatas = tuple.Item1;
                for (int it1 = 0; it1 < instaceDatas.Count; it1++)
                {
                    instaceDataIndex++;
                    InstanceData.Add(instaceDatas[it1].CubeInstanceData);

                    var decals = instaceDatas[it1].Decals;
                    if (decals == null)
                    {
                        continue;
                    }

                    for (int it2 = 0; it2 < decals.Count; it2++)
                    {
                        m_tmpDecalData.Add(new MyCubeInstanceDecalData()
                        {
                            DecalId = decals[it2], InstanceIndex = instaceDataIndex
                        });
                    }
                }
            }
            ProfilerShort.End();

            if (InstanceData.Count > 0)
            {
                ProfilerShort.Begin("Update instance buffer");

                MyRenderProxy.UpdateRenderCubeInstanceBuffer(m_instanceBufferId, InstanceData, (int)(InstanceData.Count * 1.2f), m_tmpDecalData);
                ProfilerShort.End();
            }
            InstanceData.Clear();

            ProfilerShort.Begin("Update instance entitites");
            UpdateRenderEntitiesInstanceData(renderFlags, m_parentCullObject);
            ProfilerShort.End();
        }
        public static void DebugDraw(this IMyConveyorEndpoint endpoint)
        {
            if (!MyDebugDrawSettings.DEBUG_DRAW_CONVEYORS)
            {
                return;
            }

            Vector3 centerPos = new Vector3();

            for (int i = 0; i < endpoint.GetLineCount(); ++i)
            {
                var     position = endpoint.GetPosition(i);
                Vector3 pos      = new Vector3(position.LocalGridPosition) + 0.5f * new Vector3(position.VectorDirection);
                centerPos += pos;
            }
            centerPos = centerPos * endpoint.CubeBlock.CubeGrid.GridSize / (float)endpoint.GetLineCount();
            centerPos = Vector3.Transform(centerPos, endpoint.CubeBlock.CubeGrid.WorldMatrix);

            for (int i = 0; i < endpoint.GetLineCount(); ++i)
            {
                var            position = endpoint.GetPosition(i);
                MyConveyorLine line     = endpoint.GetConveyorLine(i);
                Vector3        pos      = (new Vector3(position.LocalGridPosition) + 0.5f * new Vector3(position.VectorDirection)) * endpoint.CubeBlock.CubeGrid.GridSize;
                Vector3        pos2     = (new Vector3(position.LocalGridPosition) + 0.4f * new Vector3(position.VectorDirection)) * endpoint.CubeBlock.CubeGrid.GridSize;
                pos  = Vector3.Transform(pos, endpoint.CubeBlock.CubeGrid.WorldMatrix);
                pos2 = Vector3.Transform(pos2, endpoint.CubeBlock.CubeGrid.WorldMatrix);
                Vector3 dir = Vector3.TransformNormal(position.VectorDirection * endpoint.CubeBlock.CubeGrid.GridSize * 0.5f, endpoint.CubeBlock.CubeGrid.WorldMatrix);

                Color color = line.IsFunctional ? Color.Orange : Color.DarkRed;
                color = line.IsWorking ? Color.GreenYellow : color;

                EndpointDebugShape shape = EndpointDebugShape.SHAPE_SPHERE;
                float dirMultiplier      = 1.0f;
                float radius             = 0.05f;

                if (line.GetEndpoint(0) == null || line.GetEndpoint(1) == null)
                {
                    if (line.Type == MyObjectBuilder_ConveyorLine.LineType.SMALL_LINE)
                    {
                        dirMultiplier = 0.2f;
                        radius        = 0.015f;
                        shape         = EndpointDebugShape.SHAPE_SPHERE;
                    }
                    else
                    {
                        dirMultiplier = 0.1f;
                        radius        = 0.015f;
                        shape         = EndpointDebugShape.SHAPE_CAPSULE;
                    }
                }
                else
                {
                    if (line.Type == MyObjectBuilder_ConveyorLine.LineType.SMALL_LINE)
                    {
                        dirMultiplier = 1.0f;
                        radius        = 0.05f;
                        shape         = EndpointDebugShape.SHAPE_SPHERE;
                    }
                    else
                    {
                        dirMultiplier = 0.2f;
                        radius        = 0.05f;
                        shape         = EndpointDebugShape.SHAPE_CAPSULE;
                    }
                }

                MyRenderProxy.DebugDrawLine3D(pos, pos + dir * dirMultiplier, color, color, true);
                if (shape == EndpointDebugShape.SHAPE_SPHERE)
                {
                    MyRenderProxy.DebugDrawSphere(pos, radius * endpoint.CubeBlock.CubeGrid.GridSize, color.ToVector3(), 1.0f, false);
                }
                else if (shape == EndpointDebugShape.SHAPE_CAPSULE)
                {
                    MyRenderProxy.DebugDrawCapsule(pos - dir * dirMultiplier, pos + dir * dirMultiplier, radius * endpoint.CubeBlock.CubeGrid.GridSize, color, false);
                }

                if (MyDebugDrawSettings.DEBUG_DRAW_CONVEYORS_LINE_IDS)
                {
                    MyRenderProxy.DebugDrawText3D(pos2, line.GetHashCode().ToString(), color, 0.6f, false);
                }

                MyRenderProxy.DebugDrawLine3D(pos, centerPos, color, color, false);
            }
        }
        public override void Draw()
        {
            base.Draw();

            if (m_toggleMovementState)
            {
                var     allCharacters = MyEntities.GetEntities().OfType <MyCharacter>();
                Vector2 initPos       = new Vector2(10, 200);
                foreach (var character in allCharacters)
                {
                    MyRenderProxy.DebugDrawText2D(initPos, character.GetCurrentMovementState().ToString(), Color.Green, 0.5f, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER);
                    initPos += new Vector2(0, 20);
                }
            }

            if (MySession.Static != null && MySession.Static.LocalCharacter != null)
            {
                Text("Character look speed: {0}", MySession.Static.LocalCharacter.RotationSpeed);
            }

            if (MySession.Static != null && MySession.Static.LocalCharacter != null)
            {
                var animController            = MySession.Static.LocalCharacter.AnimationController;
                System.Text.StringBuilder str = new System.Text.StringBuilder(1024);
                if (animController != null && animController.Controller != null && animController.Controller.GetLayerByIndex(0) != null)
                {
                    str.Clear();
                    foreach (int seqNum in animController.Controller.GetLayerByIndex(0).VisitedTreeNodesPath)
                    {
                        if (seqNum == 0)
                        {
                            break;
                        }
                        str.Append(seqNum);
                        str.Append(",");
                    }
                    Text(str.ToString());
                }

                if (animController != null && animController.Variables != null)
                {
                    foreach (var variable in animController.Variables.AllVariables)
                    {
                        str.Clear();
                        str.Append(variable.Key);
                        str.Append(" = ");
                        str.Append(variable.Value);
                        Text(str.ToString());
                    }
                }

                if (animController != null)
                {
                    if (animController.LastFrameActions != null)
                    {
                        foreach (MyStringId actionId in animController.LastFrameActions)
                        {
                            m_lastAnimationActions.Add(actionId.ToString());
                        }

                        if (m_lastAnimationActions.Count > m_maxLastAnimationActions)
                        {
                            m_lastAnimationActions.RemoveRange(0, m_lastAnimationActions.Count - m_maxLastAnimationActions);
                        }
                    }

                    Text(Color.Red, "--- RECENTLY TRIGGERED ACTIONS ---");
                    foreach (var action in m_lastAnimationActions)
                    {
                        Text(Color.Yellow, action);
                    }
                }
            }

            if (m_toggleShowSkeleton)
            {
                DrawSkeleton();
            }

            MyRenderProxy.DebugDrawText2D(new Vector2(300, 10), "Debugging AC " + m_animationControllerName, Color.Yellow, 0.5f, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER);

            // debugging old animation system
            if (MySession.Static != null && MySession.Static.LocalCharacter != null &&
                MySession.Static.LocalCharacter.Definition != null &&
                MySession.Static.LocalCharacter.Definition.AnimationController == null)
            {
                var   allAnimationPlayers = MySession.Static.LocalCharacter.GetAllAnimationPlayers();
                float posY = 40;
                foreach (var animationPlayer in allAnimationPlayers)
                {
                    MyRenderProxy.DebugDrawText2D(new Vector2(400, posY), (animationPlayer.Key != "" ? animationPlayer.Key : "Body") + ": "
                                                  + animationPlayer.Value.ActualPlayer.AnimationNameDebug + " (" + animationPlayer.Value.ActualPlayer.AnimationMwmPathDebug + ")",
                                                  Color.Lime, 0.5f, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER);
                    posY += 30;
                }
            }
        }
Beispiel #10
0
        private static void Save(Resource res, Stream stream, ImageFileFormat fmt)
        {
            var texture     = res as Texture2D;
            var textureCopy = new Texture2D(MyRender11.Device, new Texture2DDescription
            {
                Width             = (int)texture.Description.Width,
                Height            = (int)texture.Description.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = texture.Description.Format,
                Usage             = ResourceUsage.Staging,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags         = BindFlags.None,
                CpuAccessFlags    = CpuAccessFlags.Read,
                OptionFlags       = ResourceOptionFlags.None
            });

            RC.CopyResource(res, textureCopy);

            DataStream dataStream;
            var        dataBox = RC.MapSubresource(
                textureCopy,
                0,
                0,
                MapMode.Read,
                MapFlags.None,
                out dataStream);

            var dataRectangle = new DataRectangle
            {
                DataPointer = dataStream.DataPointer,
                Pitch       = dataBox.RowPitch
            };

            var bitmap = new Bitmap(
                MyRender11.WIC,
                textureCopy.Description.Width,
                textureCopy.Description.Height,
                PixelFormatFromFormat(textureCopy.Description.Format), // TODO: should use some conversion from textureCopy.Description.Format
                dataRectangle);

            using (var wicStream = new WICStream(MyRender11.WIC, stream))
            {
                BitmapEncoder bitmapEncoder;
                switch (fmt)
                {
                case ImageFileFormat.Png:
                    bitmapEncoder = new PngBitmapEncoder(MyRender11.WIC, wicStream);
                    break;

                case ImageFileFormat.Jpg:
                    bitmapEncoder = new JpegBitmapEncoder(MyRender11.WIC, wicStream);
                    break;

                case ImageFileFormat.Bmp:
                    bitmapEncoder = new BmpBitmapEncoder(MyRender11.WIC, wicStream);
                    break;

                default:
                    MyRenderProxy.Assert(false, "Unsupported file format.");
                    bitmapEncoder = null;
                    break;
                }
                if (bitmapEncoder != null)
                {
                    using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder))
                    {
                        bitmapFrameEncode.Initialize();
                        bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height);
                        var pixelFormat = PixelFormat.FormatDontCare;
                        bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
                        bitmapFrameEncode.WriteSource(bitmap);
                        bitmapFrameEncode.Commit();
                        bitmapEncoder.Commit();
                    }
                    bitmapEncoder.Dispose();
                }
            }

            RC.UnmapSubresource(textureCopy, 0);
            textureCopy.Dispose();
            bitmap.Dispose();
        }
        public override void Draw()
        {
            base.Draw();

            if (!MyFakes.ENABLE_ARMOR_HAND)
            {
                return;
            }

            Vector3  forward = MySector.MainCamera.ForwardVector;
            Vector3D origin  = MySector.MainCamera.Position;
            Vector3D end     = origin + forward * 100f;

            m_lastCubeGrid = null;
            m_lastBone     = null;

            var hitInfo   = MyPhysics.CastRay(origin, end, MyPhysics.ExplosionRaycastLayer);
            var hitEntity = hitInfo.HasValue ? ((MyPhysicsBody)hitInfo.Value.HkHitInfo.Body.UserObject).Entity : null;

            var grid = (hitEntity as MyCubeGrid);

            if (grid != null)
            {
                m_lastCubeGrid = grid;
                double shortestDistance = double.MaxValue;

                LineD    line            = new LineD(origin, end);
                Vector3I hitCube         = new Vector3I();
                double   distanceSquared = double.MaxValue;

                if (m_lastCubeGrid.GetLineIntersectionExactGrid(ref line, ref hitCube, ref distanceSquared))
                {
                    m_lastCube = hitCube;
                }
                else
                {
                    m_lastCube = null;
                }

                foreach (var bone in grid.Skeleton.Bones)
                {
                    var bonePos = (Vector3D)(bone.Key / (float)grid.Skeleton.BoneDensity) * grid.GridSize + bone.Value;
                    bonePos -= new Vector3D(grid.GridSize / grid.Skeleton.BoneDensity);
                    Vector3D pos = Vector3D.Transform(bonePos, grid.PositionComp.WorldMatrix);

                    Color color = Color.Red;

                    double distance = MyUtils.GetPointLineDistance(ref origin, ref end, ref pos);
                    if (distance < 0.1f)
                    {
                        double distanceToCamera = (origin - pos).LengthSquared();
                        if (distanceToCamera < shortestDistance)
                        {
                            shortestDistance = distanceToCamera;

                            color      = Color.Blue;
                            m_lastBone = bone.Key;
                        }
                    }

                    MyRenderProxy.DebugDrawSphere(pos, 0.05f, color.ToVector3(), 0.5f, false, true);
                }
            }
        }
 public void Invalidate(int voxelMaterialId)
 {
     MyRenderProxy.Assert(voxelMaterialId < MAX_ENTRIES);
     m_needsUpdate[voxelMaterialId] = true;
 }
Beispiel #13
0
 public override void DebugDraw(Vector2 position, Vector2 size, List <MyBehaviorTreeNodeMemory> nodesMemory)
 {
     MyRenderProxy.DebugDrawText2D(position, "A:" + this.m_actionName.ToString(), nodesMemory[base.MemoryIndex].NodeStateColor, MyBehaviorTreeNode.DEBUG_TEXT_SCALE, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, false);
 }
Beispiel #14
0
        internal static int Gather(MyGPUEmitterData[] data, out SharpDX.Direct3D11.ShaderResourceView textureArraySRV)
        {
            MyRenderStats.Generic.WriteFormat("GPU particles allocated: {0}", m_totalParticles, VRage.Stats.MyStatTypeEnum.CurrentValue, 300, 0);
            MyRenderStats.Generic.WriteFormat("GPU particles overload: {0}", m_overloaded ? 1.0f : 0, VRage.Stats.MyStatTypeEnum.CurrentValue, 300, 0);

            for (int i = 0; i < MAX_LIVE_EMITTERS; i++)
            {
                data[i].NumParticlesToEmitThisFrame = 0;
            }
            int  maxEmitterIndex = -1;
            uint textureIndex    = 0;

            foreach (var id in m_idIndex.Values)
            {
                if (MyCommon.TimerMs > m_emitters.Data[id.Index].DieAt)
                {
                    m_emitters.Data[id.Index].GPUEmitter.Data.Flags |= GPUEmitterFlags.Dead;
                }

                float toEmit = MyCommon.LastFrameDelta() * m_emitters.Data[id.Index].GPUEmitter.ParticlesPerSecond +
                               m_emitters.Data[id.Index].ParticlesEmittedFraction;
                m_emitters.Data[id.Index].GPUEmitter.Data.NumParticlesToEmitThisFrame = (int)toEmit;
                m_emitters.Data[id.Index].ParticlesEmittedFraction = toEmit - m_emitters.Data[id.Index].GPUEmitter.Data.NumParticlesToEmitThisFrame;

                if (m_emitters.Data[id.Index].TextureId != Resources.TexId.NULL)
                {
                    MyRenderProxy.Assert(m_textureArrayIndices.ContainsKey(m_emitters.Data[id.Index].TextureId));
                    textureIndex = m_textureArrayIndices[m_emitters.Data[id.Index].TextureId].Index;
                }
                else
                {
                    textureIndex = 0;
                }

                int bufferIndex = m_emitters.Data[id.Index].BufferIndex;
                data[bufferIndex]                = m_emitters.Data[id.Index].GPUEmitter.Data;
                data[bufferIndex].Position       = m_emitters.Data[id.Index].GPUEmitter.WorldPosition - MyEnvironment.CameraPosition;
                data[bufferIndex].TextureIndex1 |= textureIndex << (ATLAS_INDEX_BITS + ATLAS_DIMENSION_BITS * 2);

                if (bufferIndex > maxEmitterIndex)
                {
                    maxEmitterIndex = bufferIndex;
                }
            }

            UpdateTextureArray();
            if (m_textureArray != null)
            {
                textureArraySRV = m_textureArray.ShaderView;
            }
            else
            {
                textureArraySRV = null;
            }

            foreach (var id in m_idIndex.Values.ToArray())
            {
                if ((m_emitters.Data[id.Index].GPUEmitter.Data.Flags & GPUEmitterFlags.Dead) > 0)
                {
                    m_totalParticles -= m_emitters.Data[id.Index].GPUEmitter.MaxParticles();
                    Remove(id);
                }
            }
            return(maxEmitterIndex + 1);
        }
Beispiel #15
0
 public override void InvalidateRenderObjects(bool sortIntoCullobjects = false)
 {
     MyRenderProxy.UpdateLineBasedObject(m_renderObjectIDs[0], WorldPivotA, WorldPivotB);
 }
 static void ClearDecals(MyGuiControlButton button)
 {
     MyRenderProxy.ClearDecals();
 }
Beispiel #17
0
 public override void ReleaseRenderObjectID(int index)
 {
     MyRenderProxy.RemoveRenderObject(m_renderObjectIDs[0]);
 }
Beispiel #18
0
        public void DebugDraw()
        {
            if (MyDebugDrawSettings.ENABLE_DEBUG_DRAW == false)
            {
                return;
            }

            m_aiming.DebugDraw(m_aimingPositionAndOrientation);

            if (MyDebugDrawSettings.DEBUG_DRAW_BOT_STEERING)
            {
                foreach (var steering in m_steerings)
                {
                    steering.DebugDraw();
                }
            }

            if (MyDebugDrawSettings.DEBUG_DRAW_BOT_NAVIGATION)
            {
                Vector3 pos         = PositionAndOrientation.Translation;// + /*PositionAndOrientation.Up * 1.5f + */ForwardVector;
                Vector3 rightVector = Vector3.Cross(m_forwardVector, UpVector);

                if (Stuck)
                {
                    MyRenderProxy.DebugDrawSphere(pos, 1.0f, Color.Red.ToVector3(), 1.0f, false);
                }

                //MyRenderProxy.DebugDrawLine3D(pos, pos + ForwardVector, Color.Blue, Color.Blue, false);

                //var normalizedCorrection = Vector3D.Normalize(m_correction);
                //var normalizedCorrectedDirXZ = normalizedCorrection + m_forwardVector;
                //normalizedCorrectedDirXZ = Vector3D.Normalize(Vector3D.Reject(normalizedCorrectedDirXZ, Vector3D.Up));
                //MyRenderProxy.DebugDrawLine3D(pos, pos + normalizedCorrectedDirXZ * 3, Color.Lime, Color.Lime, false);
                MyRenderProxy.DebugDrawArrow3D(pos, pos + ForwardVector, Color.Blue, Color.Blue, false, text: "Nav. FW");
                MyRenderProxy.DebugDrawArrow3D(pos + ForwardVector, pos + ForwardVector + m_correction, Color.LightBlue, Color.LightBlue, false, text: "Correction");
                //MyRenderProxy.DebugDrawLine3D(pos + ForwardVector, pos + ForwardVector + m_correction, Color.Yellow, Color.Yellow, false);
                //MyRenderProxy.DebugDrawSphere(pos + ForwardVector + m_correction, 0.05f, Color.Yellow.ToVector3(), 1.0f, true);

                if (m_destinationSphere != null)
                {
                    m_destinationSphere.DebugDraw();
                }

                var character = this.BotEntity as MyCharacter;
                if (character != null)
                {
                    var viewMatrix  = character.GetViewMatrix();
                    var worldMatrix = MatrixD.Invert(viewMatrix);
                    var headMatrix  = character.GetHeadMatrix(true, true);

                    MyRenderProxy.DebugDrawLine3D(worldMatrix.Translation, Vector3D.Transform(Vector3D.Forward * 50, worldMatrix), Color.Yellow, Color.White, false);
                    MyRenderProxy.DebugDrawLine3D(headMatrix.Translation, Vector3D.Transform(Vector3D.Forward * 50, headMatrix), Color.Red, Color.Red, false);

                    if (character.CurrentWeapon != null)
                    {
                        var direction = character.CurrentWeapon.DirectionToTarget(character.AimedPoint);
                        var spos      = (character.CurrentWeapon as MyEntity).WorldMatrix.Translation;

                        MyRenderProxy.DebugDrawSphere(character.AimedPoint, 1.0f, Color.Yellow, 1.0f, false);
                        MyRenderProxy.DebugDrawLine3D(spos, spos + direction * 20, Color.Purple, Color.Purple, false);
                    }
                }
            }
        }
        protected bool TestGridPlacementOnGrid(MyCubeGrid previewGrid, ref MyGridPlacementSettings settings, MyCubeGrid hitGrid)
        {
            Debug.Assert(previewGrid.GridSizeEnum == hitGrid.GridSizeEnum);

            bool retval = true;

            Vector3I gridOffset = hitGrid.WorldToGridInteger(previewGrid.PositionComp.WorldMatrix.Translation);
            MatrixI  transform  = hitGrid.CalculateMergeTransform(previewGrid, gridOffset);

            Matrix localPreviewMatrix = transform.GetFloatMatrix();

            localPreviewMatrix.Translation *= previewGrid.GridSize;

            if (MyDebugDrawSettings.DEBUG_DRAW_COPY_PASTE)
            {
                MyRenderProxy.DebugDrawText2D(new Vector2(0.0f, 60.0f), "First grid offset: " + gridOffset.ToString(), Color.Red, 1.0f);
            }

            retval = retval && MyCubeBuilder.CheckValidBlocksRotation(localPreviewMatrix, previewGrid);
            retval = retval && hitGrid.GridSizeEnum == previewGrid.GridSizeEnum && hitGrid.CanMergeCubes(previewGrid, gridOffset);
            retval = retval && MyCubeGrid.CheckMergeConnectivity(hitGrid, previewGrid, gridOffset);

            // Check if any block connects to hit grid
            if (retval)
            {
                bool connected = false;

                foreach (var block in previewGrid.CubeBlocks)
                {
                    if (block.FatBlock is MyCompoundCubeBlock)
                    {
                        MyCompoundCubeBlock compoundBlock = block.FatBlock as MyCompoundCubeBlock;
                        foreach (var blockInCompound in compoundBlock.GetBlocks())
                        {
                            connected |= CheckConnectivityOnGrid(blockInCompound, ref transform, ref settings, hitGrid);
                            if (connected)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        connected |= CheckConnectivityOnGrid(block, ref transform, ref settings, hitGrid);
                    }

                    if (connected)
                    {
                        break;
                    }
                }

                retval &= connected;
            }

            if (retval)
            {
                foreach (var block in previewGrid.CubeBlocks)
                {
                    if (block.FatBlock is MyCompoundCubeBlock)
                    {
                        MyCompoundCubeBlock compoundBlock = block.FatBlock as MyCompoundCubeBlock;
                        foreach (var blockInCompound in compoundBlock.GetBlocks())
                        {
                            retval = retval && TestBlockPlacementOnGrid(blockInCompound, ref transform, ref settings, hitGrid);
                            if (!retval)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        retval = retval && TestBlockPlacementOnGrid(block, ref transform, ref settings, hitGrid);
                    }

                    if (!retval)
                    {
                        break;
                    }
                }
            }

            return(retval);
        }
Beispiel #20
0
        internal static int Gather(MyGPUEmitterData[] data, out ISrvBindable textureArraySrv)
        {
            for (int i = 0; i < MAX_LIVE_EMITTERS; i++)
            {
                data[i].NumParticlesToEmitThisFrame = 0;
            }

            // sort emitters!
            List <MyLiveData> emitters = m_emitters.Values.ToList();

            //if (emitters.Count > MAX_LIVE_EMITTERS)
            emitters.Sort();

            int  maxEmitterIndex        = -1;
            uint textureIndex           = 0;
            int  unassociatedCount      = 0;
            int  skipCount              = 0;
            int  unsortedCount          = 0;
            int  firstUnassociatedIndex = -1;
            int  lastAssociatedIndex    = -1;

            for (int i = 0; i < emitters.Count; i++)
            {
                var emitter = emitters[i];
                // assiociate buffer index to new emitters & track overload to free space for unassociated near emitters later
                if (emitter.BufferIndex == -1)
                {
                    if (m_freeBufferIndices.Count > 0)
                    {
                        emitter.BufferIndex = m_freeBufferIndices.Pop();
                    }
                    else
                    {
                        unassociatedCount++;
                        if (firstUnassociatedIndex == -1)
                        {
                            firstUnassociatedIndex = i;
                        }
                    }
                }
                else
                {
                    skipCount           = unassociatedCount;
                    lastAssociatedIndex = i;
                    if (unassociatedCount > 0)
                    {
                        unsortedCount++;
                    }
                }

                if (MyCommon.TimerMs > emitter.DieAt)
                {
                    emitter.GPUEmitter.Data.Flags |= GPUEmitterFlags.Dead;
                }

                if (emitter.BufferIndex != -1)
                {
                    if ((emitter.GPUEmitter.Data.Flags & GPUEmitterFlags.FreezeEmit) == 0)
                    {
                        float toEmit = MyCommon.LastFrameDelta() * emitter.GPUEmitter.ParticlesPerSecond +
                                       emitter.ParticlesEmittedFraction;
                        emitter.GPUEmitter.Data.NumParticlesToEmitThisFrame = (int)toEmit;
                        emitter.ParticlesEmittedFraction = toEmit - emitter.GPUEmitter.Data.NumParticlesToEmitThisFrame;
                    }

                    if (string.IsNullOrEmpty(emitter.GPUEmitter.AtlasTexture))
                    {
                        MyRenderProxy.Assert(m_textureArrayIndices.ContainsKey(emitter.GPUEmitter.AtlasTexture));
                        textureIndex = m_textureArrayIndices[emitter.GPUEmitter.AtlasTexture].Index;
                    }
                    else
                    {
                        textureIndex = 0;
                    }

                    int bufferIndex = emitter.BufferIndex;
                    data[bufferIndex] = emitter.GPUEmitter.Data;
                    Vector3 pos = emitter.GPUEmitter.WorldPosition - MyRender11.Environment.Matrices.CameraPosition;
                    data[bufferIndex].RotationMatrix.M14 = pos.X;
                    data[bufferIndex].RotationMatrix.M24 = pos.Y;
                    data[bufferIndex].RotationMatrix.M34 = pos.Z;
                    data[bufferIndex].PositionDelta      = emitter.LastWorldPosition - emitter.GPUEmitter.WorldPosition;
                    data[bufferIndex].TextureIndex1     |= textureIndex << (ATLAS_INDEX_BITS + ATLAS_DIMENSION_BITS * 2);

                    if (bufferIndex > maxEmitterIndex)
                    {
                        maxEmitterIndex = bufferIndex;
                    }
                }
                emitter.LastWorldPosition = emitter.GPUEmitter.WorldPosition;
            }

            /*MyRenderStats.Generic.WriteFormat("GPU particles allocated: {0}", totalParticles, VRage.Stats.MyStatTypeEnum.CurrentValue, 300, 0);
             * MyRenderStats.Generic.WriteFormat("GPU particles overload: {0}", overloadedParticles ? 1.0f : 0, VRage.Stats.MyStatTypeEnum.CurrentValue, 300, 0);
             * MyRenderStats.Generic.WriteFormat("GPU emitters overload: {0}", overloadedEmitters ? 1.0f : 0, VRage.Stats.MyStatTypeEnum.CurrentValue, 300, 0);*/

            UpdateTextureArray();
            textureArraySrv = m_textureArray;

            // stop emitters far away to make room for emitters nearby
            if (skipCount > 0 && unsortedCount > 0)
            {
                // iterate until buffer-unassociated index is larger then unassocited one
                for (int i = firstUnassociatedIndex, j = lastAssociatedIndex; i < j;)
                {
                    var emitter = emitters[j];
                    // free last buffer-associated emitter
                    data[emitter.BufferIndex].Flags |= GPUEmitterFlags.Dead;
                    data[emitter.BufferIndex].NumParticlesToEmitThisFrame = 0;
                    m_freeBufferIndices.Push(emitter.BufferIndex);
                    emitter.BufferIndex = -1;

                    // find new last buffer-associated emitter
                    do
                    {
                        j--;
                    }while (j > 0 && emitters[j].BufferIndex == -1);

                    // find next buffer-unassociated emitter
                    do
                    {
                        i++;
                    } while (i < emitters.Count && emitters[i].BufferIndex != -1);
                }
            }

            foreach (var emitter in emitters)
            {
                if ((emitter.GPUEmitter.Data.Flags & GPUEmitterFlags.Dead) > 0)
                {
                    Remove(emitter);
                }
            }

            return(maxEmitterIndex + 1);
        }
Beispiel #21
0
        // Draws the gizmo
        public override void Draw()
        {
            if (!Active)
            {
                return;
            }

            if (DEBUG)
            {
                MyRenderProxy.DebugDrawLine3D(m_lastRay.From, m_lastRay.To, Color.Green, Color.Green, true);
            }

            if (ControlledEntity == null)
            {
                return;
            }

            if (ControlledEntity.Parent != null)
            {
                var parent = ControlledEntity.Parent;
                while (parent != null)
                {
                    // Draw line to parent
                    MyRenderProxy.DebugDrawLine3D(ControlledEntity.Parent.PositionComp.GetPosition(),
                                                  ControlledEntity.PositionComp.GetPosition(),
                                                  Color.Orange,
                                                  Color.Blue,
                                                  false);

                    parent = parent.Parent;
                }
            }

            var textPosition = new Vector2(20, Session.Camera.ViewportSize.Y / 2);

            switch (Operation)
            {
            case OperationMode.Translation:
                MyRenderProxy.DebugDrawText2D(textPosition, "Translation", Color.Yellow, 1);
                break;

            case OperationMode.Rotation:
                MyRenderProxy.DebugDrawText2D(textPosition, "Rotation", Color.Yellow, 1);
                break;

            case OperationMode.HierarchyAssignment:
                MyRenderProxy.DebugDrawText2D(textPosition, "Hierarchy", Color.Yellow, 1);
                break;
            }

            if (Operation == OperationMode.Translation && !DisableTransformation)
            {
                // Change the size of the control elements
                var camPosition = Session.Camera.Position;
                var distance    = Vector3D.Distance(m_xBB.Center, camPosition);
                var f           = Session.Camera.ProjectionMatrix.Up.LengthSquared();

                m_xBB.HalfExtent = Vector3D.One * 0.008 * distance * f;
                m_yBB.HalfExtent = Vector3D.One * 0.008 * distance * f;
                m_zBB.HalfExtent = Vector3D.One * 0.008 * distance * f;

                DrawOBB(m_xBB, Color.Red, 0.5f, 0);
                DrawOBB(m_yBB, Color.Green, 0.5f, 1);
                DrawOBB(m_zBB, Color.Blue, 0.5f, 2);
            }

            if (Operation != OperationMode.HierarchyAssignment && !DisableTransformation)
            {
                DrawOBB(m_xPlane, Color.Red, 0.2f, 3);
                DrawOBB(m_yPlane, Color.Green, 0.2f, 4);
                DrawOBB(m_zPlane, Color.Blue, 0.2f, 5);
            }
            else
            {
                var volumeCenter = ControlledEntity.PositionComp.WorldVolume.Center;
                var volumeRadius = ControlledEntity.PositionComp.WorldVolume.Radius;

                MyRenderProxy.DebugDrawSphere(volumeCenter, (float)volumeRadius, Color.Yellow, 0.2f, true);
            }
        }
Beispiel #22
0
 public MyShaderBundle GetShaderBundle(MyInstanceLodState state)
 {
     MyRenderProxy.Assert((int)state < m_shaderBundles.Length, "Shader bundle is not correctly initialised");
     MyRenderProxy.Assert(m_shaderBundles[(int)state] != null, "Shader bundle is not defined for the state");
     return(m_shaderBundles[(int)state]);
 }
Beispiel #23
0
 public void DebugDraw()
 {
     m_sensor.DebugDraw();
     MyRenderProxy.DebugDrawSphere((Vector3)m_cutOut.Sphere.Center, (float)m_cutOut.Sphere.Radius, Color.Red, 0.6f, true);
 }
Beispiel #24
0
        /// <summary>
        /// Update shown position of the weapon.
        /// </summary>
        private void UpdateGraphicalWeaponPosition()
        {
            var animController = Character.AnimationController;
            MyHandItemDefinition handItemDefinition = Character.HandItemDefinition;

            if (handItemDefinition == null || Character.CurrentWeapon == null || animController.CharacterBones == null)
            {
                return;
            }
            // ---------

            // gather useful variables
            bool isLocallyControlled = Character.ControllerInfo.IsLocallyControlled();
            bool isInFirstPerson     = (Character.IsInFirstPersonView || Character.ForceFirstPersonCamera) && isLocallyControlled;
            var  jetpack             = Character.JetpackComp;
            bool flying = jetpack != null && jetpack.Running;

            if (m_lastStateWasFalling && flying)
            {
                m_currentAnimationToIkTime = m_animationToIKDelay * (float)Math.Cos(Character.HeadLocalXAngle - m_lastLocalRotX);
            }
            if (m_lastStateWasCrouching != Character.IsCrouching)
            {
                m_suppressBouncingForTimeSec = m_suppressBouncingDelay;
            }
            if (m_suppressBouncingForTimeSec > 0)
            {
                m_spineRestPositionX.Clear();
                m_spineRestPositionY.Clear();
                m_spineRestPositionZ.Clear();
            }

            m_lastLocalRotX = Character.HeadLocalXAngle;
            // get head matrix
            MatrixD weaponMatrixPositioned = Character.GetHeadMatrix(false, !flying, false, true, preferLocalOverSync: true) * Character.PositionComp.WorldMatrixInvScaled;

            if (!isInFirstPerson && animController.CharacterBones.IsValidIndex(Character.HeadBoneIndex))
            {
                // apply feet ik (head bone is stabilized)
                weaponMatrixPositioned.M42 += animController.CharacterBonesSorted[0].Translation.Y;
            }

            // ---------

            // mix positioning matrices (variants: stand/walk/shoot/ironsight), all in character local space

            // standing (IK)
            MatrixD standingMatrix = isInFirstPerson ? handItemDefinition.ItemLocation : handItemDefinition.ItemLocation3rd;
            // walking (IK)
            MatrixD walkingMatrix = isInFirstPerson ? handItemDefinition.ItemWalkingLocation : handItemDefinition.ItemWalkingLocation3rd;
            // shooting (IK)
            MatrixD shootingMatrix = isInFirstPerson ? handItemDefinition.ItemShootLocation : handItemDefinition.ItemShootLocation3rd;
            // ironsight (IK)
            MatrixD ironsightMatrix = handItemDefinition.ItemIronsightLocation;
            // animation pose
            MatrixD weaponAnimMatrix = animController.CharacterBones.IsValidIndex(Character.WeaponBone)
                ? GetWeaponRelativeMatrix() * animController.CharacterBones[Character.WeaponBone].AbsoluteTransform
                : GetWeaponRelativeMatrix();

            ironsightMatrix.Translation = m_weaponIronsightTranslation;
            if (Character.CurrentWeapon is MyEngineerToolBase)
            {
                ironsightMatrix.Translation = m_toolIronsightTranslation;
            }
            // get weights of all state variants
            Vector4D variantWeights = UpdateAndGetWeaponVariantWeights(handItemDefinition);
            // interpolate matrices to get the resulting one
            MatrixD weaponMatrixLocal = variantWeights.X * standingMatrix
                                        + variantWeights.Y * walkingMatrix
                                        + variantWeights.Z * shootingMatrix
                                        + variantWeights.W * ironsightMatrix;

            weaponMatrixLocal = MatrixD.Normalize(weaponMatrixLocal);

            // weapon positioning - IK weight
            double weaponDataPosWeight = 0;

            if (handItemDefinition.ItemPositioning == MyItemPositioningEnum.TransformFromData && isInFirstPerson ||
                handItemDefinition.ItemPositioning3rd == MyItemPositioningEnum.TransformFromData && !isInFirstPerson)
            {
                weaponDataPosWeight += variantWeights.X;
            }
            if (handItemDefinition.ItemPositioningWalk == MyItemPositioningEnum.TransformFromData && isInFirstPerson ||
                handItemDefinition.ItemPositioningWalk3rd == MyItemPositioningEnum.TransformFromData && !isInFirstPerson)
            {
                weaponDataPosWeight += variantWeights.Y;
            }
            if (handItemDefinition.ItemPositioningShoot == MyItemPositioningEnum.TransformFromData && isInFirstPerson ||
                handItemDefinition.ItemPositioningShoot3rd == MyItemPositioningEnum.TransformFromData && !isInFirstPerson)
            {
                weaponDataPosWeight += variantWeights.Z;
            }

            weaponDataPosWeight += variantWeights.W;
            weaponDataPosWeight /= variantWeights.X + variantWeights.Y + variantWeights.Z + variantWeights.W;
            // now computing hand IK weight
            double armsIkWeight = 0;

            if (handItemDefinition.ItemPositioning != MyItemPositioningEnum.TransformFromAnim && isInFirstPerson ||
                handItemDefinition.ItemPositioning3rd != MyItemPositioningEnum.TransformFromAnim && !isInFirstPerson)
            {
                armsIkWeight += variantWeights.X;
            }
            if (handItemDefinition.ItemPositioningWalk != MyItemPositioningEnum.TransformFromAnim && isInFirstPerson ||
                handItemDefinition.ItemPositioningWalk3rd != MyItemPositioningEnum.TransformFromAnim && !isInFirstPerson)
            {
                armsIkWeight += variantWeights.Y;
            }
            if (handItemDefinition.ItemPositioningShoot != MyItemPositioningEnum.TransformFromAnim && isInFirstPerson ||
                handItemDefinition.ItemPositioningShoot3rd != MyItemPositioningEnum.TransformFromAnim && !isInFirstPerson)
            {
                armsIkWeight += variantWeights.Z;
            }
            armsIkWeight /= variantWeights.X + variantWeights.Y + variantWeights.Z + variantWeights.W;

            ApplyWeaponBouncing(handItemDefinition, ref weaponMatrixLocal, (float)(1.0 - 0.95 * variantWeights.W));

            // apply head transform on top of it
            if (!isInFirstPerson)
            {
                weaponMatrixPositioned.M43 += 0.5 * weaponMatrixLocal.M43 * Math.Max(0, weaponMatrixPositioned.M32);   // offset not to interfere with body
                weaponMatrixPositioned.M42 += 0.5 * weaponMatrixLocal.M42 * Math.Max(0, weaponMatrixPositioned.M32);   // offset not to interfere with body
            }

            MatrixD weaponMatrixPositionedLocal = weaponMatrixLocal * weaponMatrixPositioned;
            // displace sensor (maybe move to logical part? does not seem to be used at all)
            var characterWeaponEngToolBase = Character.CurrentWeapon as MyEngineerToolBase;

            if (characterWeaponEngToolBase != null)
            {
                characterWeaponEngToolBase.SensorDisplacement = -weaponMatrixLocal.Translation;
            }

            // mix plain animation with (anim+ik) result - for example, medieval uses plain animations
            double  ikRatio          = weaponDataPosWeight * m_currentAnimationToIkTime / m_animationToIKDelay;
            MatrixD weaponFinalWorld = MatrixD.Lerp(weaponAnimMatrix, weaponMatrixPositionedLocal, ikRatio) * Character.WorldMatrix;

            // propagate result to fields
            GraphicalPositionWorld = weaponFinalWorld.Translation;
            ArmsIkWeight           = (float)armsIkWeight;
            ((MyEntity)Character.CurrentWeapon).WorldMatrix = weaponFinalWorld;

            if (MyDebugDrawSettings.ENABLE_DEBUG_DRAW)
            {
                MyRenderProxy.DebugDrawAxis(weaponFinalWorld, 0.5f, false);
            }
        }
Beispiel #25
0
 public void UpdateAtmosphereSettings(MyAtmosphereSettings settings)
 {
     MyRenderProxy.UpdateAtmosphereSettings(m_renderObjectIDs[m_atmosphereRenderIndex], settings);
 }
 protected override void ValueChanged(MyGuiControlBase sender)
 {
     MyRenderProxy.SetSettingsDirty();
 }
Beispiel #27
0
        private void Create()
        {
            bool dedicated = Sandbox.Engine.Platform.Game.IsDedicated;

            Environment.SetEnvironmentVariable("SteamAppId", _appSteamId.ToString());
            var service = MySteamServiceWrapper.Init(dedicated, _appSteamId);

            MyServiceManager.Instance.AddService <IMyGameService>(service);
            var serviceInstance = MySteamUgcService.Create(_appSteamId, service);

            MyServiceManager.Instance.AddService <IMyUGCService>(serviceInstance);
            if (dedicated && !MyGameService.HasGameServer)
            {
                _log.Warn("Steam service is not running! Please reinstall dedicated server.");
                return;
            }

            SpaceEngineersGame.SetupBasicGameInfo();
            SpaceEngineersGame.SetupPerGameSettings();
            MyFinalBuildConstants.APP_VERSION       = MyPerGameSettings.BasicGameInfo.GameVersion;
            MySessionComponentExtDebug.ForceDisable = true;
            MyPerGameSettings.SendLogToKeen         = false;
            // SpaceEngineersGame.SetupAnalytics();

            MyFileSystem.ExePath = Path.GetDirectoryName(typeof(SpaceEngineersGame).Assembly.Location);

            _tweakGameSettings();

            MyFileSystem.Reset();
            MyInitializer.InvokeBeforeRun(_appSteamId, _appName, _userDataPath);
            // MyInitializer.InitCheckSum();


            // Hook into the VRage plugin system for updates.
            _getVRagePluginList().Add(_torch);

            if (!MySandboxGame.IsReloading)
            {
                MyFileSystem.InitUserSpecific(dedicated ? null : MyGameService.UserId.ToString());
            }
            MySandboxGame.IsReloading = dedicated;

            // render init
            {
                IMyRender renderer = null;
                if (dedicated)
                {
                    renderer = new MyNullRender();
                }
                else
                {
                    MyPerformanceSettings preset = MyGuiScreenOptionsGraphics.GetPreset(MyRenderQualityEnum.NORMAL);
                    MyRenderProxy.Settings.User = MyVideoSettingsManager.GetGraphicsSettingsFromConfig(ref preset, false)
                                                  .PerformanceSettings.RenderSettings;
                    MyStringId graphicsRenderer = MySandboxGame.Config.GraphicsRenderer;
                    if (graphicsRenderer == MySandboxGame.DirectX11RendererKey)
                    {
                        renderer = new MyDX11Render(new MyRenderSettings?(MyRenderProxy.Settings));
                        if (!renderer.IsSupported)
                        {
                            MySandboxGame.Log.WriteLine(
                                "DirectX 11 renderer not supported. No renderer to revert back to.");
                            renderer = null;
                        }
                    }
                    if (renderer == null)
                    {
                        throw new MyRenderException(
                                  "The current version of the game requires a Dx11 card. \\n For more information please see : http://blog.marekrosa.org/2016/02/space-engineers-news-full-source-code_26.html",
                                  MyRenderExceptionEnum.GpuNotSupported);
                    }
                    MySandboxGame.Config.GraphicsRenderer = graphicsRenderer;
                }
                MyRenderProxy.Initialize(renderer);
                MyRenderProfiler.SetAutocommit(false);
                //This broke services?
                //MyRenderProfiler.InitMemoryHack("MainEntryPoint");
            }

            // Loads object builder serializers. Intuitive, right?
            _log.Info("Setting up serializers");
            MyPlugins.RegisterGameAssemblyFile(MyPerGameSettings.GameModAssembly);
            if (MyPerGameSettings.GameModBaseObjBuildersAssembly != null)
            {
                MyPlugins.RegisterBaseGameObjectBuildersAssemblyFile(MyPerGameSettings.GameModBaseObjBuildersAssembly);
            }
            MyPlugins.RegisterGameObjectBuildersAssemblyFile(MyPerGameSettings.GameModObjBuildersAssembly);
            MyPlugins.RegisterSandboxAssemblyFile(MyPerGameSettings.SandboxAssembly);
            MyPlugins.RegisterSandboxGameAssemblyFile(MyPerGameSettings.SandboxGameAssembly);
            //typeof(MySandboxGame).GetMethod("Preallocate", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, null);
            MyGlobalTypeMetadata.Static.Init(false);
        }
        private static void DrawMountPointsAxisHelpers(MyCubeBlockDefinition def, ref MatrixD drawMatrix, float cubeSize)
        {
            Vector3I centerGrid   = def.Center;
            Vector3  centerOffset = def.Size * 0.5f;

            MatrixD drawTransf = MatrixD.CreateTranslation(centerGrid - centerOffset) * MatrixD.CreateScale(cubeSize) * drawMatrix;

            // Draw axis helpers for the six mount point walls
            for (int i = 0; i < 6; ++i)
            {
                Base6Directions.Direction dir = (Base6Directions.Direction)i;

                Vector3D position = Vector3D.Zero;
                position.Z = -0.2f;

                Vector3D normal = Vector3.Forward;
                Vector3D right  = Vector3.Right;
                Vector3D up     = Vector3.Up;

                position = def.MountPointLocalToBlockLocal(position, dir);
                position = Vector3D.Transform(position, drawTransf);

                normal = def.MountPointLocalNormalToBlockLocal(normal, dir);
                normal = Vector3D.TransformNormal(normal, drawTransf);

                up = def.MountPointLocalNormalToBlockLocal(up, dir);
                up = Vector3D.TransformNormal(up, drawTransf);

                right = def.MountPointLocalNormalToBlockLocal(right, dir);
                right = Vector3D.TransformNormal(right, drawTransf);

                MatrixD rightMat = MatrixD.CreateWorld(position + right * 0.25f, normal, right);
                MatrixD upMat    = MatrixD.CreateWorld(position + up * 0.25f, normal, up);
                Vector4 rc       = Color.Red.ToVector4();
                Vector4 uc       = Color.Green.ToVector4();

                MyRenderProxy.DebugDrawSphere(position, 0.03f * cubeSize, Color.Red.ToVector3(), 1.0f, true);
                MySimpleObjectDraw.DrawTransparentCylinder(ref rightMat, 0.0f, 0.03f * cubeSize, 0.5f * cubeSize, ref rc, false, 16, 0.01f * cubeSize);
                MySimpleObjectDraw.DrawTransparentCylinder(ref upMat, 0.0f, 0.03f * cubeSize, 0.5f * cubeSize, ref uc, false, 16, 0.01f * cubeSize);
                MyRenderProxy.DebugDrawLine3D(position, position - normal * 0.2f, Color.Red, Color.Red, true);

                float textSizeX    = 0.5f * cubeSize;
                float textSizeY    = 0.5f * cubeSize;
                float textSizeDesc = 0.5f * cubeSize;
                if (MySector.MainCamera != null)
                {
                    float distX    = (float)(position + right * 0.55f - MySector.MainCamera.Position).Length();
                    float distY    = (float)(position + up * 0.55f - MySector.MainCamera.Position).Length();
                    float distDesc = (float)(position + normal * 0.1f - MySector.MainCamera.Position).Length();
                    textSizeX    = textSizeX * 6 / distX;
                    textSizeY    = textSizeY * 6 / distY;
                    textSizeDesc = textSizeDesc * 6 / distDesc;
                }

                MyRenderProxy.DebugDrawText3D(position + right * 0.55f, "X", Color.Red, textSizeX, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER);
                MyRenderProxy.DebugDrawText3D(position + up * 0.55f, "Y", Color.Green, textSizeY, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER);
                MyRenderProxy.DebugDrawText3D(position + normal * 0.1f, m_mountPointSideNames[i], Color.White, textSizeDesc, true, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER);
            }

            // If close enough, draw a black grid spaced by tenths of a mount point unit
            float        dist = (float)(drawTransf.Translation - MySector.MainCamera.Position).Length();
            BoundingBoxD bb   = new BoundingBoxD(-def.Size * cubeSize * 0.5f, def.Size * cubeSize * 0.5f);

            dist -= (float)bb.Size.Max() * 0.866f; // sqrt(3) * 0.5 - half of the solid diagonal of a cube
            Color black = Color.Black;

            if (dist < cubeSize * 3.0f)
            {
                MySimpleObjectDraw.DrawTransparentBox(ref drawMatrix, ref bb, ref black, MySimpleObjectRasterizer.Wireframe, def.Size * 10, 0.005f / (float)bb.Size.Max() * cubeSize, onlyFrontFaces: true);
            }
        }
Beispiel #29
0
        public static void TestGPUParticles()
        {
            if (VRage.Input.MyInput.Static.IsAnyShiftKeyPressed())
            {
                if (gid0 == 0)
                {
                    gid0 = MyRenderProxy.CreateGPUEmitter();
                    gid1 = MyRenderProxy.CreateGPUEmitter();
                }
                var Position = MyTransparentGeometry.Camera.Translation;
                var emitters = new MyGPUEmitter[2];
                // sparks
                emitters[0].GID = gid0;
                emitters[0].ParticlesPerSecond = 30000.0f;
                emitters[0].Data.Color0        = new Vector4(1.0f, 1.0f, 0.0f, 1f);
                emitters[0].Data.Color1        = new Vector4(1.0f, 0.0f, 0.0f, 1f);
                emitters[0].Data.Color2        = new Vector4(1.0f, 0.0f, 0.0f, 0.0f);
                emitters[0].Data.ColorKey1     = 0.5f;
                emitters[0].Data.ColorKey2     = 1.0f;
                emitters[0].Data.AlphaKey1     = 0.95f;
                emitters[0].Data.AlphaKey2     = 1.0f;
                emitters[0].Data.Bounciness    = 0.4f;
                emitters[0].Data.Velocity      = new Vector3(0.0f, 0.0f, -1.0f);
                emitters[0].Data.NumParticlesToEmitThisFrame = 0;
                emitters[0].Data.ParticleLifeSpan            = 9.0f;
                emitters[0].Data.Size0                     = 0.02f;
                emitters[0].Data.Size1                     = 0.016f;
                emitters[0].Data.Size2                     = 0.0f;
                emitters[0].Data.SizeKeys1                 = 0.95f;
                emitters[0].Data.SizeKeys2                 = 1.0f;
                emitters[0].Data.PositionVariance          = new Vector3(0.1f, 0.1f, 0.1f);
                emitters[0].Data.VelocityVariance          = 0.4f;
                emitters[0].Data.RotationVelocity          = 0;
                emitters[0].Data.Acceleration              = new Vector3(0, 0, -0.98f);
                emitters[0].Data.StreakMultiplier          = 4.0f;
                emitters[0].Data.Flags                     = GPUEmitterFlags.Streaks | GPUEmitterFlags.Collide | GPUEmitterFlags.SleepState;
                emitters[0].Data.SoftParticleDistanceScale = 5;
                emitters[0].Data.AnimationFrameTime        = 1.0f;
                emitters[0].Data.OITWeightFactor           = 0.3f;
                emitters[0].AtlasTexture                   = "Textures\\Particles\\gpuAtlas0.dds";
                emitters[0].AtlasDimension                 = new Vector2I(2, 1);
                emitters[0].AtlasFrameOffset               = 1;
                emitters[0].AtlasFrameModulo               = 1;
                emitters[0].WorldPosition                  = Position + new Vector3D(8.0f, 0.0f, 8.0f);

                // smoke
                emitters[1].GID = gid1;
                emitters[1].ParticlesPerSecond = 100.0f;
                emitters[1].Data.Color0        = new Vector4(0.5f, 0.5f, 0.5f, 1.0f);
                emitters[1].Data.Color1        = new Vector4(0.6f, 0.6f, 0.65f, 1.0f);
                emitters[1].Data.Color2        = new Vector4(0.6f, 0.6f, 0.65f, 0.0f);
                emitters[1].Data.ColorKey1     = 0.5f;
                emitters[1].Data.ColorKey2     = 1.0f;
                emitters[1].Data.AlphaKey1     = 0.95f;
                emitters[1].Data.AlphaKey2     = 1.0f;
                emitters[1].Data.Velocity      = new Vector3(0, 0, 1.0f);
                emitters[1].Data.NumParticlesToEmitThisFrame = 0;
                emitters[1].Data.ParticleLifeSpan            = 150.0f;
                emitters[1].Data.Size0                     = 0.50f;
                emitters[1].Data.Size1                     = 2.2f;
                emitters[1].Data.SizeKeys1                 = 1.0f;
                emitters[1].Data.SizeKeys2                 = 1.0f;
                emitters[1].Data.PositionVariance          = new Vector3(0.2f, 0.2f, 0.2f);
                emitters[1].Data.VelocityVariance          = 0.3f;
                emitters[1].Data.RotationVelocity          = 100.0f;
                emitters[1].Data.Acceleration              = new Vector3(0.00707f, 0.00707f, -0.00003f * 9.8f);
                emitters[1].Data.Flags                     = GPUEmitterFlags.Light | GPUEmitterFlags.VolumetricLight;
                emitters[1].Data.SoftParticleDistanceScale = 2;
                emitters[1].Data.AnimationFrameTime        = 1.0f;
                emitters[1].Data.OITWeightFactor           = 1.0f;
                emitters[1].AtlasTexture                   = "Textures\\Particles\\gpuAtlas1.dds";
                emitters[1].AtlasDimension                 = new Vector2I(2, 1);
                emitters[1].AtlasFrameOffset               = 0;
                emitters[1].AtlasFrameModulo               = 1;
                emitters[1].WorldPosition                  = Position + new Vector3D(2.0f, 0.0f, 1.0f);
                MyRenderProxy.UpdateGPUEmitters(emitters);
            }
        }
Beispiel #30
0
 public MyCpuFrustumCullPass At(int index)
 {
     MyRenderProxy.Assert(index < Count);
     return(m_passes[index]);
 }