Exemplo n.º 1
0
        public MyMultiplayerServerBase(MySyncLayer syncLayer)
            : base(syncLayer)
        {
            var replication = new MyReplicationServer(this, () => MySandboxGame.Static.UpdateTime);

            if (MyFakes.MULTIPLAYER_REPLICATION_TEST)
            {
                replication.MaxSleepTime = MyTimeSpan.FromSeconds(30);
            }
            SetReplicationLayer(replication);
            ClientLeft += (steamId, e) => ReplicationLayer.OnClientLeft(new EndpointId(steamId));

            MyEntities.OnEntityCreate      += CreateReplicableForObject;
            MyInventory.OnCreated          += CreateReplicableForObject;
            MyExternalReplicable.Destroyed += DestroyReplicable;

            foreach (var entity in MyEntities.GetEntities())
            {
                CreateReplicableForObject(entity);
            }

            syncLayer.TransportLayer.Register(MyMessageId.RPC, ReplicationLayer.ProcessEvent);
            syncLayer.TransportLayer.Register(MyMessageId.REPLICATION_READY, ReplicationLayer.ReplicableReady);
            syncLayer.TransportLayer.Register(MyMessageId.CLIENT_UPDATE, ReplicationLayer.OnClientUpdate);
            syncLayer.TransportLayer.Register(MyMessageId.CLIENT_READY, (p) => ReplicationLayer.OnClientReady(p.Sender, new MyClientState()));
        }
Exemplo n.º 2
0
        static void GatherFrame(MyFrameProfiling frame)
        {
            QueryDataTimestampDisjoint disjoint = MyImmediateRC.RC.GetData <QueryDataTimestampDisjoint>(frame.m_disjoint.m_query, AsynchronousFlags.DoNotFlush);

#if UNSHARPER
            if (!disjoint.Disjoint.value)
#else
            if (!disjoint.Disjoint)
#endif
            {
                var    freq    = disjoint.Frequency;
                double invFreq = 1.0 / (double)freq;

                m_timestampStack.Clear();

                int stackDepth = 0;

                while (frame.m_issued.Count > 0)
                {
                    var q = frame.m_issued.Dequeue();

                    ulong timestamp;
                    MyImmediateRC.RC.GetData <ulong>(q.m_query, AsynchronousFlags.DoNotFlush, out timestamp);

                    if (q.m_info == MyIssuedQueryEnum.BlockStart)
                    {
                        stackDepth++;
                        MyRender11.GetRenderProfiler().GPU_StartProfilingBlock(q.m_tag);
                        MySimpleProfiler.BeginGPUBlock(q.m_tag);
                        m_timestampStack.Push(timestamp);
                    }
                    else if (q.m_info == MyIssuedQueryEnum.BlockEnd)
                    {
                        stackDepth--;
                        var start = m_timestampStack.Pop();
                        var time  = (timestamp - start) * invFreq;

                        // tick is 100 nanoseconds = 10^-7 second
                        MyRender11.GetRenderProfiler().GPU_EndProfilingBlock(0, MyTimeSpan.FromSeconds(time));
                        MySimpleProfiler.EndGPUBlock(MyTimeSpan.FromSeconds(time));
                    }

                    Debug.Assert(stackDepth >= 0);

                    MyQueryFactory.RelaseTimestampQuery(q.m_query);
                }

                Debug.Assert(stackDepth == 0);
            }

            frame.Clear();
        }
Exemplo n.º 3
0
        internal void StopShooting(float hitDelaySec)
        {
            if (!IsShooting)
                return;

            m_lastHit = MySandboxGame.Static.UpdateTime;
            m_hitDelay = MyTimeSpan.FromSeconds(hitDelaySec);

            m_owner.PlayCharacterAnimation(m_shotHitCondition.Animation, MyBlendOption.Immediate, MyFrameOption.JustFirstFrame, 0.2f, m_shotHitCondition.AnimationTimeScale, false, null, true);
            m_shotToolAction = null;

            m_wasShooting = false;
        }
        public void RemoveFracturePiece(MyFracturedPiece piece, float blendTimeSeconds, bool fromServer = false, bool sync = true)
        {
            System.Diagnostics.Debug.Assert(Sync.IsServer || fromServer, "Clients cannot remove pieces by themselves");
            System.Diagnostics.Debug.Assert((sync && Sync.IsServer) ^ (fromServer && !sync), "Sync must be called on server.");
            if (blendTimeSeconds == 0)
            {
                Debug.Assert((Sync.IsServer && sync) || fromServer, "Server must sync Fracture Piece removal!");

                RemoveInternal(piece);
                return;
            }

            MyTimeSpan newDeath = MySandboxGame.Static.UpdateTime + MyTimeSpan.FromSeconds(blendTimeSeconds);

            if (m_blendingPieces.Add(piece))
            {
                if (!m_piecesTimesOfDeath.ContainsKey(piece))
                {
                    Debug.Assert(fromServer, "Fracture piece missing time of death on server!");
                    m_piecesTimesOfDeath.Add(piece, newDeath);
                }

                MyTimeSpan currentDeath;
                if (m_piecesTimesOfDeath.TryGetValue(piece, out currentDeath))
                {
                    if (currentDeath > newDeath)
                    {
                        m_piecesTimesOfDeath[piece] = newDeath;
                    }
                }
                else
                {
                    Debug.Fail("Fracture Piece missing time of death!");
                }
            }
            else
            {
                MyTimeSpan currentDeath;
                if (m_piecesTimesOfDeath.TryGetValue(piece, out currentDeath))
                {
                    if (currentDeath > newDeath)
                    {
                        m_piecesTimesOfDeath[piece] = newDeath;
                    }
                }
                else
                {
                    Debug.Assert(false, "Shouldnt get here");
                }
            }
        }
 private void SetHealth(float health)
 {
     if (health < 20)
     {
         //play heavy breath indefinitely
         m_healthOverride = MyTimeSpan.MaxValue;
     }
     else
     if (health < 100)
     {
         m_healthOverride = MySandboxGame.Static.UpdateTime + MyTimeSpan.FromSeconds(300 / (health - 19.99));
     }
     Update(true);
 }
Exemplo n.º 6
0
 private MyTimeSpan RequiredInactivity(MyStatTypeEnum type)
 {
     if ((type & MyStatTypeEnum.DontDisappearFlag) == MyStatTypeEnum.DontDisappearFlag)
     {
         return(MyTimeSpan.MaxValue);
     }
     else if ((type & MyStatTypeEnum.KeepInactiveLongerFlag) == MyStatTypeEnum.KeepInactiveLongerFlag)
     {
         return(MyTimeSpan.FromSeconds(30));
     }
     else
     {
         return(MyTimeSpan.FromSeconds(3));
     }
 }
        protected MyBehaviorTreeState TryReserveAreaAroundEntity([BTParam] string areaName, [BTParam] float radius, [BTParam] int timeMs)
        {
            var logic = Bot.HumanoidLogic;
            MyBehaviorTreeState retStatus = MyBehaviorTreeState.FAILURE;

            if (logic != null)
            {
                switch (logic.ReservationStatus)
                {
                case Logic.MyReservationStatus.NONE:
                    logic.ReservationStatus   = Logic.MyReservationStatus.WAITING;
                    logic.ReservationAreaData = new MyAiTargetManager.ReservedAreaData()
                    {
                        WorldPosition    = Bot.HumanoidEntity.WorldMatrix.Translation,
                        Radius           = radius,
                        ReservationTimer = MyTimeSpan.FromMiliseconds(timeMs),
                        ReserverId       = new World.MyPlayer.PlayerId(Bot.Player.Id.SteamId, Bot.Player.Id.SerialId)
                    };
                    MyAiTargetManager.OnAreaReservationResult += AreaReservationHandler;
                    MyAiTargetManager.Static.RequestAreaReservation(areaName, Bot.HumanoidEntity.WorldMatrix.Translation, radius, timeMs, Bot.Player.Id.SerialId);
                    m_reservationTimeOut    = MySandboxGame.Static.UpdateTime + MyTimeSpan.FromSeconds(RESERVATION_WAIT_TIMEOUT_SECONDS);
                    logic.ReservationStatus = Logic.MyReservationStatus.WAITING;
                    retStatus = MyBehaviorTreeState.RUNNING;
                    break;

                case Logic.MyReservationStatus.SUCCESS:
                    retStatus = MyBehaviorTreeState.SUCCESS;
                    break;

                case Logic.MyReservationStatus.FAILURE:
                    retStatus = MyBehaviorTreeState.FAILURE;
                    break;

                case Logic.MyReservationStatus.WAITING:
                    if (m_reservationTimeOut < MySandboxGame.Static.UpdateTime)
                    {
                        retStatus = MyBehaviorTreeState.FAILURE;
                    }
                    else
                    {
                        retStatus = MyBehaviorTreeState.RUNNING;
                    }
                    break;
                }
            }
            return(retStatus);
        }
Exemplo n.º 8
0
        MyTimeSpan GetPieceAgeLength(MyFracturedPiece piece)
        {
            if (piece.Physics == null || piece.Physics.BreakableBody == null)
            {
                return(MyTimeSpan.Zero);
            }

            if (piece.Physics.RigidBody.Layer == FakePieceLayer)
            {
                return(MyTimeSpan.FromSeconds(8 + MyRandom.Instance.NextFloat(0, 4)));
            }

            float volume            = piece.Physics.BreakableBody.BreakableShape.Volume;
            float proposedAgeInSecs = volume * LIFE_OF_CUBIC_PIECE;

            return(MyTimeSpan.FromSeconds(proposedAgeInSecs));
        }
Exemplo n.º 9
0
        public static void Write()
        {
            FileMaster master = new FileMaster("Profiler master.txt", "Profiler - ", 10);

            System.IO.TextWriter writer = master.GetTextWriter(DateTime.UtcNow.Ticks + ".csv");
            writer.WriteLine("Class Name, Method Name, Seconds, Invokes, Seconds per Invoke, Worst Time, Ratio of Sum, Ratio of Game Time");

            using (ProfileValues.m_lock.AcquireExclusiveUsing())
            {
                WriteBlock(writer, "Game Time,", new Stats()
                {
                    TimeSpent = MyTimeSpan.FromSeconds(Globals.ElapsedTime.TotalSeconds)
                });
                WriteBlock(writer, "Sum,", ProfileValues.m_total);
                foreach (var pair in ProfileValues.m_profile)
                {
                    WriteBlock(writer, pair.Key, pair.Value);
                }
            }

            writer.Close();
        }
        /// <summary>
        /// Initializes a new instance of the MyMultiplayerServerBase class.
        /// </summary>
        /// <param name="localClientEndpoint">Local client endpoint (for single player or lobby host) or null (for dedicated server)</param>
        public MyMultiplayerServerBase(MySyncLayer syncLayer, EndpointId?localClientEndpoint)
            : base(syncLayer)
        {
            Debug.Assert(MyEntities.GetEntities().Count == 0, "Multiplayer server must be created before any entities are loaded!");

            var replication = new MyReplicationServer(this, localClientEndpoint, MyFakes.MULTIPLAYER_USE_PLAYOUT_DELAY_BUFFER);

            if (MyFakes.MULTIPLAYER_REPLICATION_TEST)
            {
                replication.MaxSleepTime = MyTimeSpan.FromSeconds(30);
            }
            SetReplicationLayer(replication);
            ClientLeft   += (steamId, e) => ReplicationLayer.OnClientLeft(new EndpointId(steamId));
            ClientJoined += (steamId) => ReplicationLayer.OnClientJoined(new EndpointId(steamId), CreateClientState());

            MyEntities.OnEntityCreate += CreateReplicableForObject;
            MyEntityComponentBase.OnAfterAddedToContainer += CreateReplicableForObject;
            MyExternalReplicable.Destroyed += DestroyReplicable;

            foreach (var entity in MyEntities.GetEntities())
            {
                CreateReplicableForObject(entity);
                var components = entity.Components;
                if (components != null)
                {
                    foreach (var comp in components)
                    {
                        CreateReplicableForObject(comp);
                    }
                }
            }

            syncLayer.TransportLayer.Register(MyMessageId.RPC, ReplicationLayer.ProcessEvent);
            syncLayer.TransportLayer.Register(MyMessageId.REPLICATION_READY, ReplicationLayer.ReplicableReady);
            syncLayer.TransportLayer.Register(MyMessageId.CLIENT_UPDATE, ReplicationLayer.OnClientUpdate);
            syncLayer.TransportLayer.Register(MyMessageId.CLIENT_ACKS, ReplicationLayer.OnClientAcks);
            syncLayer.TransportLayer.Register(MyMessageId.CLIENT_READY, ClientReady);
        }
Exemplo n.º 11
0
        private void UpdateManipulation()
        {
            if (m_state != MyState.NONE && SafeConstraint != null)
            {
                const float fixedConstraintMaxValue    = 1000;
                const float fixedConstraintMaxDistance = 2f;
                const float ballAndSocketMaxDistance   = 2f;

                MyTimeSpan constraintPrepareTime = MyTimeSpan.FromSeconds(1.0f);
                MyTimeSpan currentTimeDelta      = MySandboxGame.Static.UpdateTime - m_constraintCreationTime;

                MatrixD headWorldMatrix       = Owner.GetHeadMatrix(false, forceHeadBone: true);
                MatrixD worldHeadPivotMatrix  = m_headLocalPivotMatrix * headWorldMatrix;
                MatrixD worldOtherPivotMatrix = m_otherLocalPivotMatrix * m_otherEntity.PositionComp.WorldMatrix;

                double length   = (worldOtherPivotMatrix.Translation - worldHeadPivotMatrix.Translation).Length();
                double checkDst = m_fixedConstraintData != null ? fixedConstraintMaxDistance : ballAndSocketMaxDistance;

                if (currentTimeDelta > constraintPrepareTime)
                {
                    var  characterMovementState = Owner.GetCurrentMovementState();
                    bool currentCanUseIdle      = CanManipulate(characterMovementState);
                    bool previousCanUseIdle     = CanManipulate(m_previousCharacterMovementState);

                    if ((!m_constraintInitialized && currentCanUseIdle) || (currentCanUseIdle && !previousCanUseIdle))
                    {
                        if (m_state == MyState.HOLD)
                        {
                            Owner.PlayCharacterAnimation("PickLumberIdle", MyBlendOption.Immediate, MyFrameOption.Loop, 0.2f, 1f);
                        }
                        else
                        {
                            Owner.PlayCharacterAnimation("PullLumberIdle", MyBlendOption.Immediate, MyFrameOption.Loop, 0.2f, 1f);
                        }
                    }

                    m_previousCharacterMovementState = characterMovementState;

                    m_constraintInitialized = true;

                    if (m_otherRigidBody != null && !MyFakes.MANIPULATION_TOOL_VELOCITY_LIMIT)
                    {
                        m_otherRigidBody.MaxLinearVelocity  = m_otherMaxLinearVelocity;
                        m_otherRigidBody.MaxAngularVelocity = m_otherMaxAngularVelocity;
                    }

                    if (m_fixedConstraintData != null && (MyScreenManager.GetScreenWithFocus() is MyGuiScreenGamePlay))
                    {
                        float rotationSpeed = MyInput.Static.IsAnyShiftKeyPressed() ? -0.01f : 0.01f;
                        var   tran          = m_otherLocalPivotMatrix.Translation;
                        if (MyInput.Static.IsKeyPress(MyKeys.E))
                        {
                            m_otherLocalPivotMatrix             = m_otherLocalPivotMatrix * Matrix.CreateFromAxisAngle(Vector3.Up, rotationSpeed);
                            m_otherLocalPivotMatrix.Translation = tran;
                            m_fixedConstraintData.SetInBodySpace(m_otherLocalPivotMatrix, m_headLocalPivotMatrix, m_otherPhysicsBody, OwnerVirtualPhysics);
                        }
                        if (MyInput.Static.IsKeyPress(MyKeys.Q))
                        {
                            m_otherLocalPivotMatrix             = m_otherLocalPivotMatrix * Matrix.CreateFromAxisAngle(Vector3.Forward, rotationSpeed);
                            m_otherLocalPivotMatrix.Translation = tran;
                            m_fixedConstraintData.SetInBodySpace(m_otherLocalPivotMatrix, m_headLocalPivotMatrix, m_otherPhysicsBody, OwnerVirtualPhysics);
                        }
                        if (MyInput.Static.IsKeyPress(MyKeys.R))
                        {
                            m_otherLocalPivotMatrix             = m_otherLocalPivotMatrix * Matrix.CreateFromAxisAngle(Vector3.Right, rotationSpeed);
                            m_otherLocalPivotMatrix.Translation = tran;
                            m_fixedConstraintData.SetInBodySpace(m_otherLocalPivotMatrix, m_headLocalPivotMatrix, m_otherPhysicsBody, OwnerVirtualPhysics);
                        }
                    }

                    if (m_fixedConstraintData != null && !MyFakes.MANIPULATION_TOOL_VELOCITY_LIMIT)
                    {
                        m_fixedConstraintData.MaximumAngularImpulse = fixedConstraintMaxValue;
                        m_fixedConstraintData.MaximumLinearImpulse  = fixedConstraintMaxValue;

                        // Check angle between pivots
                        float upDot    = Math.Abs(Vector3.Dot(worldHeadPivotMatrix.Up, worldOtherPivotMatrix.Up));
                        float rightDot = Math.Abs(Vector3.Dot(worldHeadPivotMatrix.Right, worldOtherPivotMatrix.Right));
                        if (upDot < 0.5f || rightDot < 0.5f)
                        {
                            // Synced from local player because lagged server can drop manipulated items with fast moves
                            if (!(m_otherEntity is MyCharacter) && IsOwnerLocalPlayer())
                            {
                                SyncTool.StopManipulation();
                            }

                            return;
                        }
                    }

                    // Check length between pivots
                    if (length > checkDst)
                    {
                        // Synced from local player because lagged server can drop manipulated items with fast moves
                        if (!(m_otherEntity is MyCharacter) && IsOwnerLocalPlayer())
                        {
                            SyncTool.StopManipulation();
                        }

                        return;
                    }
                }
                else
                {
                    if (m_fixedConstraintData != null && !MyFakes.MANIPULATION_TOOL_VELOCITY_LIMIT)
                    {
                        float t = (float)(currentTimeDelta.Miliseconds / constraintPrepareTime.Miliseconds);
                        t *= t;
                        t *= t; //pow4
                        float value = t * fixedConstraintMaxValue;
                        m_fixedConstraintData.MaximumAngularImpulse = value;
                        m_fixedConstraintData.MaximumLinearImpulse  = value;

                        if (length > checkDst)
                        {
                            var characterMovementState = Owner.GetCurrentMovementState();
                            if (!CanManipulate(characterMovementState))
                            {
                                // Synced from local player because lagged server can drop manipulated items with fast moves
                                if (!(m_otherEntity is MyCharacter) && IsOwnerLocalPlayer())
                                {
                                    SyncTool.StopManipulation();
                                }

                                return;
                            }
                        }
                    }
                }
            }
        }
        public override void UpdateAfterSimulation()
        {
            CheckConsistency();

            m_addedThisFrame = 0;
            base.UpdateAfterSimulation();

            foreach (var body in m_tmpToReturn)
            {
                ReturnToPoolInternal(body);
            }
            m_tmpToReturn.Clear();

            if (Sync.IsServer)
            {
                foreach (var piece in m_piecesTimesOfDeath)
                {
                    Debug.Assert(piece.Key.Physics == null || !piece.Key.Physics.RigidBody.IsDisposed, "Disposed piece rigid body!!");
                    if (piece.Value <= MySandboxGame.Static.UpdateTime + MyTimeSpan.FromSeconds(BLEND_TIME))
                    {
                        RemoveFracturePiece(piece.Key, BLEND_TIME);
                    }
                }

                int currentFracturedPiecesCount = m_piecesTimesOfDeath.Count - m_blendingPieces.Count;
                var maxFracturePieces           = MySession.Static.Settings.MaxActiveFracturePieces;
                if (currentFracturedPiecesCount > maxFracturePieces)
                {
                    m_tmpFracturesList.AddHashset(m_inactivePieces);
                    m_tmpFracturesList.Sort(m_fracturedPieceAgeComparer);

                    foreach (var piece in m_tmpFracturesList)
                    {
                        if (currentFracturedPiecesCount <= maxFracturePieces)
                        {
                            break;
                        }
                        if (m_blendingPieces.Contains(piece))
                        {
                            continue;
                        }
                        RemoveFracturePiece(piece, BLEND_TIME);
                        currentFracturedPiecesCount--;
                    }
                    m_tmpFracturesList.Clear();

                    if (currentFracturedPiecesCount > maxFracturePieces)
                    {
                        m_tmpFracturesList.AddRange(m_piecesTimesOfDeath.Keys);
                        m_tmpFracturesList.Sort(m_fracturedPieceAgeComparer);

                        foreach (var piece in m_tmpFracturesList)
                        {
                            if (currentFracturedPiecesCount <= maxFracturePieces)
                            {
                                break;
                            }
                            if (m_blendingPieces.Contains(piece) || m_inactivePieces.Contains(piece))
                            {
                                continue;
                            }
                            m_tmpToRemove.Add(piece);
                            currentFracturedPiecesCount--;
                        }

                        m_tmpFracturesList.Clear();
                    }

                    foreach (var piece in m_tmpToRemove)
                    {
                        RemoveFracturePiece(piece, BLEND_TIME);
                    }
                    m_tmpToRemove.Clear();
                }
            }

            foreach (var piece in m_blendingPieces)
            {
                float blend = (float)(m_piecesTimesOfDeath[piece] - MySandboxGame.Static.UpdateTime).Seconds / BLEND_TIME;

                foreach (var id in piece.Render.RenderObjectIDs)
                {
                    VRageRender.MyRenderProxy.UpdateRenderEntity(
                        id,
                        null,
                        null,
                        1 - blend);
                }
                if (Sync.IsServer && m_piecesTimesOfDeath[piece] <= MySandboxGame.Static.UpdateTime)
                {
                    m_tmpToRemove.Add(piece);
                }
            }

            foreach (var fp in m_tmpToRemove)
            {
                Debug.Assert(Sync.IsServer);
                RemoveInternal(fp);
            }
            m_tmpToRemove.Clear();

            ProfilerShort.Begin("Allocate");
            while (m_bodyPool.Count < PREALLOCATE_BODIES && m_allocatedThisFrame < MAX_ALLOC_PER_FRAME)
            {
                m_bodyPool.Enqueue(AllocateBodies());
            }

            while (m_piecesPool.Count < PREALLOCATE_PIECES && m_allocatedThisFrame < MAX_ALLOC_PER_FRAME)
            {
                m_piecesPool.Enqueue(AllocatePiece());
            }
            ProfilerShort.End();
            m_allocatedThisFrame = 0;
        }
Exemplo n.º 13
0
        internal void FinalizeEnvProbes()
        {
            if (MyRender11.IsIntelBrokenCubemapsWorkaround)
            {
                return;
            }

            ProfilerShort.Begin("FinalizeEnvProbes");
            MyGpuProfiler.IC_BeginBlock("FinalizeEnvProbes");
            if (m_lastUpdateTime == MyTimeSpan.Zero)
            {
                for (int i = 0; i < 6; i++)
                {
                    PostprocessProbe(i);
                }

                MyGpuProfiler.IC_BeginBlock("BuildMipmaps");
                MyEnvProbeProcessing.BuildMipmaps(m_workCubemap);
                MyGpuProfiler.IC_EndBlock();

                MyGpuProfiler.IC_BeginBlock("Prefilter");
                MyEnvProbeProcessing.Prefilter(m_workCubemap, m_workCubemapPrefiltered);
                MyGpuProfiler.IC_EndBlock();

                MyGpuProfiler.IC_BeginBlock("CopyResource");
                MyImmediateRC.RC.CopyResource(m_workCubemapPrefiltered, m_prevWorkCubemapPrefiltered);
                MyImmediateRC.RC.CopyResource(m_workCubemapPrefiltered, Cubemap);
                MyGpuProfiler.IC_EndBlock();

                m_lastUpdateTime = MyRender11.CurrentDrawTime;
            }
            else
            {
                if (m_state >= 6 && m_state < 12)
                {
                    PostprocessProbe(m_state - 6);
                }
                else if (m_state >= 12)
                {
                    MyGpuProfiler.IC_BeginBlock("BlendAllProbes");
                    BlendAllProbes();
                    MyGpuProfiler.IC_EndBlock();
                }

                if (m_state == 12)
                {
                    MyGpuProfiler.IC_BeginBlock("BuildMipmaps");
                    m_lastUpdateTime = MyRender11.CurrentDrawTime;
                    // whole cubemap is rendered and postprocessed, we can use it
                    MyEnvProbeProcessing.BuildMipmaps(m_workCubemap);
                    MyGpuProfiler.IC_EndBlock();

                    MyGpuProfiler.IC_BeginBlock("Prefilter");
                    MyEnvProbeProcessing.Prefilter(m_workCubemap, m_workCubemapPrefiltered);
                    MyGpuProfiler.IC_EndBlock();
                }

                m_state++;
                MyTimeSpan timeForNextCubemap = m_lastUpdateTime +
                                                MyTimeSpan.FromSeconds(MyEnvironmentProbe.MAX_BLEND_TIME_S);
                if (m_state > 12 && MyRender11.CurrentDrawTime > timeForNextCubemap)
                {
                    m_state = 0; // Time is up, we need to render another environment map
                }
            }
            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();
        }
Exemplo n.º 14
0
        protected MyBehaviorTreeState TryReserveEntity([BTIn] ref MyBBMemoryTarget inTarget, [BTParam] int timeMs)
        {
            if ((this.Bot != null) && (this.Bot.Player != null))
            {
                MyHumanoidBotLogic humanoidLogic = this.Bot.HumanoidLogic;
                if (((inTarget != null) && ((inTarget.EntityId != null) && (inTarget.TargetType != MyAiTargetEnum.POSITION))) && (inTarget.TargetType != MyAiTargetEnum.NO_TARGET))
                {
                    switch (humanoidLogic.ReservationStatus)
                    {
                    case MyReservationStatus.NONE:
                        MyAiTargetManager.ReservedEntityData data;
                        switch (inTarget.TargetType)
                        {
                        case MyAiTargetEnum.GRID:
                        case MyAiTargetEnum.CUBE:
                        case MyAiTargetEnum.CHARACTER:
                        case MyAiTargetEnum.ENTITY:
                            humanoidLogic.ReservationStatus = MyReservationStatus.WAITING;
                            data = new MyAiTargetManager.ReservedEntityData {
                                Type             = MyReservedEntityType.ENTITY,
                                EntityId         = inTarget.EntityId.Value,
                                ReservationTimer = timeMs,
                                ReserverId       = new MyPlayer.PlayerId(this.Bot.Player.Id.SteamId, this.Bot.Player.Id.SerialId)
                            };
                            humanoidLogic.ReservationEntityData    = data;
                            MyAiTargetManager.OnReservationResult += new Sandbox.Game.AI.MyAiTargetManager.ReservationHandler(this.ReservationHandler);
                            MyAiTargetManager.Static.RequestEntityReservation(humanoidLogic.ReservationEntityData.EntityId, humanoidLogic.ReservationEntityData.ReservationTimer, this.Bot.Player.Id.SerialId);
                            break;

                        case MyAiTargetEnum.ENVIRONMENT_ITEM:
                            humanoidLogic.ReservationStatus = MyReservationStatus.WAITING;
                            data = new MyAiTargetManager.ReservedEntityData {
                                Type             = MyReservedEntityType.ENVIRONMENT_ITEM,
                                EntityId         = inTarget.EntityId.Value,
                                LocalId          = inTarget.TreeId.Value,
                                ReservationTimer = timeMs,
                                ReserverId       = new MyPlayer.PlayerId(this.Bot.Player.Id.SteamId, this.Bot.Player.Id.SerialId)
                            };
                            humanoidLogic.ReservationEntityData    = data;
                            MyAiTargetManager.OnReservationResult += new Sandbox.Game.AI.MyAiTargetManager.ReservationHandler(this.ReservationHandler);
                            MyAiTargetManager.Static.RequestEnvironmentItemReservation(humanoidLogic.ReservationEntityData.EntityId, humanoidLogic.ReservationEntityData.LocalId, humanoidLogic.ReservationEntityData.ReservationTimer, this.Bot.Player.Id.SerialId);
                            break;

                        case MyAiTargetEnum.VOXEL:
                            humanoidLogic.ReservationStatus = MyReservationStatus.WAITING;
                            data = new MyAiTargetManager.ReservedEntityData {
                                Type             = MyReservedEntityType.VOXEL,
                                EntityId         = inTarget.EntityId.Value,
                                GridPos          = inTarget.VoxelPosition,
                                ReservationTimer = timeMs,
                                ReserverId       = new MyPlayer.PlayerId(this.Bot.Player.Id.SteamId, this.Bot.Player.Id.SerialId)
                            };
                            humanoidLogic.ReservationEntityData    = data;
                            MyAiTargetManager.OnReservationResult += new Sandbox.Game.AI.MyAiTargetManager.ReservationHandler(this.ReservationHandler);
                            MyAiTargetManager.Static.RequestVoxelPositionReservation(humanoidLogic.ReservationEntityData.EntityId, humanoidLogic.ReservationEntityData.GridPos, humanoidLogic.ReservationEntityData.ReservationTimer, this.Bot.Player.Id.SerialId);
                            break;

                        default:
                            humanoidLogic.ReservationStatus = MyReservationStatus.FAILURE;
                            break;
                        }
                        this.m_reservationTimeOut = MySandboxGame.Static.TotalTime + MyTimeSpan.FromSeconds(3.0);
                        break;

                    case MyReservationStatus.WAITING:
                        if (this.m_reservationTimeOut < MySandboxGame.Static.TotalTime)
                        {
                            humanoidLogic.ReservationStatus = MyReservationStatus.FAILURE;
                        }
                        break;

                    default:
                        break;
                    }
                }
                switch (humanoidLogic.ReservationStatus)
                {
                case MyReservationStatus.WAITING:
                    return(MyBehaviorTreeState.RUNNING);

                case MyReservationStatus.SUCCESS:
                    return(MyBehaviorTreeState.SUCCESS);
                }
            }
            return(MyBehaviorTreeState.FAILURE);
        }
        protected MyBehaviorTreeState TryReserveEntity([BTIn] ref MyBBMemoryTarget inTarget, [BTParam] int timeMs)
        {
            MyBehaviorTreeState retStatus = MyBehaviorTreeState.FAILURE;

            if (Bot == null || Bot.Player == null)
            {
                return(MyBehaviorTreeState.FAILURE);
            }

            var logic = Bot.HumanoidLogic;

            if (inTarget != null && inTarget.EntityId.HasValue && inTarget.TargetType != MyAiTargetEnum.POSITION && inTarget.TargetType != MyAiTargetEnum.NO_TARGET)
            {
                switch (logic.ReservationStatus)
                {
                case Logic.MyReservationStatus.NONE:
                    switch (inTarget.TargetType)
                    {
                    case MyAiTargetEnum.GRID:
                    case MyAiTargetEnum.CUBE:
                    case MyAiTargetEnum.CHARACTER:
                    case MyAiTargetEnum.ENTITY:
                        logic.ReservationStatus     = Logic.MyReservationStatus.WAITING;
                        logic.ReservationEntityData = new MyAiTargetManager.ReservedEntityData()
                        {
                            Type       = MyReservedEntityType.ENTITY,
                            EntityId   = inTarget.EntityId.Value, ReservationTimer = timeMs,
                            ReserverId = new World.MyPlayer.PlayerId(Bot.Player.Id.SteamId, Bot.Player.Id.SerialId)
                        };
                        MyAiTargetManager.OnReservationResult += ReservationHandler;
                        MyAiTargetManager.Static.RequestEntityReservation(logic.ReservationEntityData.EntityId, logic.ReservationEntityData.ReservationTimer, Bot.Player.Id.SerialId);
                        break;

                    case MyAiTargetEnum.ENVIRONMENT_ITEM:
                        logic.ReservationStatus     = Logic.MyReservationStatus.WAITING;
                        logic.ReservationEntityData = new MyAiTargetManager.ReservedEntityData()
                        {
                            Type             = MyReservedEntityType.ENVIRONMENT_ITEM,
                            EntityId         = inTarget.EntityId.Value,
                            LocalId          = inTarget.TreeId.Value,
                            ReservationTimer = timeMs,
                            ReserverId       = new World.MyPlayer.PlayerId(Bot.Player.Id.SteamId, Bot.Player.Id.SerialId)
                        };
                        MyAiTargetManager.OnReservationResult += ReservationHandler;
                        MyAiTargetManager.Static.RequestEnvironmentItemReservation(logic.ReservationEntityData.EntityId, logic.ReservationEntityData.LocalId,
                                                                                   logic.ReservationEntityData.ReservationTimer, Bot.Player.Id.SerialId);
                        break;

                    case MyAiTargetEnum.VOXEL:
                        logic.ReservationStatus     = Logic.MyReservationStatus.WAITING;
                        logic.ReservationEntityData = new MyAiTargetManager.ReservedEntityData()
                        {
                            Type             = MyReservedEntityType.VOXEL,
                            EntityId         = inTarget.EntityId.Value,
                            GridPos          = inTarget.VoxelPosition,
                            ReservationTimer = timeMs,
                            ReserverId       = new World.MyPlayer.PlayerId(Bot.Player.Id.SteamId, Bot.Player.Id.SerialId)
                        };
                        MyAiTargetManager.OnReservationResult += ReservationHandler;
                        MyAiTargetManager.Static.RequestVoxelPositionReservation(logic.ReservationEntityData.EntityId, logic.ReservationEntityData.GridPos,
                                                                                 logic.ReservationEntityData.ReservationTimer, Bot.Player.Id.SerialId);
                        break;

                    default:
                        break;
                    }
                    m_reservationTimeOut    = MySandboxGame.Static.UpdateTime + MyTimeSpan.FromSeconds(RESERVATION_WAIT_TIMEOUT_SECONDS);
                    logic.ReservationStatus = Logic.MyReservationStatus.WAITING;
                    retStatus = MyBehaviorTreeState.RUNNING;
                    break;

                case Logic.MyReservationStatus.SUCCESS:
                    retStatus = MyBehaviorTreeState.SUCCESS;
                    break;

                case Logic.MyReservationStatus.FAILURE:
                    retStatus = MyBehaviorTreeState.FAILURE;
                    break;

                case Logic.MyReservationStatus.WAITING:
                    if (m_reservationTimeOut < MySandboxGame.Static.UpdateTime)
                    {
                        retStatus = MyBehaviorTreeState.FAILURE;
                    }
                    else
                    {
                        retStatus = MyBehaviorTreeState.RUNNING;
                    }
                    break;
                }
            }
            return(retStatus);
        }
Exemplo n.º 16
0
        private void UpdateManipulation()
        {
            if (m_state != MyState.NONE && SafeConstraint != null)
            {
                const float fixedConstraintMaxValue    = 1000;
                const float fixedConstraintMaxDistance = 2f;
                const float ballAndSocketMaxDistance   = 2f;

                MyTimeSpan constraintPrepareTime = MyTimeSpan.FromSeconds(1.0f);
                MyTimeSpan currentTimeDelta      = MySandboxGame.Static.UpdateTime - m_constraintCreationTime;

                MatrixD headWorldMatrix       = Owner.GetHeadMatrix(false, true, false, true);
                MatrixD worldHeadPivotMatrix  = m_headLocalPivotMatrix * headWorldMatrix;
                MatrixD worldOtherPivotMatrix = m_otherLocalPivotMatrix * m_otherEntity.PositionComp.WorldMatrix;

                double length   = (worldOtherPivotMatrix.Translation - worldHeadPivotMatrix.Translation).Length();
                double checkDst = m_fixedConstraintData != null ? fixedConstraintMaxDistance : ballAndSocketMaxDistance;

                if (currentTimeDelta > constraintPrepareTime)
                {
                    var  characterMovementState = Owner.GetCurrentMovementState();
                    bool currentCanUseIdle      = CanManipulate(characterMovementState);
                    bool previousCanUseIdle     = CanManipulate(m_previousCharacterMovementState);

                    if ((!m_constraintInitialized && currentCanUseIdle) || (currentCanUseIdle && !previousCanUseIdle))
                    {
                        if (m_state == MyState.HOLD)
                        {
                            Owner.PlayCharacterAnimation("PickLumberIdle", true, MyPlayAnimationMode.Immediate | MyPlayAnimationMode.Play, 0.2f, 1f);
                        }
                        else
                        {
                            Owner.PlayCharacterAnimation("PullLumberIdle", true, MyPlayAnimationMode.Immediate | MyPlayAnimationMode.Play, 0.2f, 1f);
                        }
                    }

                    m_previousCharacterMovementState = characterMovementState;

                    m_constraintInitialized = true;

                    if (m_otherRigidBody != null && !MyFakes.MANIPULATION_TOOL_VELOCITY_LIMIT)
                    {
                        m_otherRigidBody.MaxLinearVelocity  = m_otherMaxLinearVelocity;
                        m_otherRigidBody.MaxAngularVelocity = m_otherMaxAngularVelocity;
                    }

                    if (m_fixedConstraintData != null && !MyFakes.MANIPULATION_TOOL_VELOCITY_LIMIT)
                    {
                        m_fixedConstraintData.MaximumAngularImpulse = fixedConstraintMaxValue;
                        m_fixedConstraintData.MaximumLinearImpulse  = fixedConstraintMaxValue;

                        // Check angle between pivots
                        float upDot    = Math.Abs(Vector3.Dot(worldHeadPivotMatrix.Up, worldOtherPivotMatrix.Up));
                        float rightDot = Math.Abs(Vector3.Dot(worldHeadPivotMatrix.Right, worldOtherPivotMatrix.Right));
                        if (upDot < 0.5f || rightDot < 0.5f)
                        {
                            if (!(m_otherEntity is MyCharacter))
                            {
                                SyncTool.StopManipulation();
                            }
                            return;
                        }
                    }

                    // Check length between pivots
                    if (length > checkDst)
                    {
                        if (!(m_otherEntity is MyCharacter))
                        {
                            SyncTool.StopManipulation();
                        }
                        return;
                    }
                }
                else
                {
                    if (m_fixedConstraintData != null && !MyFakes.MANIPULATION_TOOL_VELOCITY_LIMIT)
                    {
                        float t = (float)(currentTimeDelta.Miliseconds / constraintPrepareTime.Miliseconds);
                        t *= t;
                        t *= t; //pow4
                        float value = t * fixedConstraintMaxValue;
                        m_fixedConstraintData.MaximumAngularImpulse = value;
                        m_fixedConstraintData.MaximumLinearImpulse  = value;

                        if (length > checkDst)
                        {
                            var characterMovementState = Owner.GetCurrentMovementState();
                            if (!CanManipulate(characterMovementState))
                            {
                                if (!(m_otherEntity is MyCharacter))
                                {
                                    SyncTool.StopManipulation();
                                }
                                return;
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 17
0
        public override void UpdateAfterSimulation()
        {
            base.UpdateAfterSimulation();

            bool isShooting = IsShooting;

            if (!m_isHit && IsShooting && (MySandboxGame.Static.UpdateTime - m_lastShot > MyTimeSpan.FromSeconds(m_shotToolAction.Value.HitStart)))
            {
                IMyHandToolComponent toolComponent;
                if (m_toolComponents.TryGetValue(m_shotHitCondition.Component, out toolComponent))
                {
                    MyCharacterDetectorComponent detectorComponent = m_owner.Components.Get <MyCharacterDetectorComponent>();
                    if (detectorComponent != null)
                    {
                        if (m_shotToolAction.Value.CustomShapeRadius > 0 && detectorComponent is MyCharacterShapecastDetectorComponent)
                        {
                            var shapeCastComponent = detectorComponent as MyCharacterShapecastDetectorComponent;
                            shapeCastComponent.ShapeRadius = m_shotToolAction.Value.CustomShapeRadius;
                            shapeCastComponent.DoDetectionModel();
                            shapeCastComponent.ShapeRadius = MyCharacterShapecastDetectorComponent.DEFAULT_SHAPE_RADIUS;
                        }

                        if (detectorComponent.DetectedEntity != null)
                        {
                            MyHitInfo hitInfo = new MyHitInfo();
                            hitInfo.Position = detectorComponent.HitPosition;
                            hitInfo.Normal   = detectorComponent.HitNormal;

                            bool  isBlock = false;
                            float efficiencyMultiplier = 1.0f;
                            bool  canHit = CanHit(toolComponent, detectorComponent, ref isBlock, out efficiencyMultiplier);

                            MyDecals.HandleAddDecal(detectorComponent.DetectedEntity, hitInfo, MyDamageType.Weapon);

                            bool isHit = false;
                            if (canHit)
                            {
                                if (!string.IsNullOrEmpty(m_shotToolAction.Value.StatsEfficiency) && Owner.StatComp != null)
                                {
                                    efficiencyMultiplier *= Owner.StatComp.GetEfficiencyModifier(m_shotToolAction.Value.StatsEfficiency);
                                }

                                float efficiency = m_shotToolAction.Value.Efficiency * efficiencyMultiplier;
                                var   tool       = detectorComponent.DetectedEntity as MyHandToolBase;
                                if (isBlock && tool != null)
                                {
                                    isHit = toolComponent.Hit(tool.Owner, hitInfo, detectorComponent.ShapeKey, efficiency);
                                }
                                else
                                {
                                    isHit = toolComponent.Hit((MyEntity)detectorComponent.DetectedEntity, hitInfo, detectorComponent.ShapeKey, efficiency);
                                }

                                if (isHit && Sync.IsServer && Owner.StatComp != null)
                                {
                                    if (!string.IsNullOrEmpty(m_shotHitCondition.StatsActionIfHit))
                                    {
                                        Owner.StatComp.DoAction(m_shotHitCondition.StatsActionIfHit);
                                    }
                                    if (!string.IsNullOrEmpty(m_shotHitCondition.StatsModifierIfHit))
                                    {
                                        Owner.StatComp.ApplyModifier(m_shotHitCondition.StatsModifierIfHit);
                                    }
                                }
                            }

                            if (canHit || isBlock)  // real hit is not controlled now - there isn't any server-client synchronization of hit currently and hit is performed only at server
                            {
                                if (!string.IsNullOrEmpty(m_shotToolAction.Value.HitSound))
                                {
                                    PlaySound(m_shotToolAction.Value.HitSound);
                                }
                                else
                                {
                                    MyStringId collisionType = MyMaterialPropertiesHelper.CollisionType.Hit;
                                    bool       showParticles = false;

                                    // If it didn't play the Sound with "Hit", it will try with "Start"
                                    if (MyAudioComponent.PlayContactSound(EntityId, m_hitCue, detectorComponent.HitPosition,
                                                                          m_toolItemDef.PhysicalMaterial, detectorComponent.HitMaterial))
                                    {
                                        showParticles = true;
                                    }
                                    else if (MyAudioComponent.PlayContactSound(EntityId, m_startCue, detectorComponent.HitPosition,
                                                                               m_toolItemDef.PhysicalMaterial, detectorComponent.HitMaterial))
                                    {
                                        showParticles = true;
                                        collisionType = MyMaterialPropertiesHelper.CollisionType.Start;
                                    }

                                    if (showParticles)
                                    {
                                        MyMaterialPropertiesHelper.Static.TryCreateCollisionEffect(
                                            collisionType,
                                            detectorComponent.HitPosition,
                                            detectorComponent.HitNormal,
                                            m_toolItemDef.PhysicalMaterial, detectorComponent.HitMaterial);
                                    }
                                }

                                this.RaiseEntityEvent(MyStringHash.GetOrCompute("Hit"), new MyEntityContainerEventExtensions.HitParams(MyStringHash.GetOrCompute(m_shotHitCondition.Component), detectorComponent.HitMaterial));
                                m_soundEmitter.StopSound(true);
                            }
                        }
                    }
                }

                m_isHit = true;
            }

            if (!m_swingSoundPlayed && IsShooting && !m_isHit && (MySandboxGame.Static.UpdateTime - m_lastShot > MyTimeSpan.FromSeconds(m_shotToolAction.Value.SwingSoundStart)))
            {
                if (!string.IsNullOrEmpty(m_shotToolAction.Value.SwingSound))
                {
                    PlaySound(m_shotToolAction.Value.SwingSound);
                }
                m_swingSoundPlayed = true;
            }


            if (!isShooting && m_wasShooting)
            {
                m_owner.StopUpperCharacterAnimation(0.4f);
                m_shotToolAction = null;
            }


            m_wasShooting = isShooting;

            if (m_owner != null)
            {
                MatrixD blockingMatrix = MatrixD.CreateWorld(((MyEntity)m_owner.CurrentWeapon).PositionComp.GetPosition(), m_owner.WorldMatrix.Forward, m_owner.WorldMatrix.Up);

                ((MyBlockingBody)Physics).SetWorldMatrix(blockingMatrix);
            }


            foreach (var c in m_toolComponents.Values)
            {
                c.Update();
            }
        }
Exemplo n.º 18
0
 private void UnmarkEntityBreakable(bool checkTime)
 {
     if (m_markedBreakImpulse != MyTimeSpan.Zero && (!checkTime || MySandboxGame.Static.UpdateTime - m_markedBreakImpulse > MyTimeSpan.FromSeconds(1.5)))
     {
         m_markedBreakImpulse = MyTimeSpan.Zero;
         if (Physics != null && Physics.HavokWorld != null)
         {
             Physics.HavokWorld.BreakOffPartsUtil.UnmarkEntityBreakable(Physics.RigidBody);
             if (checkTime)
             {
                 CreateEasyPenetrationAction(1f);
             }
         }
     }
 }
Exemplo n.º 19
0
        protected MyBehaviorTreeState TryReserveAreaAroundEntity([BTParam] string areaName, [BTParam] float radius, [BTParam] int timeMs)
        {
            MyHumanoidBotLogic  humanoidLogic = this.Bot.HumanoidLogic;
            MyBehaviorTreeState fAILURE       = MyBehaviorTreeState.FAILURE;

            if (humanoidLogic != null)
            {
                switch (humanoidLogic.ReservationStatus)
                {
                case MyReservationStatus.NONE:
                {
                    humanoidLogic.ReservationStatus = MyReservationStatus.WAITING;
                    MyAiTargetManager.ReservedAreaData data = new MyAiTargetManager.ReservedAreaData {
                        WorldPosition    = this.Bot.HumanoidEntity.WorldMatrix.Translation,
                        Radius           = radius,
                        ReservationTimer = MyTimeSpan.FromMilliseconds((double)timeMs),
                        ReserverId       = new MyPlayer.PlayerId(this.Bot.Player.Id.SteamId, this.Bot.Player.Id.SerialId)
                    };
                    humanoidLogic.ReservationAreaData          = data;
                    MyAiTargetManager.OnAreaReservationResult += new Sandbox.Game.AI.MyAiTargetManager.AreaReservationHandler(this.AreaReservationHandler);
                    MyAiTargetManager.Static.RequestAreaReservation(areaName, this.Bot.HumanoidEntity.WorldMatrix.Translation, radius, (long)timeMs, this.Bot.Player.Id.SerialId);
                    this.m_reservationTimeOut       = MySandboxGame.Static.TotalTime + MyTimeSpan.FromSeconds(3.0);
                    humanoidLogic.ReservationStatus = MyReservationStatus.WAITING;
                    fAILURE = MyBehaviorTreeState.RUNNING;
                    break;
                }

                case MyReservationStatus.WAITING:
                    fAILURE = (this.m_reservationTimeOut >= MySandboxGame.Static.TotalTime) ? MyBehaviorTreeState.RUNNING : MyBehaviorTreeState.FAILURE;
                    break;

                case MyReservationStatus.SUCCESS:
                    fAILURE = MyBehaviorTreeState.SUCCESS;
                    break;

                case MyReservationStatus.FAILURE:
                    fAILURE = MyBehaviorTreeState.FAILURE;
                    break;

                default:
                    break;
                }
            }
            return(fAILURE);
        }