示例#1
0
        public void AppendRoom(ProceduralRoom room)
        {
            var iwatch = new Stopwatch();

            m_remapper.Remap(room, this);
            Logger.Debug("Added room {3} of {0} blocks with {1} aux grids in {2}", room.Part.PrimaryGrid.CubeBlocks.Count, room.Part.Prefab.CubeGrids.Length - 1, iwatch.Elapsed, room.Part.Name);
        }
示例#2
0
        private void ReceiveCallback(IAsyncResult result)
        {
            try {
                var endpoint = new IPEndPoint(IPAddress.None, SSDP_PORT);
                var received = client.EndReceive(result, ref endpoint);
                if (received == null)
                {
                    throw new IOException("Didn't receive anything");
                }
                if (received.Length == 0)
                {
                    throw new IOException("Didn't receive any bytes");
                }
#if DUMP_ALL_SSDP
                DebugFormat("{0} - SSDP Received a datagram", endpoint);
#endif
                using (var reader = new StreamReader(
                           new MemoryStream(received), Encoding.ASCII)) {
                    var proto = reader.ReadLine();
                    if (proto == null)
                    {
                        throw new IOException("Couldn't read protocol line");
                    }
                    proto = proto.Trim();
                    if (string.IsNullOrEmpty(proto))
                    {
                        throw new IOException("Invalid protocol line");
                    }
                    var method  = proto.Split(new char[] { ' ' }, 2)[0];
                    var headers = new Headers();
                    for (var line = reader.ReadLine(); line != null;
                         line = reader.ReadLine())
                    {
                        line = line.Trim();
                        if (string.IsNullOrEmpty(line))
                        {
                            break;
                        }
                        var parts = line.Split(new char[] { ':' }, 2);
                        headers[parts[0]] = parts[1].Trim();
                    }
#if DUMP_ALL_SSDP
                    DebugFormat("{0} - Datagram method: {1}", endpoint, method);
                    Debug(headers);
#endif
                    if (method == "M-SEARCH")
                    {
                        RespondToSearch(endpoint, headers["st"]);
                    }
                }
            }
            catch (IOException ex) {
                _logger.Debug("Failed to read SSDP message", ex);
            }
            catch (Exception ex) {
                _logger.Warn("Failed to read SSDP message", ex);
            }
            Receive();
        }
示例#3
0
        /*============================================================================*/
        /* Private Functions                                                          */
        /*============================================================================*/

        private void StoreMapping(ICommandMapping mapping)
        {
            _mappingsByCommand [mapping.CommandClass] = mapping;
            _mappings.Add(mapping);
            if (_logger != null)
            {
                _logger.Debug("{0} mapped to {1}", new object[] { _trigger, mapping });
            }
        }
示例#4
0
        private void ScanViewManagedContainers()
        {
            _logger.Debug("ViewManager is installed. Checking for managed containers...");
            IViewManager viewManager = _injector.GetInstance(typeof(IViewManager)) as IViewManager;

            foreach (object container in viewManager.Containers)
            {
                // TODO: Matt How to check if the view is on the stage?? Use a View watcher?
                //container.stage && ScanContainer(container);
                ScanContainer(container);
            }
        }
示例#5
0
        /*============================================================================*/
        /* Private Functions                                                          */
        /*============================================================================*/

        private MediatorMapping CreateMapping(Type mediatorType)
        {
            MediatorMapping mapping = new MediatorMapping(_typeFilter, mediatorType);

            _handler.AddMapping(mapping);
            _mappings [mediatorType] = mapping;
            if (_logger != null)
            {
                _logger.Debug("{0} mapped to {1}", _typeFilter, mapping);
            }
            return(mapping);
        }
        /*============================================================================*/
        /* Private Functions                                                          */
        /*============================================================================*/

        private ViewProcessorMapping CreateMapping(object processor)
        {
            ViewProcessorMapping mapping = new ViewProcessorMapping(_matcher, processor);

            _handler.AddMapping(mapping);
            _mappings[mapping.Processor == null ? mapping.ProcessorClass : mapping.Processor] = mapping;
            if (_logger != null)
            {
                _logger.Debug("{0} mapped to {1}", _matcher, mapping);
            }
            return(mapping);
        }
        public virtual void TestInterceptor()
        {
            ILogging logger = Logger.Get(typeof(LoggingTestCase.ITestLogger));

            Logger.Intercept(new _ILoggingInterceptor_136());
            ByRef called = new ByRef();

            logger.Forward(new _ITestLogger_145(called));
            ((LoggingTestCase.ITestLogger)logger.Debug()).Msg();
            Assert.AreEqual(Logger.Debug, ((Level)called.value));
            called.value = null;
            logger       = Logger.Get(typeof(LoggingTestCase.ITestLogger));
            ((LoggingTestCase.ITestLogger)logger.Debug()).Msg();
            Assert.AreEqual(Logger.Debug, ((Level)called.value));
        }
 private void ConfigureExistenceWatcher()
 {
     if (_injector.HasDirectMapping(typeof(IViewManager)))
     {
         _logger.Debug("Context has a ViewManager. Configuring view manager based context existence watcher...");
         _viewManagerBasedExistenceWatcher = new ViewManagerBasedExistenceWatcher(_context, _contextView, _modularityDispatcher, _parentFinder, _injector.GetInstance(typeof(IViewManager)) as IViewManager);
         _viewManagerBasedExistenceWatcher.Init();
     }
     else
     {
         _logger.Debug("Context has a ContextView. Configuring context view based context existence watcher...");
         _contextViewBasedExistenceWatcher = new ContextViewBasedExistenceWatcher(_context, _contextView, _modularityDispatcher, _parentFinder);
         _contextViewBasedExistenceWatcher.Init();
     }
 }
示例#9
0
        public void Send()
        {
            var msg = Encoding.ASCII.GetBytes(Message);

            try {
                var client = new UdpClient();
                client.Client.Bind(new IPEndPoint(LocalAddress, 0));
                client.Ttl = 10;
                client.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 10);
                client.BeginSend(msg, msg.Length, EndPoint, result =>
                {
                    try {
                        client.EndSend(result);
                    }
                    catch (Exception ex) {
                        _logger.Debug(ex);
                    }
                    finally {
                        try {
                            client.Close();
                        }
                        catch (Exception) {
                        }
                    }
                }, null);
            }
            catch (Exception ex) {
                _logger.Error(ex);
            }
            ++SendCount;
        }
示例#10
0
        private static string GenerateServerSignature()
        {
            var os      = Environment.OSVersion;
            var pstring = os.Platform.ToString();

            switch (os.Platform)
            {
            case PlatformID.Win32NT:
            case PlatformID.Win32S:
            case PlatformID.Win32Windows:
                pstring = "WIN";
                break;

            default:
                try {
                    pstring = Formatting.GetSystemName();
                }
                catch (Exception ex) {
                    _logger.Debug("Failed to get uname", ex);
                }
                break;
            }
            return(String.Format(
                       "{0}{1}/{2}.{3} UPnP/1.0 DLNADOC/1.5 sdlna/{4}.{5}",
                       pstring,
                       IntPtr.Size * 8,
                       os.Version.Major,
                       os.Version.Minor,
                       Assembly.GetExecutingAssembly().GetName().Version.Major,
                       Assembly.GetExecutingAssembly().GetName().Version.Minor
                       ));
        }
示例#11
0
        public ConstructionCopy(ProceduralRoom room, RoomRemapper remapper = null)
        {
            Logger = room.Owner.Logger.Root().CreateProxy(GetType().Name);
            var i = room.Part.PrimaryGrid;
            var o = new MyObjectBuilder_CubeGrid
            {
                GridSizeEnum           = i.GridSizeEnum,
                IsStatic               = true,
                DampenersEnabled       = true,
                Handbrake              = true,
                DisplayName            = room.Owner.Seed.Name,
                DestructibleBlocks     = true,
                IsRespawnGrid          = false,
                Editable               = true,
                PersistentFlags        = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.CastShadows,
                PositionAndOrientation = new MyPositionAndOrientation(GridCreator.WorldTransformFor(room.Owner))
            };

            BoundingBox = BoundingBoxD.CreateInvalid();

            Construction = room.Owner;
            PrimaryGrid  = o;
            AuxGrids     = new List <MyObjectBuilder_CubeGrid>();
            m_remapper   = remapper ?? new RoomRemapper(Logger.Root());

            var iwatch = new Stopwatch();

            m_remapper.Remap(room, this);
            Logger.Debug("Added room {3} of {0} blocks with {1} aux grids in {2}", room.Part.PrimaryGrid.CubeBlocks.Count, room.Part.Prefab.CubeGrids.Length - 1, iwatch.Elapsed, room.Part.Name);
        }
示例#12
0
        public static float RandomizeCoordinate(float playerPosition, float PlayerCoordinate, float screenDimension, float mapDimension, ILogging log)
        {
            float returnval = -1;
            int   lastFiftyProcent;

            lastFiftyProcent = tacoCalc.Next(50);
            bool IsIncrease = lastFiftyProcent % 2 == 0;

            returnval = GetDistanceWithRandom(screenDimension, lastFiftyProcent, IsIncrease);
            log.Debug($"POS {playerPosition} COOR { PlayerCoordinate} DIM {screenDimension} MAP {mapDimension} CHANGE POS {returnval}");
            if (!IsNewSeedAcceptable(PlayerCoordinate, mapDimension, returnval))
            {
                log.Debug("CHANGE INVERSED");
                returnval *= -1;
            }
            return(playerPosition += returnval);
        }
示例#13
0
        public virtual void TestSetLoggingLevel()
        {
            IList    methodsCalled = SetRootInterceptor();
            ILogging logger        = Logger.Get(typeof(LoggingTestCase.ITestLogger));

            Logger.LoggingLevel(Logger.Debug);
            ((LoggingTestCase.ITestLogger)logger.Trace()).Msg();
            ((LoggingTestCase.ITestLogger)logger.Debug()).Msg();
            ((LoggingTestCase.ITestLogger)logger.Info()).Msg();
            Assert.AreEqual(Pair.Of(Logger.Debug, "msg"), ((Pair)PopFirst(methodsCalled)));
            Assert.AreEqual(Pair.Of(Logger.Info, "msg"), ((Pair)PopFirst(methodsCalled)));
            logger.LoggingLevel(Logger.Info);
            ((LoggingTestCase.ITestLogger)logger.Debug()).Msg();
            ((LoggingTestCase.ITestLogger)logger.Info()).Msg();
            ((LoggingTestCase.ITestLogger)logger.Error()).Msg();
            Assert.AreEqual(Pair.Of(Logger.Info, "msg"), ((Pair)PopFirst(methodsCalled)));
            Assert.AreEqual(Pair.Of(Logger.Error, "msg"), ((Pair)PopFirst(methodsCalled)));
        }
示例#14
0
        public void CreateDeltaPackage()
        {
            var applicationMetadata = new ApplicationMetadata();

            applicationMetadata.ApplicationFolder  = @"C:\Users\aaron\AppData\Local\osulazer";
            applicationMetadata.ApplicationVersion = SemanticVersion.Parse("2021.129.0");

            //Apply update
            var wasSuccessful = _updateCreator.CreateDeltaPackage(applicationMetadata,
                                                                  @"C:\Users\aaron\AppData\Local\osulazer\app-2021.302.0",
                                                                  SemanticVersion.Parse("2021.226.0"),
                                                                  @"C:\Users\aaron\AppData\Local\osulazer\app-2021.226.0",
                                                                  SemanticVersion.BaseVersion(),
                                                                  null,
                                                                  @"C:\Users\aaron\AppData\Local\osulazer",
                                                                  progress: obj => _logger.Debug($"Progress: {obj * 100}"));

            Assert.True(wasSuccessful, "Wasn't able to apply update");
        }
示例#15
0
 private void Load(FileInfo file)
 {
     try {
         // Try external
         foreach (var i in exts)
         {
             var sti = new FileInfo(
                 System.IO.Path.ChangeExtension(file.FullName, i));
             try {
                 if (!sti.Exists)
                 {
                     sti = new FileInfo(file.FullName + i);
                 }
                 if (!sti.Exists)
                 {
                     continue;
                 }
                 text = FFmpeg.GetSubtitleSubrip(sti);
             }
             catch (NotSupportedException) {
             }
             catch (Exception ex) {
                 _logger.Debug(string.Format(
                                   "Failed to get subtitle from {0}", sti.FullName), ex);
             }
         }
         try {
             text = FFmpeg.GetSubtitleSubrip(file);
         }
         catch (NotSupportedException) {
         }
         catch (Exception ex) {
             _logger.Debug(string.Format(
                               "Failed to get subtitle from {0}", file.FullName), ex);
         }
     }
     catch (Exception ex) {
         _logger.Error(string.Format(
                           "Failed to load subtitle for {0}", file.FullName), ex);
     }
 }
示例#16
0
 private static void MoveFrom(string path)
 {
     try
     {
         logger.Debug("Installer move from '{0}'", path);
         // TODO: Create the necessary structure and perform the actual move of files into it from the given install path
     }
     catch (Exception e)
     {
         Failure(e.ToString());
     }
 }
示例#17
0
        /*============================================================================*/
        /* Private Functions                                                           */
        /*============================================================================*/

        private void AddContextView(object contextViewObject)
        {
            IContextView contextView = contextViewObject as IContextView;

            if (!HasContextBinding())
            {
                _logger.Debug("Mapping {0} as contextView", contextView.view);
                _injector.Map(typeof(IContextView)).ToValue(contextView);
            }
            else
            {
                _logger.Warn("A contextView has already been installed, ignoring {0}", contextView.view);
            }
        }
示例#18
0
        /// <summary>
        /// Checks string for anything that it shouldn't be in it
        /// </summary>
        /// <param name="chars"><see cref="char"/>[] that shouldn't be in <see cref="s"/></param>
        /// <param name="s">string to check</param>
        /// <param name="invalidChar"><see cref="char"/> that was in <see cref="s"/> but shouldn't be</param>
        private static bool CheckValidation(IEnumerable <char> chars, string s, out char?invalidChar)
        {
            Logger.Debug("Checking {0}", s);
            invalidChar = null;

            //Check that the string even has anything
            if (string.IsNullOrWhiteSpace(s))
            {
                Logger.Debug("{0} contains nothing", s);
                return(false);
            }

            //Check the chars
            foreach (var sChar in s.Where(chars.Contains))
            {
                invalidChar = sChar;
                Logger.Debug("{0} is not usable", s);
                return(false);
            }

            Logger.Debug("{0} is usable", s);
            return(true);
        }
示例#19
0
        private void WatchPlayer(PlayerResearchState data, string key)
        {
            var player = data.Player.Player;

            HashSet <ResearchStatefulKey> activated;
            var newlyWatched = !_activatedEntries.TryGetValue(player.IdentityId, out activated);

            if (newlyWatched)
            {
                activated = _activatedEntries[player.IdentityId] = new HashSet <ResearchStatefulKey>();
            }
            activated.Add(new ResearchStatefulKey(data.Definition.Id, key));

            if (!newlyWatched)
            {
                return;
            }
            _log.Debug($"Beginning to watch player {player.DisplayName}");
            player.Controller.ControlledEntityChanged += OnControlledEntityChanged;
            if (player.Controller.ControlledEntity != null)
            {
                WatchEntity(player.Controller.ControlledEntity);
            }
        }
示例#20
0
        public FFmpegTaskDto GetNext(string machineName)
        {
            if (string.IsNullOrWhiteSpace(machineName))
            {
                throw new ArgumentNullException(nameof(machineName));
            }

            var res = _repository.GetNextJob(machineName);

            if (res != null)
            {
                var guid = _repository.GetGuidById(res.FfmpegJobsId);
                _logging.Debug($"Assigned task {res.Id} (job id {res.FfmpegJobsId}) to {machineName}. Job correlation id {guid}");
            }
            return(res);
        }
        /*============================================================================*/
        /* Private Functions                                                          */
        /*============================================================================*/

        private void HandleType(object obj)
        {
            if (_initialized)
            {
                _logger.Debug("Already initialized. Instantiating config type {0}", obj);
                ProcessType(obj as Type);
            }
            else
            {
                _logger.Debug("Not yet initialized. Queuing config class {0}", obj);
                _queue.Add(obj);
            }
        }
示例#22
0
        private static string?GetVsTools()
        {
            //We already check in CreateLoader but makes the compiler happy
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                return(null);
            }
            ManagementObjectCollection mcCollection;

            try
            {
                using ManagementClass mc = new ManagementClass("MSFT_VSInstance");
                mcCollection             = mc.GetInstances();
            }
            catch (Exception e)
            {
                Logger.Error(e);
                return(null);
            }

            //We want to buildtools if they have it install, we'll use VS installs if needed
            ManagementBaseObject?vsInstall = null;

            foreach (var result in mcCollection)
            {
                vsInstall ??= result;
                if ((string?)result?["ProductId"] == "Microsoft.VisualStudio.Product.BuildTools")
                {
                    Logger.Debug("Found VS Build Tools, using that install");
                    return((string?)result["InstallLocation"]);
                }
            }

            var installLocation = (string?)vsInstall?["InstallLocation"];

            if (string.IsNullOrWhiteSpace(installLocation))
            {
                Logger.Error("Unable to find any VS install or VS Build Tools");
                return(null);
            }

            Logger.Information("Found VS install ({0}), using that", vsInstall?["Name"]);
            return(installLocation);
        }
示例#23
0
        /// <summary>
        /// Processes a file that has a delta update
        /// </summary>
        /// <param name="tempFolder">Where the temp folder is located</param>
        /// <param name="originalFile">Where the original file is</param>
        /// <param name="newFile">Where the updated file should be placed on disk</param>
        /// <param name="file">Details about the update</param>
        /// <param name="progress">Progress for applying the update</param>
        /// <returns>If the file was successfully updated</returns>
        public static async Task <bool> ProcessDeltaFile(TemporaryFolder tempFolder, string originalFile, string newFile, FileEntry file, Action <double>?progress = null)
        {
            if (file.Stream == null)
            {
                Logger.Warning("{0} was updated but we don't have the delta stream for it!", file.Filename);
                return(false);
            }
            Logger.Debug("File was updated, applying delta update");

            var deltaUpdater = DeltaUpdaters.GetUpdater(file.DeltaExtension);

            if (deltaUpdater != null)
            {
                return(await deltaUpdater.ApplyDeltaFile(tempFolder, originalFile, newFile, file.Filename, file.Stream, progress));
            }

            Logger.Error("Wasn't able to find what was responsible for creating this diff file (File: {0}, Extension: {1})", file.Filename, file.DeltaExtension);
            return(false);
        }
        /*============================================================================*/
        /* Private Functions                                                          */
        /*============================================================================*/

        private void AddContextView(object contextViewObject)
        {
            IContextView contextView = contextViewObject as IContextView;

            if (!(contextView.view is UnityEngine.Transform))
            {
                _logger.Warn("Cannot map {0} as Transform for the ContextViewTransformExtension to work. Try to configure with 'new TransformContextView(transform)'", contextView.view);
                return;
            }

            if (_injector.HasDirectMapping(typeof(UnityEngine.Transform)))
            {
                _logger.Warn("A Transform has already been mapped, ignoring {0}", contextView.view);
                return;
            }

            _logger.Debug("Mapping {0} as Transform", contextView.view);
            _injector.Map(typeof(UnityEngine.Transform)).ToValue(contextView.view);
        }
示例#25
0
        /// <exception cref="System.Security.SecurityException"></exception>
        /// <exception cref="System.MissingMethodException"></exception>
        public virtual void TestPrintWriterLogger()
        {
            ByteArrayOutputStream        bout        = new ByteArrayOutputStream();
            PrintWriterLoggerInterceptor interceptor = new PrintWriterLoggerInterceptor(new PrintWriter
                                                                                            (bout, true));

            Logger.Intercept(interceptor);
            ILogging logger = Logger.Get(typeof(LoggingTestCase.ITestLogger));

            ((LoggingTestCase.ITestLogger)logger.Debug()).Msg();
            ((LoggingTestCase.ITestLogger)logger.Info()).Msg();
            string actual   = Platform4.AsUtf8(bout.ToByteArray());
            string debugMsg = PrintWriterLoggerInterceptor.FormatMessage(Logger.Debug, "msg",
                                                                         null);
            string infoMsg = PrintWriterLoggerInterceptor.FormatMessage(Logger.Info, "msg", null
                                                                        );

            Assert.IsTrue((actual.IndexOf(debugMsg) >= 0));
            Assert.IsTrue((actual.IndexOf(infoMsg) >= 0));
        }
        public void Install(object extension)
        {
            Type type = extension.GetType();

            if (_types.ContainsKey(type))
            {
                return;
            }

            _logger.Debug("Installing extension {0}", extension);
            _types[type] = true;

            if (extension is IExtension)
            {
                // This check is to prevent TargetInvokationExecptions when an extension extend method errors
                (extension as IExtension).Extend(_context);
            }
            else
            {
                MethodInfo method = type.GetMethod("Extend");
                method.Invoke(extension, new object[] { (_context) });
            }
        }
示例#27
0
        private void DoConnect(DetectorData data)
        {
            var bb = data.BoundingBox;

            _detectorTree.OverlapAllBoundingBox(ref bb, _overlapResults);
            foreach (var k in _overlapResults)
            {
                if (k != data)
                {
                    _log.Debug(
                        $"Detectors overlap {data.Entity}:{data.Path}:{data.Input}:{data.Output} and {k.Entity}:{k.Path}:{k.Input}:{k.Output}");
                    var forward = k.Input && data.Output;
                    var reverse = k.Output && data.Input;
                    if (forward)
                    {
                        _network.Link(data.Entity, data.Path, k.Entity, k.Path, _network.DetectorConnectionData(reverse));
                    }
                    else if (reverse)
                    {
                        _network.Link(k.Entity, k.Path, data.Entity, data.Path, _network.DetectorConnectionData(false));
                    }
                }
            }
        }
示例#28
0
 public void extension_does_NOT_throw_for_DEBUG()
 {
     logger.Debug("");
 }
 public void Send(string toAddress, string subject)
 {
     logging.Debug("Sending mail");
     Console.WriteLine("Sending mail to [{0}] with subject [{1}]", toAddress, subject);
 }
示例#30
0
        public void Remap(ProceduralRoom room, ConstructionCopy dest)
        {
            if (dest.PrimaryGrid.GridSizeEnum != room.Part.PrimaryCubeSize)
            {
                throw new ArgumentException("Primary grid cube size and room's primary cube size differ");
            }
            // Setup remap parameters
            {
                var localTransform = Remap <GridRemap_LocalTransform>();
                localTransform.LocalTransform = room.Transform;
            }

            {
                var naming = Remap <GridRemap_Names>();
                naming.PrefixFor(GridRemap_Names.RemapType.All, room.GetName() + " ");
            }

            {
                var coloring = Remap <Coloring>();
                coloring.OverrideColor      = DebugRoomColors ? (SerializableVector3?)Utilities.NextColor.ColorToHSV() : null;
                coloring.HueRotation        = room.Owner.Seed.Faction.HueRotation;
                coloring.SaturationModifier = room.Owner.Seed.Faction.SaturationModifier;
                coloring.ValueModifier      = room.Owner.Seed.Faction.ValueModifier;
            }

            {
                var ownership = Remap <GridRemap_Ownership>();
                var faction   = room.Owner.Seed.Faction.GetOrCreateFaction();
                ownership.OwnerID              = faction?.FounderId ?? 0;
                ownership.ShareMode            = MyOwnershipShareModeEnum.Faction;
                ownership.UpgradeShareModeOnly = true;
            }

            var worldTransform = Remap <GridRemap_WorldTransform>();
            {
                var roomTransformScaled = room.Transform.GetFloatMatrix();
                roomTransformScaled.Translation *= MyDefinitionManager.Static.GetCubeSize(dest.PrimaryGrid.GridSizeEnum);

                var prefabPrimaryGridNewWorldMatrix = Matrix.Multiply(roomTransformScaled,
                                                                      dest.PrimaryGrid.PositionAndOrientation?.GetMatrix() ?? MatrixD.Identity);
                var prefabPrimaryGridOldWorldMatrix = room.Part.PrimaryGrid.PositionAndOrientation?.GetMatrix() ??
                                                      MatrixD.Identity;


                var prefabOldToNew = Matrix.Multiply(Matrix.Invert(prefabPrimaryGridOldWorldMatrix),
                                                     prefabPrimaryGridNewWorldMatrix);

                worldTransform.WorldTransform      = prefabOldToNew;
                worldTransform.WorldLinearVelocity = dest.PrimaryGrid.LinearVelocity;
            }

            // Grab OB copies
            var timer = new Stopwatch();

            timer.Restart();
            var roomGrid   = CloneUtilities.CloneFast(room.Part.PrimaryGrid);
            var otherGrids = room.Part.Prefab.CubeGrids.Where(x => x != room.Part.PrimaryGrid).Select(CloneUtilities.CloneFast).ToList();
            var allGrids   = new List <MyObjectBuilder_CubeGrid>(otherGrids)
            {
                roomGrid
            };

            Logger.Debug("Cloned {0} grids in {1}", allGrids.Count, timer.Elapsed);


            // Remap entity IDs
            timer.Restart();
            MyAPIGateway.Entities.RemapObjectBuilderCollection(allGrids);
            // If we have a primary ID copy it now.
            if (dest.PrimaryGrid.EntityId != 0)
            {
                var constRemapID = new ConstantEntityRemap(new Dictionary <long, long> {
                    [roomGrid.EntityId] = dest.PrimaryGrid.EntityId
                });
                // Anything referring to the root grid's entity ID needs to be changed to the old grid.
                foreach (var c in allGrids)
                {
                    c.Remap(constRemapID);
                }
            }
            else // otherwise, skip
            {
                dest.PrimaryGrid.EntityId = roomGrid.EntityId;
            }
            Logger.Debug("Remapped {0} grid IDs in {1}", allGrids.Count, timer.Elapsed);

            // Apply remap operators
            m_allPre.RemapAndReset(allGrids);
            m_primary.RemapAndReset(new[] { roomGrid });
            m_auxiliary.RemapAndReset(otherGrids);
            m_allPost.RemapAndReset(allGrids);

            // Merge data into primary grid from room grid
            dest.PrimaryGrid.CubeBlocks.Capacity += roomGrid.CubeBlocks.Count;
            dest.PrimaryGrid.CubeBlocks.AddRange(roomGrid.CubeBlocks);

            dest.PrimaryGrid.BlockGroups.Capacity += roomGrid.BlockGroups.Count;
            dest.PrimaryGrid.BlockGroups.AddRange(roomGrid.BlockGroups);

            // Seems suboptimal?  Can we transform this and only invalidate ones on a room border?
            dest.PrimaryGrid.ConveyorLines.Clear();

            // Not even going to try.
            dest.PrimaryGrid.OxygenAmount = null;
            dest.PrimaryGrid.Skeleton     = null;

            // Add aux grids
            dest.AuxGrids.AddRange(otherGrids);

            dest.BoundingBox = BoundingBoxD.CreateMerged(dest.BoundingBox, Utilities.TransformBoundingBox((BoundingBoxD)room.BoundingBoxBoth, worldTransform.WorldTransform));
        }