Exemple #1
0
        private void InitMountPoints(MyObjectBuilder_CubeBlockDefinition def)
        {
            if (MountPoints != null)
            {
                return;
            }

            var center = (Size - 1) / 2;

            // Order of block sides: right, top, front, left, bottom, back
            // Right = +X;    Top = +Y; Front = +Z
            //  Left = -X; Bottom = -Y;  Back = -Z
            // Side origins are always in lower left when looking at the side from outside.
            const float OFFSET_CONST   = 0.001f;
            const float THICKNESS_HALF = 0.0004f;

            if (!Context.IsBaseGame)
            {
                if (def.MountPoints != null && def.MountPoints.Length == 0)
                {
                    def.MountPoints = null;
                    string msg = "Obsolete default definition of mount points in " + def.Id;
                    MyDefinitionErrors.Add(Context, msg, ErrorSeverity.Warning);
                }
            }

            if (def.MountPoints == null)
            {
                // If there are no mount points defined, cover whole walls.
                List <MountPoint> mps = new List <MountPoint>(6);
                Vector3I          normalRight, normalLeft, normalTop, normalBottom, normalFront, normalBack;
                Vector3I.TransformNormal(ref Vector3I.Forward, ref m_mountPointTransforms[0], out normalRight);
                Vector3I.TransformNormal(ref Vector3I.Forward, ref m_mountPointTransforms[1], out normalTop);
                Vector3I.TransformNormal(ref Vector3I.Forward, ref m_mountPointTransforms[2], out normalFront);
                Vector3I.TransformNormal(ref Vector3I.Forward, ref m_mountPointTransforms[3], out normalLeft);
                Vector3I.TransformNormal(ref Vector3I.Forward, ref m_mountPointTransforms[4], out normalBottom);
                Vector3I.TransformNormal(ref Vector3I.Forward, ref m_mountPointTransforms[5], out normalBack);

                // Right and left walls
                {
                    Vector3 start = new Vector3(OFFSET_CONST, OFFSET_CONST, THICKNESS_HALF);
                    Vector3 end = new Vector3(Size.Z - OFFSET_CONST, Size.Y - OFFSET_CONST, -THICKNESS_HALF);
                    Vector3 s1, s2, e1, e2;
                    TransformMountPointPosition(ref start, 0, Size, out s1);
                    TransformMountPointPosition(ref end, 0, Size, out e1);
                    TransformMountPointPosition(ref start, 3, Size, out s2);
                    TransformMountPointPosition(ref end, 3, Size, out e2);
                    mps.Add(new MountPoint()
                    {
                        Start = s1, End = e1, Normal = normalRight
                    });
                    mps.Add(new MountPoint()
                    {
                        Start = s2, End = e2, Normal = normalLeft
                    });
                }

                // Top and bottom walls
                {
                    Vector3 start = new Vector3(OFFSET_CONST, OFFSET_CONST, THICKNESS_HALF);
                    Vector3 end = new Vector3(Size.X - OFFSET_CONST, Size.Z - OFFSET_CONST, -THICKNESS_HALF);
                    Vector3 s1, s2, e1, e2;
                    TransformMountPointPosition(ref start, 1, Size, out s1);
                    TransformMountPointPosition(ref end, 1, Size, out e1);
                    TransformMountPointPosition(ref start, 4, Size, out s2);
                    TransformMountPointPosition(ref end, 4, Size, out e2);
                    mps.Add(new MountPoint()
                    {
                        Start = s1, End = e1, Normal = normalTop
                    });
                    mps.Add(new MountPoint()
                    {
                        Start = s2, End = e2, Normal = normalBottom
                    });
                }

                // Front and back walls
                {
                    Vector3 start = new Vector3(OFFSET_CONST, OFFSET_CONST, THICKNESS_HALF);
                    Vector3 end = new Vector3(Size.X - OFFSET_CONST, Size.Y - OFFSET_CONST, -THICKNESS_HALF);
                    Vector3 s1, s2, e1, e2;
                    TransformMountPointPosition(ref start, 2, Size, out s1);
                    TransformMountPointPosition(ref end, 2, Size, out e1);
                    TransformMountPointPosition(ref start, 5, Size, out s2);
                    TransformMountPointPosition(ref end, 5, Size, out e2);
                    mps.Add(new MountPoint()
                    {
                        Start = s1, End = e1, Normal = normalFront
                    });
                    mps.Add(new MountPoint()
                    {
                        Start = s2, End = e2, Normal = normalBack
                    });
                }

                MountPoints = mps.ToArray();
                return;
            }
            else
            {
                var mpBuilders = def.MountPoints;
                MountPoints = new MountPoint[mpBuilders.Length];
                for (int i = 0; i < MountPoints.Length; ++i)
                {
                    var mpBuilder = mpBuilders[i]; // 'mp' stands for mount point
                    // I shrink mounts points a little to avoid overlaps when they are very close.
                    var mpStart  = new Vector3((Vector2)mpBuilder.Start + OFFSET_CONST, THICKNESS_HALF);
                    var mpEnd    = new Vector3((Vector2)mpBuilder.End - OFFSET_CONST, -THICKNESS_HALF);
                    var sideIdx  = (int)mpBuilder.Side;
                    var mpNormal = Vector3I.Forward;
                    TransformMountPointPosition(ref mpStart, sideIdx, Size, out mpStart);
                    TransformMountPointPosition(ref mpEnd, sideIdx, Size, out mpEnd);
                    Vector3I.TransformNormal(ref mpNormal, ref m_mountPointTransforms[sideIdx], out mpNormal);
                    MountPoints[i].Start          = mpStart;
                    MountPoints[i].End            = mpEnd;
                    MountPoints[i].Normal         = mpNormal;
                    MountPoints[i].ExclusionMask  = mpBuilder.ExclusionMask;
                    MountPoints[i].PropertiesMask = mpBuilder.PropertiesMask;
                }
            }
        }
        public override void Draw()
        {
            base.Draw();

            //VRageRender.MyRenderProxy.DebugDrawAABB(m_cubeBuilderAABB, Vector3.One, 1, 1, false);

            if (BlockCreationIsActivated)
            {
                MyHud.Crosshair.Position = MyHudCrosshair.ScreenCenter;
            }

            if (IsActivated)
            {
                if (DynamicMode)
                {
                    CurrentGrid     = null;
                    CurrentVoxelMap = null;
                }
                else
                {
                    ChoosePlacementObject();
                }
            }

            if (ShipCreationIsActivated)
            {
                m_shipCreationClipboard.Update();
                ShipCreationClipboard.CalculateRotationHints(m_rotationHints, m_rotationHintRotating);
            }
            else if (CopyPasteIsActivated)
            {
                Clipboard.CalculateRotationHints(m_rotationHints, m_rotationHintRotating);
            }
            else if (CopyPasteFloatingObjectIsActivated)
            {
                FloatingObjectClipboard.CalculateRotationHints(m_rotationHints, m_rotationHintRotating);
            }
            else if (MultiBlockCreationIsActivated)
            {
                m_multiBlockCreationClipboard.CalculateRotationHints(m_rotationHints, false);
            }

            if (!BuildInputValid || MultiBlockCreationIsActivated || ShipCreationIsActivated || CopyPasteIsActivated || CopyPasteFloatingObjectIsActivated)
            {
                m_renderData.ClearInstanceData();
                m_renderData.UpdateRenderInstanceData();
                m_renderData.UpdateRenderEntitiesData(CurrentGrid != null ? CurrentGrid.WorldMatrix : MatrixD.Identity, UseTransparency);

                if (!ShipCreationIsActivated && !CopyPasteIsActivated && !MultiBlockCreationIsActivated)
                {
                    m_rotationHints.Clear();
                    VRageRender.MyRenderProxy.RemoveBillboardViewProjection(0);
                }

                if (MyFakes.ENABLE_DEBUG_DRAW_TEXTURE_NAMES)
                {
                    DebugDrawModelTextures();
                }

                if (MultiBlockCreationIsActivated)
                {
                    UpdateBlockInfoHud();
                }

                return;
            }
            var startPosition = m_gizmo.SpaceDefault.m_startBuild ?? m_gizmo.SpaceDefault.m_startRemove;

            if (startPosition != null && m_gizmo.SpaceDefault.m_continueBuild != null)
            {
                Vector3I rotatedSize;
                Vector3I.TransformNormal(ref CurrentBlockDefinition.Size, ref m_gizmo.SpaceDefault.m_localMatrixAdd, out rotatedSize);
                rotatedSize = Vector3I.Abs(rotatedSize);

                int      stepCount;
                Vector3I stepDelta;
                Vector3I counter;

                ComputeSteps(startPosition.Value, m_gizmo.SpaceDefault.m_continueBuild.Value,
                             m_gizmo.SpaceDefault.m_startBuild.HasValue ? rotatedSize : Vector3I.One, out stepDelta, out counter, out stepCount);
                m_cubeCountStringBuilder.Clear();
                m_cubeCountStringBuilder.Append("  ");
                m_cubeCountStringBuilder.AppendInt32(stepCount);

                MyGuiManager.DrawString(MyFontEnum.White, m_cubeCountStringBuilder, new Vector2(0.5f, 0.5f), 1.5f);
            }

            bool addPos    = m_gizmo.SpaceDefault.m_startBuild.HasValue;
            bool removePos = false;

            if (DynamicMode)
            {
                Vector3D freePlacementIntersectionPoint = GetFreeSpacePlacementPosition(out m_gizmo.SpaceDefault.m_dynamicBuildAllowed);
                m_gizmo.SpaceDefault.m_worldMatrixAdd.Translation = freePlacementIntersectionPoint;

                addPos = true;
            }
            else
            {
                if (m_gizmo.SpaceDefault.m_startBuild == null && m_gizmo.SpaceDefault.m_startRemove == null)
                {
                    if (!FreezeGizmo)
                    {
                        float gridSize = MyDefinitionManager.Static.GetCubeSize(CurrentBlockDefinition.CubeSize);
                        addPos = GetAddAndRemovePositions(gridSize, PlacingSmallGridOnLargeStatic, out m_gizmo.SpaceDefault.m_addPos, out m_gizmo.SpaceDefault.m_addPosSmallOnLarge, out m_gizmo.SpaceDefault.m_addDir,
                                                          out m_gizmo.SpaceDefault.m_removePos, out m_gizmo.SpaceDefault.m_removeBlock, out m_gizmo.SpaceDefault.m_blockIdInCompound);
                    }

                    if (addPos)
                    {
                        if (PlacingSmallGridOnLargeStatic)
                        {
                            m_gizmo.SpaceDefault.m_localMatrixAdd.Translation = m_gizmo.SpaceDefault.m_addPosSmallOnLarge.Value;
                        }
                        else
                        {
                            m_gizmo.SpaceDefault.m_localMatrixAdd.Translation = m_gizmo.SpaceDefault.m_addPos;
                        }

                        if (CurrentGrid != null)
                        {
                            m_gizmo.SpaceDefault.m_worldMatrixAdd = m_gizmo.SpaceDefault.m_localMatrixAdd * CurrentGrid.WorldMatrix;
                        }
                        else
                        {
                            m_gizmo.SpaceDefault.m_worldMatrixAdd = m_gizmo.SpaceDefault.m_localMatrixAdd;
                        }
                        Debug.Assert(!m_gizmo.SpaceDefault.m_worldMatrixAdd.IsNan(), "Invalid gizmo matrix");

                        if (m_gizmo.SpaceDefault.m_removeBlock != null)
                        {
                            removePos = true;
                        }
                    }
                }
            }

            bool buildingDisabledByCockpit = MySession.ControlledEntity != null && MySession.ControlledEntity is MyCockpit && !DeveloperSpectatorIsBuilding;

            //bool buildingDisabledByCockpit = true;
            if (!buildingDisabledByCockpit)
            {
                if (IsInSymmetrySettingMode)
                {
                    m_gizmo.SpaceDefault.m_continueBuild = null;
                    addPos    = false;
                    removePos = false;

                    if (m_gizmo.SpaceDefault.m_removeBlock != null)
                    {
                        var min = (m_gizmo.SpaceDefault.m_removeBlock.Min * CurrentGrid.GridSize);
                        var max = (m_gizmo.SpaceDefault.m_removeBlock.Max * CurrentGrid.GridSize);

                        Vector3 center = (min + max) * 0.5f;

                        Color color = DrawSymmetryPlane(m_symmetrySettingMode, CurrentGrid, center);

                        DrawSemiTransparentBox(CurrentGrid, m_gizmo.SpaceDefault.m_removeBlock, color.ToVector4());
                    }
                }

                if (CurrentGrid != null && (UseSymmetry || IsInSymmetrySettingMode))
                {
                    if (CurrentGrid.XSymmetryPlane != null)
                    {
                        Vector3 center = CurrentGrid.XSymmetryPlane.Value * CurrentGrid.GridSize;
                        DrawSymmetryPlane(CurrentGrid.XSymmetryOdd ? MySymmetrySettingModeEnum.XPlaneOdd : MySymmetrySettingModeEnum.XPlane, CurrentGrid, center);
                    }

                    if (CurrentGrid.YSymmetryPlane != null)
                    {
                        Vector3 center = CurrentGrid.YSymmetryPlane.Value * CurrentGrid.GridSize;
                        DrawSymmetryPlane(CurrentGrid.YSymmetryOdd ? MySymmetrySettingModeEnum.YPlaneOdd : MySymmetrySettingModeEnum.YPlane, CurrentGrid, center);
                    }

                    if (CurrentGrid.ZSymmetryPlane != null)
                    {
                        Vector3 center = CurrentGrid.ZSymmetryPlane.Value * CurrentGrid.GridSize;
                        DrawSymmetryPlane(CurrentGrid.ZSymmetryOdd ? MySymmetrySettingModeEnum.ZPlaneOdd : MySymmetrySettingModeEnum.ZPlane, CurrentGrid, center);
                    }
                }
            }

            UpdateGizmos(addPos, removePos, true);

            m_renderData.UpdateRenderInstanceData();

            if (DynamicMode || CurrentVoxelMap != null)
            {
                MatrixD  drawMatrix = m_gizmo.SpaceDefault.m_worldMatrixAdd;
                Vector3D rotatedModelOffset;
                Vector3D.TransformNormal(ref CurrentBlockDefinition.ModelOffset, ref drawMatrix, out rotatedModelOffset);

                drawMatrix.Translation = drawMatrix.Translation + rotatedModelOffset;

                m_renderData.UpdateRenderEntitiesData(drawMatrix, UseTransparency);
            }
            else
            {
                m_renderData.UpdateRenderEntitiesData(CurrentGrid != null ? CurrentGrid.WorldMatrix : MatrixD.Identity, UseTransparency);
            }

            UpdateBlockInfoHud();

            DebugDraw();
        }
Exemple #3
0
        private void Process(CommandFeedback feedback, IMyCubeGrid grid)
        {
            if (grid.CustomName == null || !grid.CustomName.StartsWithICase("EqProcBuild"))
            {
                return;
            }
            var ob = grid.GetObjectBuilder(true) as MyObjectBuilder_CubeGrid;

            if (ob == null)
            {
                return;
            }
            this.Info("Begin processing {0}", grid.CustomName);
            feedback?.Invoke("Processing {0}", grid.CustomName);
            try
            {
                var dummyDel  = new List <MyTuple <MyObjectBuilder_CubeBlock, string> >();
                var blockKeep = new List <MyObjectBuilder_CubeBlock>();
                var blockMap  = new Dictionary <Vector3I, MyObjectBuilder_CubeBlock>(Vector3I.Comparer);
                foreach (var block in ob.CubeBlocks)
                {
                    var mount = false;
                    foreach (var name in block.ConfigNames())
                    {
                        if (!name.StartsWithICase(MountDelegated) && !name.StartsWithICase(ReservedSpaceDelegated))
                        {
                            continue;
                        }
                        dummyDel.Add(MyTuple.Create(block, name));
                        mount = true;
                        break;
                    }
                    if (mount)
                    {
                        continue;
                    }

                    var      blockMin = (Vector3I)block.Min;
                    Vector3I blockMax;
                    BlockTransformations.ComputeBlockMax(block, out blockMax);
                    for (var rangeItr = new Vector3I_RangeIterator(ref blockMin, ref blockMax); rangeItr.IsValid(); rangeItr.MoveNext())
                    {
                        blockMap[rangeItr.Current] = block;
                    }
                    blockKeep.Add(block);
                }
                this.Info("Found {0} blocks to keep, {1} block mounts to remap", blockKeep.Count, dummyDel.Count);
                foreach (var pair in dummyDel)
                {
                    var block   = pair.Item1;
                    var useName = pair.Item2;

                    IEnumerable <Base6Directions.Direction> dirs = Base6Directions.EnumDirections;
                    var def       = MyDefinitionManager.Static.GetCubeBlockDefinition(pair.Item1);
                    var transform = new MatrixI(block.BlockOrientation);
                    if (def?.MountPoints != null)
                    {
                        var mountDirs = new HashSet <Base6Directions.Direction>();
                        foreach (var mount in def.MountPoints)
                        {
                            mountDirs.Add(Base6Directions.GetDirection(Vector3I.TransformNormal(mount.Normal, ref transform)));
                        }
                    }

                    var args     = useName.Split(' ');
                    var keepArgs = new List <string>(args.Length);
                    foreach (var arg in args)
                    {
                        if (arg.StartsWithICase(PartDummyUtils.ArgumentMountDirection))
                        {
                            Base6Directions.Direction dir;
                            if (Enum.TryParse(arg.Substring(2), out dir))
                            {
                                dirs = new[] { transform.GetDirection(Base6Directions.GetOppositeDirection(dir)) }
                            }
                            ;
                            else
                            {
                                this.Error("Failed to parse direction argument \"{0}\"", arg);
                                feedback?.Invoke("Error: Failed to parse direction argument \"{0}\"", arg);
                            }
                        }
                        else
                        {
                            keepArgs.Add(arg);
                        }
                    }
                    useName = string.Join(" ", keepArgs);

                    MyObjectBuilder_CubeBlock outputBlock = null;
                    var outputDir = Base6Directions.Direction.Forward;
                    foreach (var dir in dirs)
                    {
                        MyObjectBuilder_CubeBlock tmp;
                        if (!blockMap.TryGetValue(block.Min + Base6Directions.GetIntVector(dir), out tmp))
                        {
                            continue;
                        }
                        if (tmp.ConfigNames().Any(x => x.StartsWithICase(MountDelegated)))
                        {
                            continue;
                        }
                        if (outputBlock != null)
                        {
                            this.Error("Multiple directions found for {0}", pair.Item2);
                            feedback?.Invoke("Error: Multiple directions found for {0}", pair.Item2);
                        }
                        outputBlock = tmp;
                        outputDir   = dir;
                    }
                    if (outputBlock == null || !ApplyDelegate(ob, block, useName, outputBlock, outputDir))
                    {
                        this.Error("Failed to find delegated mount point for {0}", pair.Item2);
                        feedback?.Invoke("Error: Failed to find delegated mount point for {0}", pair.Item2);
                    }
                }
                ob.CubeBlocks = blockKeep;

                // Grab related grids!
                var relatedGrids = new HashSet <IMyCubeGrid> {
                    grid
                };
                var scanRelated           = new Queue <IMyCubeGrid>();
                var relatedGridController = new Dictionary <IMyCubeGrid, IMyCubeBlock>();
                scanRelated.Enqueue(grid);
                while (scanRelated.Count > 0)
                {
                    var          subGrid = scanRelated.Dequeue();
                    IMyCubeBlock controllerForThisGrid = null;
                    relatedGridController.TryGetValue(subGrid, out controllerForThisGrid);

                    subGrid.GetBlocks(null, (y) =>
                    {
                        var x = y?.FatBlock;
                        if (x == null)
                        {
                            return(false);
                        }
                        var childGrid = (x as IMyMechanicalConnectionBlock)?.TopGrid;
                        if (childGrid != null && relatedGrids.Add(childGrid))
                        {
                            scanRelated.Enqueue(childGrid);
                            relatedGridController[childGrid] = x.CubeGrid == grid ? x : controllerForThisGrid;
                        }
                        var parentGrid = (x as IMyAttachableTopBlock)?.Base?.CubeGrid;
                        // ReSharper disable once InvertIf
                        if (parentGrid != null && relatedGrids.Add(parentGrid))
                        {
                            scanRelated.Enqueue(parentGrid);
                            relatedGridController[parentGrid] = x.CubeGrid == grid ? x : controllerForThisGrid;
                        }
                        return(false);
                    });
                }
                relatedGrids.Remove(grid);
                var removedNoController = relatedGrids.RemoveWhere(x => !relatedGridController.ContainsKey(x));
                if (removedNoController > 0)
                {
                    this.Error("Failed to find the mechanical connection block for all subgrids.  {0} will be excluded",
                               removedNoController);
                    feedback?.Invoke("Error: Failed to find the mechanical connection block for all subgrids.  {0} will be excluded",
                                     removedNoController);
                }
                // Need to add reserved space for subgrids so they don't overlap.  So compute that.  Yay!
                foreach (var rel in relatedGrids)
                {
                    IMyCubeBlock root;
                    if (!relatedGridController.TryGetValue(rel, out root))
                    {
                        this.Error("Unable to find the mechanical connection for grid {0}", rel.CustomName);
                        feedback?.Invoke("Error: Unable to find the mechanical connection for grid {0}",
                                         rel.CustomName);
                        continue;
                    }
                    MyObjectBuilder_CubeBlock blockDest;
                    if (blockMap.TryGetValue(root.Min, out blockDest))
                    {
                        var blockLocal = (MatrixD) new MatrixI(blockDest.BlockOrientation).GetFloatMatrix();
                        blockLocal.Translation = (Vector3I)blockDest.Min * grid.GridSize;
                        var blockWorld = MatrixD.Multiply(blockLocal, grid.WorldMatrix);

                        var worldAABB = rel.WorldAABB;
                        worldAABB = Utilities.TransformBoundingBox(worldAABB, MatrixD.Invert(blockWorld));
                        var gridAABB = new BoundingBoxI(Vector3I.Floor(worldAABB.Min / grid.GridSize), Vector3I.Ceiling(worldAABB.Max / grid.GridSize));
                        var code     = $"{PartMetadata.ReservedSpacePrefix} NE:{gridAABB.Min.X}:{gridAABB.Min.Y}:{gridAABB.Min.Z} PE:{gridAABB.Max.X}:{gridAABB.Max.Y}:{gridAABB.Max.Z}";
                        this.Info("Added reserved space for subgrid {0}: Spec is \"{1}\"", rel.CustomName, code);
                        if (blockDest.Name == null || blockDest.Name.Trim().Length == 0)
                        {
                            blockDest.Name = code;
                        }
                        else
                        {
                            blockDest.Name += PartMetadata.MultiUseSentinel + code;
                        }
                    }
                    else
                    {
                        this.Error("Unable to find the OB for grid block {0} ({1}, {2}, {3}).  Is it a delegate?", (root as IMyTerminalBlock)?.CustomName ?? root.Name, root.Min.X, root.Min.Y, root.Min.Z);
                        feedback?.Invoke("Unable to the find OB for grid block {0} ({1}, {2}, {3}).  Was it a delegate?", (root as IMyTerminalBlock)?.CustomName ?? root.Name, root.Min.X, root.Min.Y, root.Min.Z);
                    }
                }

                var allGrids = new List <MyObjectBuilder_CubeGrid>(relatedGrids.Count + 1)
                {
                    ob
                };
                allGrids.AddRange(relatedGrids.Select(relGrid => relGrid.GetObjectBuilder(false)).OfType <MyObjectBuilder_CubeGrid>());

                // Compose description: TODO I'd love if this actually worked :/
                // var storage = new MyPartMetadata();
                // storage.InitFromGrids(ob, allGrids);
                // var data = Convert.ToBase64String(MyAPIGateway.Utilities.SerializeToBinary(storage.GetObjectBuilder()));

                var defOut = new MyObjectBuilder_PrefabDefinition()
                {
                    Id        = new SerializableDefinitionId(typeof(MyObjectBuilder_PrefabDefinition), grid.CustomName),
                    CubeGrids = allGrids.ToArray()
                };

                var fileName = grid.CustomName + ".sbc";
                this.Info("Saving {1} grids as {0}", fileName, defOut.CubeGrids.Length);
                feedback?.Invoke("Saving {1} grids as {0}", fileName, defOut.CubeGrids.Length);

                var mishMash = new MyObjectBuilder_Definitions()
                {
                    Prefabs = new MyObjectBuilder_PrefabDefinition[] { defOut }
                };
                var writer = MyAPIGateway.Utilities.WriteBinaryFileInLocalStorage(fileName, typeof(DesignTools));
                var obCode = MyAPIGateway.Utilities.SerializeToXML(mishMash);
                obCode = obCode.Replace("encoding=\"utf-16\"", "encoding=\"utf-8\"");
                writer.Write(Encoding.UTF8.GetBytes(obCode));
                writer.Close();
            }
            catch (Exception e)
            {
                this.Error("Failed to parse.  Error:\n{0}", e.ToString());
            }
        }
        private void InitMountPoints(MyObjectBuilder_CubeBlockDefinition def)
        {
            if (MountPoints != null)
            {
                return;
            }

            var center = (Size - 1) / 2;


            if (!Context.IsBaseGame)
            {
                if (def.MountPoints != null && def.MountPoints.Length == 0)
                {
                    def.MountPoints = null;
                    string msg = "Obsolete default definition of mount points in " + def.Id;
                    MyDefinitionErrors.Add(Context, msg, ErrorSeverity.Warning);
                }
            }

            if (def.MountPoints == null)
            {
                // If there are no mount points defined, cover whole walls.
                List <MountPoint> mps = new List <MountPoint>(6);
                Vector3I          normalRight, normalLeft, normalTop, normalBottom, normalFront, normalBack;
                Vector3I.TransformNormal(ref Vector3I.Forward, ref m_mountPointTransforms[0], out normalRight);
                Vector3I.TransformNormal(ref Vector3I.Forward, ref m_mountPointTransforms[1], out normalTop);
                Vector3I.TransformNormal(ref Vector3I.Forward, ref m_mountPointTransforms[2], out normalFront);
                Vector3I.TransformNormal(ref Vector3I.Forward, ref m_mountPointTransforms[3], out normalLeft);
                Vector3I.TransformNormal(ref Vector3I.Forward, ref m_mountPointTransforms[4], out normalBottom);
                Vector3I.TransformNormal(ref Vector3I.Forward, ref m_mountPointTransforms[5], out normalBack);

                // Right and left walls
                {
                    Vector3 start = new Vector3(OFFSET_CONST, OFFSET_CONST, THICKNESS_HALF);
                    Vector3 end = new Vector3(Size.Z - OFFSET_CONST, Size.Y - OFFSET_CONST, -THICKNESS_HALF);
                    Vector3 s1, s2, e1, e2;
                    TransformMountPointPosition(ref start, 0, Size, out s1);
                    TransformMountPointPosition(ref end, 0, Size, out e1);
                    TransformMountPointPosition(ref start, 3, Size, out s2);
                    TransformMountPointPosition(ref end, 3, Size, out e2);
                    mps.Add(new MountPoint()
                    {
                        Start = s1, End = e1, Normal = normalRight, Enabled = true
                    });
                    mps.Add(new MountPoint()
                    {
                        Start = s2, End = e2, Normal = normalLeft, Enabled = true
                    });
                }

                // Top and bottom walls
                {
                    Vector3 start = new Vector3(OFFSET_CONST, OFFSET_CONST, THICKNESS_HALF);
                    Vector3 end = new Vector3(Size.X - OFFSET_CONST, Size.Z - OFFSET_CONST, -THICKNESS_HALF);
                    Vector3 s1, s2, e1, e2;
                    TransformMountPointPosition(ref start, 1, Size, out s1);
                    TransformMountPointPosition(ref end, 1, Size, out e1);
                    TransformMountPointPosition(ref start, 4, Size, out s2);
                    TransformMountPointPosition(ref end, 4, Size, out e2);
                    mps.Add(new MountPoint()
                    {
                        Start = s1, End = e1, Normal = normalTop, Enabled = true
                    });
                    mps.Add(new MountPoint()
                    {
                        Start = s2, End = e2, Normal = normalBottom, Enabled = true
                    });
                }

                // Front and back walls
                {
                    Vector3 start = new Vector3(OFFSET_CONST, OFFSET_CONST, THICKNESS_HALF);
                    Vector3 end = new Vector3(Size.X - OFFSET_CONST, Size.Y - OFFSET_CONST, -THICKNESS_HALF);
                    Vector3 s1, s2, e1, e2;
                    TransformMountPointPosition(ref start, 2, Size, out s1);
                    TransformMountPointPosition(ref end, 2, Size, out e1);
                    TransformMountPointPosition(ref start, 5, Size, out s2);
                    TransformMountPointPosition(ref end, 5, Size, out e2);
                    mps.Add(new MountPoint()
                    {
                        Start = s1, End = e1, Normal = normalFront, Enabled = true
                    });
                    mps.Add(new MountPoint()
                    {
                        Start = s2, End = e2, Normal = normalBack, Enabled = true
                    });
                }

                MountPoints = mps.ToArray();
                return;
            }
            else
            {
                Debug.Assert(m_tmpMounts.Count == 0);
                SetMountPoints(ref MountPoints, def.MountPoints, m_tmpMounts);

                if (def.BuildProgressModels != null)
                {
                    for (int index = 0; index < def.BuildProgressModels.Count; ++index)
                    {
                        var defBuildProgressModel = BuildProgressModels[index];
                        if (defBuildProgressModel == null)
                        {
                            continue;
                        }

                        var obBuildProgressModel = def.BuildProgressModels[index];
                        if (obBuildProgressModel.MountPoints == null)
                        {
                            continue;
                        }

                        foreach (var mountPoint in obBuildProgressModel.MountPoints)
                        {
                            int sideId = (int)mountPoint.Side;
                            if (!m_tmpIndices.Contains(sideId))
                            {
                                m_tmpMounts.RemoveAll((mount) => { return((int)mount.Side == sideId); });
                                m_tmpIndices.Add(sideId);
                            }
                            m_tmpMounts.Add(mountPoint);
                        }
                        m_tmpIndices.Clear();
                        defBuildProgressModel.MountPoints = new MountPoint[m_tmpMounts.Count];
                        SetMountPoints(ref defBuildProgressModel.MountPoints, m_tmpMounts.ToArray(), null);
                    }
                }
                m_tmpMounts.Clear();
            }
        }
Exemple #5
0
        public override void Remap(MyObjectBuilder_CubeGrid grid)
        {
            var transformCopy = LocalTransform;

            var minToMin = new Dictionary <Vector3I, Vector3I>(grid.CubeBlocks.Count * 3 / 2);

            foreach (var x in grid.CubeBlocks)
            {
                var      orig = (Vector3I)x.Min;
                var      cMin = orig;
                Vector3I cMax;
                BlockTransformations.ComputeBlockMax(x, out cMax);
                x.BlockOrientation.Forward = LocalTransform.GetDirection(x.BlockOrientation.Forward);
                x.BlockOrientation.Up      = LocalTransform.GetDirection(x.BlockOrientation.Up);
                Vector3I.Transform(ref cMin, ref transformCopy, out cMin);
                Vector3I.Transform(ref cMax, ref transformCopy, out cMax);
                minToMin[orig] = x.Min = Vector3I.Min(cMin, cMax);

                var proj = x as MyObjectBuilder_ProjectorBase;
                // Don't have to update the rotation; it is bound to the world matrix of the projector.
                if (proj != null)
                {
                    Vector3I.TransformNormal(ref proj.ProjectionOffset, ref transformCopy, out proj.ProjectionOffset);
                }
            }

            if (grid.BlockGroups != null)
            {
                foreach (var g in grid.BlockGroups)
                {
                    for (var i = 0; i < g.Blocks.Count; i++)
                    {
                        Vector3I tmpOut;
                        if (minToMin.TryGetValue(g.Blocks[i], out tmpOut))
                        {
                            g.Blocks[i] = tmpOut;
                        }
                        else
                        {
                            g.Blocks[i] = Vector3I.MaxValue; // sorta discards it?
                        }
                    }
                }
            }

            if (grid.ConveyorLines != null)
            {
                foreach (var l in grid.ConveyorLines)
                {
                    l.StartDirection = LocalTransform.GetDirection(l.StartDirection);
                    l.StartPosition  = Vector3I.Transform(l.StartPosition, ref transformCopy);

                    l.EndDirection = LocalTransform.GetDirection(l.EndDirection);
                    l.EndPosition  = Vector3I.Transform(l.EndPosition, ref transformCopy);

                    if (l.Sections == null)
                    {
                        continue;
                    }
                    for (var s = 0; s < l.Sections.Count; s++)
                    {
                        l.Sections[s] = new SerializableLineSectionInformation()
                        {
                            Direction = LocalTransform.GetDirection(l.Sections[s].Direction), Length = l.Sections[s].Length
                        }
                    }
                    ;
                }
            }
        }