Example #1
0
        public static ZoneTileSet[] ExportTileSets()
        {
            foreach (var wdt in WDTReader.ReadAllWDTs())
            {
                GetTileSets(wdt);
            }

            log.Info("Exported {0} ZoneTileSets.", count);
            return(Tiles);
        }
Example #2
0
        private static void Main(string[] args)
        {
            //string basedir = ConfigurationManager.AppSettings["basedir"];
            //LoadAllMaps(basedir);
            //LoadFromListfile("C:\\WoD\\18663listfile.txt", basedir);
            //var wdtreader = new WDTReader(basedir);
            //wdtreader.LoadWDT(@"World\Maps\BlackrockFoundryTrainDepot\BlackrockFoundryTrainDepot.wdt");

            CASC.InitCasc();
            Console.WriteLine("CASC loaded!");
            var wdtreader = new WDTReader();

            wdtreader.LoadWDT("World\\Maps\\EdgeOfRealityMount\\EdgeOfRealityMount.wdt");
            Console.WriteLine("DONE!");
            Console.ReadLine();
        }
Example #3
0
        /// <summary>
        /// Load the ADT by MapId and given coords.
        /// </summary>
        /// <param name="mapId"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public static void Load(uint mapId, uint x, uint y)
        {
            var stream = CASC.OpenFile(DB2Constants.MapFileDataId);

            if (stream == null)
            {
                throw new Exception("Map.db2 is null!");
            }

            var mapStorage = new DBReader(stream).GetRecords <Map>();

            if (!mapStorage.TryGetValue((int)mapId, out var map))
            {
                throw new Exception($"{mapId} cannot be found in Map.db2");
            }

            // Read the WDT file
            WDTReader.ReadWDT(map.WdtFileDataId);

            var maid     = WDTData.MAIDs[(map.WdtFileDataId, x, y)];
Example #4
0
        private static void Main(string[] args)
        {
            CASC.InitCasc(null, null, "wowt", CASCLib.LocaleFlags.enUS);

            if (!File.Exists("listfile.txt"))
            {
                throw new Exception("Listfile not found!");
            }

            foreach (var line in File.ReadAllLines("listfile.txt"))
            {
                if (line.EndsWith(".wdt", StringComparison.CurrentCultureIgnoreCase) && !line.Contains("_mpv") && !line.Contains("_fogs") && !line.Contains("_occ") && !line.Contains("_lgt"))
                {
                    if (!CASC.FileExists(line))
                    {
                        continue;
                    }

                    var reader = new WDTReader();
                    reader.LoadWDT(line);

                    if (reader.wdtfile.filedataids == null)
                    {
                        Console.WriteLine(line + " does not have MAID chunk");
                        continue;
                    }

                    foreach (var filedataids in reader.wdtfile.filedataids)
                    {
                        if (filedataids.rootADT != 0)
                        {
                            Console.WriteLine(line + " " + filedataids.rootADT);
                        }
                    }
                }
            }
        }
Example #5
0
        private void LoadMap()
        {
            if (MapListBox.SelectedValue == null)
            {
                return;
            }

            var    basedir          = ConfigurationManager.AppSettings["basedir"];
            string _SelectedMapName = ((KeyValuePair <int, string>)MapListBox.SelectedValue).Value;

            WDTGrid.Children.Clear();
            pbLoadMap.Value = 0d;

            var wdt = new WDTReader(basedir);

            if (File.Exists(System.IO.Path.Combine(basedir, "World\\Maps\\", _SelectedMapName, _SelectedMapName + ".wdt")))
            {
                Stopwatch        _SW = new Stopwatch();
                BackgroundWorker _BackgroundWorker = new BackgroundWorker();
                _BackgroundWorker.WorkerReportsProgress = true;

                _BackgroundWorker.DoWork += new DoWorkEventHandler(
                    (object o, DoWorkEventArgs args) =>
                {
                    _SW.Start();
                    BackgroundWorker _Worker = o as BackgroundWorker;
                    wdt.LoadWDT(System.IO.Path.Combine("World\\Maps\\", _SelectedMapName, _SelectedMapName + ".wdt"));
                    List <int[]> tiles = wdt.getTiles();

                    for (int i = 0; i < tiles.Count; i++)
                    {
                        if (fCancelMapLoading)
                        {
                            break;
                        }

                        Action _LoadTileAction = delegate() { LoadTile(basedir, tiles[i]); };
                        this.Dispatcher.Invoke(_LoadTileAction);
                        _Worker.ReportProgress((i * 100) / tiles.Count);
                    }

                    _Worker.ReportProgress(100);
                });

                _BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(
                    (object o, ProgressChangedEventArgs args) =>
                {
                    pbLoadMap.Value = args.ProgressPercentage;
                });

                _BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
                    (object sender, RunWorkerCompletedEventArgs args) =>
                {
                    fCancelMapLoading = false;
                    _SW.Stop();
                    Console.WriteLine("Loading {0} took {1} seconds", _SelectedMapName, _SW.Elapsed.TotalSeconds, _SW.ElapsedMilliseconds);
                });

                _BackgroundWorker.RunWorkerAsync();
            }
        }
        /// <summary>
        /// Process the newly added files and automatically name them.
        /// </summary>
        public static void ProcessFiles(string product, List <RootEntry> entries, string buildConfig, string cdnConfig, uint buildId)
        {
            // Read the original listfile first.
            ReadOriginalListfile();

            Console.WriteLine("Opening CASC Storage..");
            CASC.OpenCasc(product, buildConfig, cdnConfig);

            var stopWatch = new Stopwatch();

            stopWatch.Start();

            Console.WriteLine($"Processing {entries.Count} root entries");
            foreach (var entry in entries)
            {
                using (var reader = CASC.OpenFile(entry.FileDataId))
                {
                    if (reader == null)
                    {
                        return;
                    }

                    var chunkId = (Chunk)reader.ReadUInt32().FlipUInt();
                    if (chunkId == Chunk.MD21)
                    {
                        reader.BaseStream.Position = 0;
                        var m2Reader = new M2Reader(reader);
                        var pathName = Names.GetPathFromName(m2Reader.GetName());

                        AddToListfile(entry.FileDataId, $"{pathName}/{m2Reader.GetName()}.m2");

                        // Name all the files.
                        m2Reader.NameAllFiles();
                    }

                    // Close the streams to save memory.
                    reader.Close();
                }
            }

            stopWatch.Stop();
            Console.WriteLine($"Finished processing {entries.Count} root entries in {stopWatch.Elapsed}\n");

            // Diff the 2 Map.db2 files.
            if (product == "wow_beta")
            {
                var oldMapStorage = new DBReader(CASC.OldStorage.OpenFile(1349477)).GetRecords <Map>();
                var newMapStorage = new DBReader(CASC.NewStorage.OpenFile(1349477)).GetRecords <Map>();

                if (oldMapStorage.Count < newMapStorage.Count)
                {
                    DiscordServer.Log("Diffing Map.db2 for new map entries...");

                    foreach (var entry in newMapStorage)
                    {
                        if (!oldMapStorage.ContainsKey(entry.Key))
                        {
                            if (entry.Value.WdtFileDataId != 0)
                            {
                                var wdt = new WDTReader();
                                wdt.ReadWDT(CASC.NewStorage, entry.Value.WdtFileDataId);

                                AddToListfile(entry.Value.WdtFileDataId, $"world/maps/{entry.Value.Directory}/{entry.Value.Directory}.wdt");
                                foreach (var maid in wdt.MAIDs)
                                {
                                    AddToListfile(maid.Value.RootADT, $"world/maps/{entry.Value.Directory}/{entry.Value.Directory}_{maid.Key}.adt");
                                    AddToListfile(maid.Value.Obj0ADT, $"world/maps/{entry.Value.Directory}/{entry.Value.Directory}_{maid.Key}_obj0.adt");
                                    AddToListfile(maid.Value.Obj1ADT, $"world/maps/{entry.Value.Directory}/{entry.Value.Directory}_{maid.Key}_obj1.adt");
                                    AddToListfile(maid.Value.Tex0ADT, $"world/maps/{entry.Value.Directory}/{entry.Value.Directory}_{maid.Key}_tex0.adt");
                                    AddToListfile(maid.Value.LodADT, $"world/maps/{entry.Value.Directory}/{entry.Value.Directory}_{maid.Key}_lod.adt");
                                    AddToListfile(maid.Value.MapTexture, $"world/maptextures/{entry.Value.Directory}/{entry.Value.Directory}_{maid.Key}.blp");
                                    AddToListfile(maid.Value.MapTextureN, $"world/maptextures/{entry.Value.Directory}/{entry.Value.Directory}_{maid.Key}_n.blp");
                                    AddToListfile(maid.Value.MinimapTexture, $"world/minimaps/{entry.Value.Directory}/{entry.Value.Directory}_{maid.Key}.blp");
                                }
                            }
                        }
                    }
                }
            }

            // Generate the listfile now.
            GenerateListfile(buildId);
        }
Example #7
0
        private void LoadMap()
        {
            if (MapListBox.SelectedValue == null)
            {
                return;
            }

            string _SelectedMapName = ((KeyValuePair <int, string>)MapListBox.SelectedValue).Value;

            WDTGrid.Children.Clear();

            progressBar.Visibility   = Visibility.Visible;
            progressLabel.Visibility = Visibility.Visible;

            progressBar.Value     = 0;
            progressLabel.Content = "Loading minimap..";

            var wdt = new WDTReader();

            if (CASC.FileExists(System.IO.Path.Combine(@"world\maps\", _SelectedMapName, _SelectedMapName + ".wdt")))
            {
                Stopwatch        _SW = new Stopwatch();
                BackgroundWorker _BackgroundWorker = new BackgroundWorker();
                _BackgroundWorker.WorkerReportsProgress = true;

                _BackgroundWorker.DoWork += new DoWorkEventHandler(
                    (object o, DoWorkEventArgs args) =>
                {
                    _SW.Start();
                    BackgroundWorker _Worker = o as BackgroundWorker;
                    wdt.LoadWDT(System.IO.Path.Combine(@"world\maps\", _SelectedMapName, _SelectedMapName + ".wdt"));
                    List <int[]> tiles = wdt.getTiles();

                    for (int i = 0; i < tiles.Count; i++)
                    {
                        if (fCancelMapLoading)
                        {
                            break;
                        }

                        Action _LoadTileAction = delegate() { LoadTile(tiles[i]); };
                        this.Dispatcher.Invoke(_LoadTileAction);
                        _Worker.ReportProgress((i * 100) / tiles.Count, "Loading minimap..");
                    }

                    _Worker.ReportProgress(100, "Minimap loaded.");
                });

                _BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(
                    (object o, ProgressChangedEventArgs args) =>
                {
                    progressBar.Value     = args.ProgressPercentage;
                    progressLabel.Content = (string)args.UserState;
                });

                _BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
                    (object sender, RunWorkerCompletedEventArgs args) =>
                {
                    fCancelMapLoading = false;
                    _SW.Stop();
                });

                _BackgroundWorker.RunWorkerAsync();
            }
        }
Example #8
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                throw new Exception("Require buildconfig and cdnconfig (and yes for fullrun)");
            }

            var fullrun = false;

            if (args.Length == 3 && args[2] == "1")
            {
                Console.WriteLine("Doing full run!");
                fullrun = true;
            }

            // TODO: Use configuration stuff instead, but I don't want to figure that out right now. :)
            if (!File.Exists("connectionstring.txt"))
            {
                throw new Exception("connectionstring.txt not found!");
            }

            var dbConn = new MySqlConnection(File.ReadAllText("connectionstring.txt"));

            dbConn.Open();

            CASCLib.Logger.Init();

            CASC.InitCasc("wow.tools", args[0], args[1]);

            var insertCmd = new MySqlCommand("INSERT INTO wow_rootfiles_links VALUES (@parent, @child, @type)", dbConn);

            insertCmd.Parameters.AddWithValue("@parent", 0);
            insertCmd.Parameters.AddWithValue("@child", 0);
            insertCmd.Parameters.AddWithValue("@type", "");
            insertCmd.Prepare();

            var insertUVFNCmd = new MySqlCommand("INSERT INTO wow_communityfiles VALUES (@id, @filename)", dbConn);

            insertUVFNCmd.Parameters.AddWithValue("@id", 0);
            insertUVFNCmd.Parameters.AddWithValue("@filename", 0);
            insertCmd.Prepare();

            #region M2
            var m2ids = new List <uint>();

            using (var cmd = dbConn.CreateCommand())
            {
                if (fullrun)
                {
                    cmd.CommandText = "SELECT id from wow_rootfiles WHERE type = 'm2' ORDER BY id DESC";
                }
                else
                {
                    Console.WriteLine("[M2] Generating list of files to process..");
                    cmd.CommandText = "SELECT id from wow_rootfiles WHERE type = 'm2' AND id NOT IN (SELECT parent FROM wow_rootfiles_links) ORDER BY id DESC";
                }

                var reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    m2ids.Add(uint.Parse(reader["id"].ToString()));
                }

                reader.Close();
            }

            foreach (var m2 in m2ids)
            {
                if (CASC.FileExists(m2))
                {
                    Console.WriteLine("[M2] Loading " + m2);
                    try
                    {
                        var reader = new M2Reader();
                        reader.LoadM2(m2, false);

                        insertCmd.Parameters[0].Value = m2;

                        if (reader.model.textureFileDataIDs != null)
                        {
                            foreach (var textureID in reader.model.textureFileDataIDs)
                            {
                                insertEntry(insertCmd, textureID, "m2 texture");
                            }
                        }

                        if (reader.model.animFileDataIDs != null)
                        {
                            foreach (var animFileID in reader.model.animFileDataIDs)
                            {
                                insertEntry(insertCmd, animFileID.fileDataID, "m2 anim");
                            }
                        }

                        if (reader.model.skinFileDataIDs != null)
                        {
                            foreach (var skinFileID in reader.model.skinFileDataIDs)
                            {
                                insertEntry(insertCmd, skinFileID, "m2 skin");
                            }
                        }

                        if (reader.model.boneFileDataIDs != null)
                        {
                            foreach (var boneFileID in reader.model.boneFileDataIDs)
                            {
                                insertEntry(insertCmd, boneFileID, "m2 bone");
                            }
                        }

                        if (reader.model.recursiveParticleModelFileIDs != null)
                        {
                            foreach (var rpID in reader.model.recursiveParticleModelFileIDs)
                            {
                                insertEntry(insertCmd, rpID, "m2 recursive particle");
                            }
                        }

                        if (reader.model.geometryParticleModelFileIDs != null)
                        {
                            foreach (var gpID in reader.model.geometryParticleModelFileIDs)
                            {
                                insertEntry(insertCmd, gpID, "m2 geometry particle");
                            }
                        }

                        insertEntry(insertCmd, reader.model.skelFileID, "m2 skel");
                        insertEntry(insertCmd, reader.model.physFileID, "m2 phys");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
            #endregion

            #region WMO
            var wmoids = new List <uint>();

            var groupFixCMD = new MySqlCommand("UPDATE wow_rootfiles SET type = '_xxxwmo' WHERE id = @id LIMIT 1", dbConn);
            groupFixCMD.Parameters.AddWithValue("@id", 0);
            groupFixCMD.Prepare();

            using (var cmd = dbConn.CreateCommand())
            {
                if (fullrun)
                {
                    cmd.CommandText = "SELECT id from wow_rootfiles WHERE type = 'wmo' ORDER BY id DESC";
                }
                else
                {
                    Console.WriteLine("[WMO] Generating list of files to process..");
                    cmd.CommandText = "SELECT id from wow_rootfiles WHERE type = 'wmo' AND id NOT IN (SELECT parent FROM wow_rootfiles_links) ORDER BY id DESC";
                }
                var reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    wmoids.Add(uint.Parse(reader["id"].ToString()));
                }

                reader.Close();
            }

            foreach (var wmoid in wmoids)
            {
                if (CASC.FileExists(wmoid))
                {
                    Console.WriteLine("[WMO] Loading " + wmoid);
                    try
                    {
                        var reader = new WMOReader();
                        var wmo    = new WoWFormatLib.Structs.WMO.WMO();
                        try
                        {
                            wmo = reader.LoadWMO(wmoid);
                        }
                        catch (NotSupportedException e)
                        {
                            Console.WriteLine("[WMO] " + wmoid + " is a group WMO, fixing type and skipping..");
                            groupFixCMD.Parameters[0].Value = wmoid;
                            groupFixCMD.ExecuteNonQuery();
                            continue;
                        }

                        insertCmd.Parameters[0].Value = wmoid;

                        var inserted = new List <uint>();

                        if (wmo.groupFileDataIDs != null)
                        {
                            foreach (var groupFileDataID in wmo.groupFileDataIDs)
                            {
                                insertEntry(insertCmd, groupFileDataID, "wmo group");
                            }
                        }

                        if (wmo.doodadIds != null)
                        {
                            foreach (var doodadID in wmo.doodadIds)
                            {
                                if (inserted.Contains(doodadID))
                                {
                                    continue;
                                }

                                inserted.Add(doodadID);

                                insertEntry(insertCmd, doodadID, "wmo doodad");
                            }
                        }

                        if (wmo.textures == null && wmo.materials != null)
                        {
                            foreach (var material in wmo.materials)
                            {
                                if (material.texture1 == 0 || inserted.Contains(material.texture1))
                                {
                                    continue;
                                }

                                inserted.Add(material.texture1);
                                insertEntry(insertCmd, material.texture1, "wmo texture");

                                if (material.texture2 == 0 || inserted.Contains(material.texture2))
                                {
                                    continue;
                                }

                                inserted.Add(material.texture2);
                                insertEntry(insertCmd, material.texture2, "wmo texture");
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
            #endregion

            #region WDT
            var wdtids         = new List <uint>();
            var wdtfullnamemap = new Dictionary <string, uint>();
            using (var cmd = dbConn.CreateCommand())
            {
                Console.WriteLine("[WDT] Generating list of WDT files..");
                cmd.CommandText = "SELECT id, filename from wow_rootfiles WHERE type = 'wdt' AND filename IS NOT NULL ORDER BY id DESC";
                var reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    var filename = (string)reader["filename"];
                    var wdtid    = uint.Parse(reader["id"].ToString());
                    if (filename.Contains("_mpv") || filename.Contains("_lgt") || filename.Contains("_occ") || filename.Contains("_fogs"))
                    {
                        continue;
                    }
                    wdtfullnamemap.Add(filename, wdtid);
                }
            }

            using (var cmd = dbConn.CreateCommand())
            {
                if (fullrun)
                {
                    cmd.CommandText = "SELECT id, filename from wow_rootfiles WHERE type = 'wdt' ORDER BY id DESC";
                }
                else
                {
                    Console.WriteLine("[WDT] Generating list of files to process..");
                    cmd.CommandText = "SELECT id, filename from wow_rootfiles WHERE type = 'wdt' AND id NOT IN (SELECT parent FROM wow_rootfiles_links) ORDER BY id DESC";
                }
                var reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    //var filename = (string)reader["filename"];
                    var wdtid = uint.Parse(reader["id"].ToString());
                    //if (filename.Contains("_mpv") || filename.Contains("_lgt") || filename.Contains("_occ") || filename.Contains("_fogs"))
                    //   continue;
                    wdtids.Add(wdtid);
                }

                reader.Close();

                foreach (var wdtid in wdtids)
                {
                    Console.WriteLine("[WDT] Loading " + wdtid);

                    insertCmd.Parameters[0].Value = wdtid;
                    try
                    {
                        var wdtreader = new WDTReader();
                        wdtreader.LoadWDT(wdtid);

                        if (wdtreader.wdtfile.modf.id != 0)
                        {
                            Console.WriteLine("WDT has WMO ID: " + wdtreader.wdtfile.modf.id);
                            insertEntry(insertCmd, wdtreader.wdtfile.modf.id, "wdt wmo");
                        }

                        foreach (var records in wdtreader.stringTileFiles)
                        {
                            insertEntry(insertCmd, records.Value.rootADT, "root adt");
                            insertEntry(insertCmd, records.Value.tex0ADT, "tex0 adt");
                            insertEntry(insertCmd, records.Value.lodADT, "lod adt");
                            insertEntry(insertCmd, records.Value.obj0ADT, "obj0 adt");
                            insertEntry(insertCmd, records.Value.obj1ADT, "obj1 adt");
                            insertEntry(insertCmd, records.Value.mapTexture, "map texture");
                            insertEntry(insertCmd, records.Value.mapTextureN, "mapn texture");
                            insertEntry(insertCmd, records.Value.minimapTexture, "minimap texture");
                        }
                    }catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
            #endregion

            #region ADT
            var adtids     = new Dictionary <uint, Dictionary <(byte, byte), uint> >();
            var wdtmapping = new Dictionary <string, uint>();

            using (var cmd = dbConn.CreateCommand())
            {
                if (fullrun)
                {
                    cmd.CommandText = " SELECT id, filename from wow_rootfiles WHERE filename LIKE '%adt' AND filename NOT LIKE '%_obj0.adt' AND filename NOT LIKE '%_obj1.adt' AND filename NOT LIKE '%_lod.adt' AND filename NOT LIKE '%tex0.adt' AND filename NOT LIKE '%tex1.adt' ORDER BY id DESC ";
                }
                else
                {
                    Console.WriteLine("[ADT] Generating list of files to process..");
                    cmd.CommandText = " SELECT id, filename from wow_rootfiles WHERE filename LIKE '%adt' AND filename NOT LIKE '%_obj0.adt' AND filename NOT LIKE '%_obj1.adt' AND filename NOT LIKE '%_lod.adt' AND filename NOT LIKE '%tex0.adt' AND filename NOT LIKE '%tex1.adt' AND id NOT IN (SELECT parent FROM wow_rootfiles_links) ORDER BY id DESC";
                }
                var reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    var filename = (string)reader["filename"];
                    var mapname  = filename.Replace("world/maps/", "").Substring(0, filename.Replace("world/maps/", "").IndexOf("/"));
                    var exploded = Path.GetFileNameWithoutExtension(filename).Split('_');

                    for (var i = 0; i < exploded.Length; i++)
                    {
                        //Console.WriteLine(i + ": " + exploded[i]);
                    }

                    byte tileX = 0;
                    byte tileY = 0;

                    if (!byte.TryParse(exploded[exploded.Length - 2], out tileX) || !byte.TryParse(exploded[exploded.Length - 1], out tileY))
                    {
                        throw new FormatException("An error occured converting coordinates from " + filename + " to bytes");
                    }

                    if (!wdtmapping.ContainsKey(mapname))
                    {
                        var wdtname = "world/maps/" + mapname + "/" + mapname + ".wdt";
                        if (!wdtfullnamemap.ContainsKey(wdtname))
                        {
                            Console.WriteLine("Unable to get filedataid for " + mapname + ", skipping...");
                            wdtmapping.Remove(mapname);
                            continue;
                        }
                        wdtmapping.Add(mapname, wdtfullnamemap[wdtname]);
                        if (wdtmapping[mapname] == 0)
                        {
                            // TODO: Support WDTs removed in current build
                            Console.WriteLine("Unable to get filedataid for " + mapname + ", skipping...");
                            wdtmapping.Remove(mapname);
                            continue;

                            /*
                             * var wdtconn = new MySqlConnection(File.ReadAllText("connectionstring.txt"));
                             * wdtconn.Open();
                             * using (var wdtcmd = wdtconn.CreateCommand())
                             * {
                             *  wdtcmd.CommandText = "SELECT id from wow_rootfiles WHERE filename = '" + wdtname + "'";
                             *  var wdtread = wdtcmd.ExecuteReader();
                             *  while (wdtread.Read())
                             *  {
                             *      wdtmapping[mapname] = uint.Parse(wdtread["id"].ToString());
                             *  }
                             * }
                             * wdtconn.Close();*/
                        }

                        adtids.Add(wdtmapping[mapname], new Dictionary <(byte, byte), uint>());
                    }

                    var id = uint.Parse(reader["id"].ToString());

                    if (id == 0)
                    {
                        Console.WriteLine("Root ADT " + tileX + ", " + tileY + " with ID 0 on WDT " + wdtmapping[mapname]);
                        continue;
                    }

                    if (wdtmapping.ContainsKey(mapname))
                    {
                        adtids[wdtmapping[mapname]].Add((tileX, tileY), id);
                    }
                }

                reader.Close();

                foreach (var wdtid in adtids)
                {
                    foreach (var adtid in wdtid.Value)
                    {
                        var inserted = new List <uint>();
                        Console.WriteLine("[ADT] Loading " + adtid.Key.Item1 + ", " + adtid.Key.Item2 + "(" + adtid.Value + ")");

                        insertCmd.Parameters[0].Value = adtid.Value;

                        var adtreader = new ADTReader();
                        try
                        {
                            adtreader.LoadADT(wdtid.Key, adtid.Key.Item1, adtid.Key.Item2);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                            continue;
                        }

                        if (adtreader.adtfile.objects.m2Names.filenames != null)
                        {
                            Console.WriteLine(adtid + " is still using old filenames, skipping!");
                        }
                        else
                        {
                            foreach (var worldmodel in adtreader.adtfile.objects.worldModels.entries)
                            {
                                if (inserted.Contains(worldmodel.mwidEntry))
                                {
                                    continue;
                                }

                                inserted.Add(worldmodel.mwidEntry);
                                insertEntry(insertCmd, worldmodel.mwidEntry, "adt worldmodel");
                            }

                            foreach (var doodad in adtreader.adtfile.objects.models.entries)
                            {
                                if (inserted.Contains(doodad.mmidEntry))
                                {
                                    continue;
                                }

                                insertEntry(insertCmd, doodad.mmidEntry, "adt doodad");
                                inserted.Add(doodad.mmidEntry);
                            }
                        }
                    }
                }
            }
            #endregion
        }
        private void LoadMap(string map)
        {
            WDTGrid.Children.Clear();

            var wdt = new WDTReader();

            if (CASC.cascHandler.FileExists(System.IO.Path.Combine(@"world\maps\", map, map + ".wdt")))
            {
                Stopwatch        _SW = new Stopwatch();
                BackgroundWorker _BackgroundWorker = new BackgroundWorker();
                _BackgroundWorker.WorkerReportsProgress = true;

                _BackgroundWorker.DoWork += new DoWorkEventHandler(
                    (object o, DoWorkEventArgs args) =>
                {
                    _SW.Start();
                    BackgroundWorker _Worker = o as BackgroundWorker;
                    wdt.LoadWDT(System.IO.Path.Combine(@"world\maps\", map, map + ".wdt"));
                    List <int[]> tiles = wdt.GetTiles();

                    if (tiles.Count == 0)
                    {
                        return;
                    }

                    for (int i = 0; i < tiles.Count; i++)
                    {
                        if (map == "Kalimdor")
                        {
                            if (tiles[i][0] < 5 && tiles[i][1] < 5)
                            {
                                // Filter out GM island
                                continue;
                            }
                        }

                        if (tiles[i][0] < min_x)
                        {
                            min_x = tiles[i][0];
                        }
                        if (tiles[i][1] < min_y)
                        {
                            min_y = tiles[i][1];
                        }

                        if (tiles[i][0] > max_x)
                        {
                            max_x = tiles[i][0];
                        }
                        if (tiles[i][1] > max_y)
                        {
                            max_y = tiles[i][1];
                        }
                    }

                    for (int i = 0; i < tiles.Count; i++)
                    {
                        if (map == "Kalimdor")
                        {
                            // Filter out GM island
                            if (tiles[i][0] < 5 && tiles[i][1] < 5)
                            {
                                continue;
                            }
                        }

                        if (fCancelMapLoading)
                        {
                            break;
                        }

                        Action _LoadTileAction = delegate() { LoadTile(tiles[i]); };
                        this.Dispatcher.Invoke(_LoadTileAction);
                        _Worker.ReportProgress((i * 100) / tiles.Count, "Loading map..");
                    }

                    _Worker.ReportProgress(100, "Map loaded.");
                });

                _BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(
                    (object o, ProgressChangedEventArgs args) =>
                {
                    progressBar.Value     = args.ProgressPercentage;
                    progressLabel.Content = (string)args.UserState;
                });

                _BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
                    (object sender, RunWorkerCompletedEventArgs args) =>
                {
                    fCancelMapLoading = false;
                    if (max_x == 0 && min_x == 64)
                    {
                        Close();
                        return;
                    }
                    Width  = (max_x - min_x) * (WDTGrid.Width / 64) + 64;
                    Height = (max_y - min_y) * (WDTGrid.Height / 64) + 64;
                    progressBar.Visibility   = Visibility.Hidden;
                    progressLabel.Visibility = Visibility.Hidden;
                    WDTGrid.Visibility       = Visibility.Visible;
                    _SW.Stop();
                });

                _BackgroundWorker.RunWorkerAsync();
            }
        }
Example #10
0
        public static BoundingBox[] ExportBoundaries()
        {
            foreach (var wdt in WDTReader.ReadAllWDTs())
            {
                Vector3 min;
                Vector3 max;

                if (wdt.IsWMOOnly)
                {
                    const float maxDim = TerrainConstants.TileSize * (32.0f);

                    // No terrain, get the boundaries from the MODF
                    min = wdt.WmoDefinitions[0].Extents.Min;
                    max = wdt.WmoDefinitions[0].Extents.Max;

                    var diff = Math.Max(max.X - min.X, max.Y - min.Y);
                    if ((min.X + diff) > maxDim)
                    {
                        var newdiff = maxDim - diff;
                        if ((min.X - newdiff) < -maxDim)
                        {
                            throw new Exception("Can't square map: " + wdt.Name);
                        }
                        min.X = min.X - newdiff;
                    }

                    if ((min.Y + diff) > maxDim)
                    {
                        var newdiff = maxDim - diff;
                        if ((min.Y - newdiff) < -maxDim)
                        {
                            throw new Exception("Can't square map: " + wdt.Name);
                        }
                        min.Y = min.Y - newdiff;
                    }

                    max.X = min.X + diff;
                    max.Y = min.Y + diff;
                }
                else
                {
                    var minX = TerrainConstants.TilesPerMapSide;
                    var maxX = 0;
                    var minY = TerrainConstants.TilesPerMapSide;
                    var maxY = 0;
                    for (var y = 0; y < TerrainConstants.TilesPerMapSide; y++)
                    {
                        for (var x = 0; x < TerrainConstants.TilesPerMapSide; x++)
                        {
                            if (!wdt.TileProfile[x, y])
                            {
                                continue;
                            }
                            minX = Math.Min(minX, x);
                            maxX = Math.Max(maxX, x);
                            minY = Math.Min(minY, y);
                            maxY = Math.Max(maxY, y);
                        }
                    }

                    var diff = Math.Max(maxX - minX, maxY - minY);
                    if ((minX + diff) > TerrainConstants.TilesPerMapSide)
                    {
                        var newdiff = TerrainConstants.TilesPerMapSide - diff;
                        if ((minX - newdiff) < 0)
                        {
                            throw new Exception("Can't square this map.");
                        }
                        minX = minX - newdiff;
                    }

                    if ((minY + diff) > TerrainConstants.TilesPerMapSide)
                    {
                        var newdiff = TerrainConstants.TilesPerMapSide - diff;
                        if ((minY - newdiff) < 0)
                        {
                            throw new Exception("Can't square this map.");
                        }
                        minY = minY - newdiff;
                    }

                    maxX = minX + diff;
                    maxY = minY + diff;

                    var maxXLoc = TerrainConstants.TileSize * (32 - minX);
                    var maxYLoc = TerrainConstants.TileSize * (32 - minY);
                    var minXLoc = TerrainConstants.TileSize * (31 - maxX);
                    var minYLoc = TerrainConstants.TileSize * (31 - maxY);

                    //var maxXLoc = TerrainConstants.TileSize * (maxX - 32);
                    //var maxYLoc = TerrainConstants.TileSize * (maxY - 32);
                    //var minXLoc = TerrainConstants.TileSize * (minX - 32);
                    //var minYLoc = TerrainConstants.TileSize * (minY - 32);

                    min = new Vector3(minXLoc, minYLoc, -2048.0f);
                    max = new Vector3(maxXLoc, maxYLoc, 2048.0f);

                    // Convert to in-game coordinates
                    var temp = min.X;
                    min.X = min.Y;
                    min.Y = temp;

                    temp  = max.X;
                    max.X = max.Y;
                    max.Y = temp;
                }

                // TODO: Map bounds that in the file are a little off
                min.X -= 200.0f;
                min.Y -= 200.0f;
                max.X += 200.0f;
                max.Y += 200.0f;

                // Some bounding boxes (specifically the ones for the WMO-only tiles) have incorrect Z spans
                min.Z = -2048.0f;
                max.Z = 2048.0f;

                //text.WriteLine(dbcMapEntry.Id + "\t" + wdtName + "\tMin: " + min + "\tMax: " + max);
                Boundaries[(int)wdt.Entry.Id] = new BoundingBox(min, max);
            }

            return(Boundaries);
        }