예제 #1
0
        /// <summary>
        /// Parses all filters to configurations
        /// </summary>
        public static void ParseFixturesXml()
        {
            var categories = fixturesXml.Descendants("FixtureCategory");

            //List<FixtureRendererConfiguration2> rendererConfigurations = new List<FixtureRendererConfiguration2>();
            foreach (XElement category in categories)
            {
                FixtureRendererConfiguration2?rendererConfiguration = ParseRendererConfigurationFromXmlNode(category);
                if (rendererConfiguration == null)
                {
                    continue;
                }
                rendererCategories.Add(rendererConfiguration.GetValueOrDefault());
            }

            var fixtures = fixturesXml.Descendants("Fixture");

            foreach (XElement fixture in fixtures)
            {
                var patternNode = fixture.Descendants("pattern");
                if (patternNode.Count() == 0 || string.IsNullOrEmpty(patternNode.First().Value))
                {
                    MainForm.Log(string.Format("Fixtures: Error in fixtures.xml, no file pattern set."), MainForm.LogLevel.error);
                    continue;
                }

                // Check pattern
                try
                {
                    Regex regexTest = new Regex(patternNode.First().Value);
                }
                catch
                {
                    MainForm.Log(string.Format("Fixtures: Error in fixtures.xml, the pattern \"{0}\" is not valid.", patternNode.First().Value), MainForm.LogLevel.error);
                    continue;
                }

                var categoryNode = fixture.Descendants("category");
                if (patternNode.Count() == 0 || string.IsNullOrEmpty(patternNode.First().Value))
                {
                    MainForm.Log(string.Format("Fixtures: Error in fixtures.xml, no category set."), MainForm.LogLevel.error);
                    continue;
                }

                string pattern  = patternNode.First().Value;
                string category = categoryNode.First().Value;

                // Get category
                var categoryResult = rendererCategories.Where(c => c.Name == category);
                if (categoryResult.Count() > 0)
                {
                    configurations.Add(pattern, categoryResult.First());
                }
            }
        }
예제 #2
0
        public static bool CheckGamePath()
        {
            string checkFile = string.Format("{0}\\{1}", Properties.Settings.Default.game_path, "camelot.exe");

            if (!File.Exists(checkFile))
            {
                MainForm.Log("camelot.exe not found in gamepath!");
                return(false);
            }

            return(true);
        }
예제 #3
0
 private void drawMapBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     if (e.Error != null)
     {
         MainForm.Log("Unhandled Exception thrown!", LogLevel.error);
         MainForm.Log(e.Error.Message, LogLevel.error);
         MainForm.Log(e.Error.StackTrace, LogLevel.error);
     }
     else
     {
         Log("Finished without errors!", LogLevel.success);
     }
 }
예제 #4
0
        /// <summary>
        /// Gets the enum value out a text value
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private static FixtureRenderererType GetRendererType(string name)
        {
            // Parse the textual representation of the renderer to its enum value
            FixtureRenderererType renderer = FixtureRenderererType.Shaded;

            try
            {
                renderer = (FixtureRenderererType)Enum.Parse(typeof(FixtureRenderererType), name);
            }
            catch
            {
                MainForm.Log(string.Format("The renderer \"{0}\" is invalid!", name), MainForm.LogLevel.error);
            }

            return(renderer);
        }
예제 #5
0
        public MapHeightmap(ZoneConfiguration zoneConfiguration)
        {
            MainForm.Log("Preloading zone heightmap ...", MainForm.LogLevel.notice);

            this.zoneConfiguration = zoneConfiguration;
            this.m_terrainfactor   = Convert.ToInt32(DataWrapper.GetDatFileProperty(zoneConfiguration.SectorDatStreamReader, "terrain", "scalefactor"));
            this.m_offsetfactor    = Convert.ToInt32(DataWrapper.GetDatFileProperty(zoneConfiguration.SectorDatStreamReader, "terrain", "offsetfactor"));
            this.m_heightmapFile   = new FileInfo(string.Format("{0}\\data\\heightmaps\\zone{1}_heightmap.png", System.Windows.Forms.Application.StartupPath, zoneConfiguration.ZoneId));

            if (!System.IO.Directory.Exists(m_heightmapFile.DirectoryName))
            {
                Directory.CreateDirectory(m_heightmapFile.DirectoryName);
            }

            // Generate it, needed for lightmap, river and fixtures
            GenerateHeightmap();
        }
예제 #6
0
        /// <summary>
        /// Gets the Vector out of a string
        /// </summary>
        /// <param name="lightVector"></param>
        /// <returns></returns>
        private static SharpDX.Vector3 GetLightVector(string lightVector)
        {
            if (lightVector == "")
            {
                return(new SharpDX.Vector3(1f, 1f, -1f));
            }

            string[] parts = lightVector.Split(',');
            if (parts.Length != 3)
            {
                MainForm.Log(string.Format("LightVector \"{0}\" is inivalid.", lightVector), MainForm.LogLevel.warning);
                return(new SharpDX.Vector3(1f, 1f, -1f));
            }

            try
            {
                return(new SharpDX.Vector3(Convert.ToSingle(parts[0]), Convert.ToSingle(parts[1]), Convert.ToSingle(parts[2])));
            }
            catch
            {
                MainForm.Log(string.Format("LightVector \"{0}\" is inivalid.", lightVector), MainForm.LogLevel.warning);
                return(new SharpDX.Vector3(1f, 1f, -1f));
            }
        }
예제 #7
0
        public void Draw(MagickImage map)
        {
            MainForm.ProgressStart("Rendering water ...");

            using (IPixelCollection heightmapPixels = zoneConfiguration.Heightmap.HeightmapScaled.GetPixels())
            {
                using (MagickImage water = new MagickImage(MagickColors.Transparent, zoneConfiguration.TargetMapSize, zoneConfiguration.TargetMapSize))
                {
                    int progressCounter = 0;

                    foreach (WaterConfiguration river in m_waterAreas)
                    {
                        MainForm.Log(river.Name + "...", MainForm.LogLevel.notice);

                        MagickColor fillColor;
                        if (m_useClientColors)
                        {
                            fillColor = river.Color;
                        }
                        else
                        {
                            fillColor = m_waterColor;
                        }
                        //water.FillColor = fillColor;

                        // Get the river coordinates and scale them to the targets size
                        List <PointD> riverCoordinates = river.GetCoordinates().Select(c => new PointD(c.X * zoneConfiguration.MapScale, c.Y * zoneConfiguration.MapScale)).ToList();

                        // Texture
                        using (MagickImage texture = new MagickImage((river.Type.ToLower() == "lava") ? GetLavaTexture() : GetWateryTexture()))
                        {
                            using (MagickImage pattern = new MagickImage(fillColor, texture.Width, texture.Height))
                            {
                                texture.Composite(pattern, 0, 0, CompositeOperator.DstIn);
                                texture.Composite(pattern, 0, 0, CompositeOperator.ColorDodge);

                                water.Settings.FillPattern = texture;
                                DrawablePolygon poly = new DrawablePolygon(riverCoordinates);
                                water.Draw(poly);
                            }
                        }

                        // get the min/max and just process them
                        int minX = Convert.ToInt32(riverCoordinates.Min(m => m.X)) - 10;
                        int maxX = Convert.ToInt32(riverCoordinates.Max(m => m.X)) + 10;
                        int minY = Convert.ToInt32(riverCoordinates.Min(m => m.Y)) - 10;
                        int maxY = Convert.ToInt32(riverCoordinates.Max(m => m.Y)) + 10;

                        using (IPixelCollection riverPixelCollection = water.GetPixels())
                        {
                            for (int x = minX; x < maxX; x++)
                            {
                                if (x < 0)
                                {
                                    continue;
                                }
                                if (x >= zoneConfiguration.TargetMapSize)
                                {
                                    continue;
                                }

                                for (int y = minY; y < maxY; y++)
                                {
                                    if (y < 0)
                                    {
                                        continue;
                                    }
                                    if (y >= zoneConfiguration.TargetMapSize)
                                    {
                                        continue;
                                    }

                                    ushort pixelHeight = heightmapPixels.GetPixel(x, y).GetChannel(0);
                                    if (pixelHeight > river.Height)
                                    {
                                        Pixel newPixel = new Pixel(x, y, new ushort[] { 0, 0, 0, ushort.MinValue });
                                        riverPixelCollection.SetPixel(newPixel);
                                    }
                                }
                            }
                        }

                        if (debug)
                        {
                            DebugRiver(progressCounter, river, riverCoordinates);
                        }

                        int percent = 100 * progressCounter / m_waterAreas.Count();
                        MainForm.ProgressUpdate(percent);
                        progressCounter++;
                    }

                    MainForm.ProgressStartMarquee("Merging...");

                    if (WaterTransparency != 0)
                    {
                        water.Alpha(AlphaOption.Set);
                        double divideValue = 100.0 / (100.0 - WaterTransparency);
                        water.Evaluate(Channels.Alpha, EvaluateOperator.Divide, divideValue);
                    }

                    water.Blur();
                    map.Composite(water, 0, 0, CompositeOperator.SrcOver);
                }
            }

            MainForm.ProgressReset();
        }
예제 #8
0
        private void DrawTreeCluster(MagickImage overlay, DrawableFixture fixture)
        {
            //MainForm.Log(string.Format("Image: {0} ({1}) ...", fixture.Name, fixture.TreeCluster.Tree), MainForm.LogLevel.notice);
            string fileName    = System.IO.Path.GetFileNameWithoutExtension(fixture.TreeCluster.Tree);
            string defaultTree = "elm1";

            // Load model image
            if (!m_modelImages.ContainsKey(fileName))
            {
                string treeImageFile = string.Format("{0}\\data\\prerendered\\trees\\{1}.png", System.Windows.Forms.Application.StartupPath, fileName);
                if (System.IO.File.Exists(treeImageFile))
                {
                    MagickImage modelImage = new MagickImage(treeImageFile);
                    modelImage.Blur();
                    m_modelImages.Add(fileName, modelImage);
                }
                else
                {
                    MainForm.Log(string.Format("Can not find image for tree {0} ({1}), using default tree", fixture.TreeCluster.Tree, fixture.NifName), MainForm.LogLevel.warning);
                    m_modelImages.Add(fileName, m_modelImages[defaultTree]);
                }
            }

            if (m_modelImages.ContainsKey(fileName) && m_modelImages[fileName] != null)
            {
                // Get the width of the orginal tree shape
                NifRow tree = FixturesLoader.NifRows.Where(n => n.Filename.ToLower() == fixture.TreeCluster.Tree.ToLower()).FirstOrDefault();
                if (tree == null)
                {
                    return;
                }

                System.Drawing.SizeF treeSize = tree.GetSize(0, 0);

                int dimensions     = ((fixture.CanvasWidth > fixture.CanvasHeight) ? fixture.CanvasWidth : fixture.CanvasHeight) + 10;
                int extendedWidth  = dimensions - fixture.CanvasWidth;
                int extendedHeight = dimensions - fixture.CanvasHeight;

                using (MagickImage treeCluster = new MagickImage(MagickColors.Transparent, dimensions, dimensions))
                {
                    double centerX = treeCluster.Width / 2d;
                    double centerY = treeCluster.Height / 2d;

                    foreach (SharpDX.Vector3 treeInstance in fixture.TreeCluster.TreeInstances)
                    {
                        using (IMagickImage treeImage = m_modelImages[fileName].Clone())
                        {
                            double scaleWidthToTreeImage  = treeSize.Width / treeImage.Width;
                            double scaleHeightToTreeImage = treeSize.Height / treeImage.Height;
                            int    width  = Convert.ToInt32(treeImage.Width * scaleWidthToTreeImage * fixture.Scale);
                            int    height = Convert.ToInt32(treeImage.Height * scaleHeightToTreeImage * fixture.Scale);
                            treeImage.Resize(width, height);

                            int x = Convert.ToInt32(centerX - width / 2d - zoneConfiguration.ZoneCoordinateToMapCoordinate(treeInstance.X) * (fixture.FixtureRow.Scale / 100));
                            int y = Convert.ToInt32(centerY - height / 2d - zoneConfiguration.ZoneCoordinateToMapCoordinate(treeInstance.Y) * (fixture.FixtureRow.Scale / 100));
                            treeCluster.Composite(treeImage, x, y, CompositeOperator.SrcOver);
                        }
                    }

                    treeCluster.Rotate((360d * fixture.FixtureRow.AxisZ3D - fixture.FixtureRow.A) * -1);

                    using (MagickImage modelCanvas = new MagickImage(MagickColors.Transparent, fixture.CanvasWidth, fixture.CanvasHeight))
                    {
                        foreach (DrawableElement drawableElement in fixture.DrawableElements)
                        {
                            modelCanvas.Settings.FillColor = new MagickColor(
                                Convert.ToUInt16(128 * 256 * drawableElement.lightning),
                                Convert.ToUInt16(128 * 256 * drawableElement.lightning),
                                Convert.ToUInt16(128 * 256 * drawableElement.lightning)
                                );

                            DrawablePolygon polyDraw = new DrawablePolygon(drawableElement.coordinates);
                            modelCanvas.Draw(polyDraw);
                        }

                        modelCanvas.Composite(treeCluster, Gravity.Center, CompositeOperator.DstIn);
                        treeCluster.Composite(modelCanvas, Gravity.Center, CompositeOperator.Overlay);
                        //treeCluster.Composite(modelCanvas, Gravity.Center, CompositeOperator.SrcOver);
                    }

                    if (fixture.RendererConf.HasShadow)
                    {
                        CastShadow(
                            treeCluster,
                            fixture.RendererConf.ShadowOffsetX,
                            fixture.RendererConf.ShadowOffsetY,
                            fixture.RendererConf.ShadowSize,
                            new Percentage(100 - fixture.RendererConf.ShadowTransparency),
                            fixture.RendererConf.ShadowColor,
                            false
                            );
                    }

                    if (fixture.RendererConf.Transparency != 0)
                    {
                        treeCluster.Alpha(AlphaOption.Set);

                        double divideValue = 100.0 / (100.0 - fixture.RendererConf.Transparency);
                        treeCluster.Evaluate(Channels.Alpha, EvaluateOperator.Divide, divideValue);
                    }

                    overlay.Composite(treeCluster, Convert.ToInt32(fixture.CanvasX - extendedWidth / 2), Convert.ToInt32(fixture.CanvasY - extendedHeight / 2), CompositeOperator.SrcOver);
                }
            }
        }
예제 #9
0
        private void DrawImage(MagickImage overlay, DrawableFixture fixture)
        {
            //MainForm.Log(string.Format("Image: {0} ({1}) ...", fixture.Name, fixture.NifName), MainForm.LogLevel.notice);
            string fileName    = System.IO.Path.GetFileNameWithoutExtension(fixture.NifName);
            string defaultTree = "elm1";

            // Load default tree
            if (!m_modelImages.ContainsKey(defaultTree))
            {
                string defaultTreeImage = string.Format("{0}\\data\\prerendered\\trees\\{1}.png", System.Windows.Forms.Application.StartupPath, defaultTree);
                if (System.IO.File.Exists(defaultTreeImage))
                {
                    MagickImage treeImage = new MagickImage(defaultTreeImage);
                    treeImage.Blur();
                    m_modelImages.Add(defaultTree, treeImage);
                }
                else
                {
                    m_modelImages.Add(fileName, null);
                }
            }

            // TreeClusters are sets of trees in a specified arrangement
            // They need to be drawe separately
            if (fixture.IsTreeCluster)
            {
                DrawTreeCluster(overlay, fixture);
                return;
            }

            // Load model image
            if (!m_modelImages.ContainsKey(fileName))
            {
                string objectImageFile = string.Format("{0}\\data\\prerendered\\objects\\{1}.png", System.Windows.Forms.Application.StartupPath, fileName);
                if (fixture.IsTree)
                {
                    objectImageFile = string.Format("{0}\\data\\prerendered\\trees\\{1}.png", System.Windows.Forms.Application.StartupPath, fileName);
                }

                if (System.IO.File.Exists(objectImageFile))
                {
                    MagickImage objectImage = new MagickImage(objectImageFile);
                    if (fixture.IsTree)
                    {
                        objectImage.Blur();
                    }
                    m_modelImages.Add(fileName, objectImage);
                }
                else
                {
                    if (fixture.IsTree)
                    {
                        MainForm.Log(string.Format("Can not find image for tree {0} ({1}), using default tree", fixture.Name, fixture.NifName), MainForm.LogLevel.warning);
                        m_modelImages.Add(fileName, m_modelImages[defaultTree]);
                    }
                    else
                    {
                        m_modelImages.Add(fileName, null);
                    }
                }
            }

            // Draw the image
            if (m_modelImages.ContainsKey(fileName) && m_modelImages[fileName] != null)
            {
                NifRow orginalNif = FixturesLoader.NifRows.Where(n => n.NifId == fixture.FixtureRow.NifId).FirstOrDefault();
                if (orginalNif == null)
                {
                    MainForm.Log(string.Format("Error with imaged nif ({0})!", fixture.FixtureRow.TextualName), MainForm.LogLevel.warning);
                }

                System.Drawing.SizeF objectSize = orginalNif.GetSize(0, 0);

                // The final image
                using (MagickImage modelImage = new MagickImage(MagickColors.Transparent, fixture.CanvasWidth, fixture.CanvasHeight))
                {
                    // Place the replacing image
                    using (IMagickImage newModelImage = m_modelImages[fileName].Clone())
                    {
                        newModelImage.BackgroundColor = MagickColors.Transparent;

                        double scaleWidthToTreeImage  = objectSize.Width / newModelImage.Width;
                        double scaleHeightToTreeImage = objectSize.Height / newModelImage.Height;
                        int    width  = Convert.ToInt32(newModelImage.Width * scaleWidthToTreeImage * fixture.Scale);
                        int    height = Convert.ToInt32(newModelImage.Height * scaleHeightToTreeImage * fixture.Scale);

                        // Resize to new size
                        newModelImage.FilterType         = FilterType.Gaussian;
                        newModelImage.VirtualPixelMethod = VirtualPixelMethod.Transparent;
                        newModelImage.Resize(width, height);

                        // Rotate the image
                        //newModelImage.Rotate(fixture.FixtureRow.A * -1 * fixture.FixtureRow.AxisZ3D);
                        newModelImage.Rotate((360d * fixture.FixtureRow.AxisZ3D - fixture.FixtureRow.A) * -1);

                        // Place in center of modelImage
                        modelImage.Composite(newModelImage, Gravity.Center, CompositeOperator.SrcOver);
                    }

                    // Draw the shaped model if wanted
                    if (fixture.RendererConf.HasLight)
                    {
                        using (MagickImage modelShaped = new MagickImage(MagickColors.Transparent, fixture.CanvasWidth, fixture.CanvasHeight))
                        {
                            foreach (DrawableElement drawableElement in fixture.DrawableElements)
                            {
                                var light = 1 - drawableElement.lightning;
                                modelShaped.Settings.FillColor = new MagickColor(
                                    Convert.ToUInt16(ushort.MaxValue * light),
                                    Convert.ToUInt16(ushort.MaxValue * light),
                                    Convert.ToUInt16(ushort.MaxValue * light)
                                    );

                                DrawablePolygon polyDraw = new DrawablePolygon(drawableElement.coordinates);
                                modelShaped.Draw(polyDraw);
                            }

                            using (MagickImage modelMask = new MagickImage(MagickColors.Transparent, fixture.CanvasWidth, fixture.CanvasHeight))
                            {
                                modelShaped.Blur();
                                modelMask.Composite(modelShaped, 0, 0, CompositeOperator.DstAtop);
                                modelMask.Composite(modelImage, 0, 0, CompositeOperator.DstIn);
                                modelMask.Level(new Percentage(20), new Percentage(100), Channels.All);
                                modelImage.Composite(modelMask, 0, 0, CompositeOperator.ColorDodge);
                            }
                        }
                    }

                    // Add the shadow if not a tree (tree shadow are substituted by a treeoverlay)
                    if (fixture.RendererConf.HasShadow && !fixture.IsTree)
                    {
                        CastShadow(
                            modelImage,
                            fixture.RendererConf.ShadowOffsetX,
                            fixture.RendererConf.ShadowOffsetY,
                            fixture.RendererConf.ShadowSize,
                            new Percentage(100 - fixture.RendererConf.ShadowTransparency),
                            fixture.RendererConf.ShadowColor
                            );

                        // Update the canvas position to match the new border
                        fixture.CanvasX -= fixture.RendererConf.ShadowSize;
                        fixture.CanvasY -= fixture.RendererConf.ShadowSize;
                    }

                    // Set transprency if not a tree (see shadow)
                    if (fixture.RendererConf.Transparency != 0 && !fixture.IsTree)
                    {
                        double divideValue = 100.0 / (100.0 - fixture.RendererConf.Transparency);
                        modelImage.Evaluate(Channels.Alpha, EvaluateOperator.Divide, divideValue);
                    }

                    // Place the image on the right position
                    overlay.Composite(modelImage, Convert.ToInt32(fixture.CanvasX), Convert.ToInt32(fixture.CanvasY), CompositeOperator.SrcOver);
                }
            }
        }
예제 #10
0
        private void Draw(MagickImage map, List <DrawableFixture> fixtures)
        {
            MainForm.ProgressStart(string.Format("Drawing fixtures ({0}) ...", fixtures.Count));
            Stopwatch timer = Stopwatch.StartNew();

            using (MagickImage modelsOverlay = new MagickImage(MagickColors.Transparent, zoneConfiguration.TargetMapSize, zoneConfiguration.TargetMapSize))
            {
                using (MagickImage treeOverlay = new MagickImage(MagickColors.Transparent, zoneConfiguration.TargetMapSize, zoneConfiguration.TargetMapSize))
                {
                    int processCounter = 0;
                    foreach (DrawableFixture fixture in fixtures)
                    {
                        // Debug single models
                        //if (fixture.FixtureRow.NifId != 408)
                        //{
                        //    continue;
                        //}

                        switch (fixture.RendererConf.Renderer)
                        {
                        case FixtureRenderererType.Shaded:
                            DrawShaded((fixture.IsTree || fixture.IsTreeCluster) ? treeOverlay : modelsOverlay, fixture);
                            break;

                        case FixtureRenderererType.Flat:
                            DrawFlat((fixture.IsTree || fixture.IsTreeCluster) ? treeOverlay : modelsOverlay, fixture);
                            break;

                        case FixtureRenderererType.Image:
                            //DrawShaded((fixture.IsTree || fixture.IsTreeCluster) ? treeOverlay : modelsOverlay, fixture);
                            DrawImage((fixture.IsTree || fixture.IsTreeCluster) ? treeOverlay : modelsOverlay, fixture);
                            break;
                        }

                        int percent = 100 * processCounter / fixtures.Count();
                        MainForm.ProgressUpdate(percent);
                        processCounter++;
                    }

                    MainForm.ProgressStartMarquee("Merging ...");

                    FixtureRendererConfiguration2 treeImagesRConf = FixtureRendererConfigurations.GetRendererById("TreeImage");
                    if (treeImagesRConf.HasShadow)
                    {
                        CastShadow(
                            treeOverlay,
                            treeImagesRConf.ShadowOffsetX,
                            treeImagesRConf.ShadowOffsetY,
                            treeImagesRConf.ShadowSize,
                            new Percentage(100 - treeImagesRConf.ShadowTransparency),
                            treeImagesRConf.ShadowColor,
                            false
                            );
                    }

                    if (treeImagesRConf.Transparency != 0)
                    {
                        treeOverlay.Alpha(AlphaOption.Set);
                        double divideValue = 100.0 / (100.0 - TreeTransparency);
                        treeOverlay.Evaluate(Channels.Alpha, EvaluateOperator.Divide, divideValue);
                    }

                    map.Composite(modelsOverlay, 0, 0, CompositeOperator.SrcOver);
                    map.Composite(treeOverlay, 0, 0, CompositeOperator.SrcOver);
                }
            }

            timer.Stop();
            MainForm.Log(string.Format("Finished in {0} seconds.", timer.Elapsed.TotalSeconds), MainForm.LogLevel.success);
            MainForm.ProgressReset();
        }
예제 #11
0
        private void DebugMaps()
        {
            MainForm.Log("Drawing debug bound images ...", MainForm.LogLevel.warning);
            MainForm.ProgressStartMarquee("Debug bound images ...");

            DirectoryInfo debugDir = new DirectoryInfo(string.Format("{0}\\debug\\bound\\{1}", System.Windows.Forms.Application.StartupPath, zoneConfiguration.ZoneId));

            if (!debugDir.Exists)
            {
                debugDir.Create();
            }
            debugDir.GetFiles().ToList().ForEach(f => f.Delete());

            int boundIndex = 0;

            foreach (List <PointF> allCoords in m_bounds)
            {
                using (MagickImage bound = new MagickImage(MagickColors.Transparent, zoneConfiguration.TargetMapSize, zoneConfiguration.TargetMapSize))
                {
                    List <PointD> coords = allCoords.Select(c => new PointD(zoneConfiguration.ZoneCoordinateToMapCoordinate(c.X), zoneConfiguration.ZoneCoordinateToMapCoordinate(c.Y))).ToList();

                    DrawablePolygon poly = new DrawablePolygon(coords);
                    bound.Settings.FillColor = new MagickColor(0, 0, 0, 256 * 128);
                    bound.Draw(poly);

                    // Print Text
                    for (int i = 0; i < coords.Count; i++)
                    {
                        double x, y;

                        if (coords[i].X > zoneConfiguration.TargetMapSize / 2)
                        {
                            x = coords[i].X - 15;
                        }
                        else
                        {
                            x = coords[i].X + 1;
                        }

                        if (coords[i].Y < zoneConfiguration.TargetMapSize / 2)
                        {
                            y = coords[i].Y + 15;
                        }
                        else
                        {
                            y = coords[i].Y - 1;
                        }

                        bound.Settings.FontPointsize = 10.0;
                        bound.Settings.FillColor     = Color.Black;
                        DrawableText text = new DrawableText(x, y, string.Format("{0} ({1}/{2})", i, zoneConfiguration.MapCoordinateToZoneCoordinate(coords[i].X), zoneConfiguration.MapCoordinateToZoneCoordinate(coords[i].Y)));
                        bound.Draw(text);

                        using (IPixelCollection pixels = bound.GetPixels())
                        {
                            int x2, y2;
                            if (coords[i].X == zoneConfiguration.TargetMapSize)
                            {
                                x2 = zoneConfiguration.TargetMapSize - 1;
                            }
                            else
                            {
                                x2 = (int)coords[i].X;
                            }
                            if (coords[i].Y == zoneConfiguration.TargetMapSize)
                            {
                                y2 = zoneConfiguration.TargetMapSize - 1;
                            }
                            else
                            {
                                y2 = (int)coords[i].Y;
                            }

                            pixels.SetPixel(x2, y2, new ushort[] { 0, 0, 65535, 0 });
                        }
                    }

                    //bound.Quality = 100;
                    bound.Write(string.Format("{0}\\bound_{1}.png", debugDir.FullName, boundIndex));

                    boundIndex++;
                }
            }

            MainForm.ProgressReset();
        }
예제 #12
0
        private static FixtureRendererConfiguration2?ParseRendererConfigurationFromXmlNode(XElement node)
        {
            // Create a NumberFormatInfo object for floats and set some of its properties.
            System.Globalization.NumberFormatInfo provider = new System.Globalization.NumberFormatInfo();
            provider.NumberDecimalSeparator = ".";
            provider.NumberGroupSeparator   = "";
            provider.NumberGroupSizes       = new int[] { 2 };

            try
            {
                FixtureRendererConfiguration2 conf = new FixtureRendererConfiguration2();

                if (node.Descendants("id").Count() > 0)
                {
                    conf.Name = node.Descendants("id").First().Value;
                }
                else if (node.Descendants("pattern").Count() > 0)
                {
                    conf.Name = node.Descendants("pattern").First().Value;
                }

                conf.Renderer     = GetRendererType(node.Descendants("renderer").First().Value);
                conf.Color        = new ImageMagick.MagickColor((node.Descendants("color").Count() > 0) ? node.Descendants("color").First().Value : "#FFF");
                conf.Transparency = Convert.ToInt32((node.Descendants("transparency").Count() > 0) ? node.Descendants("transparency").First().Value : "0");

                var lightElement = node.Descendants("light");
                if (lightElement.Count() > 0)
                {
                    var light = lightElement.First();
                    conf.HasLight    = Convert.ToBoolean(light.Value);
                    conf.LightMin    = Convert.ToDouble(!string.IsNullOrEmpty(light.Attribute("min").Value) ? light.Attribute("min").Value : "0.6", provider);
                    conf.LightMax    = Convert.ToDouble(!string.IsNullOrEmpty(light.Attribute("max").Value) ? light.Attribute("max").Value : "1.0", provider);
                    conf.LightVector = GetLightVector(string.IsNullOrEmpty(light.Attribute("direction").Value) ? light.Attribute("direction").Value : "1,1,-1");
                }

                var shadowElement = node.Descendants("shadow");
                if (shadowElement.Count() > 0)
                {
                    var shadow = shadowElement.First();
                    conf.HasShadow          = Convert.ToBoolean(shadow.Value);
                    conf.ShadowColor        = new ImageMagick.MagickColor((!string.IsNullOrEmpty(shadow.Attribute("color").Value)) ? shadow.Attribute("color").Value : "#000");
                    conf.ShadowOffsetX      = Convert.ToInt32(!string.IsNullOrEmpty(shadow.Attribute("offset_x").Value) ? shadow.Attribute("offset_x").Value : "0");
                    conf.ShadowOffsetY      = Convert.ToInt32(!string.IsNullOrEmpty(shadow.Attribute("offset_y").Value) ? shadow.Attribute("offset_y").Value : "0");
                    conf.ShadowSize         = Convert.ToDouble(!string.IsNullOrEmpty(shadow.Attribute("size").Value) ? shadow.Attribute("size").Value : "1", provider);
                    conf.ShadowTransparency = Convert.ToInt32(!string.IsNullOrEmpty(shadow.Attribute("transparency").Value) ? shadow.Attribute("transparency").Value : "75");
                }

                if (!string.IsNullOrEmpty(node.Attribute("is_default").Value) && Convert.ToBoolean(node.Attribute("is_default").Value) == true)
                {
                    defaultConfiguration = conf;
                }

                return(conf);
            }
            catch (Exception ex)
            {
                MainForm.Log("Error in fixtures XML", MainForm.LogLevel.error);
                MainForm.Log(ex.Message, MainForm.LogLevel.error);
                return(null);
            }
        }
예제 #13
0
        public MagickImage Draw()
        {
            MainForm.ProgressStart("Rendering background ...");

            // Check which terrain file is used
            string texMpk = string.Format("{0}\\tex{1}.mpk", this.textureZoneDataDirectory, this.textureZoneId);
            string lodMpk = string.Format("{0}\\lod{1}.mpk", this.textureZoneDataDirectory, this.textureZoneId);

            // Get the tile dimension
            double tileWidth    = 512.0;
            string tileTemplate = "";

            MPAK mpak = new MPAK();

            if (File.Exists(texMpk))
            {
                mpak.Load(texMpk);

                if (mpak.Files.Where(f => f.Name.ToLower() == "tex00-00.dds").Count() > 0)
                {
                    tileTemplate += "tex0{0}-0{1}.dds";
                    tileWidth     = 512.0;
                }
            }

            if (string.IsNullOrEmpty(tileTemplate))
            {
                mpak.Load(lodMpk);

                if (mpak.Files.Where(f => f.Name.ToLower() == "lod00-00.dds").Count() > 0)
                {
                    tileTemplate += "lod0{0}-0{1}.dds";
                    tileWidth     = 256.0;
                }
            }

            if (string.IsNullOrEmpty(tileTemplate))
            {
                MainForm.Log(string.Format("Zone {0}: No background textures found!", zoneConfiguration.ZoneId), MainForm.LogLevel.error);
                return(null);
            }

            // original size
            double orginalWidth = tileWidth * 8;
            double resizeFactor = (double)zoneConfiguration.TargetMapSize / (double)orginalWidth; // 0 - 1

            MagickImage map = new MagickImage(Color.Transparent, zoneConfiguration.TargetMapSize, zoneConfiguration.TargetMapSize);

            int lastWidth = 0;
            int x         = 0;

            for (int col = 0; col <= 7; col++)
            {
                int y = 0;
                for (int row = 0; row <= 7; row++)
                {
                    string filename = string.Format(tileTemplate, col, row);

                    using (MagickImage mapTile = new MagickImage(mpak.GetFile(filename).Data))
                    {
                        int newSize = Convert.ToInt32(mapTile.Width * resizeFactor);
                        mapTile.Resize(newSize, newSize);

                        map.Composite(mapTile, x, y, CompositeOperator.SrcOver);

                        // Calculate new y
                        y        += mapTile.Height;
                        lastWidth = mapTile.Height;
                    }
                }

                x += lastWidth;

                int percent = 100 * col / 8;
                MainForm.ProgressUpdate(percent);
            }

            MainForm.ProgressStartMarquee("Merging ...");

            // Remove rounding fails
            map.Trim();

            // Flip if set
            if (this.flipX)
            {
                map.Flop();
            }
            if (this.flipY)
            {
                map.Flip();
            }

            // Sharpen (tested a lot, seems to be the best values)
            map.Sharpen(4, 3);

            MainForm.ProgressReset();

            return(map);
        }
예제 #14
0
        /// <summary>
        /// Render selected Zones as Background Worker
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void drawMapBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                ZoneSelection zone = (ZoneSelection)e.Argument;

                // Start BackgroundWorker
                Log(string.Format("Start creating map for zone {0} ...", zone.Id), LogLevel.notice);

                // The filename
                string targetFilePath = string.Format("{0}\\maps", Application.StartupPath);

                string pattern = filePatternTextBox.Text;
                if (string.IsNullOrEmpty(pattern))
                {
                    pattern = "zone{id}_{size}";
                }

                // Replace some values
                pattern = pattern.Replace("{id}", zone.Id);
                pattern = pattern.Replace("{name}", zone.Name);
                pattern = pattern.Replace("{expansion}", zone.Expansion);
                pattern = pattern.Replace("{type}", zone.Type);
                pattern = pattern.Replace("{size}", TargetMapSize.ToString());
                pattern = Tools.MakeValidFileName(pattern);

                // File extension
                string fileExtension         = "jpg";
                string selectedFileExtension = "JPEG";
                this.Invoke((MethodInvoker) delegate()
                {
                    selectedFileExtension = fileTypeComboBox.Text;
                });
                switch (selectedFileExtension)
                {
                case "PNG":
                    fileExtension = "png";
                    break;

                case "JPEG":
                default:
                    fileExtension = "jpg";
                    break;
                }

                // The Target File
                FileInfo mapFile = new FileInfo(string.Format("{0}\\maps\\{1}.{2}", Application.StartupPath, pattern, fileExtension));
                if (!Directory.Exists(mapFile.DirectoryName))
                {
                    Directory.CreateDirectory(mapFile.DirectoryName);
                }

                bool     lightmap         = generateLightmapCheckBox.Checked;
                double   lightmapZScale   = Convert.ToDouble(heightmapZScaleTextBox.Value);
                double   lightmapLightMin = Convert.ToDouble(heightmapLightMinTextBox.Value);
                double   lightmapLightMax = Convert.ToDouble(heightmapLightMaxTextBox.Value);
                double[] lightmapZVector  = new double[] { Convert.ToDouble(heightmapZVector1TextBox.Value), Convert.ToDouble(heightmapZVector2TextBox.Value), Convert.ToDouble(heightmapZVector3TextBox.Value) };

                bool  rivers = generateRiversCheckBox.Checked;
                bool  riversUseDefaultColor = riversUseDefaultColorCheckBox.Checked;
                Color riversColor           = Properties.Settings.Default.mapRiverColor;
                int   riverOpacity          = Convert.ToInt32(mapRiversOpacityTextBox.Value);

                bool  bounds               = generateBoundsCheckBox.Checked;
                Color boundsColor          = Properties.Settings.Default.mapBoundsColor;
                int   boundsOpacity        = Convert.ToInt32(mapBoundsOpacityTextBox.Text);
                bool  excludeBoundsFromMap = excludeBoundsFromMapCheckbox.Checked;

                bool fixtures = drawFixturesCheckBox.Checked;
                bool trees    = drawTreesCheckBox.Checked;

                // Generate the map
                using (ZoneConfiguration conf = new ZoneConfiguration(zone.Id, TargetMapSize))
                {
                    // Create Background
                    MapBackground background = new MapBackground(conf);

                    MainForm.Log("Rendering background ...", LogLevel.notice);
                    using (MagickImage map = background.Draw())
                    {
                        if (map != null)
                        {
                            MainForm.Log("Finished background rendering!", LogLevel.success);

                            // Create lightmap
                            if (lightmap)
                            {
                                MainForm.Log("Rendering lightmap ...", LogLevel.notice);
                                MapLightmap lightmapGenerator = new MapLightmap(conf);
                                lightmapGenerator.ZScale   = lightmapZScale;
                                lightmapGenerator.LightMin = lightmapLightMin;
                                lightmapGenerator.LightMax = lightmapLightMax;
                                lightmapGenerator.ZVector  = lightmapZVector;
                                lightmapGenerator.RecalculateLights();
                                lightmapGenerator.Draw(map);
                                MainForm.Log("Finished lightmap rendering!", LogLevel.success);
                            }

                            // We need this for fixtures
                            MainForm.Log("Loading water configurations ...", LogLevel.notice);
                            MapWater river = new MapWater(conf);
                            MainForm.Log("Finished loading water configurations!", LogLevel.success);

                            MapFixtures fixturesGenerator = null;
                            if (fixtures || trees)
                            {
                                MainForm.Log("Loading fixtures ...", LogLevel.notice);
                                fixturesGenerator = new MapFixtures(conf, river.WaterAreas);
                                fixturesGenerator.DrawFixtures      = drawFixturesCheckBox.Checked;
                                fixturesGenerator.DrawTrees         = drawTreesCheckBox.Checked;
                                fixturesGenerator.DrawTreesAsImages = treesAsImages.Checked;
                                fixturesGenerator.TreeTransparency  = Convert.ToInt32(mapTreeTransparencyTextBox.Value);
                                fixturesGenerator.Start();
                                MainForm.Log("Finished loading fixtures!", LogLevel.success);
                            }

                            // Draw Fixtures below water
                            if (fixtures || trees)
                            {
                                MainForm.Log("Rendering fixtures below water level ...", LogLevel.notice);
                                fixturesGenerator.Draw(map, true);
                                MainForm.Log("Finished rendering fixtures below water level!", LogLevel.success);
                            }

                            // Create Rivers
                            if (rivers)
                            {
                                MainForm.Log("Rendering water ...", LogLevel.notice);
                                river.WaterColor        = riversColor;
                                river.WaterTransparency = riverOpacity;
                                river.UseClientColors   = riversUseDefaultColor;
                                river.Draw(map);
                                MainForm.Log("Finished water rendering!", LogLevel.success);
                            }

                            // Draw Fixtures above water
                            if (fixtures || trees)
                            {
                                MainForm.Log("Rendering fixtures above water level ...", LogLevel.notice);
                                fixturesGenerator.Draw(map, false);
                                MainForm.Log("Finished rendering fixtures above water level!", LogLevel.success);
                            }

                            if (fixturesGenerator != null)
                            {
                                fixturesGenerator.Dispose();
                            }

                            // Create bounds
                            if (bounds)
                            {
                                MainForm.Log("Adding zone bounds ...", LogLevel.notice);
                                MapBounds mapBounds = new MapBounds(conf);
                                mapBounds.BoundsColor    = boundsColor;
                                mapBounds.Transparency   = boundsOpacity;
                                mapBounds.ExcludeFromMap = excludeBoundsFromMap;
                                mapBounds.Draw(map);
                                MainForm.Log("Finished zone bunds!", LogLevel.success);
                            }

                            MainForm.Log(string.Format("Writing map image {0} ...", mapFile.Name));
                            ProgressStartMarquee("Writing map image ...");
                            map.Quality = Convert.ToInt32(mapQualityTextBox.Value);
                            map.Write(mapFile.FullName);
                        }
                    }
                }


                if (mapFile.Exists)
                {
                    LoadImage(mapFile.FullName);
                    ProgressReset();
                }
                else
                {
                    Log("Errors during progress!", LogLevel.error);
                }
            }
            catch (Exception ex)
            {
                MainForm.Log("Unhandled Exception thrown!", LogLevel.error);
                MainForm.Log(ex.Message, LogLevel.error);
                MainForm.Log(ex.StackTrace, LogLevel.error);
            }
        }