public static clsResult BitmapIsGLCompatible(Bitmap BitmapToCheck) { clsResult ReturnResult = new clsResult("Compatability check"); if ( !App.SizeIsPowerOf2(BitmapToCheck.Width) ) { ReturnResult.WarningAdd("Image width is not a power of 2."); } if ( !App.SizeIsPowerOf2(BitmapToCheck.Height) ) { ReturnResult.WarningAdd("Image height is not a power of 2."); } if ( BitmapToCheck.Width != BitmapToCheck.Height ) { ReturnResult.WarningAdd("Image is not square."); } return ReturnResult; }
public void btnCompileCampaign_Click(Object sender, EventArgs e) { clsResult ReturnResult = new clsResult("Compile campaign"); int A = 0; SaveToMap(); A = ValidateMap_WaterTris(); if ( A > 0 ) { ReturnResult.WarningAdd(A + " water tiles have an incorrect triangle direction. There might be in-game graphical glitches on those tiles."); } ReturnResult.Add(ValidateMap()); ReturnResult.Add(ValidateMap_UnitPositions()); string MapName = ""; int TypeNum = 0; MapName = txtName.Text; if ( MapName.Length < 1 ) { ReturnResult.ProblemAdd("Enter a name for the campaign files."); } TypeNum = cboCampType.SelectedIndex; if ( TypeNum < 0 | TypeNum > 2 ) { ReturnResult.ProblemAdd("Select a campaign type."); } if ( ReturnResult.HasProblems ) { App.ShowWarnings(ReturnResult); return; } FolderBrowserDialog CompileCampDialog = new FolderBrowserDialog(); if ( CompileCampDialog.ShowDialog(this) != DialogResult.OK ) { return; } clsMap.sWrite_WZ_Args WriteWZArgs = new clsMap.sWrite_WZ_Args(); WriteWZArgs.MapName = MapName; WriteWZArgs.Path = CompileCampDialog.SelectedPath; WriteWZArgs.Overwrite = false; SetScrollLimits(WriteWZArgs.ScrollMin, WriteWZArgs.ScrollMax); WriteWZArgs.Campaign = new clsMap.sWrite_WZ_Args.clsCampaign(); WriteWZArgs.Campaign.GAMType = (uint)TypeNum; WriteWZArgs.CompileType = clsMap.sWrite_WZ_Args.enumCompileType.Campaign; ReturnResult.Add(Map.Write_WZ(WriteWZArgs)); App.ShowWarnings(ReturnResult); if ( !ReturnResult.HasWarnings ) { Close(); } }
public clsResult ReadFile(StreamReader File) { clsResult ReturnResult = new clsResult(""); int InvalidLineCount = 0; int CurrentEntryNum = -1; string LineText = null; int A = 0; do { LineText = File.ReadLine(); if ( LineText == null ) { break; } LineText = LineText.Trim(); A = LineText.IndexOf('#'); if ( A >= 0 ) { LineText = Strings.Left(LineText, A).Trim(); } if ( LineText.Length >= 1 ) { A = LineText.IndexOf('='); if ( A >= 0 ) { CreateProperty(LineText.Substring(0, A).ToLower().Trim(), LineText.Substring(A + 1, LineText.Length - A - 1).Trim()); } else { InvalidLineCount++; } } else if ( LineText.Length > 0 ) { InvalidLineCount++; } } while ( true ); Properties.RemoveBuffer(); if ( InvalidLineCount > 0 ) { ReturnResult.WarningAdd("There were " + Convert.ToString(InvalidLineCount) + " invalid lines that were ignored."); } return ReturnResult; }
private clsResult Serialize_WZ_Map(Stream stream) { var returnResult = new clsResult("Serializing game.map", false); logger.Info("Serializing game.map"); var fileMAP = new BinaryWriter(stream, App.ASCIIEncoding); var x = 0; var y = 0; IOUtil.WriteText(fileMAP, false, "map "); fileMAP.Write(10U); fileMAP.Write((uint)map.Terrain.TileSize.X); fileMAP.Write((uint)map.Terrain.TileSize.Y); byte flip = 0; byte rotation = 0; var doFlipX = default(bool); var invalidTileCount = 0; var textureNum = 0; 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 doFlipX); flip = 0; if ( map.Terrain.Tiles[x, y].Tri ) { flip += 8; } flip += (byte)(rotation * 16); if ( doFlipX ) { flip += 128; } textureNum = map.Terrain.Tiles[x, y].Texture.TextureNum; if ( textureNum < 0 | textureNum > 255 ) { textureNum = 0; if ( invalidTileCount < 16 ) { returnResult.WarningAdd(string.Format("Tile texture number {0} is invalid on tile {1}, {2} and was compiled as texture number {3}.", map.Terrain.Tiles[x, y].Texture.TextureNum, x, y, textureNum)); } invalidTileCount++; } fileMAP.Write((byte)textureNum); fileMAP.Write(flip); fileMAP.Write(map.Terrain.Vertices[x, y].Height); } } if ( invalidTileCount > 0 ) { returnResult.WarningAdd(string.Format("{0} tile texture numbers were invalid.", invalidTileCount)); } fileMAP.Write(1U); //gateway version fileMAP.Write((uint)map.Gateways.Count); foreach ( var gateway in map.Gateways ) { fileMAP.Write((byte)(MathUtil.Clamp_int(gateway.PosA.X, 0, 255))); fileMAP.Write((byte)(MathUtil.Clamp_int(gateway.PosA.Y, 0, 255))); fileMAP.Write((byte)(MathUtil.Clamp_int(gateway.PosB.X, 0, 255))); fileMAP.Write((byte)(MathUtil.Clamp_int(gateway.PosB.Y, 0, 255))); } fileMAP.Flush(); return returnResult; }
public clsResult Serialize_FMap_Objects(IniWriter File) { clsResult ReturnResult = new clsResult("Serializing objects"); int A = 0; clsUnit Unit = default(clsUnit); clsDroidDesign Droid = default(clsDroidDesign); int WarningCount = 0; string Text = null; try { for ( A = 0; A <= Units.Count - 1; A++ ) { Unit = Units[A]; File.AppendSectionName(IOUtil.InvariantToString(A)); switch ( Unit.Type.Type ) { case clsUnitType.enumType.Feature: File.AppendProperty("Type", "Feature, " + ((clsFeatureType)Unit.Type).Code); break; case clsUnitType.enumType.PlayerStructure: clsStructureType StructureType = (clsStructureType)Unit.Type; File.AppendProperty("Type", "Structure, " + StructureType.Code); if ( StructureType.WallLink.IsConnected ) { File.AppendProperty("WallType", IOUtil.InvariantToString(StructureType.WallLink.ArrayPosition)); } break; case clsUnitType.enumType.PlayerDroid: Droid = (clsDroidDesign)Unit.Type; if ( Droid.IsTemplate ) { File.AppendProperty("Type", "DroidTemplate, " + ((clsDroidTemplate)Unit.Type).Code); } else { File.AppendProperty("Type", "DroidDesign"); if ( Droid.TemplateDroidType != null ) { File.AppendProperty("DroidType", Droid.TemplateDroidType.TemplateCode); } if ( Droid.Body != null ) { File.AppendProperty("Body", Droid.Body.Code); } if ( Droid.Propulsion != null ) { File.AppendProperty("Propulsion", Droid.Propulsion.Code); } File.AppendProperty("TurretCount", IOUtil.InvariantToString(Droid.TurretCount)); if ( Droid.Turret1 != null ) { if ( Droid.Turret1.GetTurretTypeName(ref Text) ) { File.AppendProperty("Turret1", Text + ", " + Droid.Turret1.Code); } } if ( Droid.Turret2 != null ) { if ( Droid.Turret2.GetTurretTypeName(ref Text) ) { File.AppendProperty("Turret2", Text + ", " + Droid.Turret2.Code); } } if ( Droid.Turret3 != null ) { if ( Droid.Turret3.GetTurretTypeName(ref Text) ) { File.AppendProperty("Turret3", Text + ", " + Droid.Turret3.Code); } } } break; default: WarningCount++; break; } File.AppendProperty("ID", IOUtil.InvariantToString(Unit.ID)); File.AppendProperty("Priority", IOUtil.InvariantToString(Unit.SavePriority)); File.AppendProperty("Pos", IOUtil.InvariantToString(Unit.Pos.Horizontal.X) + ", " + IOUtil.InvariantToString(Unit.Pos.Horizontal.Y)); File.AppendProperty("Heading", IOUtil.InvariantToString(Unit.Rotation)); File.AppendProperty("UnitGroup", Unit.UnitGroup.GetFMapINIPlayerText()); if ( Unit.Health < 1.0D ) { File.AppendProperty("Health", IOUtil.InvariantToString(Unit.Health)); } if ( Unit.Label != null ) { File.AppendProperty("ScriptLabel", Unit.Label); } File.Gap_Append(); } } catch ( Exception ex ) { ReturnResult.ProblemAdd(ex.Message); } if ( WarningCount > 0 ) { ReturnResult.WarningAdd("Error: " + Convert.ToString(WarningCount) + " units were of an unhandled type."); } return ReturnResult; }
public clsResult GenerateMipMaps(string SlashPath, string strTile, BitmapGLTexture BitmapTextureArgs, int TileNum) { var ReturnResult = new clsResult("Generating mipmaps", false); logger.Info("Generating mipmaps"); var GraphicPath = ""; var PixX = 0; var PixY = 0; var PixelColorA = new Color(); var PixelColorB = new Color(); var PixelColorC = new Color(); var PixelColorD = new Color(); var X1 = 0; var Y1 = 0; var X2 = 0; var Y2 = 0; var Red = 0; var Green = 0; var Blue = 0; var Bitmap8 = default(Bitmap); var Bitmap4 = default(Bitmap); var Bitmap2 = default(Bitmap); var Bitmap1 = default(Bitmap); Bitmap Bitmap = null; var Result = new sResult(); //-------- 64 -------- GraphicPath = SlashPath + Name + "-64" + Convert.ToString(App.PlatformPathSeparator) + strTile; Result = BitmapUtil.LoadBitmap(GraphicPath, ref Bitmap); if ( !Result.Success ) { ReturnResult.WarningAdd("Unable to load tile graphic: " + Result.Problem); return ReturnResult; } if ( Bitmap.Width != 64 | Bitmap.Height != 64 ) { ReturnResult.WarningAdd("Tile graphic " + GraphicPath + " from tileset " + Name + " is not 64x64."); return ReturnResult; } BitmapTextureArgs.Texture = Bitmap; BitmapTextureArgs.MipMapLevel = 1; BitmapTextureArgs.Perform(); //-------- 32 -------- GraphicPath = SlashPath + Name + "-32" + Convert.ToString(App.PlatformPathSeparator) + strTile; Result = BitmapUtil.LoadBitmap(GraphicPath, ref Bitmap); if ( !Result.Success ) { ReturnResult.WarningAdd("Unable to load tile graphic: " + Result.Problem); return ReturnResult; } if ( Bitmap.Width != 32 | Bitmap.Height != 32 ) { ReturnResult.WarningAdd("Tile graphic " + GraphicPath + " from tileset " + Name + " is not 32x32."); return ReturnResult; } BitmapTextureArgs.Texture = Bitmap; BitmapTextureArgs.MipMapLevel = 2; BitmapTextureArgs.Perform(); //-------- 16 -------- GraphicPath = SlashPath + Name + "-16" + Convert.ToString(App.PlatformPathSeparator) + strTile; Result = BitmapUtil.LoadBitmap(GraphicPath, ref Bitmap); if ( !Result.Success ) { ReturnResult.WarningAdd("Unable to load tile graphic: " + Result.Problem); return ReturnResult; } if ( Bitmap.Width != 16 | Bitmap.Height != 16 ) { ReturnResult.WarningAdd("Tile graphic " + GraphicPath + " from tileset " + Name + " is not 16x16."); return ReturnResult; } BitmapTextureArgs.Texture = Bitmap; BitmapTextureArgs.MipMapLevel = 3; BitmapTextureArgs.Perform(); //-------- 8 -------- Bitmap8 = new Bitmap(8, 8, System.Drawing.Imaging.PixelFormat.Format32bppArgb); for ( PixY = 0; PixY <= 7; PixY++ ) { Y1 = PixY * 2; Y2 = Y1 + 1; for ( PixX = 0; PixX <= 7; PixX++ ) { X1 = PixX * 2; X2 = X1 + 1; PixelColorA = Bitmap.GetPixel(X1, Y1); PixelColorB = Bitmap.GetPixel(X2, Y1); PixelColorC = Bitmap.GetPixel(X1, Y2); PixelColorD = Bitmap.GetPixel(X2, Y2); Red = Convert.ToInt32(((PixelColorA.R) + PixelColorB.R + PixelColorC.R + PixelColorD.R) / 4.0F); Green = Convert.ToInt32(((PixelColorA.G) + PixelColorB.G + PixelColorC.G + PixelColorD.G) / 4.0F); Blue = Convert.ToInt32(((PixelColorA.B) + PixelColorB.B + PixelColorC.B + PixelColorD.B) / 4.0F); Bitmap8.SetPixel(PixX, PixY, ColorTranslator.FromOle(ColorUtil.OSRGB(Red, Green, Blue))); } } BitmapTextureArgs.Texture = Bitmap8; BitmapTextureArgs.MipMapLevel = 4; BitmapTextureArgs.Perform(); //-------- 4 -------- Bitmap = Bitmap8; Bitmap4 = new Bitmap(4, 4, System.Drawing.Imaging.PixelFormat.Format32bppArgb); for ( PixY = 0; PixY <= 3; PixY++ ) { Y1 = PixY * 2; Y2 = Y1 + 1; for ( PixX = 0; PixX <= 3; PixX++ ) { X1 = PixX * 2; X2 = X1 + 1; PixelColorA = Bitmap.GetPixel(X1, Y1); PixelColorB = Bitmap.GetPixel(X2, Y1); PixelColorC = Bitmap.GetPixel(X1, Y2); PixelColorD = Bitmap.GetPixel(X2, Y2); Red = Convert.ToInt32(((PixelColorA.R) + PixelColorB.R + PixelColorC.R + PixelColorD.R) / 4.0F); Green = Convert.ToInt32(((PixelColorA.G) + PixelColorB.G + PixelColorC.G + PixelColorD.G) / 4.0F); Blue = Convert.ToInt32(((PixelColorA.B) + PixelColorB.B + PixelColorC.B + PixelColorD.B) / 4.0F); Bitmap4.SetPixel(PixX, PixY, ColorTranslator.FromOle(ColorUtil.OSRGB(Red, Green, Blue))); } } BitmapTextureArgs.Texture = Bitmap4; BitmapTextureArgs.MipMapLevel = 5; BitmapTextureArgs.Perform(); //-------- 2 -------- Bitmap = Bitmap4; Bitmap2 = new Bitmap(2, 2, System.Drawing.Imaging.PixelFormat.Format32bppArgb); for ( PixY = 0; PixY <= 1; PixY++ ) { Y1 = PixY * 2; Y2 = Y1 + 1; for ( PixX = 0; PixX <= 1; PixX++ ) { X1 = PixX * 2; X2 = X1 + 1; PixelColorA = Bitmap.GetPixel(X1, Y1); PixelColorB = Bitmap.GetPixel(X2, Y1); PixelColorC = Bitmap.GetPixel(X1, Y2); PixelColorD = Bitmap.GetPixel(X2, Y2); Red = Convert.ToInt32(((PixelColorA.R) + PixelColorB.R + PixelColorC.R + PixelColorD.R) / 4.0F); Green = Convert.ToInt32(((PixelColorA.G) + PixelColorB.G + PixelColorC.G + PixelColorD.G) / 4.0F); Blue = Convert.ToInt32(((PixelColorA.B) + PixelColorB.B + PixelColorC.B + PixelColorD.B) / 4.0F); Bitmap2.SetPixel(PixX, PixY, ColorTranslator.FromOle(ColorUtil.OSRGB(Red, Green, Blue))); } } BitmapTextureArgs.Texture = Bitmap2; BitmapTextureArgs.MipMapLevel = 6; BitmapTextureArgs.Perform(); //-------- 1 -------- Bitmap = Bitmap2; Bitmap1 = new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format32bppArgb); PixX = 0; PixY = 0; Y1 = PixY * 2; Y2 = Y1 + 1; X1 = PixX * 2; X2 = X1 + 1; PixelColorA = Bitmap.GetPixel(X1, Y1); PixelColorB = Bitmap.GetPixel(X2, Y1); PixelColorC = Bitmap.GetPixel(X1, Y2); PixelColorD = Bitmap.GetPixel(X2, Y2); Red = Convert.ToInt32(((PixelColorA.R) + PixelColorB.R + PixelColorC.R + PixelColorD.R) / 4.0F); Green = Convert.ToInt32(((PixelColorA.G) + PixelColorB.G + PixelColorC.G + PixelColorD.G) / 4.0F); Blue = Convert.ToInt32(((PixelColorA.B) + PixelColorB.B + PixelColorC.B + PixelColorD.B) / 4.0F); Bitmap1.SetPixel(PixX, PixY, ColorTranslator.FromOle(ColorUtil.OSRGB(Red, Green, Blue))); BitmapTextureArgs.Texture = Bitmap1; BitmapTextureArgs.MipMapLevel = 7; BitmapTextureArgs.Perform(); return ReturnResult; }
// 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; }
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; }
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; }
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; }
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; }
public clsResult Translate(int SectionNum, SectionTranslator Translator, ErrorCount ErrorCount) { clsResult ReturnResult = new clsResult("Section " + Name); int A = 0; TranslatorResult TranslatorResult = default(TranslatorResult); for ( A = 0; A <= Properties.Count - 1; A++ ) { TranslatorResult = Translator.Translate(SectionNum, Properties[A]); switch ( TranslatorResult ) { case Ini.TranslatorResult.NameUnknown: if ( ErrorCount.NameErrorCount < 16 ) { ReturnResult.WarningAdd("Property name " + Convert.ToString(ControlChars.Quote) + Properties[A].Name + Convert.ToString(ControlChars.Quote) + " is unknown."); } ErrorCount.NameErrorCount++; break; case Ini.TranslatorResult.ValueInvalid: if ( ErrorCount.ValueErrorCount < 16 ) { ReturnResult.WarningAdd("Value " + Convert.ToString(ControlChars.Quote) + Properties[A].Value + Convert.ToString(ControlChars.Quote) + " for property name " + Convert.ToString(ControlChars.Quote) + Properties[A].Name + Convert.ToString(ControlChars.Quote) + " is not valid."); } ErrorCount.ValueErrorCount++; break; } } return ReturnResult; }
public clsResult Translate(Translator Translator) { clsResult ReturnResult = new clsResult("Section " + Name); int A = 0; TranslatorResult TranslatorResult = default(TranslatorResult); ErrorCount ErrorCount = new ErrorCount(); ErrorCount.NameWarningCountMax = 16; ErrorCount.ValueWarningCountMax = 16; for ( A = 0; A <= Properties.Count - 1; A++ ) { TranslatorResult = Translator.Translate(Properties[A]); switch ( TranslatorResult ) { case TranslatorResult.NameUnknown: if ( ErrorCount.NameErrorCount < 16 ) { ReturnResult.WarningAdd("Property name " + Convert.ToString(ControlChars.Quote) + Properties[A].Name + Convert.ToString(ControlChars.Quote) + " is unknown."); } ErrorCount.NameErrorCount++; break; case TranslatorResult.ValueInvalid: if ( ErrorCount.ValueErrorCount < 16 ) { ReturnResult.WarningAdd("Value " + Convert.ToString(ControlChars.Quote) + Properties[A].Value + Convert.ToString(ControlChars.Quote) + " for property name " + Convert.ToString(ControlChars.Quote) + Properties[A].Name + Convert.ToString(ControlChars.Quote) + " is not valid."); } ErrorCount.ValueErrorCount++; break; } } if ( ErrorCount.NameErrorCount > ErrorCount.NameWarningCountMax ) { ReturnResult.WarningAdd("There were " + Convert.ToString(ErrorCount.NameErrorCount) + " unknown property names that were ignored."); } if ( ErrorCount.ValueErrorCount > ErrorCount.ValueWarningCountMax ) { ReturnResult.WarningAdd("There were " + Convert.ToString(ErrorCount.ValueErrorCount) + " invalid values that were ignored."); } return ReturnResult; }
public clsResult Serialize_FMap_TileTexture(BinaryWriter File) { clsResult ReturnResult = new clsResult("Serializing tile textures"); int X = 0; int Y = 0; int ErrorCount = 0; int Value = 0; try { for ( Y = 0; Y <= Terrain.TileSize.Y - 1; Y++ ) { for ( X = 0; X <= Terrain.TileSize.X - 1; X++ ) { Value = Convert.ToInt32(Terrain.Tiles[X, Y].Texture.TextureNum + 1); if ( Value < 0 | Value > 255 ) { ErrorCount++; Value = 0; } File.Write((byte)Value); } } } catch ( Exception ex ) { ReturnResult.ProblemAdd(ex.Message); } if ( ErrorCount > 0 ) { ReturnResult.WarningAdd(ErrorCount + " tiles had an invalid texture number."); } return ReturnResult; }
public clsResult Serialize_FMap_TileCliff(BinaryWriter File) { clsResult ReturnResult = new clsResult("Serializing tile cliffs"); int X = 0; int Y = 0; int Value = 0; int DownSideValue = 0; int ErrorCount = 0; try { for ( Y = 0; Y <= Terrain.TileSize.Y - 1; Y++ ) { for ( X = 0; X <= Terrain.TileSize.X - 1; X++ ) { Value = 0; if ( Terrain.Tiles[X, Y].Tri ) { if ( Terrain.Tiles[X, Y].TriTopLeftIsCliff ) { Value += 2; } if ( Terrain.Tiles[X, Y].TriBottomRightIsCliff ) { Value++; } } else { if ( Terrain.Tiles[X, Y].TriBottomLeftIsCliff ) { Value += 2; } if ( Terrain.Tiles[X, Y].TriTopRightIsCliff ) { Value++; } } if ( Terrain.Tiles[X, Y].Terrain_IsCliff ) { Value += 4; } if ( TileUtil.IdenticalTileDirections(Terrain.Tiles[X, Y].DownSide, TileUtil.None) ) { DownSideValue = 0; } else if ( TileUtil.IdenticalTileDirections(Terrain.Tiles[X, Y].DownSide, TileUtil.Top) ) { DownSideValue = 1; } else if ( TileUtil.IdenticalTileDirections(Terrain.Tiles[X, Y].DownSide, TileUtil.Left) ) { DownSideValue = 2; } else if ( TileUtil.IdenticalTileDirections(Terrain.Tiles[X, Y].DownSide, TileUtil.Right) ) { DownSideValue = 3; } else if ( TileUtil.IdenticalTileDirections(Terrain.Tiles[X, Y].DownSide, TileUtil.Bottom) ) { DownSideValue = 4; } else { ErrorCount++; DownSideValue = 0; } Value += DownSideValue * 8; File.Write((byte)Value); } } } catch ( Exception ex ) { ReturnResult.ProblemAdd(ex.Message); } if ( ErrorCount > 0 ) { ReturnResult.WarningAdd(ErrorCount + " tiles had an invalid cliff down side."); } return ReturnResult; }
public clsResult Serialize_FMap_Roads(BinaryWriter File) { clsResult ReturnResult = new clsResult("Serializing roads"); int X = 0; int Y = 0; int Value = 0; int ErrorCount = 0; try { for ( Y = 0; Y <= Terrain.TileSize.Y; Y++ ) { for ( X = 0; X <= Terrain.TileSize.X - 1; X++ ) { if ( Terrain.SideH[X, Y].Road == null ) { Value = 0; } else if ( Terrain.SideH[X, Y].Road.Num < 0 ) { ErrorCount++; Value = 0; } else { Value = Convert.ToInt32(Terrain.SideH[X, Y].Road.Num + 1); if ( Value > 255 ) { ErrorCount++; Value = 0; } } File.Write((byte)Value); } } for ( Y = 0; Y <= Terrain.TileSize.Y - 1; Y++ ) { for ( X = 0; X <= Terrain.TileSize.X; X++ ) { if ( Terrain.SideV[X, Y].Road == null ) { Value = 0; } else if ( Terrain.SideV[X, Y].Road.Num < 0 ) { ErrorCount++; Value = 0; } else { Value = Convert.ToInt32(Terrain.SideV[X, Y].Road.Num + 1); if ( Value > 255 ) { ErrorCount++; Value = 0; } } File.Write((byte)Value); } } } catch ( Exception ex ) { ReturnResult.ProblemAdd(ex.Message); } if ( ErrorCount > 0 ) { ReturnResult.WarningAdd(ErrorCount + " sides had an invalid road number."); } return ReturnResult; }
private clsResult Serialize_WZ_StructuresINI(IniWriter File, int PlayerCount) { var ReturnResult = new clsResult("Serializing structures INI", false); logger.Info("Serializing structures INI"); var structureTypeBase = default(StructureTypeBase); var unitModuleCount = new int[map.Units.Count]; var sectorNum = new XYInt(); var otherStructureTypeBase = default(StructureTypeBase); var otherUnit = default(clsUnit); var moduleMin = new XYInt(); var moduleMax = new XYInt(); var footprint = new XYInt(); var A = 0; var underneathTypes = new StructureTypeBase.enumStructureType[2]; var underneathTypeCount = 0; var badModuleCount = 0; var priorityOrder = new clsObjectPriorityOrderList(); foreach ( var unit in map.Units.Where(d => d.TypeBase.Type == UnitType.PlayerStructure) ) { structureTypeBase = (StructureTypeBase)unit.TypeBase; switch ( structureTypeBase.StructureType ) { case StructureTypeBase.enumStructureType.FactoryModule: underneathTypes[0] = StructureTypeBase.enumStructureType.Factory; underneathTypes[1] = StructureTypeBase.enumStructureType.VTOLFactory; underneathTypeCount = 2; break; case StructureTypeBase.enumStructureType.PowerModule: underneathTypes[0] = StructureTypeBase.enumStructureType.PowerGenerator; underneathTypeCount = 1; break; case StructureTypeBase.enumStructureType.ResearchModule: underneathTypes[0] = StructureTypeBase.enumStructureType.Research; underneathTypeCount = 1; break; default: underneathTypeCount = 0; break; } if ( underneathTypeCount == 0 ) { priorityOrder.SetItem(unit); priorityOrder.ActionPerform(); } else { // IS module. sectorNum = map.GetPosSectorNum(unit.Pos.Horizontal); clsUnit underneath = null; var connection = default(clsUnitSectorConnection); foreach ( var tempLoopVar_Connection in map.Sectors[sectorNum.X, sectorNum.Y].Units ) { connection = tempLoopVar_Connection; otherUnit = connection.Unit; if ( otherUnit.TypeBase.Type == UnitType.PlayerStructure ) { otherStructureTypeBase = (StructureTypeBase)otherUnit.TypeBase; if ( otherUnit.UnitGroup == unit.UnitGroup ) { for ( A = 0; A <= underneathTypeCount - 1; A++ ) { if ( otherStructureTypeBase.StructureType == underneathTypes[A] ) { break; } } if ( A < underneathTypeCount ) { footprint = otherStructureTypeBase.get_GetFootprintSelected(otherUnit.Rotation); moduleMin.X = otherUnit.Pos.Horizontal.X - (int)(footprint.X * Constants.TerrainGridSpacing / 2.0D); moduleMin.Y = otherUnit.Pos.Horizontal.Y - (int)(footprint.Y * Constants.TerrainGridSpacing / 2.0D); moduleMax.X = otherUnit.Pos.Horizontal.X + (int)(footprint.X * Constants.TerrainGridSpacing / 2.0D); moduleMax.Y = otherUnit.Pos.Horizontal.Y + (int)(footprint.Y * Constants.TerrainGridSpacing / 2.0D); if ( unit.Pos.Horizontal.X >= moduleMin.X & unit.Pos.Horizontal.X < moduleMax.X & unit.Pos.Horizontal.Y >= moduleMin.Y & unit.Pos.Horizontal.Y < moduleMax.Y ) { unitModuleCount[otherUnit.MapLink.ArrayPosition]++; underneath = otherUnit; break; } } } } } if ( underneath == null ) { badModuleCount++; } } } if ( badModuleCount > 0 ) { ReturnResult.WarningAdd(string.Format("{0} modules had no underlying structure.", badModuleCount)); } var tooManyModulesWarningCount = 0; var tooManyModulesWarningMaxCount = 16; var moduleCount = 0; var moduleLimit = 0; for ( A = 0; A <= priorityOrder.Result.Count - 1; A++ ) { var unit = priorityOrder.Result[A]; structureTypeBase = (StructureTypeBase)unit.TypeBase; if ( unit.ID <= 0 ) { ReturnResult.WarningAdd("Error. A structure\'s ID was zero. It was NOT saved. Delete and replace it to allow save."); } else { File.AddSection("structure_" + unit.ID.ToStringInvariant()); File.AddProperty("id", unit.ID.ToStringInvariant()); if ( unit.UnitGroup == map.ScavengerUnitGroup || (PlayerCount >= 0 & unit.UnitGroup.WZ_StartPos >= PlayerCount) ) { File.AddProperty("player", "scavenger"); } else { File.AddProperty("startpos", unit.UnitGroup.WZ_StartPos.ToStringInvariant()); } File.AddProperty("name", structureTypeBase.Code); if ( structureTypeBase.WallLink.IsConnected ) { File.AddProperty("wall/type", structureTypeBase.WallLink.ArrayPosition.ToStringInvariant()); } File.AddProperty("position", unit.GetINIPosition()); File.AddProperty("rotation", unit.GetINIRotation()); if ( unit.Health < 1.0D ) { File.AddProperty("health", unit.GetINIHealthPercent()); } switch ( structureTypeBase.StructureType ) { case StructureTypeBase.enumStructureType.Factory: moduleLimit = 2; break; case StructureTypeBase.enumStructureType.VTOLFactory: moduleLimit = 2; break; case StructureTypeBase.enumStructureType.PowerGenerator: moduleLimit = 1; break; case StructureTypeBase.enumStructureType.Research: moduleLimit = 1; break; default: moduleLimit = 0; break; } if ( unitModuleCount[unit.MapLink.ArrayPosition] > moduleLimit ) { moduleCount = moduleLimit; if ( tooManyModulesWarningCount < tooManyModulesWarningMaxCount ) { ReturnResult.WarningAdd(string.Format("Structure {0} at {1} has too many modules ({2})", structureTypeBase.GetDisplayTextCode(), unit.GetPosText(), unitModuleCount[unit.MapLink.ArrayPosition])); } tooManyModulesWarningCount++; } else { moduleCount = unitModuleCount[unit.MapLink.ArrayPosition]; } File.AddProperty("modules", moduleCount.ToStringInvariant()); } } if ( tooManyModulesWarningCount > tooManyModulesWarningMaxCount ) { ReturnResult.WarningAdd(string.Format("{0} structures had too many modules.", tooManyModulesWarningCount)); } return ReturnResult; }
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; }
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; }
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; }
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; }
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; }
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; }
private clsResult Serialize_WZ_DroidsINI(IniWriter ini, int playerCount) { var returnResult = new clsResult("Serializing droids INI", false); logger.Info("Serializing droids INI"); var droid = default(DroidDesign); var template = default(DroidTemplate); var text = ""; var unit = default(clsUnit); var asPartsNotTemplate = default(bool); var validDroid = false; var invalidPartCount = 0; var brain = default(Brain); foreach ( var tempLoopVar_Unit in map.Units ) { unit = tempLoopVar_Unit; if ( unit.TypeBase.Type == UnitType.PlayerDroid ) { droid = (DroidDesign)unit.TypeBase; validDroid = true; if ( unit.ID <= 0 ) { validDroid = false; returnResult.WarningAdd("Error. A droid\'s ID was zero. It was NOT saved. Delete and replace it to allow save."); } if ( droid.IsTemplate ) { template = (DroidTemplate)droid; asPartsNotTemplate = unit.PreferPartsOutput; } else { template = null; asPartsNotTemplate = true; } if ( asPartsNotTemplate ) { if ( droid.Body == null ) { validDroid = false; invalidPartCount++; } else if ( droid.Propulsion == null ) { validDroid = false; invalidPartCount++; } else if ( droid.TurretCount >= 1 ) { if ( droid.Turret1 == null ) { validDroid = false; invalidPartCount++; } } else if ( droid.TurretCount >= 2 ) { if ( droid.Turret2 == null ) { validDroid = false; invalidPartCount++; } else if ( droid.Turret2.TurretType != enumTurretType.Weapon ) { validDroid = false; invalidPartCount++; } } else if ( droid.TurretCount >= 3 && droid.Turret3 == null ) { if ( droid.Turret3 == null ) { validDroid = false; invalidPartCount++; } else if ( droid.Turret3.TurretType != enumTurretType.Weapon ) { validDroid = false; invalidPartCount++; } } } if ( validDroid ) { ini.AddSection("droid_" + unit.ID.ToStringInvariant()); ini.AddProperty("id", unit.ID.ToStringInvariant()); if ( unit.UnitGroup == map.ScavengerUnitGroup || (playerCount >= 0 & unit.UnitGroup.WZ_StartPos >= playerCount) ) { ini.AddProperty("player", "scavenger"); } else { ini.AddProperty("startpos", unit.UnitGroup.WZ_StartPos.ToStringInvariant()); } if ( asPartsNotTemplate ) { ini.AddProperty("name", droid.GenerateName()); } else { template = (DroidTemplate)droid; ini.AddProperty("template", template.Code); } ini.AddProperty("position", unit.GetINIPosition()); ini.AddProperty("rotation", unit.GetINIRotation()); if ( unit.Health < 1.0D ) { ini.AddProperty("health", unit.GetINIHealthPercent()); } if ( asPartsNotTemplate ) { ini.AddProperty("droidType", Convert.ToInt32(droid.GetDroidType()).ToStringInvariant()); if ( droid.TurretCount == 0 ) { text = "0"; } else { if ( droid.Turret1.TurretType == enumTurretType.Brain ) { if ( ((Brain)droid.Turret1).Weapon == null ) { text = "0"; } else { text = "1"; } } else { if ( droid.Turret1.TurretType == enumTurretType.Weapon ) { text = droid.TurretCount.ToStringInvariant(); } else { text = "0"; } } } ini.AddProperty("weapons", text); ini.AddProperty("parts\\body", droid.Body.Code); ini.AddProperty("parts\\propulsion", droid.Propulsion.Code); ini.AddProperty("parts\\sensor", droid.GetSensorCode()); ini.AddProperty("parts\\construct", droid.GetConstructCode()); ini.AddProperty("parts\\repair", droid.GetRepairCode()); ini.AddProperty("parts\\brain", droid.GetBrainCode()); ini.AddProperty("parts\\ecm", droid.GetECMCode()); if ( droid.TurretCount >= 1 ) { if ( droid.Turret1.TurretType == enumTurretType.Weapon ) { ini.AddProperty("parts\\weapon\\1", droid.Turret1.Code); if ( droid.TurretCount >= 2 ) { if ( droid.Turret2.TurretType == enumTurretType.Weapon ) { ini.AddProperty("parts\\weapon\\2", droid.Turret2.Code); if ( droid.TurretCount >= 3 ) { if ( droid.Turret3.TurretType == enumTurretType.Weapon ) { ini.AddProperty("parts\\weapon\\3", droid.Turret3.Code); } } } } } else if ( droid.Turret1.TurretType == enumTurretType.Brain ) { brain = (Brain)droid.Turret1; if ( brain.Weapon == null ) { text = "ZNULLWEAPON"; } else { text = brain.Weapon.Code; } ini.AddProperty("parts\\weapon\\1", text); } } } } } } if ( invalidPartCount > 0 ) { returnResult.WarningAdd(string.Format("There were {0} droids with parts missing. They were not saved.", invalidPartCount)); } return returnResult; }
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; }
public clsResult Read_FMap_TileTexture(BinaryReader File) { clsResult ReturnResult = new clsResult("Reading tile textures"); int X = 0; int Y = 0; byte byteTemp = 0; try { 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; } } } catch ( Exception ex ) { ReturnResult.ProblemAdd(ex.Message); return ReturnResult; } if ( File.PeekChar() >= 0 ) { ReturnResult.WarningAdd("There were unread bytes at the end of the file."); } return ReturnResult; }
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; }
private clsResult Serialize_WZ_LabelsINI(IniWriter File, int PlayerCount) { var returnResult = new clsResult("Serializing labels INI", false); logger.Info("Serializing labels INI"); try { var scriptPosition = default(clsScriptPosition); foreach ( var tempLoopVar_ScriptPosition in map.ScriptPositions ) { scriptPosition = tempLoopVar_ScriptPosition; scriptPosition.WriteWZ(File); } var ScriptArea = default(clsScriptArea); foreach ( var tempLoopVar_ScriptArea in map.ScriptAreas ) { ScriptArea = tempLoopVar_ScriptArea; ScriptArea.WriteWZ(File); } if ( PlayerCount >= 0 ) //not an FMap { var Unit = default(clsUnit); foreach ( var tempLoopVar_Unit in map.Units ) { Unit = tempLoopVar_Unit; Unit.WriteWZLabel(File, PlayerCount); } } } catch ( Exception ex ) { returnResult.WarningAdd(ex.Message); logger.ErrorException("Got an exception", ex); } return returnResult; }
private clsResult Serialize_WZ_FeaturesINI(IniWriter File) { var ReturnResult = new clsResult("Serializing features INI", false); logger.Info("Serializing features INI"); var featureTypeBase = default(FeatureTypeBase); var Unit = default(clsUnit); var Valid = default(bool); foreach ( var tempLoopVar_Unit in map.Units ) { Unit = tempLoopVar_Unit; if ( Unit.TypeBase.Type != UnitType.Feature ) { continue; } featureTypeBase = (FeatureTypeBase)Unit.TypeBase; Valid = true; if ( Unit.ID <= 0 ) { Valid = false; ReturnResult.WarningAdd("Error. A features\'s ID was zero. It was NOT saved. Delete and replace it to allow save."); } if ( Valid ) { File.AddSection("feature_" + Unit.ID.ToStringInvariant()); File.AddProperty("id", Unit.ID.ToStringInvariant()); File.AddProperty("position", Unit.GetINIPosition()); File.AddProperty("rotation", Unit.GetINIRotation()); File.AddProperty("name", featureTypeBase.Code); if ( Unit.Health < 1.0D ) { File.AddProperty("health", Unit.GetINIHealthPercent()); } } } return ReturnResult; }
public clsResult Read_FMap_TileTypes(BinaryReader File) { clsResult ReturnResult = new clsResult("Reading tile types"); int A = 0; byte byteTemp = 0; int InvalidTypeCount = 0; try { if ( Tileset != null ) { for ( A = 0; A <= Tileset.TileCount - 1; A++ ) { byteTemp = File.ReadByte(); if ( byteTemp >= App.TileTypes.Count ) { InvalidTypeCount++; } else { Tile_TypeNum[A] = byteTemp; } } } } catch ( Exception ex ) { ReturnResult.ProblemAdd(ex.Message); return ReturnResult; } if ( InvalidTypeCount > 0 ) { ReturnResult.WarningAdd(InvalidTypeCount + " tile types were invalid."); } if ( File.PeekChar() >= 0 ) { ReturnResult.WarningAdd("There were unread bytes at the end of the file."); } return ReturnResult; }