Esempio n. 1
0
        public clsResult Load(BinaryReader file)
        {
            var returnResult = new clsResult ("Loading .ttp", false);
            logger.Info ("Loading .ttp");

            var strTemp = "";
            UInt32 uintTemp = 0;
            UInt16 ushortTemp = 0;
            var A = 0;

            if (map.Tileset == null) {
                returnResult.ProblemAdd ("Set a tileset first.");
                return returnResult;
            }

            try
            {
                strTemp = IOUtil.ReadOldTextOfLength(file, 4);
                if ( strTemp != "ttyp" )
                {
                    returnResult.ProblemAdd("Incorrect identifier.");
                    return returnResult;
                }

                uintTemp = file.ReadUInt32();
                if ( uintTemp != 8U )
                {
                    returnResult.ProblemAdd("Unknown version.");
                    return returnResult;
                }
                uintTemp = file.ReadUInt32();
                for ( A = 0; A <= ((int)(Math.Min(uintTemp, (uint)map.Tileset.TileCount))) - 1; A++ )
                {
                    ushortTemp = file.ReadUInt16();
                    if ( ushortTemp > 11 )
                    {
                        returnResult.ProblemAdd("Unknown tile type number.");
                        return returnResult;
                    }
                    map.Tile_TypeNum[A] = (byte)ushortTemp;
                }
            }
            catch ( Exception ex )
            {
                Debugger.Break ();
                returnResult.ProblemAdd (ex.Message);
                logger.ErrorException("Got an exception", ex);
                return returnResult;
            }

            return returnResult;
        }
Esempio n. 2
0
        // compress is ignored.
        public clsResult Save(string path, bool overwrite, bool compress = false)
        {
            var returnResult = new clsResult(string.Format("Saving minimap to \"{0}\".", path), false);
            logger.Info ("Saving minimap to \"{0}\"", path);

            var minimapBitmap = new Bitmap(map.Terrain.TileSize.X, map.Terrain.TileSize.Y);

            var texture = new clsMinimapTexture(new XYInt(map.Terrain.TileSize.X, map.Terrain.TileSize.Y));
            map.MinimapTextureFill(texture);

            for ( var y = 0; y <= map.Terrain.TileSize.Y - 1; y++ )
            {
                for ( var x = 0; x <= map.Terrain.TileSize.X - 1; x++ )
                {
                    minimapBitmap.SetPixel(x, y,
                                           ColorTranslator.FromOle(
                        ColorUtil.OSRGB((int)(MathUtil.Clamp_sng(Convert.ToSingle(texture.get_Pixels(x, y).Red * 255.0F), 0.0F, 255.0F)),
                                    (int)(MathUtil.Clamp_sng(Convert.ToSingle(texture.get_Pixels(x, y).Green * 255.0F), 0.0F, 255.0F)),
                                    (int)(MathUtil.Clamp_sng(Convert.ToSingle(texture.get_Pixels(x, y).Blue * 255.0F), 0.0F, 255.0F)))));
                }
            }

            var subResult = BitmapUtil.SaveBitmap(path, overwrite, minimapBitmap);
            if (!subResult.Success) {
                returnResult.ProblemAdd (subResult.Problem);
            }

            return returnResult;
        }
Esempio n. 3
0
 public clsResult Load(string path)
 {
     try {
         using (var file = new BinaryReader(new FileStream(path, FileMode.Open))) {
             return Load (file);
         }
     }
     catch (Exception ex) {
         Debugger.Break ();
         var returnResult = new clsResult ("Loading .ttp", false);
         returnResult.ProblemAdd (string.Format ("Failed to open .ttp, failure was: {0}", ex.Message));
         logger.ErrorException ("Failed to open .ttp", ex);
         return returnResult;
     }
 }
Esempio n. 4
0
        public clsResult Load_FME(string Path)
        {
            clsResult ReturnResult =
                new clsResult("Loading FME from " + Convert.ToString(ControlChars.Quote) + Path + Convert.ToString(ControlChars.Quote));

            BinaryReader File = default(BinaryReader);

            try
            {
                File = new BinaryReader(new FileStream(Path, FileMode.Open));
            }
            catch ( Exception ex )
            {
                ReturnResult.ProblemAdd(ex.Message);
                return ReturnResult;
            }
            ReturnResult.Take(Read_FME(File));
            File.Close();

            return ReturnResult;
        }
Esempio n. 5
0
        // compress is ignored.
        public clsResult Save(string path, bool overwrite, bool compress = false)
        {
            var returnResult = new clsResult(string.Format("Saving heightmap to \"{0}\".", path), false);
            logger.Info ("Saving heightmap to \"{0}\"", path);

            var heightmapBitmap = new Bitmap(map.Terrain.TileSize.X + 1, map.Terrain.TileSize.Y + 1);
            for ( var Y = 0; Y <= map.Terrain.TileSize.Y; Y++ )
            {
                for ( var X = 0; X <= map.Terrain.TileSize.X; X++ )
                {
                    heightmapBitmap.SetPixel(X, Y,
                                             ColorTranslator.FromOle(ColorUtil.OSRGB(Convert.ToInt32(map.Terrain.Vertices[X, Y].Height), map.Terrain.Vertices[X, Y].Height,
                                                            map.Terrain.Vertices[X, Y].Height)));
                }
            }

            var subResult = BitmapUtil.SaveBitmap(path, overwrite, heightmapBitmap);
            if (!subResult.Success) {
                returnResult.ProblemAdd (subResult.Problem);
            }

            return returnResult;
        }
Esempio n. 6
0
        public clsResult Write_LND(string Path, bool Overwrite)
        {
            clsResult ReturnResult =
                new clsResult("Writing LND to " + Convert.ToString(ControlChars.Quote) + Path + Convert.ToString(ControlChars.Quote));

            if ( System.IO.File.Exists(Path) )
            {
                if ( Overwrite )
                {
                    System.IO.File.Delete(Path);
                }
                else
                {
                    ReturnResult.ProblemAdd("The selected file already exists.");
                    return ReturnResult;
                }
            }

            StreamWriter File = null;

            try
            {
                string Text = "";
                char EndChar = (char)0;
                char Quote = (char)0;
                int A = 0;
                int X = 0;
                int Y = 0;
                byte Flip = 0;
                int B = 0;
                int VF = 0;
                int TF = 0;
                int C = 0;
                byte Rotation = 0;
                bool FlipX = default(bool);

                Quote = ControlChars.Quote;
                EndChar = '\n';

                File = new StreamWriter(new FileStream(Path, FileMode.CreateNew), new UTF8Encoding(false, false));

                if ( Tileset == App.Tileset_Arizona )
                {
                    Text = "DataSet WarzoneDataC1.eds" + Convert.ToString(EndChar);
                }
                else if ( Tileset == App.Tileset_Urban )
                {
                    Text = "DataSet WarzoneDataC2.eds" + Convert.ToString(EndChar);
                }
                else if ( Tileset == App.Tileset_Rockies )
                {
                    Text = "DataSet WarzoneDataC3.eds" + Convert.ToString(EndChar);
                }
                else
                {
                    Text = "DataSet " + Convert.ToString(EndChar);
                }
                File.Write(Text);
                Text = "GrdLand {" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    Version 4" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    3DPosition 0.000000 3072.000000 0.000000" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    3DRotation 80.000000 0.000000 0.000000" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    2DPosition 0 0" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    CustomSnap 16 16" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    SnapMode 0" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    Gravity 1" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    HeightScale " + IOUtil.InvariantToString(HeightMultiplier) + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    MapWidth " + IOUtil.InvariantToString(Terrain.TileSize.X) + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    MapHeight " + IOUtil.InvariantToString(Terrain.TileSize.Y) + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    TileWidth 128" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    TileHeight 128" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    SeaLevel 0" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    TextureWidth 64" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    TextureHeight 64" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    NumTextures 1" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    Textures {" + Convert.ToString(EndChar);
                File.Write(Text);
                if ( Tileset == App.Tileset_Arizona )
                {
                    Text = "        texpages\\tertilesc1.pcx" + Convert.ToString(EndChar);
                }
                else if ( Tileset == App.Tileset_Urban )
                {
                    Text = "        texpages\\tertilesc2.pcx" + Convert.ToString(EndChar);
                }
                else if ( Tileset == App.Tileset_Rockies )
                {
                    Text = "        texpages\\tertilesc3.pcx" + Convert.ToString(EndChar);
                }
                else
                {
                    Text = "        " + Convert.ToString(EndChar);
                }
                File.Write(Text);
                Text = "    }" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    NumTiles " + IOUtil.InvariantToString(Terrain.TileSize.X * Terrain.TileSize.Y) + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    Tiles {" + Convert.ToString(EndChar);
                File.Write(Text);
                for ( Y = 0; Y <= Terrain.TileSize.Y - 1; Y++ )
                {
                    for ( X = 0; X <= Terrain.TileSize.X - 1; X++ )
                    {
                        TileUtil.TileOrientation_To_OldOrientation(Terrain.Tiles[X, Y].Texture.Orientation, ref Rotation, ref FlipX);
                        Flip = (byte)0;
                        if ( Terrain.Tiles[X, Y].Tri )
                        {
                            Flip += (byte)2;
                        }
                        if ( FlipX )
                        {
                            Flip += (byte)4;
                        }
                        Flip += (byte)(Rotation * 16);

                        if ( Terrain.Tiles[X, Y].Tri )
                        {
                            VF = 1;
                        }
                        else
                        {
                            VF = 0;
                        }
                        if ( FlipX )
                        {
                            TF = 1;
                        }
                        else
                        {
                            TF = 0;
                        }

                        Text = "        TID " + (Terrain.Tiles[X, Y].Texture.TextureNum + 1) + " VF " + IOUtil.InvariantToString(VF) + " TF " +
                               IOUtil.InvariantToString(TF) + " F " + IOUtil.InvariantToString((int)Flip) + " VH " +
                               IOUtil.InvariantToString(Convert.ToByte(Terrain.Vertices[X, Y].Height)) + " " +
                               IOUtil.InvariantToString(Terrain.Vertices[X + 1, Y].Height) + " " + Convert.ToString(Terrain.Vertices[X + 1, Y + 1].Height) +
                               " " + IOUtil.InvariantToString(Convert.ToByte(Terrain.Vertices[X, Y + 1].Height)) + Convert.ToString(EndChar);
                        File.Write(Text);
                    }
                }
                Text = "    }" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "}" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "ObjectList {" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    Version 3" + Convert.ToString(EndChar);
                File.Write(Text);
                if ( Tileset == App.Tileset_Arizona )
                {
                    Text = "	FeatureSet WarzoneDataC1.eds" + Convert.ToString(EndChar);
                }
                else if ( Tileset == App.Tileset_Urban )
                {
                    Text = "	FeatureSet WarzoneDataC2.eds" + Convert.ToString(EndChar);
                }
                else if ( Tileset == App.Tileset_Rockies )
                {
                    Text = "	FeatureSet WarzoneDataC3.eds" + Convert.ToString(EndChar);
                }
                else
                {
                    Text = "	FeatureSet " + Convert.ToString(EndChar);
                }
                File.Write(Text);
                Text = "    NumObjects " + IOUtil.InvariantToString(Units.Count) + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    Objects {" + Convert.ToString(EndChar);
                File.Write(Text);
                sXYZ_int XYZ_int = new sXYZ_int();
                string Code = null;
                int CustomDroidCount = 0;
                clsUnit Unit = default(clsUnit);
                foreach ( clsUnit tempLoopVar_Unit in Units )
                {
                    Unit = tempLoopVar_Unit;
                    switch ( Unit.Type.Type )
                    {
                        case clsUnitType.enumType.Feature:
                            B = 0;
                            break;
                        case clsUnitType.enumType.PlayerStructure:
                            B = 1;
                            break;
                        case clsUnitType.enumType.PlayerDroid:
                            if ( ((clsDroidDesign)Unit.Type).IsTemplate )
                            {
                                B = 2;
                            }
                            else
                            {
                                B = -1;
                            }
                            break;
                        default:
                            B = -1;
                            ReturnResult.WarningAdd("Unit type classification not accounted for.");
                            break;
                    }
                    XYZ_int = LNDPos_From_MapPos(Units[A].Pos.Horizontal);
                    if ( B >= 0 )
                    {
                        if ( Unit.Type.GetCode(ref Code) )
                        {
                            Text = "        " + IOUtil.InvariantToString(Unit.ID) + " " + Convert.ToString(B) + " " + Convert.ToString(Quote) +
                                   Code + Convert.ToString(Quote) + " " + Unit.UnitGroup.GetLNDPlayerText() + " " + Convert.ToString(Quote) + "NONAME" +
                                   Convert.ToString(Quote) + " " + IOUtil.InvariantToString(XYZ_int.X) + ".00 " + IOUtil.InvariantToString(XYZ_int.Y) +
                                   ".00 " + IOUtil.InvariantToString(XYZ_int.Z) + ".00 0.00 " + IOUtil.InvariantToString(Unit.Rotation) + ".00 0.00" +
                                   Convert.ToString(EndChar);
                            File.Write(Text);
                        }
                        else
                        {
                            ReturnResult.WarningAdd("Error. Code not found.");
                        }
                    }
                    else
                    {
                        CustomDroidCount++;
                    }
                }
                Text = "    }" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "}" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "ScrollLimits {" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    Version 1" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    NumLimits 1" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    Limits {" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "        " + Convert.ToString(Quote) + "Entire Map" + Convert.ToString(Quote) + " 0 0 0 " +
                       IOUtil.InvariantToString(Terrain.TileSize.X) + " " + IOUtil.InvariantToString(Terrain.TileSize.Y) + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    }" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "}" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "Gateways {" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    Version 1" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    NumGateways " + IOUtil.InvariantToString(Gateways.Count) + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    Gates {" + Convert.ToString(EndChar);
                File.Write(Text);
                clsGateway Gateway = default(clsGateway);
                foreach ( clsGateway tempLoopVar_Gateway in Gateways )
                {
                    Gateway = tempLoopVar_Gateway;
                    Text = "        " + IOUtil.InvariantToString(Gateway.PosA.X) + " " + IOUtil.InvariantToString(Gateway.PosA.Y) + " " +
                           IOUtil.InvariantToString(Gateway.PosB.X) + " " + IOUtil.InvariantToString(Gateway.PosB.Y) + Convert.ToString(EndChar);
                    File.Write(Text);
                }
                Text = "    }" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "}" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "TileTypes {" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    NumTiles " + Convert.ToString(Tileset.TileCount) + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    Tiles {" + Convert.ToString(EndChar);
                File.Write(Text);
                for ( A = 0; A <= ((int)(Math.Ceiling(Convert.ToDecimal((Tileset.TileCount + 1) / 16.0D)))) - 1; A++ )
                    //+1 because the first number is not a tile type
                {
                    Text = "        ";
                    C = A * 16 - 1; //-1 because the first number is not a tile type
                    for ( B = 0; B <= Math.Min(16, Tileset.TileCount - C) - 1; B++ )
                    {
                        if ( C + B < 0 )
                        {
                            Text = Text + "2 ";
                        }
                        else
                        {
                            Text = Text + IOUtil.InvariantToString(Tile_TypeNum[C + B]) + " ";
                        }
                    }
                    Text = Text + Convert.ToString(EndChar);
                    File.Write(Text);
                }
                Text = "    }" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "}" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "TileFlags {" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    NumTiles 90" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    Flags {" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "        0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "        0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "        0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "        0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "        0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "        0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    }" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "}" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "Brushes {" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    Version 2" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    NumEdgeBrushes 0" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    NumUserBrushes 0" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    EdgeBrushes {" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "    }" + Convert.ToString(EndChar);
                File.Write(Text);
                Text = "}" + Convert.ToString(EndChar);
                File.Write(Text);
            }
            catch ( Exception ex )
            {
                ReturnResult.ProblemAdd(ex.Message);
            }
            if ( File != null )
            {
                File.Close();
            }

            return ReturnResult;
        }
Esempio n. 7
0
        public clsResult GenerateLayout()
        {
            clsResult ReturnResult = new clsResult("Layout");

            int X = 0;
            int Y = 0;
            int A = 0;
            int B = 0;
            int C = 0;
            int D = 0;
            int E = 0;
            int F = 0;
            int G = 0;
            int H = 0;

            TotalPlayerCount = TopLeftPlayerCount * SymmetryBlockCount;

            sXY_int SymmetrySize = new sXY_int();

            SymmetrySize.X = (int)(TileSize.X * App.TerrainGridSpacing / SymmetryBlockCountXY.X);
            SymmetrySize.Y = (int)(TileSize.Y * App.TerrainGridSpacing / SymmetryBlockCountXY.Y);

            //create passage nodes

            int PassageRadius = (int)(128.0F * NodeScale);
            int MaxLikelyPassageNodeCount = 0;
            MaxLikelyPassageNodeCount =
                (int)(Math.Ceiling(Convert.ToDecimal(2.0D * TileSize.X * 128 * TileSize.Y * 128 / (Math.PI * PassageRadius * PassageRadius))));

            PassageNodes = new clsPassageNode[SymmetryBlockCount, MaxLikelyPassageNodeCount];
            int LoopCount = 0;
            int EdgeOffset = 0 * 128;
            bool PointIsValid;
            sXY_int EdgeSections = new sXY_int();
            Position.XY_dbl EdgeSectionSize = default(Position.XY_dbl);
            sXY_int NewPointPos = new sXY_int();

            if ( SymmetryBlockCountXY.X == 1 )
            {
                EdgeSections.X =
                    Convert.ToInt32(
                        Conversion.Int((TileSize.X * App.TerrainGridSpacing - EdgeOffset * 2.0D) / (NodeScale * App.TerrainGridSpacing * 2.0F)));
                EdgeSectionSize.X = (TileSize.X * App.TerrainGridSpacing - EdgeOffset * 2.0D) / EdgeSections.X;
                EdgeSections.X--;
            }
            else
            {
                EdgeSections.X =
                    (int)
                        (Conversion.Int((TileSize.X * App.TerrainGridSpacing / SymmetryBlockCountXY.X - EdgeOffset) /
                                        (NodeScale * App.TerrainGridSpacing * 2.0F) - 0.5D));
                EdgeSectionSize.X =
                    Convert.ToDouble((TileSize.X * App.TerrainGridSpacing / SymmetryBlockCountXY.X - EdgeOffset) /
                                            (Convert.ToDouble(
                                                Conversion.Int((TileSize.X * App.TerrainGridSpacing / SymmetryBlockCountXY.X - EdgeOffset) /
                                                               (NodeScale * App.TerrainGridSpacing * 2.0F) - 0.5D)) + 0.5D));
            }
            if ( SymmetryBlockCountXY.Y == 1 )
            {
                EdgeSections.Y =
                    Convert.ToInt32(
                        Conversion.Int((TileSize.Y * App.TerrainGridSpacing - EdgeOffset * 2.0D) / (NodeScale * App.TerrainGridSpacing * 2.0F)));
                EdgeSectionSize.Y = (TileSize.Y * App.TerrainGridSpacing - EdgeOffset * 2.0D) / EdgeSections.Y;
                EdgeSections.Y--;
            }
            else
            {
                EdgeSections.Y =
                    Convert.ToInt32(
                        Conversion.Int((TileSize.Y * App.TerrainGridSpacing / SymmetryBlockCountXY.Y - EdgeOffset) /
                                       (NodeScale * App.TerrainGridSpacing * 2.0F) - 0.5D));
                EdgeSectionSize.Y =
                    Convert.ToDouble((TileSize.Y * App.TerrainGridSpacing / SymmetryBlockCountXY.Y - EdgeOffset) /
                                            (Convert.ToDouble(
                                                Conversion.Int((TileSize.Y * App.TerrainGridSpacing / SymmetryBlockCountXY.Y - EdgeOffset) /
                                                               (NodeScale * App.TerrainGridSpacing * 2.0F) - 0.5D)) + 0.5D));
            }

            PassageNodeCount = 0;
            for ( Y = 0; Y <= EdgeSections.Y; Y++ )
            {
                if ( !MakePassageNodes(new sXY_int(EdgeOffset, EdgeOffset + (int)(Y * EdgeSectionSize.Y)), true) )
                {
                    ReturnResult.ProblemAdd("Error: Bad border node.");
                    return ReturnResult;
                }
                if ( SymmetryBlockCountXY.X == 1 )
                {
                    if (
                        !MakePassageNodes(new sXY_int(TileSize.X * App.TerrainGridSpacing - EdgeOffset, EdgeOffset + (int)(Y * EdgeSectionSize.Y)), true) )
                    {
                        ReturnResult.ProblemAdd("Error: Bad border node.");
                        return ReturnResult;
                    }
                }
            }
            for ( X = 1; X <= EdgeSections.X; X++ )
            {
                if ( !MakePassageNodes(new sXY_int(EdgeOffset + (int)(X * EdgeSectionSize.X), EdgeOffset), true) )
                {
                    ReturnResult.ProblemAdd("Error: Bad border node.");
                    return ReturnResult;
                }
                if ( SymmetryBlockCountXY.Y == 1 )
                {
                    if (
                        !MakePassageNodes(new sXY_int(EdgeOffset + (int)(X * EdgeSectionSize.X), TileSize.Y * App.TerrainGridSpacing - EdgeOffset), true) )
                    {
                        ReturnResult.ProblemAdd("Error: Bad border node.");
                        return ReturnResult;
                    }
                }
            }
            do
            {
                LoopCount = 0;
                do
                {
                    PointIsValid = true;
                    if ( SymmetryBlockCountXY.X == 1 )
                    {
                        NewPointPos.X = (int)(EdgeOffset + Conversion.Int(VBMath.Rnd() * (SymmetrySize.X - EdgeOffset * 2 + 1)));
                    }
                    else
                    {
                        NewPointPos.X = EdgeOffset + (int)(Conversion.Int(VBMath.Rnd() * (SymmetrySize.X - EdgeOffset + 1)));
                    }
                    if ( SymmetryBlockCountXY.Y == 1 )
                    {
                        NewPointPos.Y = EdgeOffset + (int)(Conversion.Int(VBMath.Rnd() * (SymmetrySize.Y - EdgeOffset * 2 + 1)));
                    }
                    else
                    {
                        NewPointPos.Y = EdgeOffset + Convert.ToInt32(Conversion.Int(VBMath.Rnd() * (SymmetrySize.Y - EdgeOffset + 1)));
                    }
                    for ( A = 0; A <= PassageNodeCount - 1; A++ )
                    {
                        for ( B = 0; B <= SymmetryBlockCount - 1; B++ )
                        {
                            if ( (PassageNodes[B, A].Pos - NewPointPos).ToDoubles().GetMagnitude() < PassageRadius * 2 )
                            {
                                goto PointTooClose;
                            }
                        }
                    }
                    PointTooClose:
                    if ( A == PassageNodeCount )
                    {
                        if ( MakePassageNodes(NewPointPos, false) )
                        {
                            break;
                        }
                    }
                    LoopCount++;
                    if ( LoopCount >= (int)(64.0F * TileSize.X * TileSize.Y / (NodeScale * NodeScale)) )
                    {
                        goto PointMakingFinished;
                    }
                } while ( true );
            } while ( true );
            PointMakingFinished:
            PassageNodes =
                (clsPassageNode[,])
                    Utils.CopyArray((Array)PassageNodes, new clsPassageNode[SymmetryBlockCount, PassageNodeCount]);

            //connect until all are connected without intersecting

            MathUtil.sIntersectPos IntersectPos = new MathUtil.sIntersectPos();
            int MaxConDist2 = PassageRadius * 2 * 4;
            MaxConDist2 *= MaxConDist2;
            clsNearest NearestA = default(clsNearest);
            Nearests = new clsNearest[PassageNodeCount * 64];
            clsPassageNode tmpPassageNodeA = default(clsPassageNode);
            clsPassageNode tmpPassageNodeB = default(clsPassageNode);
            clsTestNearestArgs NearestArgs = new clsTestNearestArgs();
            int MinConDist = (int)(NodeScale * 1.25F * 128.0F);

            NearestArgs.MaxConDist2 = MaxConDist2;
            NearestArgs.MinConDist = MinConDist;

            for ( A = 0; A <= PassageNodeCount - 1; A++ )
            {
                NearestArgs.PassageNodeA = PassageNodes[0, A];
                for ( B = A; B <= PassageNodeCount - 1; B++ )
                {
                    for ( C = 0; C <= SymmetryBlockCount - 1; C++ )
                    {
                        NearestArgs.PassageNodeB = PassageNodes[C, B];
                        if ( NearestArgs.PassageNodeA != NearestArgs.PassageNodeB )
                        {
                            TestNearest(NearestArgs);
                        }
                    }
                }
            }

            clsNearest NearestB = default(clsNearest);
            bool Flag = default(bool);

            for ( G = 0; G <= NearestCount - 1; G++ )
            {
                NearestA = Nearests[G];
                for ( A = 0; A <= NearestA.NodeCount - 1; A++ )
                {
                    tmpPassageNodeA = NearestA.NodeA[A];
                    tmpPassageNodeB = NearestA.NodeB[A];
                    for ( H = 0; H <= NearestCount - 1; H++ )
                    {
                        NearestB = Nearests[H];
                        if ( NearestB != NearestA )
                        {
                            if ( NearestB.Dist2 < NearestA.Dist2 )
                            {
                                Flag = true;
                            }
                            else if ( NearestB.Dist2 == NearestA.Dist2 )
                            {
                                Flag = NearestA.Num > NearestB.Num;
                            }
                            else
                            {
                                Flag = false;
                            }
                            if ( Flag )
                            {
                                for ( B = 0; B <= NearestB.NodeCount - 1; B++ )
                                {
                                    if ( !(tmpPassageNodeA == NearestB.NodeA[B] || tmpPassageNodeA == NearestB.NodeB[B]
                                           || tmpPassageNodeB == NearestB.NodeA[B] || tmpPassageNodeB == NearestB.NodeB[B]) )
                                    {
                                        IntersectPos = MathUtil.GetLinesIntersectBetween(tmpPassageNodeA.Pos, tmpPassageNodeB.Pos, NearestB.NodeA[B].Pos,
                                            NearestB.NodeB[B].Pos);
                                        if ( IntersectPos.Exists )
                                        {
                                            break;
                                        }
                                    }
                                }
                                if ( B < NearestB.NodeCount )
                                {
                                    NearestA.BlockedCount++;
                                    NearestB.BlockedNearests[NearestB.BlockedNearestCount] = NearestA;
                                    NearestB.BlockedNearestCount++;
                                }
                            }
                        }
                    }
                }
            }

            int ChangeCount = 0;
            Connections = new clsConnection[PassageNodeCount * 16];

            do
            {
                //create valid connections
                ChangeCount = 0;
                G = 0;
                while ( G < NearestCount )
                {
                    NearestA = Nearests[G];
                    Flag = true;
                    if ( NearestA.BlockedCount == 0 && Flag )
                    {
                        F = ConnectionCount;
                        for ( D = 0; D <= NearestA.NodeCount - 1; D++ )
                        {
                            Connections[ConnectionCount] = new clsConnection(NearestA.NodeA[D], NearestA.NodeB[D]);
                            ConnectionCount++;
                        }
                        for ( D = 0; D <= NearestA.NodeCount - 1; D++ )
                        {
                            A = F + D;
                            Connections[A].ReflectionCount = NearestA.NodeCount - 1;
                            Connections[A].Reflections = new clsConnection[Connections[A].ReflectionCount];
                            B = 0;
                            for ( E = 0; E <= NearestA.NodeCount - 1; E++ )
                            {
                                if ( E != D )
                                {
                                    Connections[A].Reflections[B] = Connections[F + E];
                                    B++;
                                }
                            }
                        }
                        for ( C = 0; C <= NearestA.BlockedNearestCount - 1; C++ )
                        {
                            NearestA.BlockedNearests[C].Invalid = true;
                        }
                        NearestCount--;
                        H = NearestA.Num;
                        NearestA.Num = -1;
                        if ( H != NearestCount )
                        {
                            Nearests[H] = Nearests[NearestCount];
                            Nearests[H].Num = H;
                        }
                        ChangeCount++;
                    }
                    else
                    {
                        if ( !Flag )
                        {
                            NearestA.Invalid = true;
                        }
                        G++;
                    }
                }
                //remove blocked ones and their blocking effect
                G = 0;
                while ( G < NearestCount )
                {
                    NearestA = Nearests[G];
                    if ( NearestA.Invalid )
                    {
                        NearestA.Num = -1;
                        for ( D = 0; D <= NearestA.BlockedNearestCount - 1; D++ )
                        {
                            NearestA.BlockedNearests[D].BlockedCount--;
                        }
                        NearestCount--;
                        if ( G != NearestCount )
                        {
                            Nearests[G] = Nearests[NearestCount];
                            Nearests[G].Num = G;
                        }
                    }
                    else
                    {
                        G++;
                    }
                }
            } while ( ChangeCount > 0 );

            //put connections in order of angle

            for ( A = 0; A <= PassageNodeCount - 1; A++ )
            {
                for ( B = 0; B <= SymmetryBlockCount - 1; B++ )
                {
                    PassageNodes[B, A].ReorderConnections();
                    PassageNodes[B, A].CalcIsNearBorder();
                }
            }

            //get nodes in random order

            clsPassageNode[] PassageNodeListOrder = new clsPassageNode[PassageNodeCount];
            int PassageNodeListOrderCount = 0;
            clsPassageNode[] PassageNodeOrder = new clsPassageNode[PassageNodeCount];
            for ( A = 0; A <= PassageNodeCount - 1; A++ )
            {
                PassageNodeListOrder[PassageNodeListOrderCount] = PassageNodes[0, A];
                PassageNodeListOrderCount++;
            }
            B = 0;
            while ( PassageNodeListOrderCount > 0 )
            {
                A = (int)(Conversion.Int(VBMath.Rnd() * PassageNodeListOrderCount));
                PassageNodeOrder[B] = PassageNodeListOrder[A];
                B++;
                PassageNodeListOrderCount--;
                PassageNodeListOrder[A] = PassageNodeListOrder[PassageNodeListOrderCount];
            }

            //designate height levels

            LevelHeight = 255.0F / (LevelCount - 1);
            int BestNum = 0;
            double Dist = 0;
            clsPassageNodeHeightLevelArgs HeightsArgs = new clsPassageNodeHeightLevelArgs();
            HeightsArgs.PassageNodesMinLevel.Nodes = new int[PassageNodeCount];
            HeightsArgs.PassageNodesMaxLevel.Nodes = new int[PassageNodeCount];
            HeightsArgs.MapLevelCount = new int[LevelCount];
            sXY_int RotatedPos = new sXY_int();

            for ( A = 0; A <= PassageNodeCount - 1; A++ )
            {
                HeightsArgs.PassageNodesMinLevel.Nodes[A] = 0;
                HeightsArgs.PassageNodesMaxLevel.Nodes[A] = LevelCount - 1;
            }

            //create bases
            double[] BestDists = new double[BaseFlatArea];
            clsPassageNode[] BestNodes = new clsPassageNode[BaseFlatArea];
            int[] BestNodesReflectionNums = new int[BaseFlatArea];
            int BestDistCount = 0;
            PlayerBases = new sPlayerBase[TotalPlayerCount];
            for ( B = 0; B <= TopLeftPlayerCount - 1; B++ )
            {
                BestDistCount = 0;
                for ( A = 0; A <= PassageNodeCount - 1; A++ )
                {
                    for ( E = 0; E <= SymmetryBlockCount - 1; E++ )
                    {
                        tmpPassageNodeA = PassageNodes[E, A];
                        if ( !tmpPassageNodeA.IsOnBorder )
                        {
                            Dist = (tmpPassageNodeA.Pos - PlayerBasePos[B]).ToDoubles().GetMagnitude();
                            for ( C = BestDistCount - 1; C >= 0; C-- )
                            {
                                if ( Dist > BestDists[C] )
                                {
                                    break;
                                }
                            }
                            C++;
                            for ( D = Math.Min(BestDistCount - 1, BaseFlatArea - 2); D >= C; D-- )
                            {
                                BestDists[D + 1] = BestDists[D];
                                BestNodes[D + 1] = BestNodes[D];
                            }
                            if ( C < BaseFlatArea )
                            {
                                BestDists[C] = Dist;
                                BestNodes[C] = tmpPassageNodeA;
                                BestDistCount = Math.Max(BestDistCount, C + 1);
                            }
                        }
                    }
                }

                if ( BaseLevel < 0 )
                {
                    D = Convert.ToInt32(Conversion.Int(VBMath.Rnd() * LevelCount));
                }
                else
                {
                    D = BaseLevel;
                }

                HeightsArgs.MapLevelCount[D] += BestDistCount;

                for ( A = 0; A <= BestDistCount - 1; A++ )
                {
                    if ( BestNodes[A].MirrorNum == 0 )
                    {
                        BestNodesReflectionNums[A] = -1;
                    }
                    else
                    {
                        for ( C = 0; C <= ((int)(SymmetryBlockCount / 2.0D)) - 1; C++ )
                        {
                            if ( SymmetryBlocks[0].ReflectToNum[C] == BestNodes[A].MirrorNum )
                            {
                                break;
                            }
                        }
                        BestNodesReflectionNums[A] = C;
                    }
                }

                for ( A = 0; A <= SymmetryBlockCount - 1; A++ )
                {
                    E = A * TopLeftPlayerCount + B;
                    PlayerBases[E].NodeCount = BestDistCount;
                    PlayerBases[E].Nodes = new clsPassageNode[PlayerBases[E].NodeCount];
                    for ( C = 0; C <= BestDistCount - 1; C++ )
                    {
                        if ( BestNodesReflectionNums[C] < 0 )
                        {
                            PlayerBases[E].Nodes[C] = PassageNodes[A, BestNodes[C].Num];
                        }
                        else
                        {
                            PlayerBases[E].Nodes[C] = PassageNodes[SymmetryBlocks[A].ReflectToNum[BestNodesReflectionNums[C]], BestNodes[C].Num];
                        }
                        PlayerBases[E].Nodes[C].PlayerBaseNum = E;
                        PlayerBases[E].Nodes[C].Level = D;
                        PassageNodesMinLevelSet(PlayerBases[E].Nodes[C], HeightsArgs.PassageNodesMinLevel, D, MaxLevelTransition);
                        PassageNodesMaxLevelSet(PlayerBases[E].Nodes[C], HeightsArgs.PassageNodesMaxLevel, D, MaxLevelTransition);
                    }
                    //PlayerBases(E).CalcPos()
                    RotatedPos = TileUtil.GetRotatedPos(SymmetryBlocks[A].Orientation, PlayerBasePos[B],
                        new sXY_int(SymmetrySize.X - 1, SymmetrySize.Y - 1));
                    PlayerBases[E].Pos.X = SymmetryBlocks[A].XYNum.X * SymmetrySize.X + RotatedPos.X;
                    PlayerBases[E].Pos.Y = SymmetryBlocks[A].XYNum.Y * SymmetrySize.Y + RotatedPos.Y;
                }
            }

            int WaterCount = 0;
            bool CanDoFlatsAroundWater = default(bool);
            int TotalWater = 0;
            int WaterSpawns = 0;

            for ( A = 0; A <= PassageNodeCount - 1; A++ )
            {
                tmpPassageNodeA = PassageNodeOrder[A];
                if ( tmpPassageNodeA.Level < 0 && !tmpPassageNodeA.IsOnBorder )
                {
                    WaterCount = 0;
                    for ( B = 0; B <= tmpPassageNodeA.ConnectionCount - 1; B++ )
                    {
                        tmpPassageNodeB = tmpPassageNodeA.Connections[B].GetOther();
                        if ( tmpPassageNodeB.IsWater )
                        {
                            WaterCount++;
                        }
                    }
                    CanDoFlatsAroundWater = true;
                    for ( B = 0; B <= tmpPassageNodeA.ConnectionCount - 1; B++ )
                    {
                        if ( HeightsArgs.PassageNodesMinLevel.Nodes[tmpPassageNodeA.Connections[B].GetOther().Num] > 0 )
                        {
                            CanDoFlatsAroundWater = false;
                        }
                    }
                    if ( CanDoFlatsAroundWater &&
                         ((WaterCount == 0 & WaterSpawns < WaterSpawnQuantity) || (WaterCount == 1 & TotalWaterQuantity - TotalWater > WaterSpawnQuantity - WaterSpawns)) &&
                         HeightsArgs.PassageNodesMinLevel.Nodes[tmpPassageNodeA.Num] == 0 & TotalWater < TotalWaterQuantity )
                    {
                        if ( WaterCount == 0 )
                        {
                            WaterSpawns++;
                        }
                        TotalWater++;
                        C = tmpPassageNodeA.Num;
                        for ( D = 0; D <= SymmetryBlockCount - 1; D++ )
                        {
                            PassageNodes[D, C].IsWater = true;
                            PassageNodes[D, C].Level = 0;
                        }
                        PassageNodesMinLevelSet(tmpPassageNodeA, HeightsArgs.PassageNodesMinLevel, 0, MaxLevelTransition);
                        PassageNodesMaxLevelSet(tmpPassageNodeA, HeightsArgs.PassageNodesMaxLevel, 0, MaxLevelTransition);
                        HeightsArgs.MapLevelCount[0]++;
                        for ( B = 0; B <= tmpPassageNodeA.ConnectionCount - 1; B++ )
                        {
                            tmpPassageNodeB = tmpPassageNodeA.Connections[B].GetOther();
                            PassageNodesMinLevelSet(tmpPassageNodeB, HeightsArgs.PassageNodesMinLevel, 0, MaxLevelTransition);
                            PassageNodesMaxLevelSet(tmpPassageNodeB, HeightsArgs.PassageNodesMaxLevel, 0, MaxLevelTransition);
                        }
                    }
                }
            }

            clsPassageNode tmpPassageNodeC = default(clsPassageNode);
            App.sResult Result = new App.sResult();

            HeightsArgs.FlatsCutoff = 1;
            HeightsArgs.PassagesCutoff = 1;
            HeightsArgs.VariationCutoff = 1;
            HeightsArgs.ActionTotal = 1;

            for ( A = 0; A <= PassageNodeCount - 1; A++ )
            {
                tmpPassageNodeA = PassageNodeOrder[A];
                if ( tmpPassageNodeA.Level < 0 && !tmpPassageNodeA.IsOnBorder && tmpPassageNodeA.IsNearBorder )
                {
                    HeightsArgs.PassageNode = tmpPassageNodeA;
                    Result = PassageNodeHeightLevel(HeightsArgs);
                    if ( !Result.Success )
                    {
                        ReturnResult.ProblemAdd(Result.Problem);
                        return ReturnResult;
                    }
                }
            }

            HeightsArgs.FlatsCutoff = FlatsChance;
            HeightsArgs.PassagesCutoff = HeightsArgs.FlatsCutoff + PassagesChance;
            HeightsArgs.VariationCutoff = HeightsArgs.PassagesCutoff + VariationChance;
            HeightsArgs.ActionTotal = HeightsArgs.VariationCutoff;
            if ( HeightsArgs.ActionTotal <= 0 )
            {
                ReturnResult.ProblemAdd("All height level behaviors are zero");
                return ReturnResult;
            }

            for ( A = 0; A <= PassageNodeCount - 1; A++ )
            {
                tmpPassageNodeA = PassageNodeOrder[A];
                if ( tmpPassageNodeA.Level < 0 && !tmpPassageNodeA.IsOnBorder )
                {
                    HeightsArgs.PassageNode = tmpPassageNodeA;
                    Result = PassageNodeHeightLevel(HeightsArgs);
                    if ( !Result.Success )
                    {
                        ReturnResult.ProblemAdd(Result.Problem);
                        return ReturnResult;
                    }
                }
            }

            //set edge points to the level of their neighbour
            for ( A = 0; A <= PassageNodeCount - 1; A++ )
            {
                tmpPassageNodeA = PassageNodes[0, A];
                if ( tmpPassageNodeA.IsOnBorder )
                {
                    if ( tmpPassageNodeA.Level >= 0 )
                    {
                        ReturnResult.ProblemAdd("Error: Border has had its height set.");
                        return ReturnResult;
                    }
                    //If tmpPassageNodeA.ConnectionCount <> 1 Then
                    //    ReturnResult.Problem = "Error: Border has incorrect connections."
                    //    Exit Function
                    //End If
                    tmpPassageNodeC = null;
                    CanDoFlatsAroundWater = true;
                    for ( B = 0; B <= tmpPassageNodeA.ConnectionCount - 1; B++ )
                    {
                        tmpPassageNodeB = tmpPassageNodeA.Connections[B].GetOther();
                        if ( tmpPassageNodeB.Level >= 0 && !tmpPassageNodeB.IsOnBorder )
                        {
                            if ( HeightsArgs.PassageNodesMinLevel.Nodes[tmpPassageNodeA.Num] <= tmpPassageNodeB.Level &&
                                 HeightsArgs.PassageNodesMaxLevel.Nodes[tmpPassageNodeA.Num] >= tmpPassageNodeB.Level )
                            {
                                if ( tmpPassageNodeC == null )
                                {
                                    tmpPassageNodeC = tmpPassageNodeB;
                                }
                            }
                        }
                        if ( HeightsArgs.PassageNodesMinLevel.Nodes[tmpPassageNodeB.Num] > 0 )
                        {
                            CanDoFlatsAroundWater = false;
                        }
                    }
                    //If tmpPassageNodeC Is Nothing Then
                    //    ReturnResult.Problem_Add("Error: No connection for border node")
                    //    Return ReturnResult
                    //End If
                    if ( tmpPassageNodeC != null )
                    {
                        BestNum = tmpPassageNodeC.Level;
                        PassageNodesMinLevelSet(tmpPassageNodeA, HeightsArgs.PassageNodesMinLevel, BestNum, MaxLevelTransition);
                        PassageNodesMaxLevelSet(tmpPassageNodeA, HeightsArgs.PassageNodesMaxLevel, BestNum, MaxLevelTransition);
                        for ( D = 0; D <= SymmetryBlockCount - 1; D++ )
                        {
                            PassageNodes[D, A].IsWater = tmpPassageNodeC.IsWater && CanDoFlatsAroundWater;
                            PassageNodes[D, A].Level = BestNum;
                        }
                        if ( tmpPassageNodeA.IsWater )
                        {
                            for ( B = 0; B <= tmpPassageNodeA.ConnectionCount - 1; B++ )
                            {
                                tmpPassageNodeB = tmpPassageNodeA.Connections[B].GetOther();
                                PassageNodesMinLevelSet(tmpPassageNodeB, HeightsArgs.PassageNodesMinLevel, tmpPassageNodeA.Level, MaxLevelTransition);
                                PassageNodesMaxLevelSet(tmpPassageNodeB, HeightsArgs.PassageNodesMaxLevel, tmpPassageNodeA.Level, MaxLevelTransition);
                            }
                        }
                    }
                }
                else if ( tmpPassageNodeA.Level < 0 )
                {
                    ReturnResult.ProblemAdd("Error: Node height not set");
                    return ReturnResult;
                }
            }
            //set level of edge points only connected to another border point
            for ( A = 0; A <= PassageNodeCount - 1; A++ )
            {
                tmpPassageNodeA = PassageNodes[0, A];
                if ( tmpPassageNodeA.IsOnBorder && tmpPassageNodeA.Level < 0 )
                {
                    tmpPassageNodeC = null;
                    CanDoFlatsAroundWater = true;
                    for ( B = 0; B <= tmpPassageNodeA.ConnectionCount - 1; B++ )
                    {
                        tmpPassageNodeB = tmpPassageNodeA.Connections[B].GetOther();
                        if ( tmpPassageNodeB.Level >= 0 )
                        {
                            if ( HeightsArgs.PassageNodesMinLevel.Nodes[tmpPassageNodeA.Num] <= tmpPassageNodeB.Level &&
                                 HeightsArgs.PassageNodesMaxLevel.Nodes[tmpPassageNodeA.Num] >= tmpPassageNodeB.Level )
                            {
                                if ( tmpPassageNodeC == null )
                                {
                                    tmpPassageNodeC = tmpPassageNodeB;
                                }
                            }
                        }
                        if ( HeightsArgs.PassageNodesMinLevel.Nodes[tmpPassageNodeB.Num] > 0 )
                        {
                            CanDoFlatsAroundWater = false;
                        }
                    }
                    if ( tmpPassageNodeC == null )
                    {
                        ReturnResult.ProblemAdd("Error: No connection for border node");
                        return ReturnResult;
                    }
                    BestNum = tmpPassageNodeC.Level;
                    PassageNodesMinLevelSet(tmpPassageNodeA, HeightsArgs.PassageNodesMinLevel, BestNum, MaxLevelTransition);
                    PassageNodesMaxLevelSet(tmpPassageNodeA, HeightsArgs.PassageNodesMaxLevel, BestNum, MaxLevelTransition);
                    for ( D = 0; D <= SymmetryBlockCount - 1; D++ )
                    {
                        PassageNodes[D, A].IsWater = tmpPassageNodeC.IsWater && CanDoFlatsAroundWater;
                        PassageNodes[D, A].Level = BestNum;
                    }
                    if ( tmpPassageNodeA.IsWater )
                    {
                        for ( B = 0; B <= tmpPassageNodeA.ConnectionCount - 1; B++ )
                        {
                            tmpPassageNodeB = tmpPassageNodeA.Connections[B].GetOther();
                            PassageNodesMinLevelSet(tmpPassageNodeB, HeightsArgs.PassageNodesMinLevel, tmpPassageNodeA.Level, MaxLevelTransition);
                            PassageNodesMaxLevelSet(tmpPassageNodeB, HeightsArgs.PassageNodesMaxLevel, tmpPassageNodeA.Level, MaxLevelTransition);
                        }
                    }
                }
            }

            RampBase = 1.0D;
            MaxDisconnectionDist = 99999.0F;

            clsResult RampResult = GenerateRamps();
            ReturnResult.Add(RampResult);

            return ReturnResult;
        }
Esempio n. 8
0
 public static ZipEntry ZipMakeEntry(ZipOutputStream ZipOutputStream, string Path, clsResult Result)
 {
     try
     {
         ZipEntry NewZipEntry = new ZipEntry(Path);
         NewZipEntry.DateTime = DateTime.Now;
         ZipOutputStream.PutNextEntry(NewZipEntry);
         return NewZipEntry;
     }
     catch ( Exception ex )
     {
         Result.ProblemAdd("Zip entry " + Convert.ToString(ControlChars.Quote) + Path + Convert.ToString(ControlChars.Quote) + " failed: " +
                           ex.Message);
         return null;
     }
 }
Esempio n. 9
0
        public static clsResult WriteMemoryToNewFile(MemoryStream Memory, string Path)
        {
            clsResult ReturnResult = new clsResult("Writing to " + Convert.ToString(ControlChars.Quote) + Path + Convert.ToString(ControlChars.Quote));

            FileStream NewFile = default(FileStream);
            try
            {
                NewFile = new FileStream(Path, FileMode.CreateNew);
            }
            catch ( Exception ex )
            {
                ReturnResult.ProblemAdd(ex.Message);
                return ReturnResult;
            }
            try
            {
                Memory.WriteTo(NewFile);
            }
            catch ( Exception ex )
            {
                ReturnResult.ProblemAdd(ex.Message);
                return ReturnResult;
            }

            Memory.Close();
            NewFile.Close();

            return ReturnResult;
        }
Esempio n. 10
0
        protected clsResult read_INI_Features(string iniText, List<IniFeature> resultData)
        {
            var resultObject = new clsResult("Reading feature.ini.", false);
            logger.Info("Reading feature.ini");

            try
            {
                var iniSections = IniReader.ReadString(iniText);
                foreach ( var iniSection in iniSections )
                {
                    var feature = new IniFeature();
                    feature.HealthPercent = -1;
                    var invalid = false;
                    foreach ( var iniToken in iniSection.Data )
                    {
                        if ( invalid )
                        {
                            break;
                        }

                        try
                        {
                            switch ( iniToken.Name )
                            {
                                case "id":
                                    feature.ID = uint.Parse(iniToken.Data);
                                    break;
                                case "name":
                                    feature.Code = iniToken.Data;
                                    break;
                                case "position":
                                    feature.Pos = XYZInt.FromString(iniToken.Data);
                                    break;
                                case "rotation":
                                    feature.Rotation = Rotation.FromString(iniToken.Data);
                                    break;
                                case "health":
                                    feature.HealthPercent = IniReader.ReadHealthPercent(iniToken.Data);
                                    if ( feature.HealthPercent < 0 || feature.HealthPercent > 100 )
                                    {
                                        resultObject.WarningAdd(string.Format("#{0} invalid health: \"{1}\"", iniSection.Name, feature.HealthPercent), false);
                                        logger.Warn("#{0} invalid health: \"{1}\"", iniSection.Name, feature.HealthPercent);
                                        invalid = true;
                                    }
                                    break;
                                default:
                                    resultObject.WarningAdd(string.Format("Found an invalid key: {0}={1}", iniToken.Name, iniToken.Data), false);
                                    logger.Warn("Found an invalid key: {0} = {1}", iniToken.Name, iniToken.Data);
                                    break;
                            }
                        }
                        catch ( Exception ex )
                        {
                            Debugger.Break();
                            resultObject.WarningAdd(
                                string.Format("#{0} invalid {2}: \"{3}\", got exception: {2}", iniSection.Name, iniToken.Name, iniToken.Data, ex.Message), false);
                            logger.WarnException(string.Format("#{0} invalid {2} \"{1}\"", iniSection.Name, iniToken.Name, iniToken.Data), ex);
                            invalid = true;
                        }
                    }

                    if ( !invalid )
                    {
                        resultData.Add(feature);
                    }
                }
            }
            catch ( Exception ex )
            {
                Debugger.Break();
                logger.ErrorException("Got exception while reading feature.ini", ex);
                resultObject.ProblemAdd(string.Format("Got exception: {0}", ex.Message), false);
                return resultObject;
            }

            return resultObject;
        }
Esempio n. 11
0
        public clsResult ReadPIE(StreamReader File, clsObjectData Owner)
        {
            clsResult ReturnResult = new clsResult("Reading PIE");

            int A = 0;
            int B = 0;
            string strTemp = "";
            string[] SplitText = null;
            int LevelCount = 0;
            int NewQuadCount = 0;
            int NewTriCount = 0;
            int C = 0;
            string TextureName = "";
            sPIELevel[] Levels = null;
            int LevelNum = 0;
            bool GotText = default(bool);
            string strTemp2;
            int D = 0;
            int PIEVersion = 0;
            int Count = 0;

            Levels = new sPIELevel[0];
            LevelNum = -1;
            do
            {
                strTemp = File.ReadLine();
                if ( strTemp == null )
                {
                    goto FileFinished;
                }
                Reeval:
                if ( strTemp.Substring(0, 3) == "PIE" )
                {
                    PIEVersion = int.Parse(strTemp.Substring(strTemp.Length - (strTemp.Length - 4), strTemp.Length - 4));
                    if ( PIEVersion != 2 & PIEVersion != 3 )
                    {
                        ReturnResult.ProblemAdd("Version is unknown.");
                        return ReturnResult;
                    }
                }
                else if ( strTemp.Substring(0, 4) == "TYPE" )
                {
                }
                else if ( strTemp.Substring(0, 7) == "TEXTURE" )
                {
                    TextureName = strTemp.Substring(strTemp.Length - (strTemp.Length - 10), strTemp.Length - 10);
                    A = Strings.InStrRev(TextureName, " ", -1, (CompareMethod)0);
                    if ( A > 0 )
                    {
                        A = Strings.InStrRev(TextureName, " ", A - 1, (CompareMethod)0);
                    }
                    else
                    {
                        ReturnResult.ProblemAdd("Bad texture name.");
                        return ReturnResult;
                    }
                    if ( A > 0 )
                    {
                        TextureName = TextureName.Substring(0, A - 1);
                    }
                    else
                    {
                        ReturnResult.ProblemAdd("Bad texture name.");
                        return ReturnResult;
                    }
                }
                else if ( strTemp.Substring(0, 6) == "LEVELS" )
                {
                    LevelCount = int.Parse(strTemp.Substring(strTemp.Length - (strTemp.Length - 7), strTemp.Length - 7));
                    Levels = new sPIELevel[LevelCount];
                }
                else if ( strTemp.Substring(0, 6) == "LEVEL " )
                {
                    LevelNum = (int.Parse(strTemp.Substring(strTemp.Length - (strTemp.Length - 6), strTemp.Length - 6))) - 1;
                    if ( LevelNum >= LevelCount )
                    {
                        ReturnResult.ProblemAdd("Level number >= number of levels.");
                        return ReturnResult;
                    }
                }
                else if ( strTemp.Substring(0, 6) == "POINTS" )
                {
                    Levels[LevelNum].PointCount = int.Parse(strTemp.Substring(strTemp.Length - (strTemp.Length - 7), strTemp.Length - 7));
                    Levels[LevelNum].Point = new sXYZ_sng[Levels[LevelNum].PointCount];
                    A = 0;
                    do
                    {
                        strTemp = File.ReadLine();
                        if ( strTemp == null )
                        {
                            goto FileFinished;
                        }

                        strTemp2 = Strings.Left(strTemp, 1);
                        if ( char.Parse(strTemp2) == '\t' || strTemp2 == " " )
                        {
                            SplitText = new string[3];
                            C = 0;
                            SplitText[0] = "";
                            GotText = false;
                            for ( B = 0; B <= strTemp.Length - 1; B++ )
                            {
                                if ( strTemp[B] != ' ' && strTemp[B] != ControlChars.Tab )
                                {
                                    GotText = true;
                                    SplitText[C] += strTemp[B].ToString();
                                }
                                else
                                {
                                    if ( GotText )
                                    {
                                        C++;
                                        if ( C == 3 )
                                        {
                                            break;
                                        }
                                        SplitText[C] = "";
                                        GotText = false;
                                    }
                                }
                            }

                            try
                            {
                                Levels[LevelNum].Point[A].X = float.Parse(SplitText[0]);
                                Levels[LevelNum].Point[A].Y = float.Parse(SplitText[1]);
                                Levels[LevelNum].Point[A].Z = float.Parse(SplitText[2]);
                            }
                            catch ( Exception )
                            {
                                ReturnResult.ProblemAdd("Bad point " + Convert.ToString(A));
                                return ReturnResult;
                            }
                            A++;
                        }
                        else if ( string.IsNullOrEmpty(strTemp2) )
                        {
                        }
                        else
                        {
                            goto Reeval;
                        }
                    } while ( true );
                }
                else if ( strTemp.Substring(0, 8) == "POLYGONS" )
                {
                    Levels[LevelNum].PolygonCount = int.Parse(strTemp.Substring(strTemp.Length - (strTemp.Length - 9), strTemp.Length - 9));
                    Levels[LevelNum].Polygon = new sPIELevel.sPolygon[Levels[LevelNum].PolygonCount];
                    A = 0;
                    do
                    {
                        strTemp = File.ReadLine();
                        if ( strTemp == null )
                        {
                            goto FileFinished;
                        }

                        strTemp2 = Strings.Left(strTemp, 1);
                        if ( char.Parse(strTemp2) == '\t' || strTemp2 == " " )
                        {
                            C = 0;
                            SplitText = new string[C + 1];
                            SplitText[C] = "";
                            for ( B = 0; B <= strTemp.Length - 1; B++ )
                            {
                                if ( strTemp[B] == ' ' || strTemp[B] == ControlChars.Tab )
                                {
                                    if ( SplitText[C].Length > 0 )
                                    {
                                        C++;
                                        Array.Resize(ref SplitText, C + 1);
                                        SplitText[C] = "";
                                    }
                                }
                                else
                                {
                                    SplitText[C] += strTemp[B].ToString();
                                }
                            }
                            if ( SplitText[C].Length == 0 )
                            {
                                Array.Resize(ref SplitText, C);
                            }
                            else
                            {
                                C++;
                            }

                            if ( PIEVersion == 3 )
                            {
                                //200, pointcount, points, texcoords
                                if ( C < 2 )
                                {
                                    ReturnResult.ProblemAdd("Too few fields for polygon " + Convert.ToString(A));
                                    return ReturnResult;
                                }
                                try
                                {
                                    Count = int.Parse(SplitText[1]);
                                }
                                catch ( Exception ex )
                                {
                                    ReturnResult.ProblemAdd("Bad polygon point count: " + ex.Message);
                                    return ReturnResult;
                                }
                                Levels[LevelNum].Polygon[A].PointCount = Count;
                                Levels[LevelNum].Polygon[A].PointNum = new int[Count];
                                Levels[LevelNum].Polygon[A].TexCoord = new sXY_sng[Count];
                                if ( Count == 3 )
                                {
                                    NewTriCount++;
                                }
                                else if ( Count == 4 )
                                {
                                    NewQuadCount++;
                                }
                                if ( SplitText.GetUpperBound(0) + 1 == 0 )
                                {
                                    goto Reeval;
                                }
                                else if ( SplitText.GetUpperBound(0) + 1 != (2 + Count * 3) )
                                {
                                    ReturnResult.ProblemAdd("Wrong number of fields (" + Convert.ToString(SplitText.GetUpperBound(0) + 1) + ") for polygon " +
                                                            Convert.ToString(A));
                                    return ReturnResult;
                                }
                                for ( B = 0; B <= Count - 1; B++ )
                                {
                                    try
                                    {
                                        Levels[LevelNum].Polygon[A].PointNum[B] = int.Parse(SplitText[2 + B]);
                                    }
                                    catch ( Exception ex )
                                    {
                                        ReturnResult.ProblemAdd("Bad polygon point: " + ex.Message);
                                        return ReturnResult;
                                    }

                                    try
                                    {
                                        Levels[LevelNum].Polygon[A].TexCoord[B].X = float.Parse(SplitText[2 + Count + 2 * B]);
                                    }
                                    catch ( Exception ex )
                                    {
                                        ReturnResult.ProblemAdd("Bad polygon x tex coord: " + ex.Message);
                                        return ReturnResult;
                                    }
                                    try
                                    {
                                        Levels[LevelNum].Polygon[A].TexCoord[B].Y = float.Parse(SplitText[2 + Count + 2 * B + 1]);
                                    }
                                    catch ( Exception ex )
                                    {
                                        ReturnResult.ProblemAdd("Bad polygon y tex coord: " + ex.Message);
                                        return ReturnResult;
                                    }
                                }
                                A++;
                            }
                            else if ( PIEVersion == 2 )
                            {
                                D = 0;
                                do
                                {
                                    //flag, numpoints, points[], x4 ignore if animated, texcoord[]xy
                                    Levels[LevelNum].Polygon[A].PointCount = int.Parse(SplitText[D + 1]);
                                    Levels[LevelNum].Polygon[A].PointNum = new int[Levels[LevelNum].Polygon[A].PointCount];
                                    Levels[LevelNum].Polygon[A].TexCoord = new sXY_sng[Levels[LevelNum].Polygon[A].PointCount];
                                    if ( Levels[LevelNum].Polygon[A].PointCount == 3 )
                                    {
                                        NewTriCount++;
                                    }
                                    else if ( Levels[LevelNum].Polygon[A].PointCount == 4 )
                                    {
                                        NewQuadCount++;
                                    }
                                    for ( B = 0; B <= Levels[LevelNum].Polygon[A].PointCount - 1; B++ )
                                    {
                                        Levels[LevelNum].Polygon[A].PointNum[B] = int.Parse(SplitText[D + 2 + B]);
                                    }
                                    C = D + 2 + Levels[LevelNum].Polygon[A].PointCount;
                                    if ( SplitText[D] == "4200" || SplitText[D] == "4000" || SplitText[D] == "6a00" || SplitText[D] == "4a00" || SplitText[D] == "6200" ||
                                         SplitText[D] == "14200" || SplitText[D] == "14a00" || SplitText[D] == "16a00" )
                                    {
                                        C += 4;
                                    }
                                    for ( B = 0; B <= Levels[LevelNum].Polygon[A].PointCount - 1; B++ )
                                    {
                                        Levels[LevelNum].Polygon[A].TexCoord[B].X = float.Parse(SplitText[C]);
                                        Levels[LevelNum].Polygon[A].TexCoord[B].Y = float.Parse(SplitText[C + 1]);
                                        C += 2;
                                    }
                                    D = C;
                                    A++;
                                } while ( D < SplitText.GetUpperBound(0) );
                            }
                        }
                        else if ( string.IsNullOrEmpty(strTemp2) )
                        {
                        }
                        else
                        {
                            goto Reeval;
                        }
                    } while ( true );
                }
                else if ( strTemp.Substring(0, 10) == "CONNECTORS" )
                {
                    ConnectorCount = int.Parse(strTemp.Substring(strTemp.Length - (strTemp.Length - 11), strTemp.Length - 11));
                    Connectors = new sXYZ_sng[ConnectorCount];
                    A = 0;
                    do
                    {
                        strTemp = File.ReadLine();
                        if ( strTemp == null )
                        {
                            goto FileFinished;
                        }

                        strTemp2 = Strings.Left(strTemp, 1);
                        if ( char.Parse(strTemp2) == '\t' || strTemp2 == " " )
                        {
                            SplitText = new string[3];
                            C = 0;
                            SplitText[0] = "";
                            GotText = false;
                            for ( B = 0; B <= strTemp.Length - 1; B++ )
                            {
                                if ( strTemp[B] != ' ' && strTemp[B] != ControlChars.Tab )
                                {
                                    GotText = true;
                                    SplitText[C] += strTemp[B].ToString();
                                }
                                else
                                {
                                    if ( GotText )
                                    {
                                        C++;
                                        if ( C == 3 )
                                        {
                                            break;
                                        }
                                        SplitText[C] = "";
                                        GotText = false;
                                    }
                                }
                            }

                            try
                            {
                                Connectors[A].X = float.Parse(SplitText[0]);
                                Connectors[A].Y = float.Parse(SplitText[2]);
                                Connectors[A].Z = float.Parse(SplitText[1]);
                            }
                            catch ( Exception )
                            {
                                ReturnResult.ProblemAdd("Bad connector " + Convert.ToString(A));
                                return ReturnResult;
                            }
                            A++;
                        }
                        else if ( string.IsNullOrEmpty(strTemp2) )
                        {
                        }
                        else
                        {
                            goto Reeval;
                        }
                    } while ( true );
                }
                else
                {
                }
            } while ( true );
            FileFinished:

            GLTextureNum = Owner.Get_TexturePage_GLTexture(TextureName.Substring(0, TextureName.Length - 4));
            if ( GLTextureNum == 0 )
            {
                ReturnResult.WarningAdd("Texture " + Convert.ToString(ControlChars.Quote) + TextureName + Convert.ToString(ControlChars.Quote) +
                                        " was not loaded");
            }

            TriangleCount = NewTriCount;
            QuadCount = NewQuadCount;
            Triangles = new sTriangle[TriangleCount];
            Quads = new sQuad[QuadCount];
            NewTriCount = 0;
            NewQuadCount = 0;
            for ( LevelNum = 0; LevelNum <= LevelCount - 1; LevelNum++ )
            {
                for ( A = 0; A <= Levels[LevelNum].PolygonCount - 1; A++ )
                {
                    if ( Levels[LevelNum].Polygon[A].PointCount == 3 )
                    {
                        Triangles[NewTriCount].PosA = Levels[LevelNum].Point[Levels[LevelNum].Polygon[A].PointNum[0]];
                        Triangles[NewTriCount].PosB = Levels[LevelNum].Point[Levels[LevelNum].Polygon[A].PointNum[1]];
                        Triangles[NewTriCount].PosC = Levels[LevelNum].Point[Levels[LevelNum].Polygon[A].PointNum[2]];
                        if ( PIEVersion == 2 )
                        {
                            Triangles[NewTriCount].TexCoordA.X = (float)(Levels[LevelNum].Polygon[A].TexCoord[0].X / 255.0D);
                            Triangles[NewTriCount].TexCoordA.Y = (float)(Levels[LevelNum].Polygon[A].TexCoord[0].Y / 255.0D);
                            Triangles[NewTriCount].TexCoordB.X = (float)(Levels[LevelNum].Polygon[A].TexCoord[1].X / 255.0D);
                            Triangles[NewTriCount].TexCoordB.Y = (float)(Levels[LevelNum].Polygon[A].TexCoord[1].Y / 255.0D);
                            Triangles[NewTriCount].TexCoordC.X = (float)(Levels[LevelNum].Polygon[A].TexCoord[2].X / 255.0D);
                            Triangles[NewTriCount].TexCoordC.Y = (float)(Levels[LevelNum].Polygon[A].TexCoord[2].Y / 255.0D);
                        }
                        else if ( PIEVersion == 3 )
                        {
                            Triangles[NewTriCount].TexCoordA = Levels[LevelNum].Polygon[A].TexCoord[0];
                            Triangles[NewTriCount].TexCoordB = Levels[LevelNum].Polygon[A].TexCoord[1];
                            Triangles[NewTriCount].TexCoordC = Levels[LevelNum].Polygon[A].TexCoord[2];
                        }
                        NewTriCount++;
                    }
                    else if ( Levels[LevelNum].Polygon[A].PointCount == 4 )
                    {
                        Quads[NewQuadCount].PosA = Levels[LevelNum].Point[Levels[LevelNum].Polygon[A].PointNum[0]];
                        Quads[NewQuadCount].PosB = Levels[LevelNum].Point[Levels[LevelNum].Polygon[A].PointNum[1]];
                        Quads[NewQuadCount].PosC = Levels[LevelNum].Point[Levels[LevelNum].Polygon[A].PointNum[2]];
                        Quads[NewQuadCount].PosD = Levels[LevelNum].Point[Levels[LevelNum].Polygon[A].PointNum[3]];
                        if ( PIEVersion == 2 )
                        {
                            Quads[NewQuadCount].TexCoordA.X = (float)(Levels[LevelNum].Polygon[A].TexCoord[0].X / 255.0D);
                            Quads[NewQuadCount].TexCoordA.Y = (float)(Levels[LevelNum].Polygon[A].TexCoord[0].Y / 255.0D);
                            Quads[NewQuadCount].TexCoordB.X = (float)(Levels[LevelNum].Polygon[A].TexCoord[1].X / 255.0D);
                            Quads[NewQuadCount].TexCoordB.Y = (float)(Levels[LevelNum].Polygon[A].TexCoord[1].Y / 255.0D);
                            Quads[NewQuadCount].TexCoordC.X = (float)(Levels[LevelNum].Polygon[A].TexCoord[2].X / 255.0D);
                            Quads[NewQuadCount].TexCoordC.Y = (float)(Levels[LevelNum].Polygon[A].TexCoord[2].Y / 255.0D);
                            Quads[NewQuadCount].TexCoordD.X = (float)(Levels[LevelNum].Polygon[A].TexCoord[3].X / 255.0D);
                            Quads[NewQuadCount].TexCoordD.Y = (float)(Levels[LevelNum].Polygon[A].TexCoord[3].Y / 255.0D);
                        }
                        else if ( PIEVersion == 3 )
                        {
                            Quads[NewQuadCount].TexCoordA = Levels[LevelNum].Polygon[A].TexCoord[0];
                            Quads[NewQuadCount].TexCoordB = Levels[LevelNum].Polygon[A].TexCoord[1];
                            Quads[NewQuadCount].TexCoordC = Levels[LevelNum].Polygon[A].TexCoord[2];
                            Quads[NewQuadCount].TexCoordD = Levels[LevelNum].Polygon[A].TexCoord[3];
                        }
                        NewQuadCount++;
                    }
                }
            }

            return ReturnResult;
        }
Esempio n. 12
0
        protected clsResult createWZObjects(List<WZBJOUnit> bjoUnits, List<IniStructure> iniStructures, List<IniDroid> iniDroids, List<IniFeature> iniFeatures)
        {
            var ReturnResult = new clsResult("Creating objects", false);
            logger.Info("Creating objects");

            var newUnit = default(clsUnit);
            UInt32 availableID = 0;
            var unitAdd = new clsUnitAdd();
            var a = 0;
            var b = 0;

            unitAdd.Map = map;

            availableID = 1U;
            foreach ( var bjoUnit in bjoUnits )
            {
                if ( bjoUnit.ID >= availableID )
                {
                    availableID = bjoUnit.ID + 1U;
                }
            }
            if ( iniStructures.Count > 0)
            {
                var structMaxId = iniStructures.Max(w => w.ID) + 10;
                if ( structMaxId > availableID )
                {
                    availableID = structMaxId;
                }
            }
            if ( iniFeatures.Count > 0 )
            {
                var featuresMaxId = iniFeatures.Max(w => w.ID) + 10;
                if ( featuresMaxId > availableID )
                {
                    availableID = featuresMaxId;
                }
            }
            if ( iniDroids.Count > 0 )
            {
                var droidsMaxId = iniDroids.Max(w => w.ID) + 10;
                if ( droidsMaxId > availableID )
                {
                    availableID += droidsMaxId;
                }
            }

            foreach ( var bjoUnit in bjoUnits )
            {
                newUnit = new clsUnit();
                newUnit.ID = bjoUnit.ID;
                newUnit.TypeBase = App.ObjectData.FindOrCreateUnitType(bjoUnit.Code, bjoUnit.ObjectType, -1);
                if ( newUnit.TypeBase == null )
                {
                    ReturnResult.ProblemAdd("Unable to create object type.");
                    return ReturnResult;
                }
                if ( bjoUnit.Player >= Constants.PlayerCountMax )
                {
                    newUnit.UnitGroup = map.ScavengerUnitGroup;
                }
                else
                {
                    newUnit.UnitGroup = map.UnitGroups[Convert.ToInt32(bjoUnit.Player)];
                }
                newUnit.Pos = bjoUnit.Pos;
                newUnit.Rotation = (int)(Math.Min(bjoUnit.Rotation, 359U));
                if ( bjoUnit.ID == 0U )
                {
                    bjoUnit.ID = availableID;
                    App.ZeroIDWarning(newUnit, bjoUnit.ID, ReturnResult);
                }
                unitAdd.NewUnit = newUnit;
                unitAdd.ID = bjoUnit.ID;
                unitAdd.Perform();
                App.ErrorIDChange(bjoUnit.ID, newUnit, "CreateWZObjects");
                if ( availableID == bjoUnit.ID )
                {
                    availableID = newUnit.ID + 1U;
                }
            }

            var structureTypeBase = default(StructureTypeBase);
            var droidType = default(DroidDesign);
            var featureTypeBase = default(FeatureTypeBase);
            var loadPartsArgs = new DroidDesign.sLoadPartsArgs();
            UnitTypeBase unitTypeBase = null;
            var errorCount = 0;
            var unknownDroidComponentCount = 0;
            var unknownDroidTypeCount = 0;
            var droidBadPositionCount = 0;
            var structureBadPositionCount = 0;
            var structureBadModulesCount = 0;
            var featureBadPositionCount = 0;
            var moduleLimit = 0;
            var zeroPos = new XYInt(0, 0);
            var moduleTypeBase = default(StructureTypeBase);
            var newModule = default(clsUnit);

            var factoryModule = App.ObjectData.FindFirstStructureType(StructureTypeBase.enumStructureType.FactoryModule);
            var researchModule = App.ObjectData.FindFirstStructureType(StructureTypeBase.enumStructureType.ResearchModule);
            var powerModule = App.ObjectData.FindFirstStructureType(StructureTypeBase.enumStructureType.PowerModule);

            if ( factoryModule == null )
            {
                ReturnResult.WarningAdd("No factory module loaded.");
            }
            if ( researchModule == null )
            {
                ReturnResult.WarningAdd("No research module loaded.");
            }
            if ( powerModule == null )
            {
                ReturnResult.WarningAdd("No power module loaded.");
            }

            foreach ( var iniStructure in iniStructures )
            {
                if ( iniStructure.Pos == null )
                {
                    logger.Debug("{0} pos was null", iniStructure.Code);
                    structureBadPositionCount++;
                }
                else if ( !App.PosIsWithinTileArea(iniStructure.Pos, zeroPos, map.Terrain.TileSize) )
                {
                    logger.Debug("{0} structure pos x{1} y{2}, is wrong.", iniStructure.Code, iniStructure.Pos.X,
                        iniStructure.Pos.Y);
                    structureBadPositionCount++;
                }
                else
                {
                    unitTypeBase = App.ObjectData.FindOrCreateUnitType(Convert.ToString(iniStructure.Code),
                        UnitType.PlayerStructure, iniStructure.WallType);
                    if ( unitTypeBase.Type == UnitType.PlayerStructure )
                    {
                        structureTypeBase = (StructureTypeBase)unitTypeBase;
                    }
                    else
                    {
                        structureTypeBase = null;
                    }
                    if ( structureTypeBase == null )
                    {
                        errorCount++;
                    }
                    else
                    {
                        newUnit = new clsUnit();
                        newUnit.TypeBase = structureTypeBase;
                        if ( iniStructure.UnitGroup == null )
                        {
                            newUnit.UnitGroup = map.ScavengerUnitGroup;
                        }
                        else
                        {
                            newUnit.UnitGroup = iniStructure.UnitGroup;
                        }
                        newUnit.Pos = new WorldPos(iniStructure.Pos, iniStructure.Pos.Z);
                        newUnit.Rotation = Convert.ToInt32(iniStructure.Rotation.Direction * 360.0D / Constants.INIRotationMax);
                        if ( newUnit.Rotation == 360 )
                        {
                            newUnit.Rotation = 0;
                        }
                        if ( iniStructure.HealthPercent >= 0 )
                        {
                            newUnit.Health = MathUtil.Clamp_dbl(iniStructure.HealthPercent / 100.0D, 0.01D, 1.0D);
                        }
                        if ( iniStructure.ID == 0U )
                        {
                            iniStructure.ID = availableID;
                            App.ZeroIDWarning(newUnit, iniStructure.ID, ReturnResult);
                        }
                        unitAdd.NewUnit = newUnit;
                        unitAdd.ID = iniStructure.ID;
                        unitAdd.Perform();
                        App.ErrorIDChange(iniStructure.ID, newUnit, "Load_WZ->INIStructures");
                        if ( availableID == iniStructure.ID )
                        {
                            availableID = newUnit.ID + 1U;
                        }
                        //create modules
                        switch ( structureTypeBase.StructureType )
                        {
                            case StructureTypeBase.enumStructureType.Factory:
                                moduleLimit = 2;
                                moduleTypeBase = factoryModule;
                                break;
                            case StructureTypeBase.enumStructureType.VTOLFactory:
                                moduleLimit = 2;
                                moduleTypeBase = factoryModule;
                                break;
                            case StructureTypeBase.enumStructureType.PowerGenerator:
                                moduleLimit = 1;
                                moduleTypeBase = powerModule;
                                break;
                            case StructureTypeBase.enumStructureType.Research:
                                moduleLimit = 1;
                                moduleTypeBase = researchModule;
                                break;
                            default:
                                moduleLimit = 0;
                                moduleTypeBase = null;
                                break;
                        }
                        if ( iniStructure.ModuleCount > moduleLimit )
                        {
                            iniStructure.ModuleCount = moduleLimit;
                            structureBadModulesCount++;
                        }
                        else if ( iniStructure.ModuleCount < 0 )
                        {
                            iniStructure.ModuleCount = 0;
                            structureBadModulesCount++;
                        }
                        if ( moduleTypeBase != null )
                        {
                            for ( b = 0; b <= iniStructure.ModuleCount - 1; b++ )
                            {
                                newModule = new clsUnit();
                                newModule.TypeBase = moduleTypeBase;
                                newModule.UnitGroup = newUnit.UnitGroup;
                                newModule.Pos = newUnit.Pos;
                                newModule.Rotation = newUnit.Rotation;
                                unitAdd.NewUnit = newModule;
                                unitAdd.ID = availableID;
                                unitAdd.Perform();
                                availableID = newModule.ID + 1U;
                            }
                        }
                    }
                }
            }
            if ( structureBadPositionCount > 0 )
            {
                ReturnResult.WarningAdd(structureBadPositionCount + " structures had an invalid position and were removed.");
            }
            if ( structureBadModulesCount > 0 )
            {
                ReturnResult.WarningAdd(structureBadModulesCount + " structures had an invalid number of modules.");
            }

            foreach ( var iniFeature in iniFeatures )
            {
                if ( iniFeature.Pos == null )
                {
                    featureBadPositionCount++;
                }
                else if ( !App.PosIsWithinTileArea(iniFeature.Pos, zeroPos, map.Terrain.TileSize) )
                {
                    featureBadPositionCount++;
                }
                else
                {
                    unitTypeBase = App.ObjectData.FindOrCreateUnitType(Convert.ToString(iniFeature.Code), UnitType.Feature, -1);
                    if ( unitTypeBase.Type == UnitType.Feature )
                    {
                        featureTypeBase = (FeatureTypeBase)unitTypeBase;
                    }
                    else
                    {
                        featureTypeBase = null;
                    }
                    if ( featureTypeBase == null )
                    {
                        errorCount++;
                    }
                    else
                    {
                        newUnit = new clsUnit();
                        newUnit.TypeBase = featureTypeBase;
                        newUnit.UnitGroup = map.ScavengerUnitGroup;
                        newUnit.Pos = new WorldPos(iniFeature.Pos, iniFeature.Pos.Z);
                        newUnit.Rotation = Convert.ToInt32(iniFeature.Rotation.Direction * 360.0D / Constants.INIRotationMax);
                        if ( newUnit.Rotation == 360 )
                        {
                            newUnit.Rotation = 0;
                        }
                        if ( iniFeature.HealthPercent >= 0 )
                        {
                            newUnit.Health = MathUtil.Clamp_dbl(iniFeature.HealthPercent / 100.0D, 0.01D, 1.0D);
                        }
                        if ( iniFeature.ID == 0U )
                        {
                            iniFeature.ID = availableID;
                            App.ZeroIDWarning(newUnit, iniFeature.ID, ReturnResult);
                        }
                        unitAdd.NewUnit = newUnit;
                        unitAdd.ID = iniFeature.ID;
                        unitAdd.Perform();
                        App.ErrorIDChange(iniFeature.ID, newUnit, "Load_WZ->INIFeatures");
                        if ( availableID == iniFeature.ID )
                        {
                            availableID = newUnit.ID + 1U;
                        }
                    }
                }
            }
            if ( featureBadPositionCount > 0 )
            {
                ReturnResult.WarningAdd(featureBadPositionCount + " features had an invalid position and were removed.");
            }

            foreach ( var iniDroid in iniDroids )
            {
                if ( iniDroid.Pos == null )
                {
                    droidBadPositionCount++;
                }
                else if ( !App.PosIsWithinTileArea(iniDroid.Pos, zeroPos, map.Terrain.TileSize) )
                {
                    droidBadPositionCount++;
                }
                else
                {
                    if ( iniDroid.Template == null || iniDroid.Template == "" )
                    {
                        droidType = new DroidDesign();
                        if ( !droidType.SetDroidType((enumDroidType)(iniDroid.DroidType)) )
                        {
                            unknownDroidTypeCount++;
                        }
                        loadPartsArgs.Body = App.ObjectData.FindOrCreateBody(iniDroid.Body);
                        if ( loadPartsArgs.Body == null )
                        {
                            unknownDroidComponentCount++;
                        }
                        else
                        {
                            if ( loadPartsArgs.Body.IsUnknown )
                            {
                                unknownDroidComponentCount++;
                            }
                        }
                        loadPartsArgs.Propulsion = App.ObjectData.FindOrCreatePropulsion(Convert.ToString(iniDroid.Propulsion));
                        if ( loadPartsArgs.Propulsion == null )
                        {
                            unknownDroidComponentCount++;
                        }
                        else
                        {
                            if ( loadPartsArgs.Propulsion.IsUnknown )
                            {
                                unknownDroidComponentCount++;
                            }
                        }
                        loadPartsArgs.Construct = App.ObjectData.FindOrCreateConstruct(Convert.ToString(iniDroid.Construct));
                        if ( loadPartsArgs.Construct == null )
                        {
                            unknownDroidComponentCount++;
                        }
                        else
                        {
                            if ( loadPartsArgs.Construct.IsUnknown )
                            {
                                unknownDroidComponentCount++;
                            }
                        }
                        loadPartsArgs.Repair = App.ObjectData.FindOrCreateRepair(iniDroid.Repair);
                        if ( loadPartsArgs.Repair == null )
                        {
                            unknownDroidComponentCount++;
                        }
                        else
                        {
                            if ( loadPartsArgs.Repair.IsUnknown )
                            {
                                unknownDroidComponentCount++;
                            }
                        }
                        loadPartsArgs.Sensor = App.ObjectData.FindOrCreateSensor(iniDroid.Sensor);
                        if ( loadPartsArgs.Sensor == null )
                        {
                            unknownDroidComponentCount++;
                        }
                        else
                        {
                            if ( loadPartsArgs.Sensor.IsUnknown )
                            {
                                unknownDroidComponentCount++;
                            }
                        }
                        loadPartsArgs.Brain = App.ObjectData.FindOrCreateBrain(iniDroid.Brain);
                        if ( loadPartsArgs.Brain == null )
                        {
                            unknownDroidComponentCount++;
                        }
                        else
                        {
                            if ( loadPartsArgs.Brain.IsUnknown )
                            {
                                unknownDroidComponentCount++;
                            }
                        }
                        loadPartsArgs.ECM = App.ObjectData.FindOrCreateECM(Convert.ToString(iniDroid.ECM));
                        if ( loadPartsArgs.ECM == null )
                        {
                            unknownDroidComponentCount++;
                        }
                        else
                        {
                            if ( loadPartsArgs.ECM.IsUnknown )
                            {
                                unknownDroidComponentCount++;
                            }
                        }
                        loadPartsArgs.Weapon1 = App.ObjectData.FindOrCreateWeapon(Convert.ToString(iniDroid.Weapons[0]));
                        if ( loadPartsArgs.Weapon1 == null )
                        {
                            unknownDroidComponentCount++;
                        }
                        else
                        {
                            if ( loadPartsArgs.Weapon1.IsUnknown )
                            {
                                unknownDroidComponentCount++;
                            }
                        }
                        loadPartsArgs.Weapon2 = App.ObjectData.FindOrCreateWeapon(Convert.ToString(iniDroid.Weapons[1]));
                        if ( loadPartsArgs.Weapon2 == null )
                        {
                            unknownDroidComponentCount++;
                        }
                        else
                        {
                            if ( loadPartsArgs.Weapon2.IsUnknown )
                            {
                                unknownDroidComponentCount++;
                            }
                        }
                        loadPartsArgs.Weapon3 = App.ObjectData.FindOrCreateWeapon(Convert.ToString(iniDroid.Weapons[2]));
                        if ( loadPartsArgs.Weapon3 == null )
                        {
                            unknownDroidComponentCount++;
                        }
                        else
                        {
                            if ( loadPartsArgs.Weapon3.IsUnknown )
                            {
                                unknownDroidComponentCount++;
                            }
                        }
                        droidType.LoadParts(loadPartsArgs);
                    }
                    else
                    {
                        unitTypeBase = App.ObjectData.FindOrCreateUnitType(iniDroid.Template, UnitType.PlayerDroid, -1);
                        if ( unitTypeBase == null )
                        {
                            droidType = null;
                        }
                        else
                        {
                            if ( unitTypeBase.Type == UnitType.PlayerDroid )
                            {
                                droidType = (DroidDesign)unitTypeBase;
                            }
                            else
                            {
                                droidType = null;
                            }
                        }
                    }
                    if ( droidType == null )
                    {
                        errorCount++;
                    }
                    else
                    {
                        newUnit = new clsUnit();
                        newUnit.TypeBase = droidType;
                        if ( iniDroid.UnitGroup == null )
                        {
                            newUnit.UnitGroup = map.ScavengerUnitGroup;
                        }
                        else
                        {
                            newUnit.UnitGroup = iniDroid.UnitGroup;
                        }
                        newUnit.Pos = new WorldPos(iniDroid.Pos, iniDroid.Pos.Z);
                        newUnit.Rotation = Convert.ToInt32(iniDroid.Rotation.Direction * 360.0D / Constants.INIRotationMax);
                        if ( newUnit.Rotation == 360 )
                        {
                            newUnit.Rotation = 0;
                        }
                        if ( iniDroid.HealthPercent >= 0 )
                        {
                            newUnit.Health = MathUtil.Clamp_dbl(iniDroid.HealthPercent / 100.0D, 0.01D, 1.0D);
                        }
                        if ( iniDroid.ID == 0U )
                        {
                            iniDroid.ID = availableID;
                            App.ZeroIDWarning(newUnit, iniDroid.ID, ReturnResult);
                        }
                        unitAdd.NewUnit = newUnit;
                        unitAdd.ID = iniDroid.ID;
                        unitAdd.Perform();
                        App.ErrorIDChange(iniDroid.ID, newUnit, "Load_WZ->INIDroids");
                        if ( availableID == iniDroid.ID )
                        {
                            availableID = newUnit.ID + 1U;
                        }
                    }
                }
            }
            if ( droidBadPositionCount > 0 )
            {
                ReturnResult.WarningAdd(droidBadPositionCount + " droids had an invalid position and were removed.");
            }
            if ( unknownDroidTypeCount > 0 )
            {
                ReturnResult.WarningAdd(unknownDroidTypeCount + " droid designs had an unrecognised droidType and were removed.");
            }
            if ( unknownDroidComponentCount > 0 )
            {
                ReturnResult.WarningAdd(unknownDroidComponentCount + " droid designs had components that are not loaded.");
            }

            if ( errorCount > 0 )
            {
                ReturnResult.WarningAdd("Object Create Error.");
            }

            return ReturnResult;
        }
Esempio n. 13
0
        public virtual clsResult Load(string path)
        {
            var returnResult = new clsResult(string.Format("Loading WZ from '{0}'.", path), false);
            logger.Info("Loading WZ from '{0}'.", path);
            var subResult = new sResult();

            ZipSplitPath splitPath;
            var mapLoadName = "";

            using ( var zip = ZipFile.Read(path) )
            {
                foreach ( var e in zip )
                {
                    if ( e.IsDirectory )
                    {
                        continue;
                    }

                    splitPath = new ZipSplitPath(e.FileName);
                    logger.Debug("Found file \"{0}\".", e.FileName);
                    // Find the maps .lev
                    if ( splitPath.FileExtension != "lev" || splitPath.PartCount != 1 )
                    {
                        continue;
                    }

                    // Buggy file > 1MB
                    if ( e.UncompressedSize > 1 * 1024 * 1024 )
                    {
                        returnResult.ProblemAdd("lev file is too large.");
                        return returnResult;
                    }

                    using ( var s = e.OpenReader() )
                    {
                        var myresult = new clsResult(string.Format("Parsing file \"{0}\"", e.FileName), false);
                        logger.Info("Parsing file \"{0}\"", e.FileName);

                        try
                        {
                            var r = new StreamReader(s);
                            var text = r.ReadToEnd();
                            var levFile = LevGrammar.Lev.Parse(text);

                            if ( levFile.Levels.Count < 1 )
                            {
                                myresult.ProblemAdd("No maps found in file.");
                                returnResult.Add(myresult);
                                return returnResult;
                            }

                            // Group games by the Game key.
                            var groupGames = levFile.Levels.GroupBy(level => level.Game);

                            // Load default map if only one Game file is found.
                            if ( groupGames.Count() == 1 )
                            {
                                var level = groupGames.First().First(); //first group, first level

                                mapLoadName = level.Game;

                                switch ( level.Dataset.Substring(level.Dataset.Length - 1, 1) )
                                {
                                    case "1":
                                        map.Tileset = App.Tileset_Arizona;
                                        break;
                                    case "2":
                                        map.Tileset = App.Tileset_Urban;
                                        break;
                                    case "3":
                                        map.Tileset = App.Tileset_Urban;
                                        break;
                                    default:
                                        myresult.ProblemAdd("Unknown tileset.");
                                        returnResult.Add(myresult);
                                        return returnResult;
                                }
                            }
                            else
                            {
                                //prompt user for which of the entries to load
                                var selectToLoadResult = new frmWZLoad.clsOutput();

                                var names = groupGames
                                    .Select(gameGroup => gameGroup.First().Name)
                                    .ToArray();

                                var selectToLoadForm = new frmWZLoad(names, selectToLoadResult,
                                    "Select a map from " + new sSplitPath(path).FileTitle);
                                selectToLoadForm.ShowDialog();
                                if ( selectToLoadResult.Result < 0 )
                                {
                                    returnResult.ProblemAdd("No map selected.");
                                    return returnResult;
                                }

                                var level = groupGames.ElementAt(selectToLoadResult.Result).First();

                                mapLoadName = level.Game;

                                switch ( level.Dataset.Substring(level.Dataset.Length - 1, 1) )
                                {
                                    case "1":
                                        map.Tileset = App.Tileset_Arizona;
                                        break;
                                    case "2":
                                        map.Tileset = App.Tileset_Urban;
                                        break;
                                    case "3":
                                        map.Tileset = App.Tileset_Urban;
                                        break;
                                    default:
                                        myresult.ProblemAdd("Unknown tileset.");
                                        returnResult.Add(myresult);
                                        return returnResult;
                                }
                            }
                        }
                        catch ( Exception ex )
                        {
                            myresult.ProblemAdd(string.Format("Got an exception while parsing the .lev file: {0}", ex), false);
                            returnResult.Add(myresult);
                            logger.ErrorException("Got an exception while parsing the .lev file", ex);
                            Debugger.Break();
                        }
                    }
                }

                map.TileType_Reset();
                map.SetPainterToDefaults();

                // mapLoadName is now multiplay/maps/<mapname>.gam (thats "game" from the .lev file
                var gameSplitPath = new ZipSplitPath(mapLoadName);
                var gameFilesPath = gameSplitPath.FilePath + gameSplitPath.FileTitleWithoutExtension + "/";

                var gameZipEntry = zip[mapLoadName];
                if ( gameZipEntry == null )
                {
                    returnResult.ProblemAdd(string.Format("Game file \"{0}\" not found.", mapLoadName), false);
                    logger.Error("Game file \"{0}\" not found.", mapLoadName);
                    return returnResult;
                }
                using ( Stream s = gameZipEntry.OpenReader() )
                {
                    var reader = new BinaryReader(s);
                    subResult = read_WZ_gam(reader);
                    reader.Close();
                    if ( !subResult.Success )
                    {
                        returnResult.ProblemAdd(subResult.Problem);
                        return returnResult;
                    }
                }

                var gameMapZipEntry = zip[gameFilesPath + "game.map"];
                if ( gameMapZipEntry == null )
                {
                    returnResult.ProblemAdd(string.Format("{0}game.map file not found", gameFilesPath));
                    return returnResult;
                }
                using ( Stream s = gameMapZipEntry.OpenReader() )
                {
                    var reader = new BinaryReader(s);
                    subResult = read_WZ_map(reader);
                    reader.Close();
                    if ( !subResult.Success )
                    {
                        returnResult.ProblemAdd(subResult.Problem);
                        return returnResult;
                    }
                }

                var bjoUnits = new List<WZBJOUnit>();

                var iniFeatures = new List<IniFeature>();
                var featureIniZipEntry = zip[gameFilesPath + "feature.ini"];
                if ( featureIniZipEntry != null )
                {
                    using ( var reader = new StreamReader(featureIniZipEntry.OpenReader()) )
                    {
                        var text = reader.ReadToEnd();
                        returnResult.Add(read_INI_Features(text, iniFeatures));
                    }
                }

                if ( iniFeatures.Count() == 0 ) // no feature.ini
                {
                    var Result = new clsResult("feat.bjo", false);
                    logger.Info("Loading feat.bjo");

                    var featBJOZipEntry = zip[gameFilesPath + "feat.bjo"];
                    if ( featBJOZipEntry == null )
                    {
                        Result.WarningAdd(string.Format("{0}feat.bjo / feature.ini file not found", gameFilesPath));
                    }
                    else
                    {
                        using ( Stream s = featBJOZipEntry.OpenReader() )
                        {
                            var reader = new BinaryReader(s);
                            subResult = read_WZ_Features(reader, bjoUnits);
                            reader.Close();
                            if ( !subResult.Success )
                            {
                                Result.WarningAdd(subResult.Problem);
                            }
                        }
                    }
                    returnResult.Add(Result);
                }

                var result = new clsResult("ttypes.ttp", false);
                logger.Info("Loading ttypes.ttp");
                var ttypesEntry = zip[gameFilesPath + "ttypes.ttp"];
                if ( ttypesEntry == null )
                {
                    result.WarningAdd(string.Format("{0}ttypes.ttp file not found", gameFilesPath));
                }
                else
                {
                    using ( Stream s = ttypesEntry.OpenReader() )
                    {
                        var reader = new BinaryReader(s);
                        subResult = read_WZ_TileTypes(reader);
                        reader.Close();
                        if ( !subResult.Success )
                        {
                            result.WarningAdd(subResult.Problem);
                        }
                    }
                }
                returnResult.Add(result);

                var iniStructures = new List<IniStructure>();
                var structIniEntry = zip[gameFilesPath + "struct.ini"];
                if ( structIniEntry != null )
                {
                    using ( var reader = new StreamReader(structIniEntry.OpenReader()) )
                    {
                        var text = reader.ReadToEnd();
                        returnResult.Add(read_INI_Structures(text, iniStructures));
                    }
                }

                if ( iniStructures.Count() == 0 )
                {
                    var Result = new clsResult("struct.bjo", false);
                    logger.Info("Loading struct.bjo");
                    var structBjoEntry = zip[gameFilesPath + "struct.bjo"];
                    if ( structBjoEntry == null )
                    {
                        Result.WarningAdd(string.Format("{0}struct.bjo / struct.ini file not found", gameFilesPath));
                    }
                    else
                    {
                        using ( Stream s = structBjoEntry.OpenReader() )
                        {
                            var reader = new BinaryReader(s);
                            subResult = read_WZ_Structures(reader, bjoUnits);
                            reader.Close();
                            if ( !subResult.Success )
                            {
                                Result.WarningAdd(subResult.Problem);
                            }
                        }
                    }
                    returnResult.Add(Result);
                }

                var iniDroids = new List<IniDroid>();
                if ( structIniEntry != null )
                {
                    var droidIniEntry = zip[gameFilesPath + "droid.ini"];
                    if ( droidIniEntry != null )
                    {
                        using ( var reader = new StreamReader(droidIniEntry.OpenReader()) )
                        {
                            var text = reader.ReadToEnd();
                            returnResult.Add(read_INI_Droids(text, iniDroids));
                        }
                    }
                }

                if ( iniDroids.Count() == 0 ) // No droid.ini
                {
                    var Result = new clsResult("dinit.bjo", false);
                    logger.Info("Loading dinit.bjo");
                    var diniBjoEntry = zip[gameFilesPath + "dinit.bjo"];
                    if ( diniBjoEntry == null )
                    {
                        Result.WarningAdd(string.Format("{0}dinit.bjo / droid.ini file not found", gameFilesPath));
                    }
                    else
                    {
                        using ( Stream s = diniBjoEntry.OpenReader() )
                        {
                            var reader = new BinaryReader(s);
                            subResult = read_WZ_Droids(reader, bjoUnits);
                            reader.Close();
                            if ( !subResult.Success )
                            {
                                Result.WarningAdd(subResult.Problem);
                            }
                        }
                    }
                    returnResult.Add(Result);
                }

                returnResult.Add(createWZObjects(bjoUnits, iniStructures, iniDroids, iniFeatures));

                //objects are modified by this and must already exist
                var labelsIniEntry = zip[gameFilesPath + "labels.ini"];
                if ( labelsIniEntry != null )
                {
                    using ( var reader = new StreamReader(labelsIniEntry.OpenReader()) )
                    {
                        var text = reader.ReadToEnd();
                        returnResult.Add(read_INI_Labels(text));
                    }
                }
            }

            return returnResult;
        }
Esempio n. 14
0
        public clsResult Save(sWrite_WZ_Args Args)
        {
            var returnResult =
                new clsResult("Compiling to \"{0}\"".Format2(Args.Path), false);
            logger.Info("Compiling to \"{0}\"".Format2(Args.Path));

            try
            {
                switch ( Args.CompileType )
                {
                    case sWrite_WZ_Args.enumCompileType.Multiplayer:
                        if ( Args.Multiplayer == null )
                        {
                            returnResult.ProblemAdd("Multiplayer arguments were not passed.");
                            return returnResult;
                        }
                        if ( Args.Multiplayer.PlayerCount < 2 | Args.Multiplayer.PlayerCount > Constants.PlayerCountMax )
                        {
                            returnResult.ProblemAdd(string.Format("Number of players was below 2 or above {0}.", Constants.PlayerCountMax));
                            return returnResult;
                        }
                        break;
                    case sWrite_WZ_Args.enumCompileType.Campaign:
                        if ( Args.Campaign == null )
                        {
                            returnResult.ProblemAdd("Campaign arguments were not passed.");
                            return returnResult;
                        }
                        break;
                    default:
                        returnResult.ProblemAdd("Unknown compile method.");
                        return returnResult;
                }

                if ( !Args.Overwrite )
                {
                    if ( File.Exists(Args.Path) )
                    {
                        returnResult.ProblemAdd("The selected file already exists.");
                        return returnResult;
                    }
                }

                if ( Args.CompileType == sWrite_WZ_Args.enumCompileType.Multiplayer )
                {
                    if ( !Args.Overwrite )
                    {
                        if ( File.Exists(Args.Path) )
                        {
                            returnResult.ProblemAdd(string.Format("A file already exists at: {0}", Args.Path));
                            return returnResult;
                        }
                    }

                    try
                    {
                        using ( var zip = new ZipOutputStream(Args.Path) )
                        {
                            // Set encoding
                            zip.AlternateEncoding = Encoding.GetEncoding("UTF-8");
                            zip.AlternateEncodingUsage = ZipOption.Always;

                            // Set compression
                            zip.CompressionLevel = CompressionLevel.BestCompression;

                            // .xplayers.lev
                            var zipPath = string.Format("{0}c-{1}.xplayers.lev", Args.Multiplayer.PlayerCount, Args.MapName);
                            if ( Args.CompileType == sWrite_WZ_Args.enumCompileType.Multiplayer )
                            {
                                zip.PutNextEntry(zipPath);
                                returnResult.Add(Serialize_WZ_LEV(zip, Args.Multiplayer.PlayerCount,
                                    Args.Multiplayer.AuthorName, Args.Multiplayer.License,
                                    Args.MapName));
                            }

                            var path = string.Format("multiplay/maps/{0}c-{1}", Args.Multiplayer.PlayerCount, Args.MapName);
                            zip.PutNextEntry(string.Format("{0}.gam", path));
                            returnResult.Add(Serialize_WZ_Gam(zip, 0U,
                                Args.CompileType, Args.ScrollMin, Args.ScrollMax));

                            zip.PutNextEntry(string.Format("{0}/struct.ini", path));
                            var iniStruct = new IniWriter(zip);
                            returnResult.Add(Serialize_WZ_StructuresINI(iniStruct, Args.Multiplayer.PlayerCount));
                            iniStruct.Flush();

                            zip.PutNextEntry(string.Format("{0}/droid.ini", path));
                            var iniDroid = new IniWriter(zip);
                            returnResult.Add(Serialize_WZ_DroidsINI(iniDroid, Args.Multiplayer.PlayerCount));
                            iniDroid.Flush();

                            zip.PutNextEntry(string.Format("{0}/labels.ini", path));
                            var iniLabels = new IniWriter(zip);
                            returnResult.Add(Serialize_WZ_LabelsINI(iniLabels, Args.Multiplayer.PlayerCount));
                            iniLabels.Flush();

                            zip.PutNextEntry(string.Format("{0}/feature.ini", path));
                            var iniFeature = new IniWriter(zip);
                            returnResult.Add(Serialize_WZ_FeaturesINI(iniFeature));
                            iniFeature.Flush();

                            zip.PutNextEntry(string.Format("{0}/game.map", path));
                            returnResult.Add(Serialize_WZ_Map(zip));

                            zip.PutNextEntry(string.Format("{0}/ttypes.ttp", path));
                            var ttpSaver = new TTP.TTP(map);
                            returnResult.Add(ttpSaver.Save(zip));
                        }
                    }
                    catch ( Exception ex )
                    {
                        Debugger.Break();
                        returnResult.ProblemAdd(ex.Message);
                        logger.ErrorException("Got an exception", ex);
                        return returnResult;
                    }

                    return returnResult;
                }
                if ( Args.CompileType == sWrite_WZ_Args.enumCompileType.Campaign )
                {
                    var CampDirectory = PathUtil.EndWithPathSeperator(Args.Path);

                    if ( !Directory.Exists(CampDirectory) )
                    {
                        returnResult.ProblemAdd(string.Format("Directory {0} does not exist.", CampDirectory));
                        return returnResult;
                    }

                    var filePath = string.Format("{0}{1}.gam", CampDirectory, Args.MapName);
                    using ( var file = File.Open(filePath, FileMode.Open | FileMode.CreateNew) )
                    {
                        returnResult.Add(Serialize_WZ_Gam(file, Args.Campaign.GAMType,
                            Args.CompileType, Args.ScrollMin, Args.ScrollMax));
                    }

                    CampDirectory += Args.MapName + Convert.ToString(App.PlatformPathSeparator);
                    try
                    {
                        Directory.CreateDirectory(CampDirectory);
                    }
                    catch ( Exception ex )
                    {
                        returnResult.ProblemAdd(string.Format("Unable to create directory {0}", CampDirectory));
                        logger.ErrorException("Got an exception", ex);
                        return returnResult;
                    }

                    filePath = CampDirectory + "droid.ini";
                    using ( var file = File.Open(filePath, FileMode.Open | FileMode.CreateNew) )
                    {
                        var iniDroid = new IniWriter(file);
                        returnResult.Add(Serialize_WZ_DroidsINI(iniDroid, -1));
                        iniDroid.Flush();
                    }

                    filePath = CampDirectory + "feature.ini";
                    using ( var file = File.Open(filePath, FileMode.Open | FileMode.CreateNew) )
                    {
                        var iniFeatures = new IniWriter(file);
                        returnResult.Add(Serialize_WZ_FeaturesINI(iniFeatures));
                        iniFeatures.Flush();
                    }

                    filePath = CampDirectory + "game.map";
                    using ( var file = File.Open(filePath, FileMode.Open | FileMode.CreateNew) )
                    {
                        returnResult.Add(Serialize_WZ_Map(file));
                    }

                    filePath = CampDirectory + "struct.ini";
                    using ( var file = File.Open(filePath, FileMode.Open | FileMode.CreateNew) )
                    {
                        var iniStruct = new IniWriter(file);
                        returnResult.Add(Serialize_WZ_StructuresINI(iniStruct, -1));
                        iniStruct.Flush();
                    }

                    filePath = CampDirectory + "ttypes.ttp";
                    var ttpSaver = new TTP.TTP(map);
                    returnResult.Add(ttpSaver.Save(filePath, false));

                    filePath = CampDirectory + "labels.ini";
                    using ( var file = File.Open(filePath, FileMode.Open | FileMode.CreateNew) )
                    {
                        var iniLabels = new IniWriter(file);
                        returnResult.Add(Serialize_WZ_LabelsINI(iniLabels, 0));
                        iniLabels.Flush();
                    }
                }
            }
            catch ( Exception ex )
            {
                Debugger.Break();
                returnResult.ProblemAdd(ex.Message);
                logger.ErrorException("Got an exception", ex);
                return returnResult;
            }

            return returnResult;
        }
Esempio n. 15
0
        private clsResult Serialize_WZ_LEV(Stream stream, int playercount, string authorname, string license, string mapName)
        {
            var returnResult = new clsResult("Serializing .lev", false);
            logger.Info("Serializing .lev");

            var fileLEV = new StreamWriter(stream, App.UTF8Encoding);

            var playersText = playercount.ToString();
            var playersPrefix = playersText + "c-";
            var fog = "";
            var tilesetNum = "";
            var endChar = "\n";

            if ( map.Tileset == App.Tileset_Arizona )
            {
                fog = "fog1.wrf";
                tilesetNum = "1";
            }
            else if ( map.Tileset == App.Tileset_Urban )
            {
                fog = "fog2.wrf";
                tilesetNum = "2";
            }
            else if ( map.Tileset == App.Tileset_Rockies )
            {
                fog = "fog3.wrf";
                tilesetNum = "3";
            }
            else
            {
                returnResult.ProblemAdd("Map must have a tileset, or unknown tileset selected.");
                return returnResult;
            }

            fileLEV.Write("// Made with {0} {1} {2}{3}", Constants.ProgramName, Constants.ProgramVersionNumber, Constants.ProgramPlatform, Convert.ToString(endChar));
            var DateNow = DateTime.Now;
            fileLEV.Write("// Date: {0}/{1}/{2} {3}:{4}:{5}{6}", DateNow.Year, App.MinDigits(DateNow.Month, 2), App.MinDigits(DateNow.Day, 2),
                App.MinDigits(DateNow.Hour, 2), App.MinDigits(DateNow.Minute, 2), App.MinDigits(DateNow.Second, 2), endChar);
            fileLEV.Write("// Author: {0}{1}", authorname, endChar);
            fileLEV.Write("// License: {0}{1}", license, endChar);
            fileLEV.Write(endChar);
            fileLEV.Write("level   {0}-T1{1}", mapName, endChar);
            fileLEV.Write("players {0}{1}", playersText, endChar);
            fileLEV.Write("type    14{0}", endChar);
            fileLEV.Write("dataset MULTI_CAM_{0}{1}", tilesetNum, endChar);
            fileLEV.Write("game    \"multiplay/maps/{0}{1}.gam\"{2}", playersPrefix, mapName, endChar);
            fileLEV.Write("data    \"wrf/multi/skirmish{0}.wrf\"{1}", playersText, endChar);
            fileLEV.Write("data    \"wrf/multi/{0}\"{1}", fog, endChar);
            fileLEV.Write(endChar);
            fileLEV.Write("level   {0}-T2{1}", mapName, endChar);
            fileLEV.Write("players {0}{1}", playersText, endChar);
            fileLEV.Write("type    18{0}", endChar);
            fileLEV.Write("dataset MULTI_T2_C{0}{1}", tilesetNum, endChar);
            fileLEV.Write("game    \"multiplay/maps/{0}{1}.gam\"{2}", playersPrefix, mapName, endChar);
            fileLEV.Write("data    \"wrf/multi/t2-skirmish{0}.wrf\"{1}", playersText, endChar);
            fileLEV.Write("data    \"wrf/multi/{0}\"{1}", fog, endChar);
            fileLEV.Write(endChar);
            fileLEV.Write("level   {0}-T3{1}", mapName, endChar);
            fileLEV.Write("players {0}{1}", playersText, endChar);
            fileLEV.Write("type    19{0}", endChar);
            fileLEV.Write("dataset MULTI_T3_C{0}{1}", tilesetNum, endChar);
            fileLEV.Write("game    \"multiplay/maps/{0}{1}.gam\"{2}", playersPrefix, mapName, endChar);
            fileLEV.Write("data    \"wrf/multi/t3-skirmish{0}.wrf\"{1}", playersText, endChar);
            fileLEV.Write("data    \"wrf/multi/{0}\"{1}", fog, endChar);
            fileLEV.Flush();

            return returnResult;
        }
Esempio n. 16
0
        protected clsResult read_INI_Structures(string iniText, List<IniStructure> resultData)
        {
            var resultObject = new clsResult("Reading struct.ini.", false);
            logger.Info("Reading struct.ini");

            try
            {
                var iniSections = IniReader.ReadString(iniText);
                foreach ( var iniSection in iniSections )
                {
                    var structure = new IniStructure();
                    structure.WallType = -1;
                    structure.HealthPercent = -1;
                    var invalid = false;
                    foreach ( var iniToken in iniSection.Data )
                    {
                        if ( invalid )
                        {
                            break;
                        }

                        try
                        {
                            switch ( iniToken.Name )
                            {
                                case "id":
                                    structure.ID = uint.Parse(iniToken.Data);
                                    break;

                                case "name":
                                    structure.Code = iniToken.Data;
                                    break;

                                case "startpos":
                                    var tmpStartPos = int.Parse(iniToken.Data);
                                    if ( tmpStartPos < 0 | tmpStartPos >= Constants.PlayerCountMax )
                                    {
                                        resultObject.WarningAdd(string.Format("#{0} invalid startpos {1}", iniSection.Name, tmpStartPos), false);
                                        logger.Warn("#{0} invalid startpos {1}", iniSection.Name, tmpStartPos);
                                        invalid = true;
                                        continue;
                                    }
                                    structure.UnitGroup = map.UnitGroups[tmpStartPos];
                                    break;

                                case "player":
                                    if ( iniToken.Data.ToLower() == "scavenger" )
                                    {
                                        structure.UnitGroup = map.ScavengerUnitGroup;
                                    }
                                    else
                                    {
                                        resultObject.WarningAdd(string.Format("#{0} invalid player: \"{1}\"", iniToken.Name, iniToken.Data), false);
                                        logger.Warn("#{0} invalid player \"{1}\"", iniToken.Name, iniToken.Data);
                                        invalid = true;
                                    }
                                    break;

                                case "position":
                                    structure.Pos = XYZInt.FromString(iniToken.Data);
                                    break;

                                case "rotation":
                                    structure.Rotation = Rotation.FromString(iniToken.Data);
                                    break;

                                case "modules":
                                    structure.ModuleCount = int.Parse(iniToken.Data);
                                    break;

                                case "health":
                                    structure.HealthPercent = IniReader.ReadHealthPercent(iniToken.Data);
                                    if ( structure.HealthPercent < 0 || structure.HealthPercent > 100 )
                                    {
                                        resultObject.WarningAdd(string.Format("#{0} invalid health: \"{1}\"", iniSection.Name, structure.HealthPercent), false);
                                        invalid = true;
                                    }
                                    break;

                                case "wall/type":
                                    structure.WallType = int.Parse(iniToken.Data);
                                    if ( structure.WallType < 0 )
                                    {
                                        resultObject.WarningAdd(string.Format("#{0} invalid wall/type: \"{1}\"", iniSection.Name, structure.WallType), false);
                                        invalid = true;
                                    }
                                    break;

                                default:
                                    resultObject.WarningAdd(string.Format("Found an invalid key: {0} = {1}", iniToken.Name, iniToken.Data), false);
                                    logger.Warn("Found an invalid key: {0} = {1}", iniToken.Name, iniToken.Data);
                                    break;
                            }
                        }
                        catch ( Exception ex )
                        {
                            Debugger.Break();
                            resultObject.WarningAdd(
                                string.Format("#{0} invalid {2}: \"{3}\", got exception: {2}", iniSection.Name, iniToken.Name, iniToken.Data, ex.Message), false);
                            logger.WarnException(string.Format("#{0} invalid {2} \"{1}\"", iniSection.Name, iniToken.Name, iniToken.Data), ex);
                            invalid = true;
                        }
                    }

                    if ( !invalid )
                    {
                        resultData.Add(structure);
                    }
                }
            }
            catch ( Exception ex )
            {
                Debugger.Break();
                logger.ErrorException("Got exception while reading droid.ini", ex);
                resultObject.ProblemAdd(string.Format("Got exception: {0}", ex.Message), false);
                return resultObject;
            }

            return resultObject;
        }
Esempio n. 17
0
        protected clsResult read_INI_Labels(string iniText)
        {
            var resultObject = new clsResult("Reading labels", false);
            logger.Info("Reading labels.");

            var typeNum = 0;
            var NewPosition = default(clsScriptPosition);
            var NewArea = default(clsScriptArea);
            var nameText = "";
            var strLabel = "";
            var strPosA = "";
            var strPosB = "";
            var idText = "";
            UInt32 idNum = 0;
            XYInt xyIntA = null;
            XYInt xyIntB = null;

            var failedCount = 0;
            var modifiedCount = 0;

            try
            {
                var iniSections = IniReader.ReadString(iniText);
                foreach ( var iniSection in iniSections )
                {
                    var idx = iniSection.Name.IndexOf('_');
                    if ( idx > 0 )
                    {
                        nameText = iniSection.Name.Substring(0, idx);
                    }
                    else
                    {
                        nameText = iniSection.Name;
                    }
                    switch ( nameText )
                    {
                        case "position":
                            typeNum = 0;
                            break;
                        case "area":
                            typeNum = 1;
                            break;
                        case "object":
                            typeNum = 2;
                            break;
                        default:
                            typeNum = int.MaxValue;
                            failedCount++;
                            continue;
                    }

                    // Raised an exception if nothing was found
                    try
                    {
                        strLabel = iniSection.Data.Where(d => d.Name == "label").First().Data;
                    }
                    catch ( Exception ex )
                    {
                        resultObject.WarningAdd(string.Format("Failed to parse \"label\", error was: {0}", ex.Message));
                        logger.WarnException("Failed to parse \"label\", error was", ex);
                        failedCount++;
                        continue;
                    }
                    strLabel = strLabel.Replace("\"", "");

                    switch ( typeNum )
                    {
                        case 0: //position
                            strPosA = iniSection.Data.Where(d => d.Name == "pos").First().Data;
                            if ( strPosA == null )
                            {
                                failedCount++;
                                continue;
                            }
                            try
                            {
                                xyIntA = XYInt.FromString(strPosA);
                                NewPosition = new clsScriptPosition(map);
                                NewPosition.PosX = xyIntA.X;
                                NewPosition.PosY = xyIntA.Y;
                                NewPosition.SetLabel(strLabel);
                                if ( NewPosition.Label != strLabel ||
                                     NewPosition.PosX != xyIntA.X || NewPosition.PosY != xyIntA.Y )
                                {
                                    modifiedCount++;
                                }
                            }
                            catch ( Exception ex )
                            {
                                resultObject.WarningAdd(string.Format("Failed to parse \"pos\", error was: {0}", ex.Message));
                                logger.WarnException("Failed to parse \"pos\", error was", ex);
                                failedCount++;
                            }
                            break;
                        case 1: //area
                            try
                            {
                                strPosA = iniSection.Data.Where(d => d.Name == "pos1").First().Data;
                                strPosB = iniSection.Data.Where(d => d.Name == "pos2").First().Data;

                                xyIntA = XYInt.FromString(strPosA);
                                xyIntB = XYInt.FromString(strPosA);
                                NewArea = new clsScriptArea(map);
                                NewArea.SetPositions(xyIntA, xyIntB);
                                NewArea.SetLabel(strLabel);
                                if ( NewArea.Label != strLabel || NewArea.PosAX != xyIntA.X | NewArea.PosAY != xyIntA.Y
                                     | NewArea.PosBX != xyIntB.X | NewArea.PosBY != xyIntB.Y )
                                {
                                    modifiedCount++;
                                }
                            }
                            catch ( Exception ex )
                            {
                                Debugger.Break();
                                resultObject.WarningAdd(string.Format("Failed to parse \"pos1\" or \"pos2\", error was: {0}", ex.Message));
                                logger.WarnException("Failed to parse \"pos1\" or \"pos2\".", ex);
                                failedCount++;
                            }
                            break;
                        case 2: //object
                            idText = iniSection.Data.Where(d => d.Name == "id").First().Data;
                            if ( IOUtil.InvariantParse(idText, ref idNum) )
                            {
                                var Unit = map.IDUsage(idNum);
                                if ( Unit != null )
                                {
                                    if ( !Unit.SetLabel(strLabel).Success )
                                    {
                                        failedCount++;
                                    }
                                }
                                else
                                {
                                    failedCount++;
                                }
                            }
                            break;
                        default:
                            resultObject.WarningAdd("Error! Bad type number for script label.");
                            break;
                    }
                }
            }
            catch ( Exception ex )
            {
                Debugger.Break();
                logger.ErrorException("Got exception while reading labels.ini", ex);
                resultObject.ProblemAdd(string.Format("Got exception: {0}", ex.Message), false);
                return resultObject;
            }

            if ( failedCount > 0 )
            {
                resultObject.WarningAdd(string.Format("Unable to translate {0} script labels.", failedCount));
            }
            if ( modifiedCount > 0 )
            {
                resultObject.WarningAdd(string.Format("{0} script labels had invalid values and were modified.", modifiedCount));
            }

            return resultObject;
        }
Esempio n. 18
0
        private clsResult Read_FME(BinaryReader File)
        {
            clsResult ReturnResult = new clsResult("Reading FME");

            UInt32 Version = 0;

            clsInterfaceOptions ResultInfo = new clsInterfaceOptions();

            clsUnitAdd UnitAdd = new clsUnitAdd();
            UnitAdd.Map = this;

            try
            {
                Version = File.ReadUInt32();

                if ( Version <= 4U )
                {
                    ReturnResult.ProblemAdd("Version " + Convert.ToString(Version) + " is not supported.");
                    return ReturnResult;
                }
                else if ( Version == 5U || Version == 6U || Version == 7U )
                {
                    byte byteTemp = 0;

                    //tileset
                    byteTemp = File.ReadByte();
                    if ( byteTemp == 0 )
                    {
                        Tileset = null;
                    }
                    else if ( byteTemp == 1 )
                    {
                        Tileset = App.Tileset_Arizona;
                    }
                    else if ( byteTemp == 2 )
                    {
                        Tileset = App.Tileset_Urban;
                    }
                    else if ( byteTemp == 3 )
                    {
                        Tileset = App.Tileset_Rockies;
                    }
                    else
                    {
                        ReturnResult.WarningAdd("Tileset value out of range.");
                        Tileset = null;
                    }

                    SetPainterToDefaults(); //depends on tileset. must be called before loading the terrains.

                    UInt16 MapWidth = 0;
                    UInt16 MapHeight = 0;

                    MapWidth = File.ReadUInt16();
                    MapHeight = File.ReadUInt16();

                    if ( MapWidth < 1U || MapHeight < 1U || MapWidth > Constants.MapMaxSize || MapHeight > Constants.MapMaxSize )
                    {
                        ReturnResult.ProblemAdd("Map size is invalid.");
                        return ReturnResult;
                    }

                    TerrainBlank(new sXY_int(MapWidth, MapHeight));
                    TileType_Reset();

                    int X = 0;
                    int Y = 0;
                    int A = 0;
                    int B = 0;
                    int intTemp = 0;
                    int WarningCount = 0;

                    WarningCount = 0;
                    for ( Y = 0; Y <= Terrain.TileSize.Y; Y++ )
                    {
                        for ( X = 0; X <= Terrain.TileSize.X; X++ )
                        {
                            Terrain.Vertices[X, Y].Height = File.ReadByte();
                            byteTemp = File.ReadByte();
                            intTemp = (byteTemp) - 1;
                            if ( intTemp < 0 )
                            {
                                Terrain.Vertices[X, Y].Terrain = null;
                            }
                            else if ( intTemp >= Painter.TerrainCount )
                            {
                                WarningCount++;
                                Terrain.Vertices[X, Y].Terrain = null;
                            }
                            else
                            {
                                Terrain.Vertices[X, Y].Terrain = Painter.Terrains[intTemp];
                            }
                        }
                    }
                    if ( WarningCount > 0 )
                    {
                        ReturnResult.WarningAdd(WarningCount + " painted ground vertices were out of range.");
                    }
                    WarningCount = 0;
                    for ( Y = 0; Y <= Terrain.TileSize.Y - 1; Y++ )
                    {
                        for ( X = 0; X <= Terrain.TileSize.X - 1; X++ )
                        {
                            byteTemp = File.ReadByte();
                            Terrain.Tiles[X, Y].Texture.TextureNum = (byteTemp) - 1;

                            byteTemp = File.ReadByte();

                            intTemp = 128;
                            A = (int)(Conversion.Int(byteTemp / intTemp));
                            byteTemp -= (byte)(A * intTemp);
                            Terrain.Tiles[X, Y].Terrain_IsCliff = A == 1;

                            intTemp = 64;
                            A = (int)(Conversion.Int(byteTemp / intTemp));
                            byteTemp -= (byte)(A * intTemp);
                            Terrain.Tiles[X, Y].Texture.Orientation.SwitchedAxes = A == 1;

                            intTemp = 32;
                            A = (int)(Conversion.Int(byteTemp / intTemp));
                            byteTemp -= (byte)(A * intTemp);
                            Terrain.Tiles[X, Y].Texture.Orientation.ResultXFlip = A == 1;

                            intTemp = 16;
                            A = (int)(Conversion.Int(byteTemp / intTemp));
                            byteTemp -= (byte)(A * intTemp);
                            Terrain.Tiles[X, Y].Texture.Orientation.ResultYFlip = A == 1;

                            intTemp = 4;
                            A = (int)(Conversion.Int(byteTemp / intTemp));
                            byteTemp -= (byte)(A * intTemp);
                            Terrain.Tiles[X, Y].Tri = A == 1;

                            intTemp = 2;
                            A = (int)(Conversion.Int(byteTemp / intTemp));
                            byteTemp -= (byte)(A * intTemp);
                            if ( Terrain.Tiles[X, Y].Tri )
                            {
                                Terrain.Tiles[X, Y].TriTopLeftIsCliff = A == 1;
                            }
                            else
                            {
                                Terrain.Tiles[X, Y].TriBottomLeftIsCliff = A == 1;
                            }

                            intTemp = 1;
                            A = (int)(Conversion.Int(byteTemp / intTemp));
                            byteTemp -= (byte)(A * intTemp);
                            if ( Terrain.Tiles[X, Y].Tri )
                            {
                                Terrain.Tiles[X, Y].TriBottomRightIsCliff = A == 1;
                            }
                            else
                            {
                                Terrain.Tiles[X, Y].TriTopRightIsCliff = A == 1;
                            }

                            //attributes2
                            byteTemp = File.ReadByte();

                            if ( byteTemp == ((byte)0) )
                            {
                                Terrain.Tiles[X, Y].DownSide = TileUtil.None;
                            }
                            else if ( byteTemp == ((byte)1) )
                            {
                                Terrain.Tiles[X, Y].DownSide = TileUtil.Top;
                            }
                            else if ( byteTemp == ((byte)2) )
                            {
                                Terrain.Tiles[X, Y].DownSide = TileUtil.Left;
                            }
                            else if ( byteTemp == ((byte)3) )
                            {
                                Terrain.Tiles[X, Y].DownSide = TileUtil.Right;
                            }
                            else if ( byteTemp == ((byte)4) )
                            {
                                Terrain.Tiles[X, Y].DownSide = TileUtil.Bottom;
                            }
                            else
                            {
                                WarningCount++;
                            }
                        }
                    }
                    if ( WarningCount > 0 )
                    {
                        ReturnResult.WarningAdd(WarningCount + " tile cliff down-sides were out of range.");
                    }
                    WarningCount = 0;
                    for ( Y = 0; Y <= Terrain.TileSize.Y; Y++ )
                    {
                        for ( X = 0; X <= Terrain.TileSize.X - 1; X++ )
                        {
                            byteTemp = File.ReadByte();
                            intTemp = (byteTemp) - 1;
                            if ( intTemp < 0 )
                            {
                                Terrain.SideH[X, Y].Road = null;
                            }
                            else if ( intTemp >= Painter.RoadCount )
                            {
                                WarningCount++;
                                Terrain.SideH[X, Y].Road = null;
                            }
                            else
                            {
                                Terrain.SideH[X, Y].Road = Painter.Roads[intTemp];
                            }
                        }
                    }
                    for ( Y = 0; Y <= Terrain.TileSize.Y - 1; Y++ )
                    {
                        for ( X = 0; X <= Terrain.TileSize.X; X++ )
                        {
                            byteTemp = File.ReadByte();
                            intTemp = (byteTemp) - 1;
                            if ( intTemp < 0 )
                            {
                                Terrain.SideV[X, Y].Road = null;
                            }
                            else if ( intTemp >= Painter.RoadCount )
                            {
                                WarningCount++;
                                Terrain.SideV[X, Y].Road = null;
                            }
                            else
                            {
                                Terrain.SideV[X, Y].Road = Painter.Roads[intTemp];
                            }
                        }
                    }
                    if ( WarningCount > 0 )
                    {
                        ReturnResult.WarningAdd(WarningCount + " roads were out of range.");
                    }
                    UInt32 TempUnitCount = 0;
                    TempUnitCount = File.ReadUInt32();
                    sFMEUnit[] TempUnit = new sFMEUnit[(Convert.ToInt32(TempUnitCount))];
                    for ( A = 0; A <= (Convert.ToInt32(TempUnitCount)) - 1; A++ )
                    {
                        TempUnit[A].Code = new string(File.ReadChars(40));
                        B = Strings.InStr(TempUnit[A].Code, Convert.ToString('\0'), (CompareMethod)0);
                        if ( B > 0 )
                        {
                            TempUnit[A].Code = Strings.Left(TempUnit[A].Code, B - 1);
                        }
                        TempUnit[A].LNDType = File.ReadByte();
                        TempUnit[A].ID = File.ReadUInt32();
                        if ( Version == 6U )
                        {
                            TempUnit[A].SavePriority = File.ReadInt32();
                        }
                        TempUnit[A].X = File.ReadUInt32();
                        TempUnit[A].Z = File.ReadUInt32();
                        TempUnit[A].Y = File.ReadUInt32();
                        TempUnit[A].Rotation = File.ReadUInt16();
                        TempUnit[A].Name = IOUtil.ReadOldText(File);
                        TempUnit[A].Player = File.ReadByte();
                    }

                    clsUnit NewUnit = default(clsUnit);
                    clsUnitType UnitType = null;
                    UInt32 AvailableID = 0;

                    AvailableID = 1U;
                    for ( A = 0; A <= (Convert.ToInt32(TempUnitCount)) - 1; A++ )
                    {
                        if ( TempUnit[A].ID >= AvailableID )
                        {
                            AvailableID = TempUnit[A].ID + 1U;
                        }
                    }
                    WarningCount = 0;
                    for ( A = 0; A <= (Convert.ToInt32(TempUnitCount)) - 1; A++ )
                    {
                        if ( TempUnit[A].LNDType == ((byte)0) )
                        {
                            UnitType = App.ObjectData.FindOrCreateUnitType(TempUnit[A].Code, clsUnitType.enumType.Feature, -1);
                        }
                        else if ( TempUnit[A].LNDType == ((byte)1) )
                        {
                            UnitType = App.ObjectData.FindOrCreateUnitType(TempUnit[A].Code, clsUnitType.enumType.PlayerStructure, -1);
                        }
                        else if ( TempUnit[A].LNDType == ((byte)2) )
                        {
                            UnitType = App.ObjectData.FindOrCreateUnitType(Convert.ToString(TempUnit[A].Code), clsUnitType.enumType.PlayerDroid, -1);
                        }
                        else
                        {
                            UnitType = null;
                        }
                        if ( UnitType != null )
                        {
                            NewUnit = new clsUnit();
                            NewUnit.Type = UnitType;
                            NewUnit.ID = TempUnit[A].ID;
                            NewUnit.SavePriority = TempUnit[A].SavePriority;
                            //NewUnit.Name = TempUnit(A).Name
                            if ( TempUnit[A].Player >= Constants.PlayerCountMax )
                            {
                                NewUnit.UnitGroup = ScavengerUnitGroup;
                            }
                            else
                            {
                                NewUnit.UnitGroup = UnitGroups[TempUnit[A].Player];
                            }
                            NewUnit.Pos.Horizontal.X = Convert.ToInt32(TempUnit[A].X);
                            //NewUnit.Pos.Altitude = TempUnit(A).Y
                            NewUnit.Pos.Horizontal.Y = Convert.ToInt32(TempUnit[A].Z);
                            NewUnit.Rotation = Math.Min(Convert.ToInt32(TempUnit[A].Rotation), 359);
                            if ( TempUnit[A].ID == 0U )
                            {
                                TempUnit[A].ID = AvailableID;
                                App.ZeroIDWarning(NewUnit, TempUnit[A].ID, ReturnResult);
                            }
                            UnitAdd.ID = TempUnit[A].ID;
                            UnitAdd.NewUnit = NewUnit;
                            UnitAdd.Perform();
                            App.ErrorIDChange(TempUnit[A].ID, NewUnit, "Read_FMEv5+");
                            if ( AvailableID == TempUnit[A].ID )
                            {
                                AvailableID = NewUnit.ID + 1U;
                            }
                        }
                        else
                        {
                            WarningCount++;
                        }
                    }
                    if ( WarningCount > 0 )
                    {
                        ReturnResult.WarningAdd(WarningCount + " types of units were invalid. That many units were ignored.");
                    }

                    UInt32 NewGatewayCount = 0;
                    sXY_int NewGateStart = new sXY_int();
                    sXY_int NewGateFinish = new sXY_int();

                    NewGatewayCount = File.ReadUInt32();
                    WarningCount = 0;
                    for ( A = 0; A <= (Convert.ToInt32(NewGatewayCount)) - 1; A++ )
                    {
                        NewGateStart.X = File.ReadUInt16();
                        NewGateStart.Y = File.ReadUInt16();
                        NewGateFinish.X = File.ReadUInt16();
                        NewGateFinish.Y = File.ReadUInt16();
                        if ( GatewayCreate(NewGateStart, NewGateFinish) == null )
                        {
                            WarningCount++;
                        }
                    }
                    if ( WarningCount > 0 )
                    {
                        ReturnResult.WarningAdd(WarningCount + " gateways were invalid.");
                    }

                    if ( Tileset != null )
                    {
                        for ( A = 0; A <= Tileset.TileCount - 1; A++ )
                        {
                            byteTemp = File.ReadByte();
                            Tile_TypeNum[A] = byteTemp;
                        }
                    }

                    //scroll limits
                    ResultInfo.ScrollMin.X = File.ReadInt32();
                    ResultInfo.ScrollMin.Y = File.ReadInt32();
                    ResultInfo.ScrollMax.X = File.ReadUInt32();
                    ResultInfo.ScrollMax.Y = File.ReadUInt32();

                    //other compile info

                    string strTemp = null;

                    ResultInfo.CompileName = IOUtil.ReadOldText(File);
                    byteTemp = File.ReadByte();
                    if ( byteTemp == ((byte)0) )
                    {
                        //no compile type
                    }
                    else if ( byteTemp == ((byte)1) )
                    {
                        //compile multi
                    }
                    else if ( byteTemp == ((byte)2) )
                    {
                        //compile campaign
                    }
                    else
                    {
                        //error
                    }
                    ResultInfo.CompileMultiPlayers = IOUtil.ReadOldText(File);
                    byteTemp = File.ReadByte();
                    if ( byteTemp == ((byte)0) )
                    {
                        ResultInfo.CompileMultiXPlayers = false;
                    }
                    else if ( byteTemp == ((byte)1) )
                    {
                        ResultInfo.CompileMultiXPlayers = true;
                    }
                    else
                    {
                        ReturnResult.WarningAdd("Compile player format out of range.");
                    }
                    ResultInfo.CompileMultiAuthor = IOUtil.ReadOldText(File);
                    ResultInfo.CompileMultiLicense = IOUtil.ReadOldText(File);
                    strTemp = IOUtil.ReadOldText(File); //game time
                    ResultInfo.CampaignGameType = File.ReadInt32();
                    if ( ResultInfo.CampaignGameType < -1 | ResultInfo.CampaignGameType >= Constants.GameTypeCount )
                    {
                        ReturnResult.WarningAdd("Compile campaign type out of range.");
                        ResultInfo.CampaignGameType = -1;
                    }

                    if ( File.PeekChar() >= 0 )
                    {
                        ReturnResult.WarningAdd("There were unread bytes at the end of the file.");
                    }
                }
                else
                {
                    ReturnResult.ProblemAdd("File version number not recognised.");
                }

                InterfaceOptions = ResultInfo;
            }
            catch ( Exception ex )
            {
                ReturnResult.ProblemAdd("Read error: " + ex.Message);
            }

            return ReturnResult;
        }
Esempio n. 19
0
        public clsResult INIWrite(IniWriter file)
        {
            clsResult returnResult = new clsResult("Writing options to INI");

            foreach ( OptionInterface item in _Options.Options )
            {
                if ( get_Changes(item) == null )
                {
                    continue;
                }
                object optionValue = get_Value(item);
                string valueText = null;
                if ( item is Option<KeyboardControl> )
                {
                    KeyboardControl control = (KeyboardControl)optionValue;
                    valueText = "";
                    for ( int i = 0; i <= control.Keys.GetUpperBound(0); i++ )
                    {
                        Keys key = Keys.A;
                        valueText += IOUtil.InvariantToString((Int32)key);
                        if ( i < control.Keys.GetUpperBound(0) )
                        {
                            valueText += ",";
                        }
                    }
                    if ( control.UnlessKeys.GetUpperBound(0) >= 0 )
                    {
                        valueText += "unless ";
                        for ( int i = 0; i <= control.UnlessKeys.GetUpperBound(0); i++ )
                        {
                            Keys key = Keys.A;
                            valueText += IOUtil.InvariantToString((Int32)key);
                            if ( i < control.UnlessKeys.GetUpperBound(0) )
                            {
                                valueText += ",";
                            }
                        }
                    }
                }
                else if ( item is Option<SimpleList<string>> )
                {
                    SimpleList<string> list = (SimpleList<string>)optionValue;
                    for ( int i = 0; i <= list.Count - 1; i++ )
                    {
                        file.AppendProperty(item.SaveKey, list[i]);
                    }
                }
                else if ( item is Option<clsRGB_sng> )
                {
                    valueText = ((clsRGB_sng)optionValue).GetINIOutput();
                }
                else if ( item is Option<clsRGBA_sng> )
                {
                    valueText = ((clsRGBA_sng)optionValue).GetINIOutput();
                }
                else if ( item is Option<FontFamily> )
                {
                    valueText = ((FontFamily)optionValue).Name;
                }
                else if ( item is Option<bool> )
                {
                    valueText = IOUtil.InvariantToString(Convert.ToBoolean(optionValue));
                }
                else if ( item is Option<byte> )
                {
                    valueText = IOUtil.InvariantToString(Convert.ToByte(optionValue));
                }
                else if ( item is Option<short> )
                {
                    valueText = IOUtil.InvariantToString((int)(short)optionValue);
                }
                else if ( item is Option<int> )
                {
                    valueText = IOUtil.InvariantToString(Convert.ToInt32(optionValue));
                }
                else if ( item is Option<UInt32> )
                {
                    valueText = IOUtil.InvariantToString(Convert.ToUInt32(optionValue));
                }
                else if ( item is Option<Single> )
                {
                    valueText = IOUtil.InvariantToString(Convert.ToSingle(Convert.ToSingle(optionValue)));
                }
                else if ( item is Option<double> )
                {
                    valueText = IOUtil.InvariantToString(Convert.ToDouble(optionValue));
                }
                else if ( item is Option<string> )
                {
                    valueText = Convert.ToString(optionValue);
                }
                else
                {
                    returnResult.ProblemAdd("Value for option " + Convert.ToString(ControlChars.Quote) + item.SaveKey +
                                            Convert.ToString(ControlChars.Quote) + " could not be written because it is of type " +
                                            optionValue.GetType().FullName);
                }
                if ( valueText != null )
                {
                    file.AppendProperty(item.SaveKey, valueText);
                }
            }

            return returnResult;
        }
Esempio n. 20
0
        // Compress is ignored.
        public clsResult Save(string path, bool overwrite, bool compress = false)
        {
            var returnResult =
                new clsResult("Writing LND to \"{0}\"".Format2(path), false);

            logger.Info("Writing LND to \"{0}\"".Format2(path));

            if ( System.IO.File.Exists(path) )
            {
                if ( overwrite )
                {
                    System.IO.File.Delete(path);
                }
                else
                {
                    returnResult.ProblemAdd("The selected file already exists.");
                    return returnResult;
                }
            }

            StreamWriter File = null;

            try
            {
                var text = "";
                var endChar = '\n';
                var quote = '\"';;
                var a = 0;
                var x = 0;
                var y = 0;
                byte flip = 0;
                var b = 0;
                var vf = 0;
                var tf = 0;
                var c = 0;
                byte rotation = 0;
                var flipX = default(bool);

                File = new StreamWriter(new FileStream(path, FileMode.CreateNew), App.UTF8Encoding);

                if ( map.Tileset == App.Tileset_Arizona )
                {
                    text = "DataSet WarzoneDataC1.eds" + Convert.ToString(endChar);
                }
                else if ( map.Tileset == App.Tileset_Urban )
                {
                    text = "DataSet WarzoneDataC2.eds" + Convert.ToString(endChar);
                }
                else if ( map.Tileset == App.Tileset_Rockies )
                {
                    text = "DataSet WarzoneDataC3.eds" + Convert.ToString(endChar);
                }
                else
                {
                    text = "DataSet " + Convert.ToString(endChar);
                }
                File.Write(text);
                text = "GrdLand {" + Convert.ToString(endChar);
                File.Write(text);
                text = "    Version 4" + Convert.ToString(endChar);
                File.Write(text);
                text = "    3DPosition 0.000000 3072.000000 0.000000" + Convert.ToString(endChar);
                File.Write(text);
                text = "    3DRotation 80.000000 0.000000 0.000000" + Convert.ToString(endChar);
                File.Write(text);
                text = "    2DPosition 0 0" + Convert.ToString(endChar);
                File.Write(text);
                text = "    CustomSnap 16 16" + Convert.ToString(endChar);
                File.Write(text);
                text = "    SnapMode 0" + Convert.ToString(endChar);
                File.Write(text);
                text = "    Gravity 1" + Convert.ToString(endChar);
                File.Write(text);
                text = "    HeightScale " + map.HeightMultiplier.ToStringInvariant() + Convert.ToString(endChar);
                File.Write(text);
                text = "    MapWidth " + map.Terrain.TileSize.X.ToStringInvariant() + Convert.ToString(endChar);
                File.Write(text);
                text = "    MapHeight " + map.Terrain.TileSize.Y.ToStringInvariant() + Convert.ToString(endChar);
                File.Write(text);
                text = "    TileWidth 128" + Convert.ToString(endChar);
                File.Write(text);
                text = "    TileHeight 128" + Convert.ToString(endChar);
                File.Write(text);
                text = "    SeaLevel 0" + Convert.ToString(endChar);
                File.Write(text);
                text = "    TextureWidth 64" + Convert.ToString(endChar);
                File.Write(text);
                text = "    TextureHeight 64" + Convert.ToString(endChar);
                File.Write(text);
                text = "    NumTextures 1" + Convert.ToString(endChar);
                File.Write(text);
                text = "    Textures {" + Convert.ToString(endChar);
                File.Write(text);
                if ( map.Tileset == App.Tileset_Arizona )
                {
                    text = "        texpages\\tertilesc1.pcx" + Convert.ToString(endChar);
                }
                else if ( map.Tileset == App.Tileset_Urban )
                {
                    text = "        texpages\\tertilesc2.pcx" + Convert.ToString(endChar);
                }
                else if ( map.Tileset == App.Tileset_Rockies )
                {
                    text = "        texpages\\tertilesc3.pcx" + Convert.ToString(endChar);
                }
                else
                {
                    text = "        " + Convert.ToString(endChar);
                }
                File.Write(text);
                text = "    }" + Convert.ToString(endChar);
                File.Write(text);
                text = "    NumTiles " + (map.Terrain.TileSize.X * map.Terrain.TileSize.Y).ToStringInvariant() + Convert.ToString(endChar);
                File.Write(text);
                text = "    Tiles {" + Convert.ToString(endChar);
                File.Write(text);
                for ( y = 0; y <= map.Terrain.TileSize.Y - 1; y++ )
                {
                    for ( x = 0; x <= map.Terrain.TileSize.X - 1; x++ )
                    {
                        TileUtil.TileOrientation_To_OldOrientation(map.Terrain.Tiles[x, y].Texture.Orientation, ref rotation, ref flipX);
                        flip = 0;
                        if ( map.Terrain.Tiles[x, y].Tri )
                        {
                            flip += 2;
                        }
                        if ( flipX )
                        {
                            flip += 4;
                        }
                        flip += (byte)(rotation * 16);

                        if ( map.Terrain.Tiles[x, y].Tri )
                        {
                            vf = 1;
                        }
                        else
                        {
                            vf = 0;
                        }
                        if ( flipX )
                        {
                            tf = 1;
                        }
                        else
                        {
                            tf = 0;
                        }

                        text = "        TID " + (map.Terrain.Tiles[x, y].Texture.TextureNum + 1) + " VF " + vf.ToStringInvariant() + " TF " +
                            tf.ToStringInvariant() + " F " + ((int)flip).ToStringInvariant() + " VH " +
                                Convert.ToByte(map.Terrain.Vertices[x, y].Height).ToStringInvariant() + " " +
                                map.Terrain.Vertices[x + 1, y].Height.ToStringInvariant() + " " + Convert.ToString(map.Terrain.Vertices[x + 1, y + 1].Height) +
                                " " + Convert.ToByte(map.Terrain.Vertices[x, y + 1].Height).ToStringInvariant() + Convert.ToString(endChar);
                        File.Write(text);
                    }
                }
                text = "    }" + Convert.ToString(endChar);
                File.Write(text);
                text = "}" + Convert.ToString(endChar);
                File.Write(text);
                text = "ObjectList {" + Convert.ToString(endChar);
                File.Write(text);
                text = "    Version 3" + Convert.ToString(endChar);
                File.Write(text);
                if ( map.Tileset == App.Tileset_Arizona )
                {
                    text = "    FeatureSet WarzoneDataC1.eds" + Convert.ToString(endChar);
                }
                else if ( map.Tileset == App.Tileset_Urban )
                {
                    text = "    FeatureSet WarzoneDataC2.eds" + Convert.ToString(endChar);
                }
                else if ( map.Tileset == App.Tileset_Rockies )
                {
                    text = "    FeatureSet WarzoneDataC3.eds" + Convert.ToString(endChar);
                }
                else
                {
                    text = "    FeatureSet " + Convert.ToString(endChar);
                }
                File.Write(text);
                text = "    NumObjects " + map.Units.Count.ToStringInvariant() + Convert.ToString(endChar);
                File.Write(text);
                text = "    Objects {" + Convert.ToString(endChar);
                File.Write(text);
                var XYZ_int = new XYZInt(0, 0, 0);
                string Code = null;
                var CustomDroidCount = 0;
                foreach ( var unit in map.Units )
                {
                    switch ( unit.TypeBase.Type )
                    {
                        case UnitType.Feature:
                        b = 0;
                        break;
                        case UnitType.PlayerStructure:
                        b = 1;
                        break;
                        case UnitType.PlayerDroid:
                        if ( ((DroidDesign)unit.TypeBase).IsTemplate )
                        {
                            b = 2;
                        }
                        else
                        {
                            b = -1;
                        }
                        break;
                        default:
                        b = -1;
                        returnResult.WarningAdd("Unit type classification not accounted for.");
                        break;
                    }
                    XYZ_int = lndPos_From_MapPos(map.Units[a].Pos.Horizontal);
                    if ( b >= 0 )
                    {
                        if ( unit.TypeBase.GetCode(ref Code) )
                        {
                            text = "        " + unit.ID.ToStringInvariant() + " " + Convert.ToString(b) + " " + Convert.ToString(quote) +
                                Code + Convert.ToString(quote) + " " + unit.UnitGroup.GetLNDPlayerText() + " " + Convert.ToString(quote) + "NONAME" +
                                    Convert.ToString(quote) + " " + XYZ_int.X.ToStringInvariant() + ".00 " + XYZ_int.Y.ToStringInvariant() +
                                    ".00 " + XYZ_int.Z.ToStringInvariant() + ".00 0.00 " + unit.Rotation.ToStringInvariant() + ".00 0.00" +
                                    Convert.ToString(endChar);
                            File.Write(text);
                        }
                        else
                        {
                            returnResult.WarningAdd("Error. Code not found.");
                        }
                    }
                    else
                    {
                        CustomDroidCount++;
                    }
                }
                text = "    }" + Convert.ToString(endChar);
                File.Write(text);
                text = "}" + Convert.ToString(endChar);
                File.Write(text);
                text = "ScrollLimits {" + Convert.ToString(endChar);
                File.Write(text);
                text = "    Version 1" + Convert.ToString(endChar);
                File.Write(text);
                text = "    NumLimits 1" + Convert.ToString(endChar);
                File.Write(text);
                text = "    Limits {" + Convert.ToString(endChar);
                File.Write(text);
                text = "        " + Convert.ToString(quote) + "Entire Map" + Convert.ToString(quote) + " 0 0 0 " +
                    map.Terrain.TileSize.X.ToStringInvariant() + " " + map.Terrain.TileSize.Y.ToStringInvariant() + Convert.ToString(endChar);
                File.Write(text);
                text = "    }" + Convert.ToString(endChar);
                File.Write(text);
                text = "}" + Convert.ToString(endChar);
                File.Write(text);
                text = "Gateways {" + Convert.ToString(endChar);
                File.Write(text);
                text = "    Version 1" + Convert.ToString(endChar);
                File.Write(text);
                text = "    NumGateways " + map.Gateways.Count.ToStringInvariant() + Convert.ToString(endChar);
                File.Write(text);
                text = "    Gates {" + Convert.ToString(endChar);
                File.Write(text);
                foreach ( var gateway in map.Gateways )
                {
                    text = "        " + gateway.PosA.X.ToStringInvariant() + " " + gateway.PosA.Y.ToStringInvariant() + " " +
                        gateway.PosB.X.ToStringInvariant() + " " + gateway.PosB.Y.ToStringInvariant() + Convert.ToString(endChar);
                    File.Write(text);
                }
                text = "    }" + Convert.ToString(endChar);
                File.Write(text);
                text = "}" + Convert.ToString(endChar);
                File.Write(text);
                text = "TileTypes {" + Convert.ToString(endChar);
                File.Write(text);
                text = "    NumTiles " + Convert.ToString(map.Tileset.TileCount) + Convert.ToString(endChar);
                File.Write(text);
                text = "    Tiles {" + Convert.ToString(endChar);
                File.Write(text);
                for ( a = 0; a <= ((int)(Math.Ceiling(Convert.ToDecimal((map.Tileset.TileCount + 1) / 16.0D)))) - 1; a++ )
                    //+1 because the first number is not a tile type
                {
                    text = "        ";
                    c = a * 16 - 1; //-1 because the first number is not a tile type
                    for ( b = 0; b <= Math.Min(16, map.Tileset.TileCount - c) - 1; b++ )
                    {
                        if ( c + b < 0 )
                        {
                            text = text + "2 ";
                        }
                        else
                        {
                            text = text + map.Tile_TypeNum[c + b].ToStringInvariant() + " ";
                        }
                    }
                    text = text + Convert.ToString(endChar);
                    File.Write(text);
                }
                text = "    }" + Convert.ToString(endChar);
                File.Write(text);
                text = "}" + Convert.ToString(endChar);
                File.Write(text);
                text = "TileFlags {" + Convert.ToString(endChar);
                File.Write(text);
                text = "    NumTiles 90" + Convert.ToString(endChar);
                File.Write(text);
                text = "    Flags {" + Convert.ToString(endChar);
                File.Write(text);
                text = "        0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(endChar);
                File.Write(text);
                text = "        0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(endChar);
                File.Write(text);
                text = "        0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(endChar);
                File.Write(text);
                text = "        0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(endChar);
                File.Write(text);
                text = "        0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(endChar);
                File.Write(text);
                text = "        0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(endChar);
                File.Write(text);
                text = "    }" + Convert.ToString(endChar);
                File.Write(text);
                text = "}" + Convert.ToString(endChar);
                File.Write(text);
                text = "Brushes {" + Convert.ToString(endChar);
                File.Write(text);
                text = "    Version 2" + Convert.ToString(endChar);
                File.Write(text);
                text = "    NumEdgeBrushes 0" + Convert.ToString(endChar);
                File.Write(text);
                text = "    NumUserBrushes 0" + Convert.ToString(endChar);
                File.Write(text);
                text = "    EdgeBrushes {" + Convert.ToString(endChar);
                File.Write(text);
                text = "    }" + Convert.ToString(endChar);
                File.Write(text);
                text = "}" + Convert.ToString(endChar);
                File.Write(text);
            }
            catch ( Exception ex )
            {
                returnResult.ProblemAdd(ex.Message);
            }
            if ( File != null )
            {
                File.Close();
            }

            return returnResult;
        }
Esempio n. 21
0
        private clsResult FinishTextures()
        {
            clsResult ReturnResult = new clsResult("");

            if ( cbxMasterTexture.Checked )
            {
                switch ( cboTileset.SelectedIndex )
                {
                    case 0:
                        Generator.GenerateTileset = DefaultGenerator.Generator_TilesetArizona;
                        DefaultGenerator.TerrainStyle_Arizona.Watermap = Generator.GetWaterMap();
                        DefaultGenerator.TerrainStyle_Arizona.LevelCount = Generator.LevelCount;
                        Generator.Map.GenerateMasterTerrain(DefaultGenerator.TerrainStyle_Arizona);
                        DefaultGenerator.TerrainStyle_Arizona.Watermap = null;
                        break;
                    case 1:
                        Generator.GenerateTileset = DefaultGenerator.Generator_TilesetUrban;
                        DefaultGenerator.TerrainStyle_Urban.Watermap = Generator.GetWaterMap();
                        DefaultGenerator.TerrainStyle_Urban.LevelCount = Generator.LevelCount;
                        Generator.Map.GenerateMasterTerrain(DefaultGenerator.TerrainStyle_Urban);
                        DefaultGenerator.TerrainStyle_Urban.Watermap = null;
                        break;
                    case 2:
                        Generator.GenerateTileset = DefaultGenerator.Generator_TilesetRockies;
                        DefaultGenerator.TerrainStyle_Rockies.Watermap = Generator.GetWaterMap();
                        DefaultGenerator.TerrainStyle_Rockies.LevelCount = Generator.LevelCount;
                        Generator.Map.GenerateMasterTerrain(DefaultGenerator.TerrainStyle_Rockies);
                        DefaultGenerator.TerrainStyle_Rockies.Watermap = null;
                        break;
                    default:
                        ReturnResult.ProblemAdd("Error: bad tileset selection.");
                        btnGenerateLayout.Enabled = true;
                        return ReturnResult;
                }
                Generator.Map.TileType_Reset();
                Generator.Map.SetPainterToDefaults();
            }
            else
            {
                switch ( cboTileset.SelectedIndex )
                {
                    case 0:
                        Generator.Map.Tileset = App.Tileset_Arizona;
                        Generator.GenerateTileset = DefaultGenerator.Generator_TilesetArizona;
                        break;
                    case 1:
                        Generator.Map.Tileset = App.Tileset_Urban;
                        Generator.GenerateTileset = DefaultGenerator.Generator_TilesetUrban;
                        break;
                    case 2:
                        Generator.Map.Tileset = App.Tileset_Rockies;
                        Generator.GenerateTileset = DefaultGenerator.Generator_TilesetRockies;
                        break;
                    default:
                        ReturnResult.ProblemAdd("Error: bad tileset selection.");
                        btnGenerateLayout.Enabled = true;
                        return ReturnResult;
                }
                Generator.Map.TileType_Reset();
                Generator.Map.SetPainterToDefaults();
                double CliffAngle = Math.Atan(255.0D * Generator.Map.HeightMultiplier / (2.0D * (Generator.LevelCount - 1.0D) * App.TerrainGridSpacing)) -
                                    MathUtil.RadOf1Deg;
                clsBrush tmpBrush = new clsBrush((Math.Max(Generator.Map.Terrain.TileSize.X, Generator.Map.Terrain.TileSize.Y)) * 1.1D, clsBrush.enumShape.Square);
                clsMap.clsApplyCliff ApplyCliff = new clsMap.clsApplyCliff();
                ApplyCliff.Map = Generator.Map;
                ApplyCliff.Angle = CliffAngle;
                ApplyCliff.SetTris = true;
                clsBrush.sPosNum Alignments = new clsBrush.sPosNum();
                Alignments.Normal = new sXY_int((int)(Conversion.Int(Generator.Map.Terrain.TileSize.X / 2.0D)),
                    (int)(Conversion.Int(Generator.Map.Terrain.TileSize.Y / 2.0D)));
                Alignments.Alignment = Alignments.Normal;
                tmpBrush.PerformActionMapTiles(ApplyCliff, Alignments);
                bool[] RevertSlope = null;
                bool[] RevertHeight = null;
                clsBooleanMap WaterMap = new clsBooleanMap();
                clsBooleanMap bmTemp = new clsBooleanMap();
                int A = 0;
                WaterMap = Generator.GetWaterMap();
                RevertSlope = new bool[Generator.GenerateTileset.OldTextureLayers.LayerCount];
                RevertHeight = new bool[Generator.GenerateTileset.OldTextureLayers.LayerCount];
                for ( A = 0; A <= Generator.GenerateTileset.OldTextureLayers.LayerCount - 1; A++ )
                {
                    App.sLayerList.clsLayer with_2 = Generator.GenerateTileset.OldTextureLayers.Layers[A];
                    with_2.Terrainmap = Generator.Map.GenerateTerrainMap(with_2.Scale, with_2.Density);
                    if ( with_2.SlopeMax < 0.0F )
                    {
                        with_2.SlopeMax = (float)(CliffAngle - MathUtil.RadOf1Deg);
                        if ( with_2.HeightMax < 0.0F )
                        {
                            with_2.HeightMax = 255.0F;
                            bmTemp.Within(with_2.Terrainmap, WaterMap);
                            with_2.Terrainmap.ValueData = bmTemp.ValueData;
                            bmTemp.ValueData = new clsBooleanMap.clsValueData();
                            RevertHeight[A] = true;
                        }
                        RevertSlope[A] = true;
                    }
                }
                Generator.Map.MapTexturer(Generator.GenerateTileset.OldTextureLayers);
                for ( A = 0; A <= Generator.GenerateTileset.OldTextureLayers.LayerCount - 1; A++ )
                {
                    App.sLayerList.clsLayer with_3 = Generator.GenerateTileset.OldTextureLayers.Layers[A];
                    with_3.Terrainmap = null;
                    if ( RevertSlope[A] )
                    {
                        with_3.SlopeMax = -1.0F;
                    }
                    if ( RevertHeight[A] )
                    {
                        with_3.HeightMax = -1.0F;
                    }
                }
            }

            Generator.Map.LevelWater();

            Generator.Map.WaterTriCorrection();

            Generator.Map.SectorGraphicsChanges.SetAllChanged();
            Generator.Map.SectorUnitHeightsChanges.SetAllChanged();

            Generator.Map.Update();

            Generator.Map.UndoStepCreate("Generated Textures");

            if ( Generator.Map == _Owner.MainMap )
            {
                Program.frmMainInstance.PainterTerrains_Refresh(-1, -1);
                Program.frmMainInstance.MainMapTilesetChanged();
            }

            return ReturnResult;
        }
Esempio n. 22
0
        protected clsResult read_INI_Droids(string iniText, List<IniDroid> resultData)
        {
            var resultObject = new clsResult("Reading droids.ini.", false);

            try
            {
                var iniSections = IniReader.ReadString(iniText);
                foreach ( var iniSection in iniSections )
                {
                    var droid = new IniDroid();
                    droid.HealthPercent = -1;
                    var invalid = false;
                    foreach ( var iniToken in iniSection.Data )
                    {
                        if ( invalid )
                        {
                            break;
                        }

                        try
                        {
                            switch ( iniToken.Name )
                            {
                                case "id":
                                    droid.ID = uint.Parse(iniToken.Data);
                                    break;

                                case "startpos":
                                    var tmpStartPos = int.Parse(iniToken.Data);
                                    if ( tmpStartPos < 0 | tmpStartPos >= Constants.PlayerCountMax )
                                    {
                                        resultObject.WarningAdd(string.Format("#{0} invalid startpos {1}", iniSection.Name, tmpStartPos), false);
                                        logger.Warn("#{0} invalid startpos {1}", iniSection.Name, tmpStartPos);
                                        invalid = true;
                                        continue;
                                    }
                                    droid.UnitGroup = map.UnitGroups[tmpStartPos];
                                    break;

                                case "template":
                                    droid.Template = iniToken.Data;
                                    break;

                                case "position":
                                    droid.Pos = XYZInt.FromString(iniToken.Data);
                                    break;

                                case "rotation":
                                    droid.Rotation = Rotation.FromString(iniToken.Data);
                                    break;

                                case "player":
                                    if ( iniToken.Data.ToLower() == "scavenger" )
                                    {
                                        droid.UnitGroup = map.ScavengerUnitGroup;
                                    }
                                    else
                                    {
                                        resultObject.WarningAdd(string.Format("#{0} invalid player: \"{1}\"", iniToken.Name, iniToken.Data), false);
                                        logger.Warn("#{0} invalid player \"{1}\"", iniToken.Name, iniToken.Data);
                                        invalid = true;
                                    }
                                    break;

                                case "name":
                                    // ignore
                                    break;

                                case "health":
                                    droid.HealthPercent = IniReader.ReadHealthPercent(iniToken.Data);
                                    if ( droid.HealthPercent < 0 || droid.HealthPercent > 100 )
                                    {
                                        resultObject.WarningAdd(string.Format("#{0} invalid health: \"{1}\"", iniSection.Name, droid.HealthPercent), false);
                                        invalid = true;
                                    }
                                    break;

                                case "droidtype":
                                    droid.DroidType = Numerics.Int.Parse(iniToken.Data);
                                    break;

                                case "weapons":
                                    droid.WeaponCount = Numerics.Int.Parse(iniToken.Data);
                                    break;

                                case "parts\\body":
                                    droid.Body = iniToken.Data;
                                    break;

                                case "parts\\propulsion":
                                    droid.Propulsion = iniToken.Data;
                                    break;

                                case "parts\\brain":
                                    droid.Brain = iniToken.Data;
                                    break;

                                case "parts\\repair":
                                    droid.Repair = iniToken.Data;
                                    break;

                                case "parts\\ecm":
                                    droid.ECM = iniToken.Data;
                                    break;

                                case "parts\\sensor":
                                    droid.Sensor = iniToken.Data;
                                    break;

                                case "parts\\construct":
                                    droid.Construct = iniToken.Data;
                                    break;

                                case "parts\\weapon\\1":
                                    if ( droid.Weapons == null )
                                    {
                                        droid.Weapons = new string[3];
                                    }
                                    droid.Weapons[0] = iniToken.Data;
                                    break;

                                case "parts\\weapon\\2":
                                    if ( droid.Weapons == null )
                                    {
                                        droid.Weapons = new string[3];
                                    }

                                    droid.Weapons[1] = iniToken.Data;
                                    break;

                                case "parts\\weapon\\3":
                                    if ( droid.Weapons == null )
                                    {
                                        droid.Weapons = new string[3];
                                    }

                                    droid.Weapons[2] = iniToken.Data;
                                    break;

                                default:
                                    resultObject.WarningAdd(string.Format("Found an invalid key: {0} = {1}", iniToken.Name, iniToken.Data), false);
                                    logger.Warn("Found an invalid key: {0} = {1}", iniToken.Name, iniToken.Data);
                                    break;
                            }
                        }
                        catch ( Exception ex )
                        {
                            Debugger.Break();
                            resultObject.WarningAdd(
                                string.Format("#{0} invalid {2}: \"{3}\", got exception: {2}", iniSection.Name, iniToken.Name, iniToken.Data, ex.Message), false);
                            logger.ErrorException(string.Format("#{0} invalid {2} \"{1}\"", iniSection.Name, iniToken.Name, iniToken.Data), ex);
                            invalid = true;
                        }
                    }

                    if ( !invalid )
                    {
                        resultData.Add(droid);
                    }
                }
            }
            catch ( Exception ex )
            {
                Debugger.Break();
                logger.ErrorException("Got exception while reading droid.ini", ex);
                resultObject.ProblemAdd(string.Format("Got exception: {0}", ex.Message), false);
                return resultObject;
            }

            return resultObject;
        }
Esempio n. 23
0
        public clsResult Load(string path)
        {
            var returnResult =
                new clsResult("Loading LND from \"{0}\"".Format2(path), false);
            logger.Info("Loading LND from \"{0}\"".Format2(path));
            try
            {
                var strTemp = "";
                var strTemp2 = "";
                var X = 0;
                var Y = 0;
                var A = 0;
                var B = 0;
                var Tile_Num = 0;
                // SimpleList<string> LineData = default(SimpleList<string>);
                var Line_Num = 0;
                LNDTile[] LNDTile = null;
                var LNDObjects = new SimpleList<LNDObject>();
                var UnitAdd = new clsUnitAdd();

                UnitAdd.Map = map;

                var Reader = default(BinaryReader);
                try
                {
                    Reader = new BinaryReader(new FileStream(path, FileMode.Open), App.UTF8Encoding);
                }
                catch ( Exception ex )
                {
                    returnResult.ProblemAdd(ex.Message);
                    return returnResult;
                }
                var LineData = IOUtil.BytesToLinesRemoveComments(Reader);
                Reader.Close();

                Array.Resize(ref LNDTile, LineData.Count);

                var strTemp3 = "";
                var GotTiles = default(bool);
                var GotObjects = default(bool);
                var GotGates = default(bool);
                var GotTileTypes = default(bool);
                var LNDTileType = new byte[0];
                var ObjectText = new string[11];
                var GateText = new string[4];
                var TileTypeText = new string[256];
                var LNDTileTypeCount = 0;
                var LNDGates = new SimpleList<clsGateway>();
                var Gateway = default(clsGateway);
                var C = 0;
                var D = 0;
                var GotText = default(bool);
                var FlipX = default(bool);
                var FlipZ = default(bool);
                byte Rotation = 0;
                var NewTileSize = new XYInt();
                double dblTemp = 0;

                Line_Num = 0;
                while ( Line_Num < LineData.Count )
                {
                    strTemp = LineData[Line_Num];

                    A = strTemp.IndexOf("TileWidth ") + 1;
                    if ( A == 0 )
                    {
                    }

                    A = strTemp.IndexOf("TileHeight ") + 1;
                    if ( A == 0 )
                    {
                    }

                    A = strTemp.IndexOf("MapWidth ") + 1;
                    if ( A == 0 )
                    {
                    }
                    else
                    {
                        IOUtil.InvariantParse(strTemp.Substring(strTemp.Length - (strTemp.Length - (A + 8)), strTemp.Length - (A + 8)), ref NewTileSize.X);
                        goto LineDone;
                    }

                    A = strTemp.IndexOf("MapHeight ") + 1;
                    if ( A == 0 )
                    {
                    }
                    else
                    {
                        IOUtil.InvariantParse(strTemp.Substring(strTemp.Length - (strTemp.Length - (A + 9)), strTemp.Length - (A + 9)), ref NewTileSize.Y);
                        goto LineDone;
                    }

                    A = strTemp.IndexOf("Textures {") + 1;
                    if ( A == 0 )
                    {
                    }
                    else
                    {
                        Line_Num++;
                        strTemp = LineData[Line_Num];

                        strTemp2 = strTemp.ToLower();
                        if ( strTemp2.IndexOf("tertilesc1") + 1 > 0 )
                        {
                            map.Tileset = App.Tileset_Arizona;
                        }
                        if ( strTemp2.IndexOf("tertilesc2") + 1 > 0 )
                        {
                            map.Tileset = App.Tileset_Urban;
                        }
                        if ( strTemp2.IndexOf("tertilesc3") + 1 > 0 )
                        {
                            map.Tileset = App.Tileset_Rockies;
                        }

                        goto LineDone;
                    }

                    A = strTemp.IndexOf("Tiles {") + 1;
                    if ( A == 0 || GotTiles )
                    {
                    }
                    else
                    {
                        Line_Num++;
                        while ( Line_Num < LineData.Count )
                        {
                            strTemp = LineData[Line_Num];

                            A = strTemp.IndexOf("}") + 1;
                            if ( A == 0 )
                            {
                                A = strTemp.IndexOf("TID ") + 1;
                                if ( A == 0 )
                                {
                                    returnResult.ProblemAdd("Tile ID missing");
                                    return returnResult;
                                }
                                strTemp2 = strTemp.Substring(strTemp.Length - (strTemp.Length - A - 3), strTemp.Length - A - 3);
                                A = strTemp2.IndexOf(" ") + 1;
                                if ( A > 0 )
                                {
                                    strTemp2 = strTemp2.Substring(0, A - 1);
                                }
                                var temp_Result = LNDTile[Tile_Num].TID;
                                IOUtil.InvariantParse(strTemp2, ref temp_Result);

                                A = strTemp.IndexOf("VF ") + 1;
                                if ( A == 0 )
                                {
                                    returnResult.ProblemAdd("Tile VF missing");
                                    return returnResult;
                                }
                                strTemp2 = strTemp.Substring(strTemp.Length - (strTemp.Length - A - 2), strTemp.Length - A - 2);
                                A = strTemp2.IndexOf(" ") + 1;
                                if ( A > 0 )
                                {
                                    strTemp2 = strTemp2.Substring(0, A - 1);
                                }
                                var temp_Result2 = LNDTile[Tile_Num].VF;
                                IOUtil.InvariantParse(strTemp2, ref temp_Result2);

                                A = strTemp.IndexOf("TF ") + 1;
                                if ( A == 0 )
                                {
                                    returnResult.ProblemAdd("Tile TF missing");
                                    return returnResult;
                                }
                                strTemp2 = strTemp.Substring(strTemp.Length - (strTemp.Length - A - 2), strTemp.Length - A - 2);
                                A = strTemp2.IndexOf(" ") + 1;
                                if ( A > 0 )
                                {
                                    strTemp2 = strTemp2.Substring(0, A - 1);
                                }
                                var temp_Result3 = LNDTile[Tile_Num].TF;
                                IOUtil.InvariantParse(strTemp2, ref temp_Result3);

                                A = strTemp.IndexOf(" F ") + 1;
                                if ( A == 0 )
                                {
                                    returnResult.ProblemAdd("Tile flip missing");
                                    return returnResult;
                                }
                                strTemp2 = strTemp.Substring(strTemp.Length - A - 2, strTemp.Length - A - 2);
                                A = strTemp2.IndexOf(" ");
                                if ( A > 0 )
                                {
                                    strTemp2 = strTemp2.Substring(0, A);
                                }
                                var temp_Result4 = LNDTile[Tile_Num].F;
                                IOUtil.InvariantParse(strTemp2, ref temp_Result4);

                                A = strTemp.IndexOf(" VH ") + 1;
                                if ( A == 0 )
                                {
                                    returnResult.ProblemAdd("Tile height is missing");
                                    return returnResult;
                                }
                                strTemp3 = strTemp.Substring(strTemp.Length - (strTemp.Length - A - 3), strTemp.Length - A - 3);
                                for ( A = 0; A <= 2; A++ )
                                {
                                    B = strTemp3.IndexOf(" ") + 1;
                                    if ( B == 0 )
                                    {
                                        returnResult.ProblemAdd("A tile height value is missing");
                                        return returnResult;
                                    }
                                    strTemp2 = strTemp3.Substring(0, B - 1);
                                    strTemp3 = strTemp3.Substring(strTemp3.Length - (strTemp3.Length - B), strTemp3.Length - B);

                                    if ( A == 0 )
                                    {
                                        var temp_Result5 = LNDTile[Tile_Num].Vertex0Height;
                                        IOUtil.InvariantParse(strTemp2, ref temp_Result5);
                                    }
                                    else if ( A == 1 )
                                    {
                                        var temp_Result6 = LNDTile[Tile_Num].Vertex1Height;
                                        IOUtil.InvariantParse(strTemp2, ref temp_Result6);
                                    }
                                    else if ( A == 2 )
                                    {
                                        var temp_Result7 = LNDTile[Tile_Num].Vertex2Height;
                                        IOUtil.InvariantParse(strTemp2, ref temp_Result7);
                                    }
                                }
                                var temp_Result8 = LNDTile[Tile_Num].Vertex3Height;
                                IOUtil.InvariantParse(strTemp3, ref temp_Result8);

                                Tile_Num++;
                            }
                            else
                            {
                                GotTiles = true;
                                goto LineDone;
                            }

                            Line_Num++;
                        }

                        GotTiles = true;
                        goto LineDone;
                    }

                    A = strTemp.IndexOf("Objects {") + 1;
                    if ( A == 0 || GotObjects )
                    {
                    }
                    else
                    {
                        Line_Num++;
                        while ( Line_Num < LineData.Count )
                        {
                            strTemp = LineData[Line_Num];

                            A = strTemp.IndexOf("}") + 1;
                            if ( A == 0 )
                            {
                                C = 0;
                                ObjectText[0] = "";
                                GotText = false;
                                for ( B = 0; B <= strTemp.Length - 1; B++ )
                                {
                                    if ( strTemp[B] != ' ' && strTemp[B] != '\t' )
                                    {
                                        GotText = true;
                                        ObjectText[C] += strTemp[B].ToString();
                                    }
                                    else
                                    {
                                        if ( GotText )
                                        {
                                            C++;
                                            if ( C == 11 )
                                            {
                                                returnResult.ProblemAdd("Too many fields for an object, or a space at the end.");
                                                return returnResult;
                                            }
                                            ObjectText[C] = "";
                                            GotText = false;
                                        }
                                    }
                                }

                                var NewObject = new LNDObject();
                                IOUtil.InvariantParse(ObjectText[0], ref NewObject.ID);
                                IOUtil.InvariantParse(ObjectText[1], ref NewObject.TypeNum);
                                NewObject.Code = ObjectText[2].Substring(1, ObjectText[2].Length - 2); //remove quotes
                                IOUtil.InvariantParse(ObjectText[3], ref NewObject.PlayerNum);
                                NewObject.Name = ObjectText[4].Substring(1, ObjectText[4].Length - 2); //remove quotes
                                IOUtil.InvariantParse(ObjectText[5], ref NewObject.Pos.X);
                                IOUtil.InvariantParse(ObjectText[6], ref NewObject.Pos.Y);
                                IOUtil.InvariantParse(ObjectText[7], ref NewObject.Pos.Z);
                                if ( IOUtil.InvariantParse(ObjectText[8], ref dblTemp) )
                                {
                                    NewObject.Rotation.X = (int)(MathUtil.Clamp_dbl(dblTemp, 0.0D, 359.0D));
                                }
                                if ( IOUtil.InvariantParse(ObjectText[9], ref dblTemp) )
                                {
                                    NewObject.Rotation.Y = (int)(MathUtil.Clamp_dbl(dblTemp, 0.0D, 359.0D));
                                }
                                if ( IOUtil.InvariantParse(ObjectText[10], ref dblTemp) )
                                {
                                    NewObject.Rotation.Z = (int)(MathUtil.Clamp_dbl(dblTemp, 0.0D, 359.0D));
                                }
                                LNDObjects.Add(NewObject);
                            }
                            else
                            {
                                GotObjects = true;
                                goto LineDone;
                            }

                            Line_Num++;
                        }

                        GotObjects = true;
                        goto LineDone;
                    }

                    A = strTemp.IndexOf("Gates {") + 1;
                    if ( A == 0 || GotGates )
                    {
                    }
                    else
                    {
                        Line_Num++;
                        while ( Line_Num < LineData.Count )
                        {
                            strTemp = LineData[Line_Num];

                            A = strTemp.IndexOf("}") + 1;
                            if ( A == 0 )
                            {
                                C = 0;
                                GateText[0] = "";
                                GotText = false;
                                for ( B = 0; B <= strTemp.Length - 1; B++ )
                                {
                                    if ( strTemp[B] != ' ' && strTemp[B] != '\t' )
                                    {
                                        GotText = true;
                                        GateText[C] += strTemp[B].ToString();
                                    }
                                    else
                                    {
                                        if ( GotText )
                                        {
                                            C++;
                                            if ( C == 4 )
                                            {
                                                returnResult.ProblemAdd("Too many fields for a gateway, or a space at the end.");
                                                return returnResult;
                                            }
                                            GateText[C] = "";
                                            GotText = false;
                                        }
                                    }
                                }

                                Gateway = new clsGateway();
                                IOUtil.InvariantParse(GateText[0], ref Gateway.PosA.X);
                                Gateway.PosA.X = Math.Max(Gateway.PosA.X, 0);
                                IOUtil.InvariantParse(GateText[1], ref Gateway.PosA.Y);
                                Gateway.PosA.Y = Math.Max(Gateway.PosA.Y, 0);
                                IOUtil.InvariantParse(GateText[2], ref Gateway.PosB.X);
                                Gateway.PosB.X = Math.Max(Gateway.PosB.X, 0);
                                IOUtil.InvariantParse(GateText[3], ref Gateway.PosB.Y);
                                Gateway.PosB.Y = Math.Max(Gateway.PosB.Y, 0);
                                LNDGates.Add(Gateway);
                            }
                            else
                            {
                                GotGates = true;
                                goto LineDone;
                            }

                            Line_Num++;
                        }

                        GotGates = true;
                        goto LineDone;
                    }

                    A = strTemp.IndexOf("Tiles {") + 1;
                    if ( A == 0 || GotTileTypes || !GotTiles )
                    {
                    }
                    else
                    {
                        Line_Num++;
                        while ( Line_Num < LineData.Count )
                        {
                            strTemp = LineData[Line_Num];

                            A = strTemp.IndexOf("}") + 1;
                            if ( A == 0 )
                            {
                                C = 0;
                                TileTypeText[0] = "";
                                GotText = false;
                                for ( B = 0; B <= strTemp.Length - 1; B++ )
                                {
                                    if ( strTemp[B] != ' ' && strTemp[B] != '\t' )
                                    {
                                        GotText = true;
                                        TileTypeText[C] += strTemp[B].ToString();
                                    }
                                    else
                                    {
                                        if ( GotText )
                                        {
                                            C++;
                                            if ( C == 256 )
                                            {
                                                returnResult.ProblemAdd("Too many fields for tile types.");
                                                return returnResult;
                                            }
                                            TileTypeText[C] = "";
                                            GotText = false;
                                        }
                                    }
                                }

                                if ( TileTypeText[C] == "" || TileTypeText[C] == " " )
                                {
                                    C--;
                                }

                                for ( D = 0; D <= C; D++ )
                                {
                                    Array.Resize(ref LNDTileType, LNDTileTypeCount + 1);
                                    LNDTileType[LNDTileTypeCount] = Math.Min(byte.Parse(TileTypeText[D]), (byte)11);
                                    LNDTileTypeCount++;
                                }
                            }
                            else
                            {
                                GotTileTypes = true;
                                goto LineDone;
                            }

                            Line_Num++;
                        }

                        GotTileTypes = true;
                    }

                    LineDone:
                        Line_Num++;
                }

                Array.Resize(ref LNDTile, Tile_Num);

                map.SetPainterToDefaults();

                if ( NewTileSize.X < 1 | NewTileSize.Y < 1 )
                {
                    returnResult.ProblemAdd("The LND\'s terrain dimensions are missing or invalid.");
                    return returnResult;
                }

                map.TerrainBlank(NewTileSize);
                map.TileType_Reset();

                for ( Y = 0; Y <= map.Terrain.TileSize.Y - 1; Y++ )
                {
                    for ( X = 0; X <= map.Terrain.TileSize.X - 1; X++ )
                    {
                        Tile_Num = Y * map.Terrain.TileSize.X + X;
                        //lnd uses different order! (3 = 2, 2 = 3), this program goes left to right, lnd goes clockwise around each tile
                        map.Terrain.Vertices[X, Y].Height = (byte)(LNDTile[Tile_Num].Vertex0Height);
                    }
                }

                for ( Y = 0; Y <= map.Terrain.TileSize.Y - 1; Y++ )
                {
                    for ( X = 0; X <= map.Terrain.TileSize.X - 1; X++ )
                    {
                        Tile_Num = Y * map.Terrain.TileSize.X + X;

                        map.Terrain.Tiles[X, Y].Texture.TextureNum = LNDTile[Tile_Num].TID - 1;

                        //ignore higher values
                        A = Convert.ToInt32((LNDTile[Tile_Num].F / 64.0D));
                        LNDTile[Tile_Num].F = (short)(LNDTile[Tile_Num].F - A * 64);

                        A = (int)((LNDTile[Tile_Num].F / 16.0D));
                        LNDTile[Tile_Num].F = (short)(LNDTile[Tile_Num].F - A * 16);
                        if ( A < 0 | A > 3 )
                        {
                            returnResult.ProblemAdd("Invalid flip value.");
                            return returnResult;
                        }
                        Rotation = (byte)A;

                        A = (int)((LNDTile[Tile_Num].F / 8.0D));
                        LNDTile[Tile_Num].F -= (short)(A * 8);
                        FlipZ = A == 1;

                        A = (int)((LNDTile[Tile_Num].F / 4.0D));
                        LNDTile[Tile_Num].F -= (short)(A * 4);
                        FlipX = A == 1;

                        A = Convert.ToInt32((LNDTile[Tile_Num].F / 2.0D));
                        LNDTile[Tile_Num].F -= (short)(A * 2);
                        map.Terrain.Tiles[X, Y].Tri = A == 1;

                        //vf, tf, ignore

                        TileUtil.OldOrientation_To_TileOrientation(Rotation, FlipX, FlipZ, ref map.Terrain.Tiles[X, Y].Texture.Orientation);
                    }
                }

                var newUnit = default(clsUnit);
                var xyzInt = new XYZInt(0, 0, 0);
                var newTypeBase = default(UnitTypeBase);
                UInt32 availableID = 0;

                availableID = 1U;
                foreach ( var currentObject in LNDObjects )
                {
                    if ( currentObject.ID >= availableID )
                    {
                        availableID = currentObject.ID + 1U;
                    }
                }
                foreach ( var currentObject in LNDObjects )
                {
                    switch ( currentObject.TypeNum )
                    {
                        case 0:
                        newTypeBase = App.ObjectData.FindOrCreateUnitType(currentObject.Code, UnitType.Feature, -1);
                        break;
                        case 1:
                        newTypeBase = App.ObjectData.FindOrCreateUnitType(currentObject.Code, UnitType.PlayerStructure, -1);
                        break;
                        case 2:
                        newTypeBase = App.ObjectData.FindOrCreateUnitType(currentObject.Code, UnitType.PlayerDroid, -1);
                        break;
                        default:
                        newTypeBase = null;
                        break;
                    }
                    if ( newTypeBase != null )
                    {
                        newUnit = new clsUnit();
                        newUnit.TypeBase = newTypeBase;
                        if ( currentObject.PlayerNum < 0 | currentObject.PlayerNum >= Constants.PlayerCountMax )
                        {
                            newUnit.UnitGroup = map.ScavengerUnitGroup;
                        }
                        else
                        {
                            newUnit.UnitGroup = map.UnitGroups[currentObject.PlayerNum];
                        }
                        xyzInt.X = (int)currentObject.Pos.X;
                        xyzInt.Y = (int)currentObject.Pos.Y;
                        xyzInt.Z = (int)currentObject.Pos.Z;
                        newUnit.Pos = mapPos_From_LNDPos(xyzInt);
                        newUnit.Rotation = currentObject.Rotation.Y;
                        if ( currentObject.ID == 0U )
                        {
                            currentObject.ID = availableID;
                            App.ZeroIDWarning(newUnit, currentObject.ID, returnResult);
                        }
                        UnitAdd.NewUnit = newUnit;
                        UnitAdd.ID = currentObject.ID;
                        UnitAdd.Perform();
                        App.ErrorIDChange(currentObject.ID, newUnit, "Load_LND");
                        if ( availableID == currentObject.ID )
                        {
                            availableID = newUnit.ID + 1U;
                        }
                    }
                }

                foreach ( var tempLoopVar_Gateway in LNDGates )
                {
                    Gateway = tempLoopVar_Gateway;
                    map.GatewayCreate(Gateway.PosA, Gateway.PosB);
                }

                if ( map.Tileset != null )
                {
                    for ( A = 0; A <= Math.Min(LNDTileTypeCount - 1, map.Tileset.TileCount) - 1; A++ )
                    {
                        map.Tile_TypeNum[A] = LNDTileType[A + 1]; //lnd value 0 is ignored
                    }
                }
            }
            catch ( Exception ex )
            {
                returnResult.ProblemAdd(ex.Message);
                return returnResult;
            }

            return returnResult;
        }
Esempio n. 24
0
        public clsResult GenerateLayoutTerrain()
        {
            clsResult ReturnResult = new clsResult("Terrain heights");

            clsNodeTag NodeTag = default(clsNodeTag);
            PathfinderNode tmpNodeA = default(PathfinderNode);
            PathfinderNode tmpNodeB = default(PathfinderNode);
            int A = 0;
            int B = 0;
            int C = 0;
            int D = 0;
            int X = 0;
            int Y = 0;
            sXY_int XY_int = new sXY_int();
            double Dist = 0;
            double BestDist = 0;
            bool Flag = default(bool);

            Map = new clsMap(TileSize);
            GenerateTerrainTiles = new GenerateTerrainTile[Map.Terrain.TileSize.X, Map.Terrain.TileSize.Y];
            GenerateTerrainVertices = new GenerateTerrainVertex[Map.Terrain.TileSize.X + 1, Map.Terrain.TileSize.Y + 1];

            //set terrain heights

            VertexPathMap = new PathfinderNetwork();

            for ( Y = 0; Y <= Map.Terrain.TileSize.Y; Y++ )
            {
                for ( X = 0; X <= Map.Terrain.TileSize.X; X++ )
                {
                    GenerateTerrainVertices[X, Y] = new GenerateTerrainVertex();
                    GenerateTerrainVertices[X, Y].Node = new PathfinderNode(VertexPathMap);
                    NodeTag = new clsNodeTag();
                    NodeTag.Pos = new sXY_int(X * 128, Y * 128);
                    GenerateTerrainVertices[X, Y].Node.Tag = NodeTag;
                }
            }
            for ( Y = 0; Y <= Map.Terrain.TileSize.Y; Y++ )
            {
                for ( X = 0; X <= Map.Terrain.TileSize.X; X++ )
                {
                    tmpNodeA = GenerateTerrainVertices[X, Y].Node;
                    if ( X > 0 )
                    {
                        tmpNodeB = GenerateTerrainVertices[X - 1, Y].Node;
                        GenerateTerrainVertices[X, Y].LeftLink = tmpNodeA.GetOrCreateConnection(tmpNodeB, GetNodePosDist(tmpNodeA, tmpNodeB));
                    }
                    if ( Y > 0 )
                    {
                        if ( X > 0 )
                        {
                            tmpNodeB = GenerateTerrainVertices[X - 1, Y - 1].Node;
                            GenerateTerrainVertices[X, Y].TopLeftLink = tmpNodeA.GetOrCreateConnection(tmpNodeB, GetNodePosDist(tmpNodeA, tmpNodeB));
                        }
                        tmpNodeB = GenerateTerrainVertices[X, Y - 1].Node;
                        GenerateTerrainVertices[X, Y].TopLink = tmpNodeA.GetOrCreateConnection(tmpNodeB, GetNodePosDist(tmpNodeA, tmpNodeB));
                        if ( X < Map.Terrain.TileSize.X )
                        {
                            tmpNodeB = GenerateTerrainVertices[X + 1, Y - 1].Node;
                            GenerateTerrainVertices[X, Y].TopRightLink = tmpNodeA.GetOrCreateConnection(tmpNodeB, GetNodePosDist(tmpNodeA, tmpNodeB));
                        }
                    }
                    if ( X < Map.Terrain.TileSize.X )
                    {
                        tmpNodeB = GenerateTerrainVertices[X + 1, Y].Node;
                        GenerateTerrainVertices[X, Y].RightLink = tmpNodeA.GetOrCreateConnection(tmpNodeB, GetNodePosDist(tmpNodeA, tmpNodeB));
                    }
                    if ( Y < Map.Terrain.TileSize.Y )
                    {
                        if ( X > 0 )
                        {
                            tmpNodeB = GenerateTerrainVertices[X - 1, Y + 1].Node;
                            GenerateTerrainVertices[X, Y].BottomLeftLink = tmpNodeA.GetOrCreateConnection(tmpNodeB, GetNodePosDist(tmpNodeA, tmpNodeB));
                        }
                        tmpNodeB = GenerateTerrainVertices[X, Y + 1].Node;
                        GenerateTerrainVertices[X, Y].BottomLink = tmpNodeA.GetOrCreateConnection(tmpNodeB, GetNodePosDist(tmpNodeA, tmpNodeB));
                        if ( X < Map.Terrain.TileSize.X )
                        {
                            tmpNodeB = GenerateTerrainVertices[X + 1, Y + 1].Node;
                            GenerateTerrainVertices[X, Y].BottomRightLink = tmpNodeA.GetOrCreateConnection(tmpNodeB, GetNodePosDist(tmpNodeA, tmpNodeB));
                        }
                    }
                }
            }

            VertexPathMap.LargeArraysResize();
            VertexPathMap.FindCalc();

            PathfinderLayer BaseLayer = VertexPathMap.get_GetNodeLayer(0);
            PathfinderLayer JitterLayer = VertexPathMap.get_GetNodeLayer(JitterScale);
            A = JitterLayer.GetNodeCount - 1;
            int[] NodeLevel = new int[A + 1];
            clsBaseNodeLevels BaseNodeLevel = new clsBaseNodeLevels();
            BaseNodeLevel.NodeLevels = new float[BaseLayer.GetNodeCount];

            //set position of jitter layer nodes

            Position.XY_dbl XY_dbl = default(Position.XY_dbl);

            if ( A > 0 )
            {
                for ( B = 0; B <= A; B++ )
                {
                    tmpNodeA = JitterLayer.get_GetNode(B);
                    C = 0;
                    XY_dbl.X = 0.0D;
                    XY_dbl.Y = 0.0D;
                    CalcNodePos(tmpNodeA, ref XY_dbl, ref C);
                    NodeTag = new clsNodeTag();
                    NodeTag.Pos.X = (int)(XY_dbl.X / C);
                    NodeTag.Pos.Y = (int)(XY_dbl.Y / C);
                    tmpNodeA.Tag = NodeTag;
                }
            }

            //set node heights

            clsConnection BestConnection = default(clsConnection);
            clsPassageNode BestNode = default(clsPassageNode);

            for ( A = 0; A <= JitterLayer.GetNodeCount - 1; A++ )
            {
                NodeTag = (clsNodeTag)(JitterLayer.get_GetNode(A).Tag);
                NodeLevel[A] = -1;
                BestDist = float.MaxValue;
                BestConnection = null;
                BestNode = null;
                for ( B = 0; B <= ConnectionCount - 1; B++ )
                {
                    //If Not (Connections(B).PassageNodeA.IsOnBorder Or Connections(B).PassageNodeB.IsOnBorder) Then
                    if ( Connections[B].PassageNodeA.Level == Connections[B].PassageNodeB.Level )
                    {
                        //only do this if the levels are the same
                        //this is to make sure nodes that are connected are actually connected on the terrain
                        XY_int = MathUtil.PointGetClosestPosOnLine(Connections[B].PassageNodeA.Pos, Connections[B].PassageNodeB.Pos, NodeTag.Pos);
                        Dist = Convert.ToSingle((XY_int - NodeTag.Pos).ToDoubles().GetMagnitude());
                        if ( Dist < BestDist )
                        {
                            BestDist = Dist;
                            if ( (NodeTag.Pos - Connections[B].PassageNodeA.Pos).ToDoubles().GetMagnitude() <=
                                 (NodeTag.Pos - Connections[B].PassageNodeB.Pos).ToDoubles().GetMagnitude() )
                            {
                                BestNode = Connections[B].PassageNodeA;
                            }
                            else
                            {
                                BestNode = Connections[B].PassageNodeB;
                            }
                            Flag = true;
                        }
                    }
                }
                for ( C = 0; C <= PassageNodeCount - 1; C++ )
                {
                    //If Not PassageNodesA(C).IsOnBorder Then
                    for ( D = 0; D <= SymmetryBlockCount - 1; D++ )
                    {
                        Dist = Convert.ToSingle((NodeTag.Pos - PassageNodes[D, C].Pos).ToDoubles().GetMagnitude());
                        if ( Dist < BestDist )
                        {
                            BestDist = Dist;
                            BestNode = PassageNodes[D, C];
                            Flag = true;
                        }
                    }
                    //End If
                }
                if ( Flag )
                {
                    NodeLevel[A] = BestNode.Level;
                }
                else
                {
                    NodeLevel[A] = BestConnection.PassageNodeA.Level;
                }
                if ( NodeLevel[A] < 0 )
                {
                    ReturnResult.ProblemAdd("Error: Node height is not set.");
                    return ReturnResult;
                }
            }

            for ( A = 0; A <= LevelCount - 1; A++ )
            {
                for ( B = 0; B <= JitterLayer.GetNodeCount - 1; B++ )
                {
                    if ( NodeLevel[B] >= A )
                    {
                        SetBaseLevel(JitterLayer.get_GetNode(B), A, BaseNodeLevel);
                    }
                }
            }

            //make ramp slopes

            int MinRampLength = ((int)(LevelHeight * Map.HeightMultiplier * 2.0D)) + 128;
            clsSetBaseLevelRampArgs RampArgs = new clsSetBaseLevelRampArgs();
            RampArgs.BaseLevel = BaseNodeLevel;
            RampArgs.RampRadius = 320.0F;
            for ( B = 0; B <= ConnectionCount - 1; B++ )
            {
                RampArgs.Connection = Connections[B];
                RampArgs.RampLength =
                    Math.Max(Convert.ToInt32((Connections[B].PassageNodeA.Pos - Connections[B].PassageNodeB.Pos).ToDoubles().GetMagnitude() * 0.75D),
                        MinRampLength * Math.Abs(Connections[B].PassageNodeA.Level - Connections[B].PassageNodeB.Level));
                for ( A = 0; A <= JitterLayer.GetNodeCount - 1; A++ )
                {
                    if ( Connections[B].IsRamp )
                    {
                        NodeTag = (clsNodeTag)(JitterLayer.get_GetNode(A).Tag);
                        XY_int = MathUtil.PointGetClosestPosOnLine(Connections[B].PassageNodeA.Pos, Connections[B].PassageNodeB.Pos, NodeTag.Pos);
                        Dist = Convert.ToSingle((XY_int - NodeTag.Pos).ToDoubles().GetMagnitude());
                        if ( Dist < RampArgs.RampLength * 2.0F )
                        {
                            SetBaseLevelRamp(RampArgs, JitterLayer.get_GetNode(A));
                        }
                    }
                }
            }

            for ( A = 0; A <= BaseLayer.GetNodeCount - 1; A++ )
            {
                NodeTag = (clsNodeTag)(BaseLayer.get_GetNode(A).Tag);
                Map.Terrain.Vertices[(int)(NodeTag.Pos.X / 128.0F), (int)(NodeTag.Pos.Y / 128.0F)].Height = (byte)(BaseNodeLevel.NodeLevels[A] * LevelHeight);
            }

            return ReturnResult;
        }
Esempio n. 25
0
        public clsResult LoadDirectory(string path)
        {
            var returnResult = new clsResult("Loading tileset from '{0}'".Format2(path), false);
            logger.Info("Loading tileset from '{0}'".Format2(path));

            Bitmap bitmap = null;
            var SplitPath = new sSplitPath(path);
            var slashPath = PathUtil.EndWithPathSeperator(path);
            var result = new sResult();

            if ( SplitPath.FileTitle != "" )
            {
                Name = SplitPath.FileTitle;
            }
            else if ( SplitPath.PartCount >= 2 )
            {
                Name = SplitPath.Parts[SplitPath.PartCount - 2];
            }

            var ttpFileName = Path.ChangeExtension(Name, ".ttp");

            result = LoadTileType(Path.Combine(slashPath, ttpFileName));

            if ( !result.Success )
            {
                returnResult.ProblemAdd("Loading tile types: " + result.Problem);
                return returnResult;
            }

            var redTotal = 0;
            var greenTotal = 0;
            var blueTotal = 0;
            var tileNum = 0;
            var strTile = "";
            var bmpTextureArgs = new BitmapGLTexture();
            var AverageColour = new float[4];
            var x = 0;
            var y = 0;
            var Pixel = new Color();

            var graphicPath = "";

            //tile count has been set by the ttp file

            for ( tileNum = 0; tileNum <= TileCount - 1; tileNum++ )
            {
                strTile = "tile-" + App.MinDigits(tileNum, 2) + ".png";

                //-------- 128 --------

                var tileDir = Path.Combine(Name + "-128", strTile);
                graphicPath = Path.Combine(slashPath, tileDir);

                result = BitmapUtil.LoadBitmap(graphicPath, ref bitmap);
                if ( !result.Success )
                {
                    //ignore and exit, since not all tile types have a corresponding tile graphic
                    return returnResult;
                }

                if ( bitmap.Width != 128 | bitmap.Height != 128 )
                {
                    returnResult.WarningAdd("Tile graphic " + graphicPath + " from tileset " + Name + " is not 128x128.");
                    return returnResult;
                }

                bmpTextureArgs.Texture = bitmap;
                bmpTextureArgs.MipMapLevel = 0;
                bmpTextureArgs.MagFilter = TextureMagFilter.Nearest;
                bmpTextureArgs.MinFilter = TextureMinFilter.Nearest;
                bmpTextureArgs.TextureNum = 0;
                bmpTextureArgs.Perform();
                Tiles[tileNum].TextureViewGlTextureNum = bmpTextureArgs.TextureNum;

                bmpTextureArgs.MagFilter = TextureMagFilter.Nearest;
                if ( SettingsManager.Settings.Mipmaps )
                {
                    bmpTextureArgs.MinFilter = TextureMinFilter.LinearMipmapLinear;
                }
                else
                {
                    bmpTextureArgs.MinFilter = TextureMinFilter.Nearest;
                }
                bmpTextureArgs.TextureNum = 0;

                bmpTextureArgs.Perform();
                Tiles[tileNum].MapViewGlTextureNum = bmpTextureArgs.TextureNum;

                if ( SettingsManager.Settings.Mipmaps )
                {
                    if ( SettingsManager.Settings.MipmapsHardware )
                    {
                        GL.Enable(EnableCap.Texture2D);
                        GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);
                        GL.Disable(EnableCap.Texture2D);
                    }
                    else
                    {
                        var MipmapResult = default(clsResult);
                        MipmapResult = GenerateMipMaps(slashPath, strTile, bmpTextureArgs, tileNum);
                        returnResult.Add(MipmapResult);
                        if ( MipmapResult.HasProblems )
                        {
                            return returnResult;
                        }
                    }
                    GL.GetTexImage(TextureTarget.Texture2D, 7, PixelFormat.Rgba, PixelType.Float, AverageColour);
                    Tiles[tileNum].AverageColour.Red = AverageColour[0];
                    Tiles[tileNum].AverageColour.Green = AverageColour[1];
                    Tiles[tileNum].AverageColour.Blue = AverageColour[2];
                }
                else
                {
                    redTotal = 0;
                    greenTotal = 0;
                    blueTotal = 0;
                    for ( y = 0; y <= bitmap.Height - 1; y++ )
                    {
                        for ( x = 0; x <= bitmap.Width - 1; x++ )
                        {
                            Pixel = bitmap.GetPixel(x, y);
                            redTotal += Pixel.R;
                            greenTotal += Pixel.G;
                            blueTotal += Pixel.B;
                        }
                    }
                    Tiles[tileNum].AverageColour.Red = (float)(redTotal / 4177920.0D);
                    Tiles[tileNum].AverageColour.Green = (float)(greenTotal / 4177920.0D);
                    Tiles[tileNum].AverageColour.Blue = (float)(blueTotal / 4177920.0D);
                }
            }

            return returnResult;
        }
Esempio n. 26
0
        public clsResult GenerateOil()
        {
            clsResult ReturnResult = new clsResult("Oil");

            int A = 0;
            int B = 0;
            int C = 0;
            int D = 0;

            for ( A = 0; A <= PassageNodeCount - 1; A++ )
            {
                for ( B = 0; B <= SymmetryBlockCount - 1; B++ )
                {
                    PassageNodes[B, A].OilCount = 0;
                }
            }

            //store passage node route distances
            clsPassageNodeNework PassageNodePathMap = MakePassageNodeNetwork();
            PathfinderNode[] GetPathStartNodes = new PathfinderNode[1];
            PathfinderNetwork.PathList[] ResultPaths = null;

            PassageNodeDists = new float[SymmetryBlockCount, PassageNodeCount, SymmetryBlockCount, PassageNodeCount];
            for ( A = 0; A <= PassageNodeCount - 1; A++ )
            {
                for ( D = 0; D <= SymmetryBlockCount - 1; D++ )
                {
                    PassageNodeDists[D, A, D, A] = 0.0F;
                    for ( B = 0; B <= PassageNodeCount - 1; B++ )
                    {
                        for ( C = 0; C <= SymmetryBlockCount - 1; C++ )
                        {
                            if ( PassageNodes[0, A].IsWater || PassageNodes[C, B].IsWater || (C != 0 & D != 0) )
                            {
                                PassageNodeDists[D, A, C, B] = float.MaxValue;
                                PassageNodeDists[C, B, D, A] = float.MaxValue;
                            }
                            else
                            {
                                GetPathStartNodes[0] = PassageNodePathMap.PassageNodePathNodes[D, A];
                                ResultPaths = PassageNodePathMap.Network.GetPath(GetPathStartNodes, PassageNodePathMap.PassageNodePathNodes[C, B], -1, 0);
                                if ( ResultPaths == null )
                                {
                                    ReturnResult.ProblemAdd("Map is not all connected.");
                                    PassageNodePathMap.Network.Deallocate();
                                    return ReturnResult;
                                }
                                else
                                {
                                    if ( ResultPaths[0].PathCount != 1 )
                                    {
                                        Debugger.Break();
                                    }
                                    PassageNodeDists[D, A, C, B] = ResultPaths[0].Paths[0].Value;
                                    PassageNodeDists[C, B, D, A] = ResultPaths[0].Paths[0].Value;
                                }
                            }
                        }
                    }
                }
            }

            PassageNodePathMap.Network.Deallocate();

            //place oil
            int PlacedExtraOilCount = 0;
            int MaxBestNodeCount = 0;
            MaxBestNodeCount = 1;
            for ( A = 0; A <= OilAtATime - 1; A++ )
            {
                MaxBestNodeCount *= PassageNodeCount;
            }
            var oilArgs = new clsOilBalanceLoopArgs
                {
                    OilClusterSizes = new int[OilAtATime],
                    PlayerOilScore = new double[TopLeftPlayerCount],
                    OilNodes = new clsPassageNode[OilAtATime]
                };

            //balanced oil
            while ( PlacedExtraOilCount < ExtraOilCount )
            {
                //place oil farthest away from other oil and where it best balances the player oil score
                for ( A = 0; A <= OilAtATime - 1; A++ )
                {
                    oilArgs.OilClusterSizes[A] =
                        Math.Min(ExtraOilClusterSizeMin + (int)(Conversion.Int(VBMath.Rnd() * (ExtraOilClusterSizeMax - ExtraOilClusterSizeMin + 1))),
                            Math.Max((int)(Math.Ceiling(Convert.ToDecimal((ExtraOilCount - PlacedExtraOilCount) / SymmetryBlockCount))), 1));
                }
                oilArgs.OilPossibilities = new clsOilPossibilities();
                OilBalanceLoop(oilArgs, 0);

                clsOilPossibilities.clsPossibility bestPossibility = oilArgs.OilPossibilities.BestPossibility;

                if ( bestPossibility != null )
                {
                    for ( B = 0; B <= OilAtATime - 1; B++ )
                    {
                        for ( A = 0; A <= SymmetryBlockCount - 1; A++ )
                        {
                            PassageNodes[A, bestPossibility.Nodes[B].Num].OilCount += oilArgs.OilClusterSizes[B];
                        }
                        PlacedExtraOilCount += oilArgs.OilClusterSizes[B] * SymmetryBlockCount;
                    }
                    for ( A = 0; A <= TopLeftPlayerCount - 1; A++ )
                    {
                        oilArgs.PlayerOilScore[A] += bestPossibility.PlayerOilScoreAddition[A];
                    }
                }
                else
                {
                    ReturnResult.WarningAdd("Could not place all of the oil. " + Convert.ToString(PlacedExtraOilCount) + " oil was placed.");
                    break;
                }
            }

            //base oil
            for ( A = 0; A <= TopLeftPlayerCount - 1; A++ )
            {
                for ( B = 0; B <= SymmetryBlockCount - 1; B++ )
                {
                    PassageNodes[B, PlayerBases[A].Nodes[0].Num].OilCount += BaseOilCount;
                }
            }

            return ReturnResult;
        }
Esempio n. 27
0
        public static clsResult WriteMemoryToZipEntryAndFlush(MemoryStream Memory, ZipOutputStream Stream)
        {
            clsResult ReturnResult = new clsResult("Writing to zip stream");

            try
            {
                Memory.WriteTo(Stream);
                Memory.Flush();
                Stream.Flush();
                Stream.CloseEntry();
            }
            catch ( Exception ex )
            {
                ReturnResult.ProblemAdd(ex.Message);
                return ReturnResult;
            }

            return ReturnResult;
        }
Esempio n. 28
0
        public clsResult GenerateRamps()
        {
            clsResult ReturnResult = new clsResult("Ramps");

            int A = 0;
            int B = 0;
            int C = 0;
            int E = 0;
            double BestDist = 0;
            int BestNum = 0;
            sXY_int XY_int = new sXY_int();
            clsPassageNode tmpPassageNodeA = default(clsPassageNode);
            clsPassageNode tmpPassageNodeB = default(clsPassageNode);
            double Dist = 0;

            //make ramps

            for ( A = 0; A <= ConnectionCount - 1; A++ )
            {
                Connections[A].IsRamp = false;
            }

            PathfinderNode tmpNodeA = default(PathfinderNode);
            PathfinderNode tmpNodeB = default(PathfinderNode);
            PathfinderNode[,] PassageNodePathNodes = null;
            PathfinderConnection NewConnection;

            clsPassageNodeNework PassageNodeNetwork = MakePassageNodeNetwork();
            PassageNodePathNodes = PassageNodeNetwork.PassageNodePathNodes;

            clsConnection[] PossibleRamps = new clsConnection[ConnectionCount];
            int PossibleRampCount = 0;
            PathfinderNode[] GetPathStartNodes = new PathfinderNode[1];
            PathfinderNetwork.PathList[] ResultPaths = null;

            //ramp connections whose points are too far apart

            bool[] ConnectionsCanRamp = new bool[ConnectionCount];

            for ( B = 0; B <= ConnectionCount - 1; B++ )
            {
                C = Math.Abs(Connections[B].PassageNodeA.Level - Connections[B].PassageNodeB.Level);
                if ( C == 1 )
                {
                    if ( !(Connections[B].PassageNodeA.IsOnBorder || Connections[B].PassageNodeB.IsOnBorder)
                         && Connections[B].PassageNodeA.MirrorNum == 0
                         && Connections[B].PassageNodeA.Num != Connections[B].PassageNodeB.Num )
                    {
                        ConnectionsCanRamp[B] = true;
                    }
                    else
                    {
                        ConnectionsCanRamp[B] = false;
                    }
                }
                else
                {
                    ConnectionsCanRamp[B] = false;
                }
            }

            clsNodeConnectedness Connectedness = new clsNodeConnectedness();
            Connectedness.NodeConnectedness = new float[PassageNodeCount];
            Connectedness.PassageNodeVisited = new bool[SymmetryBlockCount, PassageNodeCount];
            Connectedness.PassageNodePathNodes = PassageNodePathNodes;
            Connectedness.PassageNodePathMap = PassageNodeNetwork.Network;

            PathfinderConnection[] tmpPathConnection = new PathfinderConnection[4];
            double Value = 0;
            double BestDistB = 0;
            double BaseDist = 0;
            double RampDist = 0;
            clsUpdateNodeConnectednessArgs UpdateNodeConnectednessArgs = new clsUpdateNodeConnectednessArgs();
            clsUpdateNetworkConnectednessArgs UpdateNetworkConnectednessArgs = new clsUpdateNetworkConnectednessArgs();

            UpdateNodeConnectednessArgs.Args = Connectedness;
            UpdateNetworkConnectednessArgs.Args = Connectedness;
            UpdateNetworkConnectednessArgs.PassageNodeUpdated = new bool[PassageNodeCount];
            UpdateNetworkConnectednessArgs.SymmetryBlockCount = SymmetryBlockCount;

            for ( A = 0; A <= PassageNodeCount - 1; A++ )
            {
                Connectedness.NodeConnectedness[A] = 0.0F;
                for ( B = 0; B <= PassageNodeCount - 1; B++ )
                {
                    for ( C = 0; C <= SymmetryBlockCount - 1; C++ )
                    {
                        Connectedness.PassageNodeVisited[C, B] = false;
                    }
                }
                UpdateNodeConnectednessArgs.OriginalNode = PassageNodes[0, A];
                UpdateNodeConnectedness(UpdateNodeConnectednessArgs, PassageNodes[0, A]);
            }

            do
            {
                BestNum = -1;
                BestDist = 1.0F; //for connections that can already reach the other side
                BestDistB = 0.0F; //for connections that cant
                PossibleRampCount = 0;
                for ( B = 0; B <= ConnectionCount - 1; B++ )
                {
                    if ( ConnectionsCanRamp[B] && !Connections[B].IsRamp )
                    {
                        if ( CheckRampAngles(Connections[B], Convert.ToDouble(80.0D * MathUtil.RadOf1Deg), Convert.ToDouble(120.0D * MathUtil.RadOf1Deg),
                            0.0D * MathUtil.RadOf1Deg) )
                        {
                            GetPathStartNodes[0] = PassageNodePathNodes[Connections[B].PassageNodeA.MirrorNum, Connections[B].PassageNodeA.Num];
                            ResultPaths = PassageNodeNetwork.Network.GetPath(GetPathStartNodes,
                                PassageNodePathNodes[Connections[B].PassageNodeB.MirrorNum, Connections[B].PassageNodeB.Num], -1, 0);
                            BaseDist = double.MaxValue;
                            XY_int.X = (int)((Connections[B].PassageNodeA.Pos.X + Connections[B].PassageNodeB.Pos.X) / 2.0D);
                            XY_int.Y = (int)((Connections[B].PassageNodeA.Pos.Y + Connections[B].PassageNodeB.Pos.Y) / 2.0D);
                            for ( E = 0; E <= TotalPlayerCount - 1; E++ )
                            {
                                Dist = Convert.ToDouble((PlayerBases[E].Pos - XY_int).ToDoubles().GetMagnitude());
                                if ( Dist < BaseDist )
                                {
                                    BaseDist = Dist;
                                }
                            }
                            RampDist = Math.Max(MaxDisconnectionDist * Math.Pow(RampBase, (BaseDist / 1024.0D)), 1.0F);
                            if ( ResultPaths == null )
                            {
                                Value = Connectedness.NodeConnectedness[Connections[B].PassageNodeA.Num] +
                                        Connectedness.NodeConnectedness[Connections[B].PassageNodeB.Num];
                                if ( double.MaxValue > BestDist )
                                {
                                    BestDist = double.MaxValue;
                                    BestDistB = Value;
                                    PossibleRamps[0] = Connections[B];
                                    PossibleRampCount = 1;
                                }
                                else
                                {
                                    if ( Value < BestDistB )
                                    {
                                        BestDistB = Value;
                                        PossibleRamps[0] = Connections[B];
                                        PossibleRampCount = 1;
                                    }
                                    else if ( Value == BestDistB )
                                    {
                                        PossibleRamps[PossibleRampCount] = Connections[B];
                                        PossibleRampCount++;
                                    }
                                }
                            }
                            else if ( ResultPaths[0].PathCount != 1 )
                            {
                                ReturnResult.ProblemAdd("Error: Invalid number of routes returned.");
                                goto Finish;
                            }
                            else if ( ResultPaths[0].Paths[0].Value / RampDist > BestDist )
                            {
                                BestDist = ResultPaths[0].Paths[0].Value / RampDist;
                                PossibleRamps[0] = Connections[B];
                                PossibleRampCount = 1;
                            }
                            else if ( ResultPaths[0].Paths[0].Value / RampDist == BestDist )
                            {
                                PossibleRamps[PossibleRampCount] = Connections[B];
                                PossibleRampCount++;
                            }
                            else if ( ResultPaths[0].Paths[0].Value <= RampDist )
                            {
                                ConnectionsCanRamp[B] = false;
                            }
                        }
                        else
                        {
                            ConnectionsCanRamp[B] = false;
                        }
                    }
                    else
                    {
                        ConnectionsCanRamp[B] = false;
                    }
                }
                if ( PossibleRampCount > 0 )
                {
                    BestNum = (int)(Conversion.Int(VBMath.Rnd() * PossibleRampCount));
                    PossibleRamps[BestNum].IsRamp = true;
                    tmpPassageNodeA = PossibleRamps[BestNum].PassageNodeA;
                    tmpPassageNodeB = PossibleRamps[BestNum].PassageNodeB;
                    tmpNodeA = PassageNodePathNodes[tmpPassageNodeA.MirrorNum, tmpPassageNodeA.Num];
                    tmpNodeB = PassageNodePathNodes[tmpPassageNodeB.MirrorNum, tmpPassageNodeB.Num];
                    NewConnection = tmpNodeA.CreateConnection(tmpNodeB, GetNodePosDist(tmpNodeA, tmpNodeB));
                    for ( C = 0; C <= PossibleRamps[BestNum].ReflectionCount - 1; C++ )
                    {
                        PossibleRamps[BestNum].Reflections[C].IsRamp = true;
                        tmpPassageNodeA = PossibleRamps[BestNum].Reflections[C].PassageNodeA;
                        tmpPassageNodeB = PossibleRamps[BestNum].Reflections[C].PassageNodeB;
                        tmpNodeA = PassageNodePathNodes[tmpPassageNodeA.MirrorNum, tmpPassageNodeA.Num];
                        tmpNodeB = PassageNodePathNodes[tmpPassageNodeB.MirrorNum, tmpPassageNodeB.Num];
                        NewConnection = tmpNodeA.CreateConnection(tmpNodeB, GetNodePosDist(tmpNodeA, tmpNodeB));
                    }
                    PassageNodeNetwork.Network.FindCalc();
                    for ( E = 0; E <= PassageNodeCount - 1; E++ )
                    {
                        UpdateNetworkConnectednessArgs.PassageNodeUpdated[E] = false;
                    }
                    if ( PossibleRamps[BestNum].PassageNodeA.MirrorNum == 0 )
                    {
                        UpdateNetworkConnectedness(UpdateNetworkConnectednessArgs, PossibleRamps[BestNum].PassageNodeA);
                    }
                    else if ( PossibleRamps[BestNum].PassageNodeB.MirrorNum == 0 )
                    {
                        UpdateNetworkConnectedness(UpdateNetworkConnectednessArgs, PossibleRamps[BestNum].PassageNodeB);
                    }
                    else
                    {
                        ReturnResult.ProblemAdd("Error: Initial ramp not in area 0.");
                        goto Finish;
                    }
                }
                else
                {
                    break;
                }
            } while ( true );

            PathfinderNetwork.sFloodProximityArgs FloodArgs = new PathfinderNetwork.sFloodProximityArgs();
            FloodArgs.StartNode = PassageNodeNetwork.PassageNodePathNodes[0, 0];
            FloodArgs.NodeValues = PassageNodeNetwork.Network.NetworkLargeArrays.Nodes_ValuesA;
            for ( A = 0; A <= PassageNodeCount - 1; A++ )
            {
                for ( B = 0; B <= SymmetryBlockCount - 1; B++ )
                {
                    FloodArgs.NodeValues[PassageNodeNetwork.PassageNodePathNodes[B, A].Layer_NodeNum] = float.MaxValue;
                }
            }
            PassageNodeNetwork.Network.FloodProximity(FloodArgs);
            for ( A = 0; A <= PassageNodeCount - 1; A++ )
            {
                for ( B = 0; B <= SymmetryBlockCount - 1; B++ )
                {
                    if ( !PassageNodes[B, A].IsWater )
                    {
                        if ( FloodArgs.NodeValues[PassageNodeNetwork.PassageNodePathNodes[B, A].Layer_NodeNum] == float.MaxValue )
                        {
                            ReturnResult.ProblemAdd("Land is unreachable. Reduce variation or retry.");
                            goto Finish;
                        }
                    }
                }
            }

            Finish:
            PassageNodeNetwork.Network.Deallocate();

            return ReturnResult;
        }
Esempio n. 29
0
        public clsResult AutoSavePerform()
        {
            clsResult ReturnResult = new clsResult("Autosave");

            if ( !Directory.Exists(App.AutoSavePath) )
            {
                try
                {
                    Directory.CreateDirectory(App.AutoSavePath);
                }
                catch ( Exception )
                {
                    ReturnResult.ProblemAdd("Unable to create directory at " + Convert.ToString(ControlChars.Quote) + App.AutoSavePath +
                                            Convert.ToString(ControlChars.Quote));
                }
            }

            DateTime DateNow = DateTime.Now;
            string Path = "";

            Path = App.AutoSavePath + "autosaved-" + IOUtil.InvariantToString(DateNow.Year) + "-" + App.MinDigits(DateNow.Month, 2) + "-" +
                   App.MinDigits(DateNow.Day, 2) + "-" + App.MinDigits(DateNow.Hour, 2) + "-" + App.MinDigits(DateNow.Minute, 2) + "-" +
                   App.MinDigits(DateNow.Second, 2) + "-" + App.MinDigits(DateNow.Millisecond, 3) + ".fmap";

            ReturnResult.Add(Write_FMap(Path, false, SettingsManager.Settings.AutoSaveCompress));

            return ReturnResult;
        }
Esempio n. 30
0
        public clsResult GenerateUnits()
        {
            clsResult ReturnResult = new clsResult("Objects");

            int A = 0;
            int B = 0;
            int C = 0;
            int D = 0;
            clsMap.clsUnit tmpUnit = default(clsMap.clsUnit);
            int Count = 0;
            int FeaturePlaceRange = 6 * 128;
            int BasePlaceRange = 16 * 128;
            sXY_int TilePos = new sXY_int();
            byte AverageHeight = 0;
            int PlayerNum = 0;
            clsMap.clsTerrain Terrain = Map.Terrain;

            for ( A = 0; A <= PassageNodeCount - 1; A++ )
            {
                for ( B = 0; B <= SymmetryBlockCount - 1; B++ )
                {
                    PassageNodes[B, A].HasFeatureCluster = false;
                }
            }

            for ( A = 0; A <= TotalPlayerCount - 1; A++ )
            {
                PlayerNum = A;
                tmpUnit = PlaceUnitNear(DefaultGenerator.UnitType_CommandCentre, PlayerBases[A].Pos, Map.UnitGroups[PlayerNum], 3, 0, BasePlaceRange);
                if ( tmpUnit == null )
                {
                    ReturnResult.ProblemAdd("No room for base structures");
                    return ReturnResult;
                }
                tmpUnit = PlaceUnitNear(DefaultGenerator.UnitType_PowerGenerator, PlayerBases[A].Pos, Map.UnitGroups[PlayerNum], 3, 0, BasePlaceRange);
                if ( tmpUnit == null )
                {
                    ReturnResult.ProblemAdd("No room for base structures.");
                    return ReturnResult;
                }
                tmpUnit = PlaceUnit(DefaultGenerator.UnitType_PowerModule, tmpUnit.Pos, Map.UnitGroups[PlayerNum], 0);
                if ( tmpUnit == null )
                {
                    ReturnResult.ProblemAdd("No room for module.");
                    return ReturnResult;
                }
                for ( B = 1; B <= 2; B++ )
                {
                    tmpUnit = PlaceUnitNear(DefaultGenerator.UnitType_ResearchFacility, PlayerBases[A].Pos, Map.UnitGroups[PlayerNum], 3, 0, BasePlaceRange);
                    if ( tmpUnit == null )
                    {
                        ReturnResult.ProblemAdd("No room for base structures");
                        return ReturnResult;
                    }
                    tmpUnit = PlaceUnit(DefaultGenerator.UnitType_ResearchModule, tmpUnit.Pos, Map.UnitGroups[PlayerNum], 0);
                    if ( tmpUnit == null )
                    {
                        ReturnResult.ProblemAdd("No room for module.");
                        return ReturnResult;
                    }
                }
                for ( B = 1; B <= 2; B++ )
                {
                    tmpUnit = PlaceUnitNear(DefaultGenerator.UnitType_Factory, PlayerBases[A].Pos, Map.UnitGroups[PlayerNum], 4, 0, BasePlaceRange);
                    if ( tmpUnit == null )
                    {
                        ReturnResult.ProblemAdd("No room for base structures");
                        return ReturnResult;
                    }
                    tmpUnit = PlaceUnit(DefaultGenerator.UnitType_FactoryModule, tmpUnit.Pos, Map.UnitGroups[PlayerNum], 0);
                    if ( tmpUnit == null )
                    {
                        ReturnResult.ProblemAdd("No room for module.");
                        return ReturnResult;
                    }
                }
                tmpUnit = PlaceUnitNear(DefaultGenerator.UnitType_CyborgFactory, PlayerBases[A].Pos, Map.UnitGroups[PlayerNum], 3, 0, BasePlaceRange);
                if ( tmpUnit == null )
                {
                    ReturnResult.ProblemAdd("No room for base structures");
                    return ReturnResult;
                }
                for ( B = 1; B <= BaseTruckCount; B++ )
                {
                    tmpUnit = PlaceUnitNear(DefaultGenerator.UnitType_Truck, PlayerBases[A].Pos, Map.UnitGroups[PlayerNum], 2, 0, BasePlaceRange);
                    if ( tmpUnit == null )
                    {
                        ReturnResult.ProblemAdd("No room for trucks");
                        return ReturnResult;
                    }
                }
            }
            for ( A = 0; A <= PassageNodeCount - 1; A++ )
            {
                for ( D = 0; D <= SymmetryBlockCount - 1; D++ )
                {
                    for ( B = 0; B <= PassageNodes[D, A].OilCount - 1; B++ )
                    {
                        if ( PassageNodes[D, A].PlayerBaseNum >= 0 )
                        {
                            tmpUnit = PlaceUnitNear(DefaultGenerator.UnitType_OilResource, PassageNodes[D, A].Pos, Map.ScavengerUnitGroup, 2, 0, BasePlaceRange);
                        }
                        else
                        {
                            tmpUnit = PlaceUnitNear(DefaultGenerator.UnitType_OilResource, PassageNodes[D, A].Pos, Map.ScavengerUnitGroup, 2, 0, FeaturePlaceRange);
                        }
                        if ( tmpUnit == null )
                        {
                            ReturnResult.ProblemAdd("No room for oil.");
                            return ReturnResult;
                        }
                        //flatten ground underneath
                        TilePos.X = Conversion.Int(tmpUnit.Pos.Horizontal.X / App.TerrainGridSpacing);
                        TilePos.Y = (int)(Conversion.Int(tmpUnit.Pos.Horizontal.Y / App.TerrainGridSpacing));
                        AverageHeight =
                            (byte)
                                (((Terrain.Vertices[TilePos.X, TilePos.Y].Height) + (Terrain.Vertices[TilePos.X + 1, TilePos.Y].Height) +
                                  (Terrain.Vertices[TilePos.X, TilePos.Y + 1].Height) + Terrain.Vertices[TilePos.X + 1, TilePos.Y + 1].Height) / 4.0D);
                        Terrain.Vertices[TilePos.X, TilePos.Y].Height = AverageHeight;
                        Terrain.Vertices[TilePos.X + 1, TilePos.Y].Height = AverageHeight;
                        Terrain.Vertices[TilePos.X, TilePos.Y + 1].Height = AverageHeight;
                        Terrain.Vertices[TilePos.X + 1, TilePos.Y + 1].Height = AverageHeight;
                        Map.SectorGraphicsChanges.TileChanged(TilePos);
                        Map.SectorUnitHeightsChanges.TileChanged(TilePos);
                        Map.SectorTerrainUndoChanges.TileChanged(TilePos);
                        tmpUnit.Pos.Altitude = AverageHeight * Map.HeightMultiplier;
                        if ( PassageNodes[D, A].PlayerBaseNum >= 0 )
                        {
                            //place base derrick
                            tmpUnit = PlaceUnit(DefaultGenerator.UnitType_Derrick, tmpUnit.Pos, Map.UnitGroups[PassageNodes[D, A].PlayerBaseNum], 0);
                            if ( tmpUnit == null )
                            {
                                ReturnResult.ProblemAdd("No room for derrick.");
                                return ReturnResult;
                            }
                        }
                    }
                }
            }

            //feature clusters
            for ( A = 0; A <= PassageNodeCount - 1; A++ )
            {
                for ( D = 0; D <= SymmetryBlockCount - 1; D++ )
                {
                    if ( PassageNodes[D, A].PlayerBaseNum < 0 && !PassageNodes[D, A].IsOnBorder )
                    {
                        PassageNodes[D, A].HasFeatureCluster = VBMath.Rnd() < FeatureClusterChance;
                    }
                }
            }

            UInt32 RandNum = 0;
            UInt32 uintTemp = 0;
            PathfinderNode tmpNode = default(PathfinderNode);
            int E = 0;
            sXY_int Footprint = new sXY_int();
            int MissingUnitCount = 0;
            int Rotation = 0;

            if ( GenerateTileset.ClusteredUnitChanceTotal > 0 )
            {
                for ( A = 0; A <= PassageNodeCount - 1; A++ )
                {
                    for ( D = 0; D <= SymmetryBlockCount - 1; D++ )
                    {
                        if ( PassageNodes[D, A].HasFeatureCluster )
                        {
                            Count = FeatureClusterMinUnits +
                                    Convert.ToInt32(Conversion.Int(VBMath.Rnd() * (FeatureClusterMaxUnits - FeatureClusterMinUnits + 1)));
                            for ( B = 1; B <= Count; B++ )
                            {
                                RandNum = (uint)(Conversion.Int(VBMath.Rnd() * GenerateTileset.ClusteredUnitChanceTotal));
                                uintTemp = 0;
                                for ( C = 0; C <= GenerateTileset.ClusteredUnitCount - 1; C++ )
                                {
                                    uintTemp += GenerateTileset.ClusteredUnits[C].Chance;
                                    if ( RandNum < uintTemp )
                                    {
                                        break;
                                    }
                                }
                                Rotation = 0;
                                Footprint = GenerateTileset.ClusteredUnits[C].Type.get_GetFootprintSelected(Rotation);
                                E = ((int)(Math.Ceiling((decimal)(Math.Max(Footprint.X, Footprint.Y) / 2.0F)))) + 1;
                                tmpUnit = PlaceUnitNear(GenerateTileset.ClusteredUnits[C].Type, PassageNodes[D, A].Pos, Map.ScavengerUnitGroup, E, Rotation,
                                    FeaturePlaceRange);
                                if ( tmpUnit == null )
                                {
                                    MissingUnitCount += Count - B + 1;
                                    break;
                                }
                            }
                        }
                    }
                }
                if ( MissingUnitCount > 0 )
                {
                    ReturnResult.WarningAdd("Not enough space for " + Convert.ToString(MissingUnitCount) + " clustered objects.");
                }
            }

            if ( TilePathMap.get_GetNodeLayer(TilePathMap.GetNodeLayerCount - 1).GetNodeCount != 1 )
            {
                ReturnResult.ProblemAdd("Error: bad node count on top layer!");
                return ReturnResult;
            }

            if ( GenerateTileset.ScatteredUnitChanceTotal > 0 )
            {
                for ( A = 1; A <= FeatureScatterCount; A++ )
                {
                    RandNum = (uint)(Conversion.Int(VBMath.Rnd() * GenerateTileset.ScatteredUnitChanceTotal));
                    uintTemp = 0;
                    for ( C = 0; C <= GenerateTileset.ScatteredUnitCount - 1; C++ )
                    {
                        uintTemp += GenerateTileset.ScatteredUnits[C].Chance;
                        if ( RandNum < uintTemp )
                        {
                            break;
                        }
                    }
                    Rotation = 0;
                    Footprint = GenerateTileset.ScatteredUnits[C].Type.get_GetFootprintSelected(Rotation);
                    B = FeatureScatterGap + (int)(Math.Ceiling((decimal)(Math.Max(Footprint.X, Footprint.Y) / 2.0F)));
                    tmpNode = GetRandomChildNode(TilePathMap.get_GetNodeLayer(TilePathMap.GetNodeLayerCount - 1).get_GetNode(0), B);
                    if ( tmpNode == null )
                    {
                        break;
                    }
                    else
                    {
                        clsNodeTag NodeTag = (clsNodeTag)tmpNode.Tag;
                        if ( PlaceUnitNear(GenerateTileset.ScatteredUnits[C].Type, NodeTag.Pos, Map.ScavengerUnitGroup, B, Rotation, FeaturePlaceRange) == null )
                        {
                            break;
                        }
                    }
                }
                if ( A < FeatureScatterCount + 1 )
                {
                    ReturnResult.WarningAdd("Only enough space for " + Convert.ToString(A - 1) + " scattered objects.");
                }
            }

            return ReturnResult;
        }