public LruCache(int capacity, IEqualityComparer <TK> comparer = null)
 {
     _cache    = new Dictionary <TK, LinkedListNode <CacheItem> >(capacity > 1024 ? (int)Math.Sqrt(capacity) : capacity, comparer ?? EqualityComparer <TK> .Default);
     _lruCache = new LinkedList <CacheItem>();
     _capacity = capacity;
     _lock     = new FastResourceLock();
 }
        public void InitWriteCache(int prealloc = 128)
        {
            //Debug.Assert(m_cachedChunks == null, "Error: Cache already initialized"); disabled due to shared storages

            if (m_cachedChunks != null)
            {
                return;
            }

            if (OperationsComponent != null)
            {
                CachedWrites = true;
            }
            else
            {
                return;
            }

            m_cachedChunks         = new MyConcurrentDictionary <Vector3I, VoxelChunk>(prealloc, Vector3I.Comparer);
            m_pendingChunksToWrite = new MyConcurrentQueue <Vector3I>(prealloc / 10);
            m_chunksbyAge          = new MyQueue <Vector3I>(prealloc);

            m_cacheMap = new MyDynamicAABBTree(Vector3.Zero);

            m_cacheLock = new FastResourceLock();

            OperationsComponent.Add(this);
        }
Пример #3
0
 public HistoryLock(MyProfiler profiler, FastResourceLock historyLock)
 {
     m_profiler = profiler;
     m_lock     = historyLock;
     m_lock.AcquireExclusive();
     m_profiler.OnHistorySafe();
 }
Пример #4
0
 public HistoryLock(MyProfiler profiler, FastResourceLock historyLock)
 {
     m_profiler = profiler;
     m_lock = historyLock;
     m_lock.AcquireExclusive();
     m_profiler.OnHistorySafe();
 }
        public NaniteOreDetector(IMyFunctionalBlock entity)
        {
            m_block             = entity as IMyOreDetector;
            m_lastUpdate        = DateTime.MinValue;
            m_scanStart         = DateTime.MinValue;
            m_scanEnd           = DateTime.MinValue;
            m_lock              = new FastResourceLock();
            m_oreListCache      = new StringBuilder();
            m_detectorState     = DetectorStates.Disabled;
            m_lastDetectorState = DetectorStates.Disabled;

            m_block.Components.TryGet(out Sink);
            ResourceInfo = new MyResourceSinkInfo()
            {
                ResourceTypeId    = MyResourceDistributorComponent.ElectricityId,
                MaxRequiredInput  = 0f,
                RequiredInputFunc = () => (m_block.Enabled && m_block.IsFunctional) ? _power : 0f
            };
            Sink.RemoveType(ref ResourceInfo.ResourceTypeId);
            Sink.Init(MyStringHash.GetOrCompute("Utility"), ResourceInfo);
            Sink.AddType(ref ResourceInfo);

            m_effects.Add(new OreDetectorEffect((MyCubeBlock)m_block));

            if (!NaniteConstructionManager.OreDetectors.ContainsKey(entity.EntityId))
            {
                NaniteConstructionManager.OreDetectors.Add(entity.EntityId, this);
            }
        }
Пример #6
0
        internal void Close()
        {
            try
            {
                if (m_writer != null)
                {
                    if (m_writeCache.Length > 0)
                    {
                        m_writer.WriteLine(m_writeCache);
                    }

                    m_writer.Flush();
                    m_writer.Close();
                    m_writer = null;
                }

                m_instance = null;
                if (m_lock != null)
                {
                    m_lock.ReleaseExclusive();
                    m_lock = null;
                }
            }
            catch { }
        }
Пример #7
0
        //protected override void UnloadData()
        //{ TurretActions = null; }

        public static void EnqueueAction(Action item, FastResourceLock lock_MyAPIGateway = null)
        {
            using (lock_TurretActions.AcquireExclusiveUsing())
                TurretActions.Push(item);
            using (lock_isRunning.AcquireExclusiveUsing())
            {
                if (isRunning)
                {
                    return;
                }
                isRunning = true;
            }
            if (lock_MyAPIGateway != null)
            {
                lock_MyAPIGateway.AcquireShared();
            }
            try { MyAPIGateway.Parallel.Start(Run); }
            finally
            {
                if (lock_MyAPIGateway != null)
                {
                    lock_MyAPIGateway.ReleaseShared();
                }
            }
        }
Пример #8
0
		private static void Entities_OnCloseAll()
		{
			MyAPIGateway.Entities.OnCloseAll -= Entities_OnCloseAll;
			lock_constructing = null;
			lock_knownDefinitions = null;
			knownDefinitions = null;
		}
Пример #9
0
 public NaniteTargetBlocksBase(NaniteConstructionBlock constructionBlock)
 {
     m_lock                = new FastResourceLock();
     m_targetList          = new List <object>();
     m_potentialTargetList = new List <object>();
     m_componentsRequired  = new Dictionary <string, int>();
     m_constructionBlock   = constructionBlock;
 }
Пример #10
0
        //public static string VoxelMapMaterialManagerNamespace = "DC3F8F35BD18173B1D075139B475AD8E";
        //public static string VoxelMapMaterialManagerClass = "119B0A83D4E9B352826763AD3746A162";

        //public static string VoxelMapMaterialManagerGetVoxelsDictionaryMethod = "473DE42B0B661DE27A29562438E87943";

        //public static string VoxelMapMaterialManagerVoxelsField = "4E39EA62F3374F5CCE29BA40FE62818C";

        #endregion

        #region "Constructors and Initializers"

        public VoxelMapMaterialManager(VoxelMap parent, Object backingObject)
        {
            m_parent        = parent;
            m_backingObject = backingObject;

            m_resourceLock   = new FastResourceLock();
            m_materialTotals = new Dictionary <MyVoxelMaterialDefinition, float>();
        }
 public NaniteConstructionTargets(NaniteConstructionBlock constructionBlock) : base(constructionBlock)
 {
     m_targetBlocks     = new Dictionary <IMySlimBlock, int>();
     m_maxDistance      = NaniteConstructionManager.Settings.ConstructionMaxBeaconDistance;
     m_remoteTargets    = new HashSet <IMySlimBlock>();
     m_remoteLock       = new FastResourceLock();
     m_areaTargetBlocks = new Dictionary <IMySlimBlock, NaniteAreaBeacon>();
 }
Пример #12
0
 public CustomLogger()
 {
     _file          = DefaultLogFile;
     _writer        = null;
     _lock          = new FastResourceLock();
     _writeLock     = new FastResourceLock();
     _cache         = new StringBuilder();
     _readyTicks    = 0;
     _lastWriteTime = DateTime.Now;
 }
Пример #13
0
        static MyStringId()
        {
            m_lock       = new FastResourceLock();
            m_stringToId = new Dictionary <string, MyStringId>(50);
            m_idToString = new Dictionary <MyStringId, string>(50, Comparer);

            NullOrEmpty = GetOrCompute("");
            Debug.Assert(NullOrEmpty == default(MyStringId));
            Debug.Assert(NullOrEmpty.m_id == 0);
        }
Пример #14
0
 public Logging(string logFile)
 {
     try {
         m_instance   = this;
         m_writeCache = new StringBuilder();
         m_lock       = new FastResourceLock();
         m_logFile    = logFile;
     } catch {
     }
 }
Пример #15
0
        static MyStringHash()
        {
            m_lock         = new FastResourceLock();
            m_stringToHash = new Dictionary <string, MyStringHash>(50);
            m_hashToString = new Dictionary <MyStringHash, string>(50, Comparer);

            NullOrEmpty = GetOrCompute("");
            Debug.Assert(NullOrEmpty == default(MyStringHash));
            Debug.Assert(NullOrEmpty.m_hash == MyUtils.GetHash(null, 0));
            Debug.Assert(NullOrEmpty.m_hash == MyUtils.GetHash("", 0));
        }
Пример #16
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);
            }
        }
Пример #17
0
        public static void Register()
        {
            MyLog.Default.WriteLineAndConsole("TORCH MOD: Registering mod communication.");
            _outgoing    = new ConcurrentQueue <MessageBase>();
            _incoming    = new ConcurrentQueue <byte[]>();
            _playerCache = new List <IMyPlayer>();
            _lock        = new FastResourceLock();


            MyAPIGateway.Multiplayer.RegisterMessageHandler(NET_ID, MessageHandler);
            //background thread to handle de/compression and processing
            _task = MyAPIGateway.Parallel.StartBackground(DoProcessing);
            MyLog.Default.WriteLineAndConsole("TORCH MOD: Mod communication registered successfully.");
        }
        internal FastResourceLock InternalGetResourceLock()
        {
            try
            {
                Type             type   = SandboxGameAssemblyWrapper.Instance.GetAssemblyType(WorldResourceManagerNamespace, WorldResourceManagerClass);
                FastResourceLock result = (FastResourceLock)BaseObject.GetStaticFieldValue(type, WorldResourceManagerResourceLockField);

                return(result);
            }
            catch (Exception ex)
            {
                LogManager.ErrorLog.WriteLine(ex);
                return(null);
            }
        }
        public override void Init(MyObjectBuilder_EntityBase objectBuilder)
        {
            if (m_lock == null)
            {
                m_lock = new FastResourceLock();
            }

            base.Init(objectBuilder);

            using (m_lock.AcquireExclusiveUsing())
            {
                Logging.Instance.WriteLine(string.Format("ADDING Area Beacon: {0}", Entity.EntityId));
                m_beacon = new NaniteAreaBeacon((IMyTerminalBlock)Entity);
                NaniteConstructionManager.BeaconList.Add(m_beacon);
            }
        }
Пример #20
0
        public override void Init(MyObjectBuilder_EntityBase objectBuilder)
        {
            if (m_lock == null)
            {
                m_lock = new FastResourceLock();
            }

            base.Init(objectBuilder);

            using (m_lock.AcquireExclusiveUsing())
            {
                Logging.Instance.WriteLine(string.Format("ADDING Mining Hammer: {0}", Entity.EntityId));
                m_mining = new NaniteMining(Entity as IMyTerminalBlock);
                NaniteConstructionManager.MiningList.Add(m_mining);
            }
        }
Пример #21
0
        //private Dictionary<Vector3D, NaniteMiningItem> m_oreLocations;

        public NaniteMining(IMyTerminalBlock block)
        {
            m_block        = block;
            m_busy         = false;
            m_lastUpdate   = DateTime.MinValue;
            m_lastRefresh  = DateTime.MinValue;
            m_lock         = new FastResourceLock();
            m_locationLock = new FastResourceLock();
            m_initialize   = false;
            m_working      = false;
            m_syncDetails  = new StringBuilder();
            m_updateCount  = 0;
            m_oreListCache = new StringBuilder();
            //m_oreLocations = new Dictionary<Vector3D, NaniteMiningItem>();

            MiningBlock.AppendingCustomInfo += MiningBlock_AppendingCustomInfo;
        }
Пример #22
0
        public override void Init(MyObjectBuilder_EntityBase objectBuilder)
        {
            if (m_lock == null)
            {
                m_lock = new FastResourceLock();
            }

            base.Init(objectBuilder);

            using (m_lock.AcquireExclusiveUsing())
            {
                if (!NaniteConstructionManager.ProjectorBlocks.ContainsKey(Entity.EntityId))
                {
                    NaniteConstructionManager.ProjectorBlocks.Add(Entity.EntityId, Entity as IMyCubeBlock);
                }
            }
        }
Пример #23
0
 public GameWindowForm(string text)
 {
     this.m_emptyMouseEventArgs = new MouseEventArgs(MouseButtons.None, 0, 0, 0, 0);
     this.m_bufferedCharsLock   = new FastResourceLock();
     this.m_bufferedChars       = new List <char>();
     base.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
     base.FormBorderStyle  = FormBorderStyle.FixedSingle;
     this.BypassedMessages = new HashSet <int>();
     if (MyFakes.ENABLE_IME && (MySandboxGame.Config.Language == MyLanguagesEnum.ChineseChina))
     {
         this.InitializeIME();
     }
     else
     {
         this.BypassedMessages.Add(0x282);
         this.BypassedMessages.Add(6);
     }
     this.BypassedMessages.Add(0x100);
     this.BypassedMessages.Add(0x101);
     this.BypassedMessages.Add(0x102);
     this.BypassedMessages.Add(0x103);
     this.BypassedMessages.Add(260);
     this.BypassedMessages.Add(0x105);
     this.BypassedMessages.Add(0x106);
     this.BypassedMessages.Add(0x107);
     this.BypassedMessages.Add(0x20a);
     this.BypassedMessages.Add(0x200);
     this.BypassedMessages.Add(0x201);
     this.BypassedMessages.Add(0x202);
     this.BypassedMessages.Add(0x203);
     this.BypassedMessages.Add(0x204);
     this.BypassedMessages.Add(0x205);
     this.BypassedMessages.Add(0x206);
     this.BypassedMessages.Add(0x207);
     this.BypassedMessages.Add(520);
     this.BypassedMessages.Add(0x209);
     this.BypassedMessages.Add(0x20d);
     this.BypassedMessages.Add(0x20b);
     this.BypassedMessages.Add(0x20c);
     this.BypassedMessages.Add(20);
     this.BypassedMessages.Add(0x18);
     this.BypassedMessages.Add(7);
     this.BypassedMessages.Add(8);
 }
Пример #24
0
        public override void LoadData()
        {
            base.LoadData();

            if (MyPerGameSettings.EnableAi)
            {
                Sync.Players.NewPlayerRequestSucceeded += PlayerCreated;
                Sync.Players.LocalPlayerLoaded += LocalPlayerLoaded;
                Sync.Players.NewPlayerRequestFailed += Players_NewPlayerRequestFailed;
                if (Sync.IsServer)
                {
                    Sync.Players.PlayerRemoved += Players_PlayerRemoved;
                    Sync.Players.PlayerRequesting += Players_PlayerRequesting;
                }

                if (MyPerGameSettings.PathfindingType != null)
                {
                    m_pathfinding = Activator.CreateInstance(MyPerGameSettings.PathfindingType) as IMyPathfinding;
                }
                m_behaviorTreeCollection = new MyBehaviorTreeCollection();
                m_botCollection = new MyBotCollection(m_behaviorTreeCollection);
                m_loadedLocalPlayers = new List<int>();
                m_loadedBotObjectBuildersByHandle = new Dictionary<int, MyObjectBuilder_Bot>();
                m_agentsToSpawn = new Dictionary<int, AgentSpawnData>();
                m_removeQueue = new MyConcurrentQueue<BotRemovalRequest>();
                m_maxBotNotification = new MyHudNotification(MyCommonTexts.NotificationMaximumNumberBots, 2000, MyFontEnum.Red);
                m_processQueue = new MyConcurrentQueue<AgentSpawnData>();
                m_lock = new FastResourceLock();

#if !XB1
                if (MyFakes.ENABLE_BEHAVIOR_TREE_TOOL_COMMUNICATION)
                {
                    MyMessageLoop.AddMessageHandler(MyWMCodes.BEHAVIOR_GAME_UPLOAD_TREE, OnUploadNewTree);
                    MyMessageLoop.AddMessageHandler(MyWMCodes.BEHAVIOR_GAME_STOP_SENDING, OnBreakDebugging);
                    MyMessageLoop.AddMessageHandler(MyWMCodes.BEHAVIOR_GAME_RESUME_SENDING, OnResumeDebugging);
                }
#endif

                MyToolbarComponent.CurrentToolbar.SelectedSlotChanged += CurrentToolbar_SelectedSlotChanged;
                MyToolbarComponent.CurrentToolbar.SlotActivated += CurrentToolbar_SlotActivated;
                MyToolbarComponent.CurrentToolbar.Unselected += CurrentToolbar_Unselected;
            }
        }
Пример #25
0
        public static void InvokeOnGameThreadBlocking(Action action, ILogging logger = null)
        {
            var mutex = new FastResourceLock();

            mutex.AcquireExclusive();
            MyAPIGateway.Utilities.InvokeOnGameThread(WrapAction(() =>
            {
                try
                {
                    action();
                }
                finally
                {
                    mutex.ReleaseExclusive();
                }
            }, logger));
            mutex.AcquireExclusive();
            mutex.ReleaseExclusive();
        }
Пример #26
0
        public static void SaveFile <T>(string filename, T data)
        {
            try
            {
                FastResourceLock ExecutionLock = new FastResourceLock();

                using (ExecutionLock.AcquireExclusiveUsing())
                {
                    string xml = MyAPIGateway.Utilities.SerializeToXML(data);

                    string fileName;

                    if (!string.IsNullOrEmpty(filename))
                    {
                        fileName = string.Format(CfgFormat, filename);
                    }
                    else
                    {
                        fileName = string.Format(CfgFormat, "NewCfg");
                    }

                    Log.Write("Saving file \"" + fileName + "\"...");

                    TextWriter writer = MyAPIGateway.Utilities.WriteFileInLocalStorage(fileName, typeof(T));
                    writer.Write(MyAPIGateway.Utilities.SerializeToXML(data));
                    writer.Flush();
                    writer.Close();

                    Log.Write("Done!");
                }
            }
            catch (Exception e)
            {
                Log.Write("There was an error while saving:");
                Log.Write(" - " + e.Message);

                if (e.InnerException != null)
                {
                    Log.Write(" - " + e.InnerException.Message);
                }
            }
        }
Пример #27
0
        public override void Init(MyObjectBuilder_EntityBase objectBuilder)
        {
            if (m_lock == null)
            {
                m_lock = new FastResourceLock();
            }

            base.Init(objectBuilder);
            using (m_lock.AcquireExclusiveUsing())
            {
                if (!NaniteConstructionManager.NaniteBlocks.ContainsKey(Entity.EntityId))
                {
                    m_block = new NaniteConstructionBlock(Entity);
                    NaniteConstructionManager.NaniteBlocks.Add(Entity.EntityId, m_block);
                    IMySlimBlock slimBlock = ((MyCubeBlock)m_block.ConstructionBlock).SlimBlock as IMySlimBlock;
                    Logging.Instance.WriteLine(string.Format("ADDING Nanite Factory: conid={0} physics={1} ratio={2}", Entity.EntityId, m_block.ConstructionBlock.CubeGrid.Physics == null, slimBlock.BuildLevelRatio));

                    //if (NaniteConstructionManager.NaniteSync != null)
                    //    NaniteConstructionManager.NaniteSync.SendNeedTerminalSettings(Entity.EntityId);
                }
            }
        }
Пример #28
0
        internal MyVoxelPhysicsBody(MyVoxelBase voxelMap, float phantomExtend, float predictionSize = 3f, bool lazyPhysics = false) : base(voxelMap, RigidBodyFlag.RBF_STATIC)
        {
            this.RunningBatchTask     = new MyPrecalcJobPhysicsBatch[2];
            this.m_nearbyEntities     = new HashSet <IMyEntity>();
            this.m_nearbyEntitiesLock = new FastResourceLock();
            this.m_workTracker        = new MyWorkTracker <MyCellCoord, MyPrecalcJobPhysicsPrefetch>(MyCellCoord.Comparer);
            this.m_cellsOffset        = new Vector3I(0, 0, 0);
            this.m_staticForCluster   = true;
            this.m_predictionSize     = 3f;
            this.m_queuedRange        = new BoundingBoxI(-1, -1);
            this.InvalidCells         = new HashSet <Vector3I>[] { new HashSet <Vector3I>(), new HashSet <Vector3I>() };
            this.m_predictionSize     = predictionSize;
            this.m_phantomExtend      = phantomExtend;
            this.m_voxelMap           = voxelMap;
            Vector3I vectori1 = this.m_voxelMap.Size >> 3;

            this.m_cellsOffset = this.m_voxelMap.StorageMin >> 3;
            if (!MyFakes.ENABLE_LAZY_VOXEL_PHYSICS || !lazyPhysics)
            {
                this.CreateRigidBodies();
            }
            base.MaterialType = VRage.Game.MyMaterialType.ROCK;
        }
Пример #29
0
        public override void Init(MyObjectBuilder_EntityBase objectBuilder)
        {
            if (m_lock == null)
            {
                m_lock = new FastResourceLock();
            }

            base.Init(objectBuilder);

            using (m_lock.AcquireExclusiveUsing())
            {
                if (!NaniteConstructionManager.AssemblerBlocks.Contains(Entity.EntityId))
                {
                    NaniteConstructionManager.AssemblerBlocks.Add(Entity.EntityId);
                    if (NaniteConstructionManager.NaniteSync != null)
                    {
                        NaniteConstructionManager.NaniteSync.SendNeedAssemblerSettings(Entity.EntityId);
                    }
                }

                Logging.Instance.WriteLine($"Initializing NaniteAssemblerLogic for block: {Entity.EntityId}");
            }
        }
Пример #30
0
 public override void LoadData()
 {
     base.LoadData();
     if (MyPerGameSettings.EnableAi)
     {
         Sync.Players.NewPlayerRequestSucceeded += new Action <MyPlayer.PlayerId>(this.PlayerCreated);
         Sync.Players.LocalPlayerLoaded         += new Action <int>(this.LocalPlayerLoaded);
         Sync.Players.NewPlayerRequestFailed    += new Action <int>(this.Players_NewPlayerRequestFailed);
         if (Sync.IsServer)
         {
             Sync.Players.PlayerRemoved    += new Action <MyPlayer.PlayerId>(this.Players_PlayerRemoved);
             Sync.Players.PlayerRequesting += new PlayerRequestDelegate(this.Players_PlayerRequesting);
         }
         if (MyPerGameSettings.PathfindingType != null)
         {
             this.m_pathfinding = Activator.CreateInstance(MyPerGameSettings.PathfindingType) as IMyPathfinding;
         }
         this.m_behaviorTreeCollection          = new MyBehaviorTreeCollection();
         this.m_botCollection                   = new MyBotCollection(this.m_behaviorTreeCollection);
         this.m_loadedLocalPlayers              = new List <int>();
         this.m_loadedBotObjectBuildersByHandle = new Dictionary <int, MyObjectBuilder_Bot>();
         this.m_agentsToSpawn                   = new Dictionary <int, AgentSpawnData>();
         this.m_removeQueue        = new MyConcurrentQueue <BotRemovalRequest>();
         this.m_maxBotNotification = new MyHudNotification(MyCommonTexts.NotificationMaximumNumberBots, 0x7d0, "Red", MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, 0, MyNotificationLevel.Normal);
         this.m_processQueue       = new MyConcurrentQueue <AgentSpawnData>();
         this.m_lock = new FastResourceLock();
         if (MyFakes.ENABLE_BEHAVIOR_TREE_TOOL_COMMUNICATION)
         {
             MyMessageLoop.AddMessageHandler((uint)0x40a, new ActionRef <System.Windows.Forms.Message>(this.OnUploadNewTree));
             MyMessageLoop.AddMessageHandler((uint)0x40c, new ActionRef <System.Windows.Forms.Message>(this.OnBreakDebugging));
             MyMessageLoop.AddMessageHandler((uint)0x40b, new ActionRef <System.Windows.Forms.Message>(this.OnResumeDebugging));
         }
         MyToolbarComponent.CurrentToolbar.SelectedSlotChanged += new Action <MyToolbar, MyToolbar.SlotArgs>(this.CurrentToolbar_SelectedSlotChanged);
         MyToolbarComponent.CurrentToolbar.SlotActivated       += new Action <MyToolbar, MyToolbar.SlotArgs, bool>(this.CurrentToolbar_SlotActivated);
         MyToolbarComponent.CurrentToolbar.Unselected          += new Action <MyToolbar>(this.CurrentToolbar_Unselected);
     }
 }
            public LoadingConstruction(ProceduralStationModule module, Vector4I cell, ProceduralConstructionSeed seed) : base(module)
            {
                m_cell        = cell;
                m_boundingBox = module.StationNoise.GetNodeAABB(cell);
                RaiseMoved();
                Seed = seed;

                m_creationQueued         = false;
                m_creationQueueSemaphore = new FastResourceLock();

                m_construction  = null;
                m_grids         = null;
                m_component     = null;
                base.OnRemoved += (x) =>
                {
                    var station = x as LoadingConstruction;
                    if (station == null)
                    {
                        return;
                    }
                    station.TimeRemoved = DateTime.UtcNow;
                    Module.Debug("Marking station entity for removal!");
                };
            }
Пример #32
0
 private void grid_OnClosing(IMyEntity obj)
 {
     IMyCubeGrid grid = obj as IMyCubeGrid;
     grid.OnBlockAdded -= grid_OnBlockAdded;
     grid.OnBlockRemoved -= grid_OnBlockRemoved;
     grid.OnClosing -= grid_OnClosing;
     if (lock_cellCache == null)
         return;
     using (lock_cellPositions.AcquireExclusiveUsing())
     {
         CellPositions = null;
         LargeDoors = null;
     }
     lock_cellPositions = null;
     using (lock_cellCache.AcquireExclusiveUsing())
         CellCache.Remove(grid);
 }
Пример #33
0
        public void AsynchronousSaveWorld( )
        {
            if (m_isSaving)
            {
                return;
            }

            m_isSaving = true;

            try
            {
                DateTime saveStartTime = DateTime.Now;

                Task.Factory.StartNew(() =>
                {
                    SandboxGameAssemblyWrapper.Instance.GameAction(() =>
                    {
                        Type type = SandboxGameAssemblyWrapper.Instance.GetAssemblyType(WorldSnapshotNamespace, WorldSnapshotStaticClass);
                        BaseObject.InvokeStaticMethod(type,
                                                      WorldSnapshotSaveMethod,
                                                      new object[]
                        {
                            new Action(() =>
                            {
                                ApplicationLog.BaseLog.Info("Asynchronous Save Setup Started: {0}ms",
                                                            (DateTime.Now - saveStartTime)
                                                            .TotalMilliseconds);
                            }),
                            null
                        });
                    });

                    // Ugly -- Get rid of this?
                    DateTime start            = DateTime.Now;
                    FastResourceLock saveLock = InternalGetResourceLock( );
                    while (!saveLock.Owned)
                    {
                        if (DateTime.Now - start > TimeSpan.FromMilliseconds(20000))
                        {
                            return;
                        }

                        Thread.Sleep(1);
                    }

                    while (saveLock.Owned)
                    {
                        if (DateTime.Now - start > TimeSpan.FromMilliseconds(60000))
                        {
                            return;
                        }

                        Thread.Sleep(1);
                    }

                    ApplicationLog.BaseLog.Info("Asynchronous Save Completed: {0}ms", (DateTime.Now - saveStartTime).TotalMilliseconds);
                    OnWorldSaved( );
                    EntityEventManager.EntityEvent newEvent = new EntityEventManager.EntityEvent
                    {
                        type      = EntityEventManager.EntityEventType.OnSectorSaved,
                        timestamp = DateTime.Now,
                        entity    = null,
                        priority  = 0
                    };
                    EntityEventManager.Instance.AddEvent(newEvent);
                });
            }
            catch (Exception ex)
            {
            }
            finally
            {
                m_isSaving = false;
            }

            /*
             * try
             * {
             *      DateTime saveStartTime = DateTime.Now;
             *
             *      // It looks like keen as an overloaded save function that returns the WorldResourceManager after setting up a save, and then
             *      // allows you to write to disk from a separate thread?  Why aren't they using this on normal saves?!
             *      bool result = false;
             *      String arg0 = null;
             *      Object[] parameters =
             *      {
             *              null,
             *              arg0,
             *      };
             *
             *      Type[] paramTypes =
             *      {
             *              SandboxGameAssemblyWrapper.Instance.GetAssemblyType(WorldResourceManagerNamespace, WorldResourceManagerClass).MakeByRefType(),
             *              typeof(string),
             *      };
             *
             *      // Run overloaded save function with extra an out parameter that is set to a WorldResourceManagerClass
             *      SandboxGameAssemblyWrapper.Instance.GameAction(() =>
             *      {
             *              result = (bool)BaseObject.InvokeEntityMethod(BackingObject, WorldManagerSaveWorldMethod, parameters, paramTypes);
             *      });
             *
             *
             *      // Write to disk on a different thread using the WorldResourceManagerClass in the parameter
             *      ThreadPool.QueueUserWorkItem(new WaitCallback((object state) =>
             *      {
             *              if (result)
             *              {
             *                      ApplicationLog.BaseLog.Info((string.Format("Asynchronous Save Setup Time: {0}ms", (DateTime.Now - saveStartTime).TotalMilliseconds));
             *                      saveStartTime = DateTime.Now;
             *                      result = (bool)BaseObject.InvokeEntityMethod(parameters[0], WorldManagerSaveSnapshot);
             *              }
             *              else
             *              {
             *                      ApplicationLog.BaseLog.Error("Failed to save world (1)");
             *                      return;
             *              }
             *
             *              if (result)
             *              {
             *                      ApplicationLog.BaseLog.Info((string.Format("Asynchronous Save Successful: {0}ms", (DateTime.Now - saveStartTime).TotalMilliseconds));
             *              }
             *              else
             *              {
             *                      ApplicationLog.BaseLog.Error("Failed to save world (2)");
             *                      return;
             *              }
             *
             *              EntityEventManager.EntityEvent newEvent = new EntityEventManager.EntityEvent();
             *              newEvent.type = EntityEventManager.EntityEventType.OnSectorSaved;
             *              newEvent.timestamp = DateTime.Now;
             *              newEvent.entity = null;
             *              newEvent.priority = 0;
             *              EntityEventManager.Instance.AddEvent(newEvent);
             *      }));
             * }
             * catch (Exception ex)
             * {
             *      ApplicationLog.BaseLog.Error(ex);
             * }
             * finally
             * {
             *      m_isSaving = false;
             * }
             */
        }
Пример #34
0
 public void Dispose()
 {
     m_profiler.OnHistorySafe();
     m_lock.ReleaseExclusive();
     m_lock = null;
 }
Пример #35
0
		private static void Entities_OnCloseAll()
		{
			MyAPIGateway.Entities.OnCloseAll -= Entities_OnCloseAll;
			lock_search = null;
		}
Пример #36
0
 private static void Entities_OnCloseAll()
 {
     MyAPIGateway.Entities.OnCloseAll -= Entities_OnCloseAll;
     CellCache = null;
     lock_cellCache = null;
 }
Пример #37
0
 public SharedLock(FastResourceLock toLock)
 {
     this.MyLock = toLock;
     this.MyLock.AcquireShared();
 }
Пример #38
0
 static void Entities_OnCloseAll()
 {
     MyAPIGateway.Entities.OnCloseAll -= Entities_OnCloseAll;
     myLogger = null;
     MainThread_ReleaseExclusive();
     Lock_MainThread = null;
     lock_dummy = null;
 }
Пример #39
0
 public ExclusiveLock(FastResourceLock toLock)
 {
     this.MyLock = toLock;
     this.MyLock.AcquireExclusive();
 }