/// <summary>
        /// Maps the single component pattern, to a list of implemented patterns.
        /// </summary>
        /// <param name="pattern">The pattern.</param>
        /// <param name="componentMatches">The component matches.</param>
        /// <returns>The founddesignpatterns model, with the pattern and a list of implementations</returns>
        private FoundDesignPattern MapSingleComponentPattern(DesignPattern pattern, Dictionary <Component, List <ComponentMatch> > componentMatches)
        {
            var foundPattern = new FoundDesignPattern()
            {
                DesignPattern   = pattern,
                Implementations = new List <Dictionary <Component, List <SymbolInformation> > >()
            };

            foreach (var matches in componentMatches.Values.SelectMany(v => v))
            {
                foundPattern.Implementations.Add(
                    new Dictionary <Component, List <SymbolInformation> >()
                {
                    {
                        pattern.Components.Single(),
                        new List <SymbolInformation>()
                        {
                            matches.SymbolInformation
                        }
                    }
                }
                    );
            }

            return(foundPattern);
        }
Exemplo n.º 2
0
    public void ShowPattern(DesignServer.Pattern pattern, PatternExchange exchange)
    {
        try
        {
            PatternExchange = exchange;
            Pattern         = pattern;
            if (CurrentTexture != null)
            {
                CurrentTexture.Dispose();
                CurrentTexture = null;
            }

            ACNHFileFormat format = new ACNHFileFormat(pattern.Bytes);
            DesignPattern  patt   = null;
            if (format.IsPro)
            {
                patt = new ProDesignPattern();
                patt.CopyFrom(format);
            }
            else
            {
                patt = new SimpleDesignPattern();
                patt.CopyFrom(format);
            }

            CurrentTexture = patt.GetBitmap();
            CurrentTexture.Apply();
            CurrentTexture.Texture.filterMode = FilterMode.Point;
            CurrentTexture.Texture.wrapMode   = TextureWrapMode.Clamp;
            this.Image.texture = CurrentTexture.Texture;
        }
        catch (System.Exception e)
        {
        }
    }
Exemplo n.º 3
0
 public DesignPattern GetResultPattern()
 {
     if (IsReady)
     {
         if (ResultPattern != null)
         {
             if (ResultPreview != null)
             {
                 GameObject.DestroyImmediate(ResultPreview.texture);
                 GameObject.DestroyImmediate(ResultPreview);
             }
             ResultPreview = null;
             ResultPixels  = null;
         }
         ResultPattern = new DesignPattern();
         ResultPattern.FromBitmap(Result);
         ResultPattern.Name       = Pattern.Name;
         ResultPattern.PersonalID = new MyHorizons.Data.PlayerData.PersonalID()
         {
             UniqueId = 0xFFFFFFFF, TownId = Pattern.PersonalID.TownId
         };
         ResultPattern.PersonalID.SetName(Pattern.PersonalID.GetName());
         IsReady = false;
     }
     return(ResultPattern);
 }
        /// <summary>
        /// Maps the multiple component pattern.
        /// </summary>
        /// <param name="pattern">The pattern.</param>
        /// <param name="componentMatches">The component matches.</param>
        /// <returns>The founddesignpatterns model, with the pattern and a list of implementations</returns>
        private FoundDesignPattern MapMultipleComponentPattern(DesignPattern pattern, Dictionary <Component, List <ComponentMatch> > componentMatches)
        {
            var foundPattern = new FoundDesignPattern()
            {
                DesignPattern   = pattern,
                Implementations = new List <Dictionary <Component, List <SymbolInformation> > >()
            };

            var graph = new PatternGraph(pattern);
            var implementationCandidates = this.GetPatternImplementations(graph, componentMatches);

            foreach (var implementationCandidate in implementationCandidates)
            {
                var cleanedImplementation = this.RemoveDuplicateComponentMatches(implementationCandidate);

                if (this.MatchComponentCount(pattern, cleanedImplementation))
                {
                    var checkedImplementation = this.MatchImplementationComponentTypes(graph, cleanedImplementation);

                    if (this.MatchComponentCount(pattern, checkedImplementation) && this.ValidComponentOccurrence(checkedImplementation))
                    {
                        foundPattern.Implementations.Add(this.CastDictionary(checkedImplementation));
                    }
                }
            }

            if (foundPattern.Implementations.Count > 0)
            {
                return(foundPattern);
            }

            return(null);
        }
Exemplo n.º 5
0
 public void SetPattern(DesignPattern pattern)
 {
     Initialize();
     if (this.Pattern != null)
     {
         Logger.Log(Logger.Level.TRACE, "Removing old pattern preview and texture.");
         GameObject.Destroy(Preview.texture);
         GameObject.Destroy(Preview);
     }
     if (pattern == null)
     {
         Logger.Log(Logger.Level.ERROR, "Pattern is null!");
     }
     this.Pattern = pattern;
     this.Name    = pattern.Name;
     if (TooltipHandler == null)
     {
         TooltipHandler = GetComponent <TooltipHandler>();
     }
     if (TooltipHandler != null)
     {
         TooltipHandler.Tooltip = this.Name;
     }
     Preview = pattern.GetPreview();
     if (ImageImage == null)
     {
         Logger.Log(Logger.Level.ERROR, "ImageImage is null!");
     }
     ImageImage.sprite = Preview;
 }
Exemplo n.º 6
0
    public void Show(DesignPattern pattern, System.Action confirm, System.Action cancel)
    {
        this.CurrentBrush = new Brush()
        {
            Editor = this
        };
        if (pattern != null)
        {
            this.CurrentPattern = new Pattern(this, pattern);
            this.CurrentPattern.Load();

            IsShown       = true;
            ConfirmAction = confirm;
            CancelAction  = cancel;

            Type = pattern.Type;
        }

        Preview.texture = Previews.AllPreviews[Type].Camera.targetTexture;
        Previews.AllPreviews[Type].ResetPosition();
        Previews.AllPreviews[Type].Render();

        Tools.PatternChanged();
        Tools.BrushUpdated();
        Tools.SwitchTool(Tools.Tool.None);
        Tools.SwitchToolset(Tools.Toolset.RasterLayer);
        PixelGrid.PatternLoaded();
    }
    public static TextureBitmap GetBitmap(this DesignPattern pattern)
    {
        int width  = pattern.Width;
        int height = pattern.Height;

        var bitmap = new TextureBitmap(width, height);

        unsafe
        {
            TextureBitmap.Color *ptr = bitmap.GetColors();

            for (var y = 0; y < height; y++)
            {
                for (var x = 0; x < width; x++)
                {
                    var b = pattern.GetPixel(x, y);
                    if (b == 15)
                    {
                        *(ptr + x + (height - 1 - y) * width) = new TextureBitmap.Color(0, 0, 0, 0);
                    }
                    else
                    {
                        var c = pattern.Palette[b];
                        *(ptr + x + (height - 1 - y) * width) = new TextureBitmap.Color(c.R, c.G, c.B, 255);
                    }
                }
            }
        }
        return(bitmap);
    }
Exemplo n.º 8
0
        public PatternEditor(DesignPattern pattern, double width = 32, double height = 32) : base(pattern, width, height)
        {
            Resize(Width, Height);

            this.GetObservable(WidthProperty).Subscribe(newWidth => Resize(newWidth, Height));
            this.GetObservable(HeightProperty).Subscribe(newHeight => Resize(Width, newHeight));
        }
Exemplo n.º 9
0
    static void Main(string[] args)
    {
        DesignPattern dp = new DesignPattern();

        // dp.PlaySingleton();
        // dp.ExampleTemplateMethod();
        dp.ExampleFacade();
    }
Exemplo n.º 10
0
 private void LoadPattern(DesignPattern designPattern)
 {
     PB_Pattern.Image   = ImageUtil.ResizeImage(designPattern.GetImage(), 128, 128);
     PB_Palette.Image   = ImageUtil.ResizeImage(designPattern.GetPalette(), 150, 10);
     L_PatternName.Text = designPattern.DesignName + Environment.NewLine +
                          designPattern.TownName + Environment.NewLine +
                          designPattern.PlayerName;
 }
 public void SetPattern(DesignPattern pattern)
 {
     this.CurrentPattern = pattern;
     for (int i = 0; i < 15; i++)
     {
         Buttons[i].SetColor(new Color(((float)pattern.Palette[i].R) / 255f, ((float)pattern.Palette[i].G) / 255f, ((float)pattern.Palette[i].B) / 255f));
     }
 }
Exemplo n.º 12
0
    public Pattern(PatternEditor editor, DesignPattern pattern)
    {
        try
        {
            Logger.Log(Logger.Level.INFO, "[PatternEditor/Pattern] Creating new pattern");
            StartPreviewThread();
            Logger.Log(Logger.Level.DEBUG, "[PatternEditor/Pattern] Preview generator thread started!");
            _Type = pattern.Type;
            Logger.Log(Logger.Level.DEBUG, "[PatternEditor/Pattern] Pattern type: " + _Type.ToString());
            Bitmap = new TextureBitmap(pattern.Width, pattern.Height);
            Logger.Log(Logger.Level.DEBUG, "[PatternEditor/Pattern] Created TextureBitmap " + pattern.Width + "x" + pattern.Height);
            Bitmap.Clear();
            PreviewBitmap = new TextureBitmap(pattern.Width, pattern.Height);
            Logger.Log(Logger.Level.DEBUG, "[PatternEditor/Pattern] Created preview TextureBitmap " + pattern.Width + "x" + pattern.Height);
            PreviewBitmap.Clear();
            PreviewSprite = UnityEngine.Sprite.Create(PreviewBitmap.Texture, new UnityEngine.Rect(0, 0, PreviewBitmap.Width, PreviewBitmap.Height), new UnityEngine.Vector2(0.5f, 0.5f));
            Logger.Log(Logger.Level.DEBUG, "[PatternEditor/Pattern] Created preview sprite");

            UpscaledPreviewBitmap = new TextureBitmap(pattern.Width * 4, pattern.Height * 4);
            Logger.Log(Logger.Level.DEBUG, "[PatternEditor/Pattern] Created upscaled preview TextureBitmap " + (pattern.Width * 4) + "x" + (pattern.Height * 4));
            UpscaledPreviewBitmap.Clear();

            Quantizer = Quantizers[0];
            Logger.Log(Logger.Level.DEBUG, "[PatternEditor/Pattern] Selected Quantizer: " + Quantizer.GetType().ToString());
            ColorCache = ColorCaches[0];
            Logger.Log(Logger.Level.DEBUG, "[PatternEditor/Pattern] Selected Color Cache: " + ColorCache.GetType().ToString());

            Editor        = editor;
            DesignPattern = pattern;
            var colors = pattern.GetPixels();

            Logger.Log(Logger.Level.DEBUG, "[PatternEditor/Pattern] Parsing colors of pattern...");
            unsafe
            {
                var bitmapColors = Bitmap.GetColors();
                for (int y = 0; y < Height; y++)
                {
                    for (int x = 0; x < Width; x++)
                    {
                        var col = new TextureBitmap.Color(
                            (byte)(colors[x + y * Width].r * 255f),
                            (byte)(colors[x + y * Width].g * 255f),
                            (byte)(colors[x + y * Width].b * 255f),
                            (byte)(colors[x + y * Width].a * 255f)
                            );
                        *(bitmapColors + x + (Height - 1 - y) * Width) = col;
                    }
                }
            }
            Logger.Log(Logger.Level.DEBUG, "[PatternEditor/Pattern] Parsed " + (Width * Height) + " pixels.");
            Info = DesignPatternInformation.Types[pattern.Type];
            Logger.Log(Logger.Level.DEBUG, "[PatternEditor/Pattern] Pattern information obtained.");
        }
        catch (System.Exception e)
        {
            Logger.Log(Logger.Level.ERROR, "[PatternEditor/Pattern] Error while creating pattern: " + e.ToString());
        }
    }
Exemplo n.º 13
0
        public List <string> Validate(DesignPattern pattern)
        {
            this.errorMessages = new List <string>();
            this.designPattern = pattern;

            this.ValidateDesignPattern(pattern);

            return(this.errorMessages);
        }
Exemplo n.º 14
0
    public DesignPattern Save()
    {
        var pattern = new DesignPattern();

        pattern.Type  = Type;
        pattern.IsPro = Type != DesignPattern.TypeEnum.SimplePattern;
        pattern.FromTexture(this.CurrentPattern.GetPreviewSprite().texture);
        return(pattern);
    }
Exemplo n.º 15
0
    public void Clear()
    {
        var p = new DesignPattern();

        p.Type   = this.Type;
        p.IsPro  = this.Type != DesignPattern.TypeEnum.SimplePattern;
        p.Pixels = new byte[p.Width / 2 * p.Height];
        p.Empty();
        Colors = p.GetPixels();
        Load();
    }
Exemplo n.º 16
0
 public void SetPattern(DesignPattern pattern)
 {
     if (this.Pattern != null)
     {
         GameObject.DestroyImmediate(Preview.texture);
         GameObject.DestroyImmediate(Preview);
     }
     this.Pattern      = pattern;
     this.Name         = pattern.Name;
     Preview           = pattern.GetPreview();
     ImageImage.sprite = Preview;
 }
    public static void FromBitmap(this DesignPattern pattern, TextureBitmap bitmap)
    {
        Dictionary <TextureBitmap.Color, byte> colorMap = new Dictionary <TextureBitmap.Color, byte>();

        for (int i = 0; i < 15; i++)
        {
            pattern.Palette[i].R = 0;
            pattern.Palette[i].G = 0;
            pattern.Palette[i].B = 0;
        }

        int width  = pattern.Width;
        int height = pattern.Height;

        unsafe
        {
            var colors = bitmap.GetColors();
            pattern.Image = new byte[width * height];
            int bitmapHeight = bitmap.Height;
            int bitmapWidth  = bitmap.Width;
            for (var y = 0; y < width; y++)
            {
                for (var x = 0; x < height; x++)
                {
                    var pixelColor = new TextureBitmap.Color(0, 0, 0, 0);
                    if (x < bitmapWidth && y < bitmapHeight)
                    {
                        pixelColor = colors[x + (bitmapHeight - 1 - y) * bitmapHeight];
                    }

                    byte index = 0xF;
                    if (pixelColor.A == 255)
                    {
                        if (colorMap.ContainsKey(pixelColor))
                        {
                            index = colorMap[pixelColor];
                        }
                        else
                        {
                            index = (byte)colorMap.Count;
                            pattern.Palette[index].R = pixelColor.R;
                            pattern.Palette[index].G = pixelColor.G;
                            pattern.Palette[index].B = pixelColor.B;
                            colorMap.Add(pixelColor, index);
                        }
                    }

                    pattern.SetPixel(x, y, index);
                }
            }
        }
    }
 public void SelectPattern(DesignPattern pattern)
 {
     if (pattern == Pattern)
     {
         return;
     }
     Controller.Instance.ConfirmationPopup.Show("<align=\"center\"><#827157>,,<#12c7ce>" + pattern.Name + "<#827157>‘‘\r\nwill be removed by this", () => {
         pattern.CopyFrom(Pattern);
         _IsFinished = true;
     }, () => {
         _IsFinished = true;
     });
 }
    public static Sprite GetPreview(this DesignPattern pattern)
    {
        int width  = pattern.Width;
        int height = pattern.Height;

        var texture = new Texture2D(width, height, TextureFormat.RGBA32, false);

        texture.filterMode = FilterMode.Point;
        UnityEngine.Color[] pixels       = pattern.GetPixels();
        UnityEngine.Color[] resultPixels = new UnityEngine.Color[pixels.Length];
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                resultPixels[x + (height - 1 - y) * width] = pixels[x + y * width];
            }
        }

        var visible = new bool[width * height];

        try
        {
            var info = DesignPatternInformation.Types[pattern.Type];
            foreach (var part in info.Parts)
            {
                for (var x = 0; x < part.Width; x++)
                {
                    for (var y = 0; y < part.Height; y++)
                    {
                        var picX = part.X + x;
                        var picY = part.Y + y;
                        var vis  = part.Visible[x + y * part.Width] == '1';
                        visible[picX + (height - 1 - picY) * width] = vis;
                    }
                }
            }
        }
        catch (Exception e)
        {
            Debug.LogException(e);
            Debug.LogError("Pattern type " + pattern.Type);
        }
        for (var i = 0; i < visible.Length; i++)
        {
            resultPixels[i] = visible[i] ? resultPixels[i] : new UnityEngine.Color(0f, 0f, 0f, 0f);
        }

        texture.SetPixels(resultPixels);
        texture.Apply();
        return(UnityEngine.Sprite.Create(texture, new Rect(0, 0, pattern.Width, pattern.Height), new Vector2(0.5f, 0.5f)));
    }
Exemplo n.º 20
0
    public void SelectPattern(DesignPattern pattern)
    {
        if (pattern == Pattern)
        {
            return;
        }
        var backup = new DesignPattern();

        backup.CopyFrom(Controller.Instance.CurrentSavegame.DesignPatterns[Pattern.Index]);

        Controller.Instance.CurrentSavegame.DesignPatterns[Pattern.Index].CopyFrom(Controller.Instance.CurrentSavegame.DesignPatterns[pattern.Index]);
        Controller.Instance.CurrentSavegame.DesignPatterns[pattern.Index].CopyFrom(backup);

        _IsFinished = true;
    }
Exemplo n.º 21
0
    public Pattern(PatternEditor editor, DesignPattern pattern)
    {
        _Type      = pattern.Type;
        Result     = new Bitmap(1, 1);
        Quantizer  = Quantizers[0];
        ColorCache = ColorCaches[0];

        Editor        = editor;
        DesignPattern = pattern;
        Colors        = pattern.GetPixels();

        Info = DesignPatternInformation.Types[pattern.Type];

        UpscaledPreviewTexture = new UnityEngine.Texture2D(Width * 4, Height * 4, UnityEngine.TextureFormat.RGB24, false);
        PreviewTexture         = new UnityEngine.Texture2D(Width, Height, UnityEngine.TextureFormat.ARGB32, false);
    }
Exemplo n.º 22
0
        private void B_LoadDesign_Click(object sender, EventArgs e)
        {
            var original = SAV.Main.GetDesign(PatternIndex);
            var name     = original.DesignName;

            using var ofd = new OpenFileDialog
                  {
                      Filter   = "New Horizons Design Pattern (*.nhd)|*.nhd|All files (*.*)|*.*",
                      FileName = $"{name}.nhd",
                  };
            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            var file         = ofd.FileName;
            var expectLength = original.Data.Length;
            var fi           = new FileInfo(file);

            if (fi.Length != expectLength)
            {
                var msg = string.Format(MessageStrings.MsgDataSizeMismatchImport, fi.Length, expectLength);
                WinFormsUtil.Error(MessageStrings.MsgCanceling, msg);
                return;
            }

            var data    = File.ReadAllBytes(ofd.FileName);
            var d       = new DesignPattern(data);
            var player0 = SAV.Players[0].Personal;

            if (!d.IsOriginatedFrom(player0))
            {
                var notHost = string.Format(MessageStrings.MsgDataDidNotOriginateFromHost_0, player0.PlayerName);
                var result  = WinFormsUtil.Prompt(MessageBoxButtons.YesNoCancel, notHost, MessageStrings.MsgAskUpdateValues);
                if (result == DialogResult.Cancel)
                {
                    return;
                }
                if (result == DialogResult.Yes)
                {
                    d.ChangeOrigins(player0, d.Data);
                }
            }

            SAV.Main.SetDesign(d, PatternIndex);
            LoadPattern(d);
        }
Exemplo n.º 23
0
        private void B_LoadDesign_Click(object sender, EventArgs e)
        {
            var original = SAV.Main.GetDesign(PatternIndex);
            var name     = original.DesignName;

            using var ofd = new OpenFileDialog
                  {
                      Filter   = "New Horizons Design Pattern (*.nhd)|*.nhd|All files (*.*)|*.*",
                      FileName = $"{name}.nhd",
                  };
            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            var file         = ofd.FileName;
            var expectLength = original.Data.Length;
            var fi           = new FileInfo(file);

            if (fi.Length != expectLength)
            {
                var msg = $"Imported Design Pattern's data length (0x{fi.Length:X}) does not match the required length (0x{expectLength:X}).";
                WinFormsUtil.Error("Cancelling:", msg);
                return;
            }

            var data    = File.ReadAllBytes(ofd.FileName);
            var d       = new DesignPattern(data);
            var player0 = SAV.Players[0].Personal;

            if (!d.IsOriginatedFrom(player0))
            {
                var result = WinFormsUtil.Prompt(MessageBoxButtons.YesNoCancel,
                                                 $"Imported Design Pattern did not originate from Villager0 ({player0.PlayerName})'s data.", "Update values?");
                if (result == DialogResult.Cancel)
                {
                    return;
                }
                if (result == DialogResult.Yes)
                {
                    d.ChangeOrigins(player0, d.Data);
                }
            }

            SAV.Main.SetDesign(d, PatternIndex);
            LoadPattern(d);
        }
    public static void FromBitmap(this DesignPattern pattern, Bitmap bitmap)
    {
        Dictionary <System.Drawing.Color, byte> colorMap = new Dictionary <System.Drawing.Color, byte>();

        for (int i = 0; i < 15; i++)
        {
            pattern.Palette[i].R = 0;
            pattern.Palette[i].G = 0;
            pattern.Palette[i].B = 0;
        }

        int width  = pattern.Width;
        int height = pattern.Height;

        pattern.Pixels = new byte[width * height];
        for (var y = 0; y < width; y++)
        {
            for (var x = 0; x < height; x++)
            {
                var pixelColor = System.Drawing.Color.FromArgb(0, 0, 0, 0);
                if (x < bitmap.Width && y < bitmap.Height)
                {
                    pixelColor = bitmap.GetPixel(x, y);
                }


                byte index = 0xF;
                if (pixelColor.A == 255)
                {
                    if (colorMap.ContainsKey(pixelColor))
                    {
                        index = colorMap[pixelColor];
                    }
                    else
                    {
                        index = (byte)colorMap.Count;
                        pattern.Palette[index].R = pixelColor.R;
                        pattern.Palette[index].G = pixelColor.G;
                        pattern.Palette[index].B = pixelColor.B;
                        colorMap.Add(pixelColor, index);
                    }
                }

                pattern.SetPixel(x, y, index);
            }
        }
    }
Exemplo n.º 25
0
        public PatternEditor(DesignPattern pattern, PaletteSelector selector, double width = 32, double height = 32) : base(pattern, width, height)
        {
            _paletteSelector = selector;
            Resize(Width, Height);
            ToolTip.SetTip(this, null);

            this.GetObservable(WidthProperty).Subscribe(newWidth => Resize(newWidth, Height));
            this.GetObservable(HeightProperty).Subscribe(newHeight => Resize(Width, newHeight));
            PointerMoved += OnPointerMoved;
            PointerLeave += (o, e) =>
            {
                CellX = CellY = -1;
                InvalidateVisual();
            };
            PointerPressed  += OnPointerPressed;
            PointerReleased += OnPointerReleased;
        }
Exemplo n.º 26
0
 public void Show(DesignPattern pattern, System.Action <DesignServer.Pattern> confirm, System.Action cancel, string label = null)
 {
     Pattern = pattern;
     CreatorInputField.text = PlayerPrefs.GetString("CreatorName");
     Tags    = new List <string>();
     Confirm = confirm;
     Cancel  = cancel;
     Animator.SetTrigger("TransitionIn");
     if (Controller.Instance.CurrentOperation is IPatternOperation patternOperation)
     {
         CreatorInputField.text = patternOperation.GetPattern().Name;
     }
     UpdateTags();
     NameInputField.text = pattern.Name;
     CreatorInputField.Select();
     CreatorInputField.ActivateInputField();
 }
Exemplo n.º 27
0
    public void Show(DesignPattern pattern, System.Action confirm, System.Action cancel)
    {
        try
        {
            Logger.Log(Logger.Level.DEBUG, "[PatternEditor] Showing pattern editor...");

            Logger.Log(Logger.Level.DEBUG, "[PatternEditor] Creating new brush...");
            if (this.CurrentBrush != null)
            {
                this.CurrentBrush.Dispose();
                this.CurrentBrush = null;
            }

            this.CurrentBrush = new Brush()
            {
                Editor = this
            };
            if (pattern != null)
            {
                Logger.Log(Logger.Level.DEBUG, "[PatternEditor] Adding pattern to editor.");
                IsPro = pattern is ProDesignPattern;
                this.CurrentPattern = new Pattern(this, pattern);
                this.CurrentPattern.Load();

                IsShown       = true;
                ConfirmAction = confirm;
                CancelAction  = cancel;

                Type = pattern.Type;
            }

            Logger.Log(Logger.Level.DEBUG, "[PatternEditor] Setting textures to previews.");
            Preview.texture = Previews.AllPreviews[Type].Camera.targetTexture;
            Previews.AllPreviews[Type].ResetPosition();
            Previews.AllPreviews[Type].Render();

            Logger.Log(Logger.Level.DEBUG, "[PatternEditor] Updating tools state.");
            Tools.PatternChanged();
            Tools.BrushUpdated();
            Tools.SwitchTool(Tools.Tool.None);
            Tools.SwitchToolset(Tools.Toolset.RasterLayer);
            PixelGrid.PatternLoaded();
        }
        catch (System.Exception e) { Logger.Log(Logger.Level.ERROR, "[PatternEditor] Error while showing PatternEditor: " + e.ToString()); }
    }
    public static UnityEngine.Texture2D GetTexture(this DesignPattern pattern)
    {
        int       width        = pattern.Width;
        int       height       = pattern.Height;
        Texture2D ret          = new Texture2D(width, height, UnityEngine.TextureFormat.RGBA32, false);
        var       colors       = pattern.GetPixels();
        var       resultColors = new UnityEngine.Color[colors.Length];

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                resultColors[x + (height - 1 - y) * width] = colors[x + y * width];
            }
        }
        ret.SetPixels(resultColors);
        ret.Apply();
        return(ret);
    }
    public static void FromTexture(this DesignPattern pattern, Texture2D texture)
    {
        var colors = texture.GetPixels();
        Dictionary <UnityEngine.Color, byte> colorMap = new Dictionary <UnityEngine.Color, byte>();

        for (int i = 0; i < 15; i++)
        {
            pattern.Palette[i].R = 0;
            pattern.Palette[i].G = 0;
            pattern.Palette[i].B = 0;
        }

        int width  = pattern.Width;
        int height = pattern.Height;

        pattern.Image = new byte[width * height];
        for (var y = 0; y < height; y++)
        {
            for (var x = 0; x < width; x++)
            {
                var pixelColor = colors[x + (height - 1 - y) * width];

                byte index = 0xF;
                if (pixelColor.a == 1f)
                {
                    if (colorMap.ContainsKey(pixelColor))
                    {
                        index = colorMap[pixelColor];
                    }
                    else
                    {
                        index = (byte)colorMap.Count;
                        pattern.Palette[index].R = (byte)(pixelColor.r * 255f);
                        pattern.Palette[index].G = (byte)(pixelColor.g * 255f);
                        pattern.Palette[index].B = (byte)(pixelColor.b * 255f);
                        colorMap.Add(pixelColor, index);
                    }
                }

                pattern.SetPixel(x, y, index);
            }
        }
    }
    public static System.Drawing.Bitmap GetBitmap(this DesignPattern pattern)
    {
        int width  = pattern.Width;
        int height = pattern.Height;

        var bitmap    = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        var data      = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        var pixelSize = data.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb ? 4 : 3;
        var padding   = data.Stride - (data.Width * pixelSize);

        unsafe
        {
            byte *ptr = (byte *)data.Scan0.ToPointer();

            var index = 0;
            for (var y = 0; y < data.Height; y++)
            {
                for (var x = 0; x < data.Width; x++)
                {
                    var b = pattern.GetPixel(x, y);
                    if (b == 15)
                    {
                        *(ptr + index + 2) = 0;
                        *(ptr + index + 1) = 0;
                        *(ptr + index + 0) = 0;
                        *(ptr + index + 3) = 0;
                    }
                    else
                    {
                        var c = pattern.Palette[b];
                        *(ptr + index + 2) = c.R;
                        *(ptr + index + 1) = c.G;
                        *(ptr + index + 0) = c.B;
                        *(ptr + index + 3) = 255;
                    }
                    index += pixelSize;
                }
                index += padding;
            }
        }
        bitmap.UnlockBits(data);
        return(bitmap);
    }
		/// <summary>
		/// Constructor
		/// Creates a DesignHasDesignPatterns link in the same Partition as the given Design
		/// </summary>
		/// <param name="source">Design to use as the source of the relationship.</param>
		/// <param name="target">DesignPattern to use as the target of the relationship.</param>
		public DesignHasDesignPatterns(Design source, DesignPattern target)
			: base((source != null ? source.Partition : null), new DslModeling::RoleAssignment[]{new DslModeling::RoleAssignment(DesignHasDesignPatterns.DesignDomainRoleId, source), new DslModeling::RoleAssignment(DesignHasDesignPatterns.ElementDomainRoleId, target)}, null)
		{
		}
		public static void SetDesign(DesignPattern element, Design newDesign)
		{
			DslModeling::DomainRoleInfo.SetLinkedElement(element, ElementDomainRoleId, newDesign);
		}
		private static void WriteChildElements(DslModeling::SerializationContext serializationContext, DesignPattern element, global::System.Xml.XmlWriter writer)
		{
			// DesignPatternHasAbstractClasses
			global::System.Collections.ObjectModel.ReadOnlyCollection<DesignPatternHasAbstractClasses> allDesignPatternHasAbstractClassesInstances = DesignPatternHasAbstractClasses.GetLinksToAbstractClasses(element);
			if (!serializationContext.Result.Failed && allDesignPatternHasAbstractClassesInstances.Count > 0)
			{
				writer.WriteStartElement("abstractClasses");
				foreach (DesignPatternHasAbstractClasses eachDesignPatternHasAbstractClassesInstance in allDesignPatternHasAbstractClassesInstances)
				{
					if (serializationContext.Result.Failed)
						break;
	
					DslModeling::DomainClassXmlSerializer relSerializer = serializationContext.Directory.GetSerializer(eachDesignPatternHasAbstractClassesInstance.GetDomainClass().Id);
					global::System.Diagnostics.Debug.Assert(relSerializer != null, "Cannot find serializer for " + eachDesignPatternHasAbstractClassesInstance.GetDomainClass().Name + "!");
					relSerializer.Write(serializationContext, eachDesignPatternHasAbstractClassesInstance, writer);
				}
				writer.WriteEndElement();
			}
	
			// DesignPatternHasConcreteClasses
			global::System.Collections.ObjectModel.ReadOnlyCollection<DesignPatternHasConcreteClasses> allDesignPatternHasConcreteClassesInstances = DesignPatternHasConcreteClasses.GetLinksToConcreteClasses(element);
			if (!serializationContext.Result.Failed && allDesignPatternHasConcreteClassesInstances.Count > 0)
			{
				writer.WriteStartElement("concreteClasses");
				foreach (DesignPatternHasConcreteClasses eachDesignPatternHasConcreteClassesInstance in allDesignPatternHasConcreteClassesInstances)
				{
					if (serializationContext.Result.Failed)
						break;
	
					DslModeling::DomainClassXmlSerializer relSerializer = serializationContext.Directory.GetSerializer(eachDesignPatternHasConcreteClassesInstance.GetDomainClass().Id);
					global::System.Diagnostics.Debug.Assert(relSerializer != null, "Cannot find serializer for " + eachDesignPatternHasConcreteClassesInstance.GetDomainClass().Name + "!");
					relSerializer.Write(serializationContext, eachDesignPatternHasConcreteClassesInstance, writer);
				}
				writer.WriteEndElement();
			}
	
		}
		public static void SetDesignPattern(ConcreteClass element, DesignPattern newDesignPattern)
		{
			DslModeling::DomainRoleInfo.SetLinkedElement(element, ConcreteClassDomainRoleId, newDesignPattern);
		}
		/// <summary>
		/// Constructor
		/// Creates a DesignPatternHasConcreteClasses link in the same Partition as the given DesignPattern
		/// </summary>
		/// <param name="source">DesignPattern to use as the source of the relationship.</param>
		/// <param name="target">ConcreteClass to use as the target of the relationship.</param>
		public DesignPatternHasConcreteClasses(DesignPattern source, ConcreteClass target)
			: base((source != null ? source.Partition : null), new DslModeling::RoleAssignment[]{new DslModeling::RoleAssignment(DesignPatternHasConcreteClasses.DesignPatternDomainRoleId, source), new DslModeling::RoleAssignment(DesignPatternHasConcreteClasses.ConcreteClassDomainRoleId, target)}, null)
		{
		}
		public static DslModeling::LinkedElementCollection<ConcreteClass> GetConcreteClasses(DesignPattern element)
		{
			return GetRoleCollection<DslModeling::LinkedElementCollection<ConcreteClass>, ConcreteClass>(element, DesignPatternDomainRoleId);
		}
		/// <summary>
		/// Reads all instances of relationship DesignPatternHasConcreteClasses.
		/// </summary>
		/// <remarks>
		/// The caller will position the reader at the open tag of the first XML element inside the relationship tag, so it can be
		/// either the first instance, or a bogus tag. This method will deserialize all instances and ignore all bogus tags. When the
		/// method returns, the reader will be positioned at the end tag of the relationship (or EOF if somehow that happens).
		/// </remarks>
		/// <param name="serializationContext">Serialization context.</param>
		/// <param name="element">In-memory DesignPattern instance that will get the deserialized data.</param>
		/// <param name="reader">XmlReader to read serialized data from.</param>
		private static void ReadDesignPatternHasConcreteClassesInstances(DslModeling::SerializationContext serializationContext, DesignPattern element, global::System.Xml.XmlReader reader)
		{
			while (!serializationContext.Result.Failed && !reader.EOF && reader.NodeType == global::System.Xml.XmlNodeType.Element)
			{
				DslModeling::DomainClassXmlSerializer newDesignPatternHasConcreteClassesSerializer = serializationContext.Directory.GetSerializer(DesignPatternHasConcreteClasses.DomainClassId);
				global::System.Diagnostics.Debug.Assert(newDesignPatternHasConcreteClassesSerializer != null, "Cannot find serializer for DesignPatternHasConcreteClasses!");
				DesignPatternHasConcreteClasses newDesignPatternHasConcreteClasses = newDesignPatternHasConcreteClassesSerializer.TryCreateInstance (serializationContext, reader, element.Partition) as DesignPatternHasConcreteClasses;
				if (newDesignPatternHasConcreteClasses != null)
				{
					DslModeling::DomainRoleInfo.SetRolePlayer (newDesignPatternHasConcreteClasses, DesignPatternHasConcreteClasses.DesignPatternDomainRoleId, element);
					DslModeling::DomainClassXmlSerializer targetSerializer = serializationContext.Directory.GetSerializer (newDesignPatternHasConcreteClasses.GetDomainClass().Id);	
					global::System.Diagnostics.Debug.Assert (targetSerializer != null, "Cannot find serializer for " + newDesignPatternHasConcreteClasses.GetDomainClass().Name + "!");
					targetSerializer.Read(serializationContext, newDesignPatternHasConcreteClasses, reader);
				}
				else
				{	// Maybe the relationship is serialized in short-form by mistake.
					DslModeling::DomainClassXmlSerializer newConcreteClassOfDesignPatternHasConcreteClassesSerializer = serializationContext.Directory.GetSerializer(ConcreteClass.DomainClassId);
					global::System.Diagnostics.Debug.Assert(newConcreteClassOfDesignPatternHasConcreteClassesSerializer != null, "Cannot find serializer for ConcreteClass!");
					ConcreteClass newConcreteClassOfDesignPatternHasConcreteClasses = newConcreteClassOfDesignPatternHasConcreteClassesSerializer.TryCreateInstance(serializationContext, reader, element.Partition) as ConcreteClass;
					if (newConcreteClassOfDesignPatternHasConcreteClasses != null)
					{
						DesiSerializationBehaviorSerializationMessages.ExpectingFullFormRelationship(serializationContext, reader, typeof(DesignPatternHasConcreteClasses));
						element.ConcreteClasses.Add(newConcreteClassOfDesignPatternHasConcreteClasses);
						DslModeling::DomainClassXmlSerializer targetSerializer = serializationContext.Directory.GetSerializer (newConcreteClassOfDesignPatternHasConcreteClasses.GetDomainClass().Id);	
						global::System.Diagnostics.Debug.Assert (targetSerializer != null, "Cannot find serializer for " + newConcreteClassOfDesignPatternHasConcreteClasses.GetDomainClass().Name + "!");
						targetSerializer.Read(serializationContext, newConcreteClassOfDesignPatternHasConcreteClasses, reader);
					}
					else
					{	// Unknown element, skip.
						DslModeling::SerializationUtilities.Skip(reader);
					}
				}
			}
		}
		/// <summary>
		/// This method deserializes all child model elements.
		/// </summary>
		/// <remarks>
		/// The caller will position the reader at the open tag of the first child XML element to deserialized.
		/// This method will read as many child elements as it can. It returns under three circumstances:
		/// 1) When an unknown child XML element is encountered. In this case, this method will position the reader at the 
		///    open tag of the unknown element. This implies that if the first child XML element is unknown, this method 
		///    should return immediately and do nothing.
		/// 2) When all child XML elemnets are read. In this case, the reader will be positioned at the end tag of the parent element.
		/// 3) EOF.
		/// </remarks>
		/// <param name="serializationContext">Serialization context.</param>
		/// <param name="reader">XmlReader to read serialized data from.</param>
		/// <param name="element">In-memory DesignPattern instance that will get the deserialized data.</param>
		private static void ReadChildElements(DslModeling::SerializationContext serializationContext, DesignPattern element, global::System.Xml.XmlReader reader)
		{
			while (!serializationContext.Result.Failed && !reader.EOF && reader.NodeType == global::System.Xml.XmlNodeType.Element)
			{
				switch (reader.LocalName)
				{
					case "abstractClasses":	// Relationship "DesignPatternHasAbstractClasses"
						if (reader.IsEmptyElement)
						{	// No instance of this relationship, just skip
							DslModeling::SerializationUtilities.Skip(reader);
						}
						else
						{
							DslModeling::SerializationUtilities.SkipToFirstChild(reader);  // Skip the open tag of <abstractClasses>
							ReadDesignPatternHasAbstractClassesInstances(serializationContext, element, reader);
							DslModeling::SerializationUtilities.Skip(reader);  // Skip the close tag of </abstractClasses>
						}
						break;
					case "concreteClasses":	// Relationship "DesignPatternHasConcreteClasses"
						if (reader.IsEmptyElement)
						{	// No instance of this relationship, just skip
							DslModeling::SerializationUtilities.Skip(reader);
						}
						else
						{
							DslModeling::SerializationUtilities.SkipToFirstChild(reader);  // Skip the open tag of <concreteClasses>
							ReadDesignPatternHasConcreteClassesInstances(serializationContext, element, reader);
							DslModeling::SerializationUtilities.Skip(reader);  // Skip the close tag of </concreteClasses>
						}
						break;
					default:
						return;  // Don't know this element.
				}
			}
		}
		public static Design GetDesign(DesignPattern element)
		{
			return DslModeling::DomainRoleInfo.GetLinkedElement(element, ElementDomainRoleId) as Design;
		}