示例#1
0
        public EngineResult Execute()
        {
            try {
                _logger.Info("Initializing virtual filesystem");

                var         mapStream = File.Open(_settings.InputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                VirtualFile vmapFile;
                var         mixMap = new MixFile(mapStream, _settings.InputFile, 0, mapStream.Length, false, false);
                if (mixMap.IsValid())                   // input max is a mix
                {
                    var mapArchive = new MixFile(mapStream, Path.GetFileName(_settings.InputFile), true);
                    // grab the largest file in the archive
                    var mixEntry = mapArchive.Index.OrderByDescending(me => me.Value.Length).First();
                    vmapFile = mapArchive.OpenFile(mixEntry.Key);
                }
                else
                {
                    vmapFile = new VirtualFile(mapStream, Path.GetFileName(_settings.InputFile), true);
                }
                var mapFile = new MapFile(vmapFile, Path.GetFileName(_settings.InputFile));

                ModConfig modConfig = null;
                if (!string.IsNullOrEmpty(_settings.ModConfig))
                {
                    if (File.Exists(_settings.ModConfig))
                    {
                        try {
                            using (FileStream f = File.OpenRead(_settings.ModConfig))
                                modConfig = ModConfig.Deserialize(f);
                        }
                        catch (IOException) {
                            _logger.Fatal("IOException while loading mod config");
                        }
                        catch (XmlException) {
                            _logger.Fatal("XmlException while loading mod config");
                        }
                        catch (SerializationException) {
                            _logger.Fatal("Serialization exception while loading mod config");
                        }
                    }
                    else
                    {
                        _logger.Fatal("Invalid mod config file specified");
                    }
                }

                if (_settings.Engine == EngineType.AutoDetect)
                {
                    _settings.Engine = EngineDetector.DetectEngineType(mapFile);
                    _logger.Info("Engine autodetect result: {0}", _settings.Engine);
                }

                // Engine type is now definitive, load mod config
                if (modConfig == null)
                {
                    modConfig = ModConfig.GetDefaultConfig(_settings.Engine);
                }

                var map = new Map.Map {
                    IgnoreLighting  = _settings.IgnoreLighting,
                    StartPosMarking = _settings.StartPositionMarking,
                    StartMarkerSize = _settings.MarkerStartSize,
                    MarkOreFields   = _settings.MarkOreFields
                };

                using (var vfs = new VirtualFileSystem()) {
                    // first add the dirs, then load the extra mixes, then scan the dirs
                    foreach (string modDir in modConfig.Directories)
                    {
                        vfs.Add(modDir);
                    }

                    // add mixdir to VFS (if it's not included in the mod config)
                    if (!modConfig.Directories.Any())
                    {
                        string mixDir =
                            VirtualFileSystem.DetermineMixDir(_settings.MixFilesDirectory, _settings.Engine);
                        vfs.Add(mixDir);
                    }

                    foreach (string mixFile in modConfig.ExtraMixes)
                    {
                        vfs.Add(mixFile);
                    }

                    vfs.LoadMixes(_settings.Engine);

                    if (!map.Initialize(mapFile, modConfig, vfs))
                    {
                        _logger.Error("Could not successfully load this map. Try specifying the engine type manually.");
                        return(EngineResult.LoadRulesFailed);
                    }

                    if (!map.LoadTheater())
                    {
                        _logger.Error("Could not successfully load all required components for this map. Aborting.");
                        return(EngineResult.LoadTheaterFailed);
                    }

                    if (_settings.MarkStartPos && _settings.StartPositionMarking == StartPositionMarking.Tiled)
                    {
                        map.MarkTiledStartPositions();
                    }

                    if (_settings.MarkOreFields)
                    {
                        map.MarkOreAndGems();
                    }

                    if ((_settings.GeneratePreviewPack || _settings.FixupTiles || _settings.FixOverlays ||
                         _settings.CompressTiles) && _settings.Backup)
                    {
                        if (mapFile.BaseStream is MixFile)
                        {
                            _logger.Error("Cannot generate a map file backup into an archive (.mmx/.yro/.mix)!");
                        }
                        else
                        {
                            try {
                                string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
                                string fileInput = Path.Combine(Path.GetDirectoryName(_settings.InputFile),
                                                                Path.GetFileName(_settings.InputFile));
                                fileInput = fileInput.TrimEnd(Path.DirectorySeparatorChar,
                                                              Path.AltDirectorySeparatorChar);
                                string fileInputNoExtn = Path.Combine(Path.GetDirectoryName(_settings.InputFile),
                                                                      Path.GetFileNameWithoutExtension(_settings.InputFile));
                                fileInputNoExtn = fileInputNoExtn.TrimEnd(Path.DirectorySeparatorChar,
                                                                          Path.AltDirectorySeparatorChar);
                                string fileBackup = fileInputNoExtn + "_" + timestamp + ".bkp";
                                File.Copy(fileInput, fileBackup, true);
                                _logger.Info("Creating map backup: " + fileBackup);
                            }
                            catch (Exception) {
                                _logger.Error("Unable to generate a map file backup!");
                            }
                        }
                    }

                    if (_settings.FixupTiles)
                    {
                        map.FixupTileLayer();
                    }

                    map.Draw();

                    if (_settings.MarkIceGrowth)
                    {
                        map.MarkIceGrowth();
                    }

                    if (_settings.TunnelPaths)
                    {
                        map.PlotTunnels(_settings.TunnelPosition);
                    }

                    if (_settings.MarkStartPos && (_settings.StartPositionMarking == StartPositionMarking.Squared ||
                                                   _settings.StartPositionMarking == StartPositionMarking.Circled ||
                                                   _settings.StartPositionMarking == StartPositionMarking.Diamond ||
                                                   _settings.StartPositionMarking == StartPositionMarking.Ellipsed ||
                                                   _settings.StartPositionMarking == StartPositionMarking.Starred))
                    {
                        map.DrawStartPositions();
                    }

                    if (_settings.OutputFile == "")
                    {
                        _settings.OutputFile = DetermineMapName(mapFile, _settings.Engine, vfs);
                    }

                    if (_settings.OutputDir == "")
                    {
                        _settings.OutputDir = Path.GetDirectoryName(_settings.InputFile);
                    }

                    if (_settings.DiagnosticWindow)
                    {
                        using (var form = new DebugDrawingSurfaceWindow(map.GetDrawingSurface(), map.GetTiles(),
                                                                        map.GetTheater(), map)) {
                            form.RequestTileEvaluate += map.DebugDrawTile;
                            form.ShowDialog();
                        }
                    }
                }                 // VFS resources can now be released

                // free up as much memory as possible before saving the large images
                Rectangle      saveRect = map.GetSizePixels(_settings.SizeMode);
                DrawingSurface ds       = map.GetDrawingSurface();
                saveRect.Intersect(new Rectangle(0, 0, ds.Width, ds.Height));
                // if we don't need this data anymore, we can try to save some memory
                if (!_settings.GeneratePreviewPack)
                {
                    ds.FreeNonBitmap();
                    map.FreeUseless();
                    GC.Collect();
                }

                if (_settings.SaveJPEG)
                {
                    ds.SaveJPEG(Path.Combine(_settings.OutputDir, _settings.OutputFile + ".jpg"),
                                _settings.JPEGCompression, saveRect);
                }

                if (_settings.SavePNG)
                {
                    ds.SavePNG(Path.Combine(_settings.OutputDir, _settings.OutputFile + ".png"),
                               _settings.PNGQuality, saveRect);
                }

                Regex reThumb = new Regex(@"(\+|)?\((\d+),(\d+)\)");
                var   match   = reThumb.Match(_settings.ThumbnailConfig);
                if (match.Success)
                {
                    Size dimensions = new Size(
                        int.Parse(match.Groups[2].Captures[0].Value),
                        int.Parse(match.Groups[3].Captures[0].Value));
                    var cutRect = map.GetSizePixels(_settings.SizeMode);

                    if (match.Groups[1].Captures[0].Value == "+")
                    {
                        // + means maintain aspect ratio

                        if (dimensions.Width > 0 && dimensions.Height > 0)
                        {
                            float scaleHeight = (float)dimensions.Height / (float)cutRect.Height;
                            float scaleWidth  = (float)dimensions.Width / (float)cutRect.Width;
                            float scale       = Math.Min(scaleHeight, scaleWidth);
                            dimensions.Width  = Math.Max((int)(cutRect.Width * scale), 1);
                            dimensions.Height = Math.Max((int)(cutRect.Height * scale), 1);
                        }
                        else
                        {
                            double aspectRatio = cutRect.Width / (double)cutRect.Height;
                            if (dimensions.Width / (double)dimensions.Height > aspectRatio)
                            {
                                dimensions.Height = (int)(dimensions.Width / aspectRatio);
                            }
                            else
                            {
                                dimensions.Width = (int)(dimensions.Height * aspectRatio);
                            }
                        }
                    }

                    _logger.Info("Saving thumbnail with dimensions {0}x{1}", dimensions.Width, dimensions.Height);

                    if (!_settings.SavePNGThumbnails)
                    {
                        ds.SaveThumb(dimensions, cutRect,
                                     Path.Combine(_settings.OutputDir, "thumb_" + _settings.OutputFile + ".jpg"));
                    }
                    else
                    {
                        ds.SaveThumb(dimensions, cutRect,
                                     Path.Combine(_settings.OutputDir, "thumb_" + _settings.OutputFile + ".png"), true);
                    }
                }

                if (_settings.GeneratePreviewPack || _settings.FixupTiles || _settings.FixOverlays ||
                    _settings.CompressTiles)
                {
                    if (mapFile.BaseStream is MixFile)
                    {
                        _logger.Error(
                            "Cannot fix tile layer or inject thumbnail into an archive (.mmx/.yro/.mix)!");
                    }
                    else
                    {
                        if (_settings.GeneratePreviewPack)
                        {
                            map.GeneratePreviewPack(_settings.PreviewMarkers, _settings.SizeMode, mapFile,
                                                    _settings.FixPreviewDimensions);
                        }

                        if (_settings.FixOverlays)
                        {
                            map.FixupOverlays();                             // fixing is done earlier, it now creates overlay and its data pack
                        }
                        // Keep this last in tiles manipulation
                        if (_settings.CompressTiles)
                        {
                            map.CompressIsoMapPack5();
                        }

                        _logger.Info("Saving map to " + _settings.InputFile);
                        mapFile.Save(_settings.InputFile);
                    }
                }
            }
            catch (Exception exc) {
                _logger.Error(string.Format("An unknown fatal exception occurred: {0}", exc), exc);
#if DEBUG
                throw;
#endif
                return(EngineResult.Exception);
            }
            return(EngineResult.RenderedOk);
        }