예제 #1
0
 public void Enqueue(T item)
 {
     if (_hashSet.Add(item))
     {
         _queue.Enqueue(item);
     }
 }
예제 #2
0
        internal void MarkReplicable(MyProceduralLogicalSector sector)
        {
            Debug.Assert(!sector.Replicable);

            m_sectorsForReplication.Add(sector);
            QueueRaiseLogicalSector(sector);
            sector.Replicable = true;
        }
예제 #3
0
        private void CleanupTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            var toRemove = new MyConcurrentHashSet <IMyEntity>();
            var entities = new HashSet <IMyEntity>();
            var players  = new List <IMyPlayer>();

            MyAPIGateway.Entities.GetEntities(entities);
            MyAPIGateway.Players.GetPlayers(players);

            MyAPIGateway.Parallel.ForEach(entities, entity =>
            {
                var grid = entity as IMyCubeGrid;
                if (grid == null)
                {
                    return;
                }

                if (grid.BigOwners.Count == 0)
                {
                    toRemove.Add(entity);
                    return;
                }

                if (!grid.BigOwners.Any(o => players.Any(p => p.IdentityId == o)))
                {
                    toRemove.Add(entity);
                }
            });

            if (toRemove.Any())
            {
                MyAPIGateway.Utilities.InvokeOnGameThread(() =>
                {
                    foreach (IMyEntity ent in toRemove)
                    {
                        ent.Close();
                    }

                    Communication.SendServerChat(0, $"Removed {toRemove.Count} grids without online owners");
                });
            }
        }
예제 #4
0
        /// <summary>
        ///     Invokes actions on the game thread, and blocks until completion
        /// </summary>
        /// <param name="action"></param>
        public static void InvokeBlocking(Action action)
        {
            var threadLock = new FastResourceLock();

            if (!SessionClosing)
            {
                ThreadLocks.Add(threadLock);
            }

            threadLock.AcquireExclusive();
            try
            {
                MyAPIGateway.Utilities.InvokeOnGameThread(() =>
                {
                    try
                    {
                        var invokeBlock = Profiler.Start(FullName, nameof(InvokeBlocking));
                        action();
                        invokeBlock.End();
                    }
                    catch (Exception ex)
                    {
                        Logging.Instance.WriteLine("Exception on blocking game thread invocation: " + ex);

                        if (!SessionClosing && ShipyardCore.Debug)
                        {
                            throw;
                        }
                    }
                    finally
                    {
                        threadLock.ReleaseExclusive();
                    }
                });
            }
            catch (Exception ex)
            {
                Logging.Instance.WriteLine("Exception in Utilities.InvokeBlocking: " + ex);
                threadLock.ReleaseExclusive();

                if (!SessionClosing && ShipyardCore.Debug)
                {
                    throw;
                }
            }

            threadLock.AcquireExclusive();
            threadLock.ReleaseExclusive();

            if (!SessionClosing)
            {
                ThreadLocks.Remove(threadLock);
            }
        }
예제 #5
0
        public void UpdateBlacklist()
        {
            var blacklist  = MyScriptCompiler.Static.Whitelist.OpenIngameBlacklistBatch();
            var types      = new MyConcurrentHashSet <Type>();
            var memberDict = new MyConcurrentDictionary <Type, List <string> >();

            Parallel.ForEach(PluginSettings.Instance.BlacklistItems, item =>
            {
                if (string.IsNullOrEmpty(item.Type))
                {
                    return;
                }

                var targetType = FindTypeInAllAssemblies(item.Type);
                if (targetType == null)
                {
                    return;
                }

                if (string.IsNullOrEmpty(item.Member))
                {
                    lock (types)
                        types.Add(targetType);
                }

                var members = targetType.GetMember(item.Member);
                if (members.Length != 0)
                {
                    if (!memberDict.ContainsKey(targetType))
                    {
                        memberDict.Add(targetType, new List <string>());
                    }
                    memberDict[targetType].Add(item.Member);
                }
            });

            if (types.Count > 0)
            {
                blacklist.AddTypes(types.ToArray());
                foreach (var type in types)
                {
                    Essentials.Log.Info($"Added type {type.Name} to PB blacklist.");
                }
            }
            foreach (var entry in memberDict)
            {
                blacklist.AddMembers(entry.Key, entry.Value.ToArray());
                foreach (var name in entry.Value)
                {
                    Essentials.Log.Info($"Added {entry.Key.Name}.{name} to PB blacklist.");
                }
            }
        }
예제 #6
0
        /// <summary>
        /// Adds newly added grids to cache and update count to meet change
        /// </summary>
        /// <param name="entity"></param>
        private void MyEntitiesOnOnEntityAdd(MyEntity entity)
        {
            if (!BlockLimiterConfig.Instance.EnableLimits)
            {
                return;
            }

            if (!(entity is MyCubeGrid grid))
            {
                return;
            }

            if (grid.Projector != null || grid.IsPreview)
            {
                return;
            }
            // Do Not Add to grid cache at this point to allow MyCubeGridsOnBlockBuild to add and prevent double counts
            var blocks = grid.CubeBlocks;

            GridCache.AddGrid(grid);
            foreach (var block in blocks)
            {
                if (_justAdded.Contains(block))
                {
                    _justAdded.Remove(block);
                    continue;
                }
                _justAdded.Add(block);
                Block.IncreaseCount(block.BlockDefinition,
                                    block.BuiltBy == block.OwnerId
                        ? new List <long> {
                    block.BuiltBy
                }
                        : new List <long> {
                    block.BuiltBy, block.OwnerId
                }, 1, grid.EntityId);
            }
        }
        internal MySourceVoice NextAvailable()
        {
            MySourceVoice voice = null;

            if (m_owner.DisablePooling || !m_availableVoices.TryDequeue(out voice))
            {
                if (m_currentCount < MAX_COUNT)
                {
                    voice = new MySourceVoice(this, m_audioEngine, m_waveFormat);
                    m_allVoices.Add(voice);
                    m_currentCount++;
                }
            }
#if DEBUG
            if (voice != null)
            {
                m_debugPlayingList.Add(voice);
            }
#endif
            return(voice);
        }
예제 #8
0
        private static void UnregisterHierarchy(MyEntity entity, bool top = true)
        {
            if (entity.Hierarchy == null)
            {
                return;
            }

            if (RemovedGrids.Contains(entity.EntityId))
            {
                return;
            }

            foreach (var child in entity.Hierarchy.Children)
            {
                MyEntity childEntity = (MyEntity)child.Container.Entity;
                UnregisterHierarchy(childEntity, false);
                MyEntities.UnregisterForUpdate(childEntity);
                //childEntity.RemoveFromGamePruningStructure();

                //child.Container.Entity.InScene = false;
            }

            if (!top)
            {
                return;
            }

            RemovedGrids.Add(entity.EntityId);

            MyEntities.UnregisterForUpdate(entity);
            entity.RemoveFromGamePruningStructure();

            /*
             * if ( !PluginSettings.Instance.DynamicConcealPhysics )
             *  return;
             *
             * if ( entity.Physics != null )
             *  entity.Physics.Enabled = false;
             */
        }
예제 #9
0
 /// <summary>
 /// Trigger an action in this layer.
 /// If there is a transition having given (non-null) name, it is followed immediatelly.
 /// Conditions of transition are ignored.
 /// </summary>
 public void TriggerAction(MyStringId actionName)
 {
     m_enqueuedActions.Add(actionName);
 }
예제 #10
0
        public static List <IMySlimBlock> GetBlocksContactingVoxel(IMyCubeGrid grid, MyPlanet planet, out byte voxelType)
        {
            Vector3D[] corners = grid.WorldAABB.GetCorners();
            if (corners.All(c => Vector3D.DistanceSquared(c, planet.GetClosestSurfacePointGlobal(c)) > 2500))
            {
                voxelType = 0;
                return(new List <IMySlimBlock>());
            }

            Vector3D planetPos = planet.PositionComp.GetPosition();

            var result = new MyConcurrentHashSet <IMySlimBlock>();
            var blocks = new List <IMySlimBlock>();

            grid.GetBlocks(blocks);
            byte id = 0;

            MyAPIGateway.Parallel.ForEach(blocks, block =>
            {
                try
                {
                    var b = block.GetPosition();
                    Vector3D closestSurfacePoint = planet.GetClosestSurfacePointGlobal(ref b);

                    if (Vector3D.DistanceSquared(planetPos, closestSurfacePoint) > Vector3D.DistanceSquared(planetPos, b))
                    {
                        var hits = new List <IHitInfo>();
                        MyAPIGateway.Physics.CastRay(b, closestSurfacePoint, hits);
                        foreach (IHitInfo hit in hits)
                        {
                            if (hit.HitEntity is IMyVoxelBase)
                            {
                                closestSurfacePoint = hit.Position;
                            }
                        }
                    }

                    double cd = Vector3D.DistanceSquared(b, closestSurfacePoint);
                    if (cd > 200)
                    {
                        return;
                    }

                    if (cd > 6.25)
                    {
                        BoundingBoxD box;
                        block.GetWorldBoundingBox(out box, true);
                        Vector3D[] bc = box.GetCorners();
                        if (bc.All(c => Vector3D.DistanceSquared(c, planet.GetClosestSurfacePointGlobal(c)) > 6.25))
                        {
                            return;
                        }
                    }

                    MyVoxelMaterialDefinition mat = planet.GetMaterialAt_R(ref closestSurfacePoint);
                    if (Config.VOXEL_IDS.ContainsKey(mat.Index))
                    {
                        result.Add(block);
                    }
                    id = mat.Index;
                }
                catch
                {
                    //meh!
                }
            });
            voxelType = id;
            return(result.ToList());

            /*
             * var chunks = new HashSet<Vector3I[]>();
             *
             * int chunkSize = grid.GridSizeEnum == MyCubeSize.Large ? 3 : 5;
             * for (int x = grid.Min.X; x < grid.Max.X + chunkSize; x += chunkSize)
             * {
             *  for (int y = grid.Min.Y; y < grid.Max.Y + chunkSize; y += chunkSize)
             *  {
             *      for (int z = grid.Min.Z; z < grid.Max.Z + chunkSize; z += chunkSize)
             *      {
             *          chunks.Add(new[]
             *                     {
             *                         new Vector3I(x, y, z),
             *                         new Vector3I(x + chunkSize, y, z),
             *                         new Vector3I(x, y + chunkSize, z),
             *                         new Vector3I(x, y, z + chunkSize),
             *                         new Vector3I(x + chunkSize, y + chunkSize, z),
             *                         new Vector3I(x + chunkSize, y, z + chunkSize),
             *                         new Vector3I(x, y + chunkSize, z + chunkSize),
             *                         new Vector3I(x + chunkSize, y + chunkSize, z + chunkSize),
             *                     });
             *      }
             *  }
             * }
             *
             * MyAPIGateway.Parallel.ForEach(chunks, chunk =>
             *                                    {
             *                                        var success = false;
             *                                        foreach (Vector3I pos in chunk)
             *                                        {
             *                                            Vector3D d = grid.GridIntegerToWorld(pos);
             *                                            Vector3D s = planet.GetClosestSurfacePointGlobal(ref d);
             *                                            if (Vector3D.DistanceSquared(d, s) > 6.25)
             *                                                continue;
             *
             *                                            if (!Config.VOXEL_IDS.ContainsKey(planet.GetMaterialAt_R(ref s).Index))
             *                                                continue;
             *                                            success = true;
             *                                            break;
             *                                        }
             *
             *                                        if (!success)
             *                                            return;
             *
             *                                        foreach (Vector3I pos in chunk)
             *                                        {
             *                                            IMySlimBlock block = grid.GetCubeBlock(pos);
             *                                            if (block != null)
             *                                                result.Add(block);
             *                                        }
             *                                    });
             *
             * return result.ToList();
             */
        }
        public void Add(MyStorageBase storage)
        {
            StorageData sdata = new StorageData(storage);

            m_storagesWithCache.Add(sdata);
        }
예제 #12
0
 // Caches action for next update pass. Mostly for nodes triggering theire own action.
 public void TriggerCachedAction(MyStringId actionName)
 {
     m_cachedActions.Add(actionName);
 }
예제 #13
0
        public override void UpdateAfterSimulation10()
        {
            base.UpdateAfterSimulation10();

            if (!Sync.IsServer || !IsWorking)
            {
                return;
            }

            if (!ResourceSink.IsPoweredByType(MyResourceDistributorComponent.ElectricityId))
            {
                if (ResourceSink.IsPowerAvailable(MyResourceDistributorComponent.ElectricityId, BlockDefinition.RequiredPowerInput))
                {
                    float origInput = ResourceSink.RequiredInputByType(MyResourceDistributorComponent.ElectricityId);
                    ResourceSink.SetRequiredInputByType(MyResourceDistributorComponent.ElectricityId, 0);
                    ResourceSink.SetRequiredInputByType(MyResourceDistributorComponent.ElectricityId, origInput);
                }
                else
                {
                    return;
                }
            }

            var rotation1 = Quaternion.CreateFromForwardUp(WorldMatrix.Forward, WorldMatrix.Up);
            var position1 = PositionComp.GetPosition() + Vector3D.Transform(PositionComp.LocalVolume.Center + (m_fieldMax.Value + m_fieldMin.Value) * 0.5f, rotation1);

            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("Recreate Field");
            if (m_recreateField)
            {
                m_recreateField = false;
                m_fieldShape.RemoveReference();
                m_fieldShape = GetHkShape();
                ResourceSink.Update();
            }
            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

            var boundingBox = new BoundingBoxD(m_fieldMin.Value, m_fieldMax.Value).Translate(PositionComp.LocalVolume.Center).TransformFast(WorldMatrix.GetOrientation()).Translate(PositionComp.GetPosition());

            m_potentialPenetrations.Clear();
            MyGamePruningStructure.GetTopMostEntitiesInBox(ref boundingBox, m_potentialPenetrations);

            m_potentialVoxelPenetrations.Clear();
            MyGamePruningStructure.GetAllVoxelMapsInBox(ref boundingBox, m_potentialVoxelPenetrations);//disabled until heightmap queries are finished

            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("Sensor Physics");
            LastDetectedEntity = null;
            bool empty = true;

            m_detectedEntities.Clear();
            //foreach (var entity in m_potentialPenetrations)
            Parallel.ForEach(m_potentialPenetrations, entity =>
            {
                if (entity is MyVoxelBase)
                {
                    //voxels are handled in different loop (becaose of planets)
                    return;
                }
                if (ShouldDetect(entity))
                {
                    Quaternion rotation2;
                    Vector3 posDiff;
                    HkShape?shape2;
                    if (GetPropertiesFromEntity(entity, ref position1, out rotation2, out posDiff, out shape2))
                    {
                        if (entity.GetPhysicsBody().HavokWorld.IsPenetratingShapeShape(m_fieldShape, ref Vector3.Zero, ref rotation1, shape2.Value, ref posDiff, ref rotation2))
                        {
                            if (LastDetectedEntity == null)
                            {
                                LastDetectedEntity = entity;
                            }
                            empty = false;
                            //entities.Add(entity);
                            var inf = MyDetectedEntityInfoHelper.Create(entity, this.OwnerId);
                            m_detectedEntities.Add(inf);
                        }
                    }
                }
            });

            if (DetectAsteroids)
            {
                //foreach (var entity in m_potentialVoxelPenetrations)
                Parallel.ForEach(m_potentialVoxelPenetrations, entity =>
                {
                    var voxel = entity as MyVoxelPhysics;
                    if (voxel != null)
                    {
                        Vector3D localPositionMin, localPositionMax;

                        MyVoxelCoordSystems.WorldPositionToLocalPosition(boundingBox.Min, voxel.PositionComp.WorldMatrix, voxel.PositionComp.WorldMatrixInvScaled, voxel.SizeInMetresHalf, out localPositionMin);
                        MyVoxelCoordSystems.WorldPositionToLocalPosition(boundingBox.Max, voxel.PositionComp.WorldMatrix, voxel.PositionComp.WorldMatrixInvScaled, voxel.SizeInMetresHalf, out localPositionMax);
                        var aabb = new BoundingBox(localPositionMin, localPositionMax);
                        aabb.Translate(voxel.StorageMin);
                        if (voxel.Storage.Intersect(ref aabb) != ContainmentType.Disjoint)
                        {
                            if (LastDetectedEntity == null)
                            {
                                LastDetectedEntity = entity;
                            }
                            empty = false;
                            //entities.Add(entity);
                            var inf = MyDetectedEntityInfoHelper.Create(entity, this.OwnerId);
                            m_detectedEntities.Add(inf);
                        }
                    }
                    else
                    {
                        Quaternion rotation2;
                        Vector3 posDiff;
                        HkShape?shape2;
                        if (GetPropertiesFromEntity(entity, ref position1, out rotation2, out posDiff, out shape2))
                        {
                            if (entity.GetPhysicsBody().HavokWorld.IsPenetratingShapeShape(m_fieldShape, ref Vector3.Zero, ref rotation1, shape2.Value, ref posDiff, ref rotation2))
                            {
                                if (LastDetectedEntity == null)
                                {
                                    LastDetectedEntity = entity;
                                }
                                empty = false;
                                //entities.Add(entity);
                                var inf = MyDetectedEntityInfoHelper.Create(entity, this.OwnerId);
                                m_detectedEntities.Add(inf);
                            }
                        }
                    }
                });
            }

            IsActive = !empty;
            m_potentialPenetrations.Clear();
            m_potentialVoxelPenetrations.Clear();
            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
        }