Пример #1
0
        private static PaletteFile GetLddPaletteFile(LDDEnvironment environment)
        {
            var appDataPalettes = environment.GetAppDataSubDir("Palettes");

            if (File.Exists(Path.Combine(appDataPalettes, "LDD.lif")))
            {
                return(PaletteFile.FromLif(Path.Combine(appDataPalettes, "LDD.lif")));
            }

            if (Directory.Exists(Path.Combine(appDataPalettes, "LDD")))
            {
                return(PaletteFile.FromDirectory(Path.Combine(appDataPalettes, "LDD")));
            }

            string dbLifPath = environment.GetLifFilePath(LddLif.DB);

            if (File.Exists(dbLifPath))
            {
                using (var lif = LifFile.Open(dbLifPath))
                {
                    var paletteEntry = lif.GetAllFiles().FirstOrDefault(x => x.Name == "LDD.lif");
                    if (paletteEntry != null)
                    {
                        using (var paletteLif = LifFile.Read(paletteEntry.GetStream()))
                            return(PaletteFile.FromLif(paletteLif));
                    }
                }
            }

            return(null);
        }
Пример #2
0
        private void LoadSetParts(List <Rebrickable.Models.SetPart> parts)
        {
            var setParts = parts.Select(x => new SetPartWrapper(x)).ToList();

            SetPartsGridView.DataSource = setParts;

            Task.Factory.StartNew(() =>
            {
                using (var db = GetDbContext())
                {
                    PalatteGenerator.FindLddPartsForSet(db, setParts);
                    var palette = PalatteGenerator.GeneratePalette(db, setParts);

                    var paletteFile = new PaletteFile(new LDD.Palettes.Bag()
                    {
                        Name        = $"{SetInfo.SetNum} {SetInfo.Name}",
                        Countable   = true,
                        ParentBrand = LDD.Data.Brand.LDD
                    });

                    paletteFile.Palettes.Add(palette);

                    var userPaletteDir     = LDD.LDDEnvironment.Current.GetAppDataSubDir("UserPalettes");
                    string paletteFileName = FileHelper.GetSafeFileName(SetInfo.Name.Replace(" ", ""));

                    paletteFile.SaveToDirectory(Path.Combine(userPaletteDir, paletteFileName), false);

                    //paletteFile.SaveAsLif(Path.Combine(userPaletteDir, paletteFileName) + ".lif");
                }
            });
        }
Пример #3
0
 private void SaveCommand_Executed(object sender, ExecutedRoutedEventArgs e)
 {
     if (!String.IsNullOrWhiteSpace(txtName.Text))
     {
         palette.Name = txtName.Text;
     }
     isSaved = PaletteFile.SavePalette(palette);
 }
Пример #4
0
        private void OpenCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            Palette palette;

            openedFile = PaletteFile.OpenPalette(out palette);
            if (openedFile)
            {
                isSaved          = true;
                this.palette     = palette;
                this.DataContext = palette;
            }
        }
Пример #5
0
        private void bExportPalette_Click(object sender, EventArgs e)
        {
            int index = lboxItems.SelectedIndex;

            if (_resourceFile == null)
            {
                return;
            }
            if (index < 0 || index >= _resourceFile.Resources.Count)
            {
                return;
            }

            if (_resourceFile.Resources[index].PaletteType == PaletteType.EMPTY_ENTRY || _resourceFile.Resources[index].PaletteType == PaletteType.INVALID)
            {
                MessageBox.Show("The resource entry does not contain a palette.");
                return;
            }
            else if (_resourceFile.Resources[index].PaletteType == PaletteType.HIGH_COLOR)
            {
                MessageBox.Show("The resource entry is in 15-bit HighColor mode and does not contain a palette.");
                return;
            }
            else if (_resourceFile.Resources[index].PaletteType == PaletteType.BASE_PALETTE)
            {
                MessageBox.Show("The resource entry uses the game's base palette and does not itself contain a palette.");
                return;
            }

            if (sfdExportPalette.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    PaletteFile paletteFile = new PaletteFile();
                    paletteFile.Palette.Import(pbPalette.Palette);
                    if (paletteFile.Palette.HasNonUniqueSpecialIndices(out byte[] affected))
                    {
                        MessageBox.Show("The palette has some special indices that are mapped to the same colors as other indices. This may give incorrect results when importing images with this palette.\n\n" +
                                        "Affected indices: {0}".F(string.Join(",", affected)));
                    }

                    paletteFile.WriteToFile(sfdExportPalette.FileName);
                    MessageBox.Show("Palette extracted successfully.");
                }
                catch
                {
                    MessageBox.Show("Unable to write to file.");
                }
            }
        }
Пример #6
0
 public bool LoadPaletteFile(string path)
 {
     try
     {
         PaletteFile pal = new PaletteFile();
         pal.ReadFromFile(path);
         _paletteFile = pal;
         return(true);
     }
     catch
     {
         MessageBox.Show("The file is not a valid palette file.");
         return(false);
     }
 }
Пример #7
0
 public override bool LoadFile(string path)
 {
     try
     {
         PaletteFile pal = new PaletteFile();
         pal.ReadFromFile(path);
         _pal   = pal;
         _dirty = false;
         _path  = path;
         return(true);
     }
     catch
     {
         MessageBox.Show("The file is not a valid resource file.");
         return(false);
     }
 }
Пример #8
0
        private void bImportPalette_Click(object sender, EventArgs e)
        {
            if (ofdImportPalette.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    PaletteFile paletteFile = new PaletteFile();
                    paletteFile.ReadFromFile(ofdImportPalette.FileName);
                    UserPalette = paletteFile.Palette;
                }
                catch
                {
                    MessageBox.Show("Unable to load new palette.");
                }

                _choice = PaletteChoice.USER;
                ImportImageData();
            }
        }
Пример #9
0
        private void Import(ref List <ResourceElement> workingList, Palette_18Bit basePalette, string rootDir, IProgress <int> progress = null)
        {
            foreach (string key in Entries.GetKeys())
            {
                if (!int.TryParse(key, out int ikey))
                {
                    continue;
                }

                ResourceExportEntry entry = Entries[key];
                if (ikey >= workingList.Count)
                {
                    continue;
                }

                Bitmap   image = new Bitmap(Path.Combine(rootDir, entry.ImagePath));
                IPalette pal   = basePalette;
                if (entry.UseOwnPalette == true)
                {
                    PaletteFile palfile = new PaletteFile();
                    palfile.ReadFromFile(Path.Combine(rootDir, entry.PalettePath));
                    pal = palfile.Palette;
                }

                if (entry.UsePalette)
                {
                    workingList[ikey].ImportImageDataAs8Bit(image, pal, entry.UseOwnPalette == false, out int _);
                }
                else
                {
                    workingList[ikey].ImportImageDataAs15Bit(image);
                }

                workingList[ikey].FrameSize     = entry.FrameSize;
                workingList[ikey].ImageOffset   = entry.ImageOffset;
                workingList[ikey].Alignment     = entry.Alignment;
                workingList[ikey].ImageHandle   = entry.ImageHandle;
                workingList[ikey].PaletteHandle = entry.PaletteHandle;

                progress?.Report(ikey);
            }
        }
Пример #10
0
        public IList <PixDTO> GetAllPixData()
        {
            // todo refactor - use some mapping for pix directories to palettes if possible
            var palette1 = new PaletteFile(_paletteDirsFull[0]);
            var palette2 = new PaletteFile(_paletteDirsFull[1]);

            var result    = new List <PixDTO>();
            var filePaths = _filesService.GetFilePaths(_pixDirs, "pix");

            foreach (var filePath in filePaths)
            {
                PixFile pixFile = new PixFile(filePath, palette1);
                result.Add(new PixDTO
                {
                    FileName = Path.GetFileName(filePath),
                    FilePath = filePath,
                    Images   = pixFile.PixMaps.Select(x => x.BitmapSource).ToList()
                });
            }
            return(result);
        }
Пример #11
0
        public static void CreateLDDPackages()
        {
            string lddDir        = Environment.ExpandEnvironmentVariables(@"%appdata%\LEGO Company\LEGO Digital Designer\");
            string primitiveDir  = Path.Combine(lddDir, "db\\Primitives");
            string meshDir       = Path.Combine(lddDir, "db\\Primitives\\LOD0");
            string decorationDir = Path.Combine(lddDir, "db\\Decorations");
            var    lddPalette    = PaletteFile.FromLif(Path.Combine(lddDir, "Palettes\\LDD.lif")).Palettes[0];
            var    xmlDecMap     = XDocument.Load(Path.Combine(lddDir, "db\\DecorationMapping.xml"));
            var    decMappings   = new List <LDD.Data.DecorationMapping>();

            foreach (var elem in xmlDecMap.Root.Elements("Mapping"))
            {
                decMappings.Add(XmlHelper.DefaultDeserialize <LDD.Data.DecorationMapping>(elem));
            }

            foreach (var primitivePath in Directory.GetFiles(primitiveDir, "*.xml")
                     .OrderBy(x => int.Parse(Path.GetFileNameWithoutExtension(x))))
            {
                var primitive = Primitive.Load(primitivePath);

                var package = new PartPackage()
                {
                    PartID    = int.Parse(Path.GetFileNameWithoutExtension(primitivePath)),
                    Primitive = primitive
                };
                var myDecorations = decMappings.Where(x => x.DesignID == package.PartID);

                if (myDecorations.Any())
                {
                    package.DecorationMappings.AddRange(
                        myDecorations.Select(x =>
                                             new LDD.Palettes.Decoration(x.SurfaceID, x.DecorationID)));

                    foreach (string decID in package.DecorationMappings.Select(x => x.DecorationID).Distinct())
                    {
                        var imagePath = Directory.EnumerateFiles(decorationDir, decID + ".*").FirstOrDefault();
                        if (string.IsNullOrEmpty(imagePath))
                        {
                            continue;
                        }
                        var img = Image.FromFile(imagePath);
                        package.DecorationImages.Add(new DecorationImage(decID, img));
                    }
                }

                var myElements = lddPalette.Bricks.Where(x => x.DesignID == package.PartID);
                if (myElements.Any())
                {
                    package.Configurations.AddRange(myElements);
                }

                int surfaceId = 0;
                foreach (var meshPath in Directory.GetFiles(meshDir, package.PartID + ".g*").OrderBy(x => x))
                {
                    var mesh = MeshFile.Read(meshPath);
                    package.Meshes.Add(new PartMesh(package.PartID, surfaceId++, mesh));
                }

                string folderName = package.PartID.ToString()[0].ToString().PadRight(package.PartID.ToString().Length, '0');

                package.Save($"LPI TEST\\{folderName}\\{package.PartID}.lpi");

                package.Dispose();
            }
        }
Пример #12
0
        public void Export(Palette_18Bit basePalette, int key, ResourceElement element, string rootDir, string imagePath, string palettePath, IProgress <int> progress = null)
        {
            if (element.PaletteType == PaletteType.EMPTY_ENTRY)
            {
                return;
            }

            ResourceExportEntry expentry = new ResourceExportEntry();

            expentry.FrameSize     = element.FrameSize;
            expentry.ImageOffset   = element.ImageOffset;
            expentry.Alignment     = element.Alignment;
            expentry.ImageHandle   = element.ImageHandle;
            expentry.PaletteHandle = element.PaletteHandle;
            expentry.UsePalette    = element.BitsPerPixel == 8;
            if (expentry.UsePalette)
            {
                expentry.UseOwnPalette = element.PaletteHandle != 0;
            }
            else
            {
                expentry.UseOwnPalette = null;
            }

            HousePaletteFile dummy = new HousePaletteFile();
            // modify palette to remove unique colors.
            Palette_15Bit opal = element.Palette?.Clone();

            if (element.Palette != null)
            {
                element.Palette.MakeSpecialIndicesUnique(out _);
            }

            Bitmap image = element.GetBitmap(basePalette, dummy, false, false, -1);

            if (!Path.IsPathRooted(imagePath))
            {
                imagePath = Path.Combine(rootDir, imagePath);
            }
            Directory.CreateDirectory(Path.GetDirectoryName(imagePath));
            image.Save(imagePath);
            expentry.ImagePath = WinAPI.GetRelativePath(rootDir + @"\", imagePath);

            if (expentry.UseOwnPalette ?? false)
            {
                PaletteFile palfile = new PaletteFile();
                palfile.Palette.Import(element.Palette);
                if (!Path.IsPathRooted(palettePath))
                {
                    palettePath = Path.Combine(rootDir, palettePath);
                }
                Directory.CreateDirectory(Path.GetDirectoryName(palettePath));
                palfile.WriteToFile(palettePath);
                expentry.PalettePath = WinAPI.GetRelativePath(rootDir + @"\", palettePath);
            }

            // restore the original palette
            element.Palette = opal;

            Entries.Put(key.ToString(), expentry);
            progress?.Report(key);
        }
Пример #13
0
        public PixFile(string filename, PaletteFile palette)
        {
            Stream file = OpenDataFile(filename);

            EndianBinaryReader reader     = new EndianBinaryReader(EndianBitConverter.Big, file);
            PixMap             currentPix = null;

            while (true)
            {
                int          blockLength = 0;
                PixBlockType blockType   = (PixBlockType)reader.ReadInt32();

                if (blockType == PixBlockType.Null && reader.BaseStream.Position + 3 >= reader.BaseStream.Length)
                {
                    break;
                }

                blockLength = reader.ReadInt32();

                switch (blockType)
                {
                case PixBlockType.Attributes:

                    int type = reader.ReadByte();
                    if (type == 7)
                    {
                        /* bmp palette data? - seen in some splat pack textures. Jump over it, and its pixel data */
                        reader.Seek(blockLength - 1, SeekOrigin.Current);
                        _skipNextPixelSection = true;
                        break;
                    }
                    currentPix       = new PixMap();
                    currentPix.Width = reader.ReadInt16();
                    int width2 = reader.ReadInt16();
                    currentPix.Height = reader.ReadInt16();

                    byte[] unk2 = reader.ReadBytes(4);
                    currentPix.Name = ReadNullTerminatedString(reader);
                    _pixMaps.Add(currentPix);
                    break;

                case PixBlockType.PixelData:

                    if (_skipNextPixelSection)
                    {
                        reader.Seek(blockLength, SeekOrigin.Current);
                        _skipNextPixelSection = false;
                        break;
                    }
                    int pixelCount    = reader.ReadInt32();
                    int bytesPerPixel = reader.ReadInt32();
                    if (bytesPerPixel > 3)
                    {
                        bytesPerPixel = 1;      //PixEd sometimes doesnt get this right
                    }

                    if (currentPix == null)
                    {
                        int size = (int)Math.Sqrt(pixelCount);
                        currentPix        = new PixMap();
                        currentPix.Name   = Path.GetFileName(filename);
                        currentPix.Width  = size;
                        currentPix.Height = size;
                        _pixMaps.Add(currentPix);
                    }

                    byte[] pixels = reader.ReadBytes(pixelCount * bytesPerPixel);
                    //Texture2D texture = null;
                    BitmapSource bitmap = null;
                    if (bytesPerPixel == 1)
                    {
                        //texture = new Texture2D(Engine.Device, currentPix.Width, currentPix.Height, 1, TextureUsage.None, SurfaceFormat.Color);
                        bitmap = ToImage(ImageHelper.GetBytesForImage(pixels, currentPix.Width, currentPix.Height, palette), currentPix.Width, currentPix.Height, PixelFormats.Bgra32);
                        //texture.SetData<byte>(Helpers.GetBytesForImage(pixels, currentPix.Width, currentPix.Height, palette));
                    }
                    else if (bytesPerPixel == 2)
                    {
                        //texture = new Texture2D(Engine.Device, currentPix.Width, currentPix.Height, 1, TextureUsage.None, SurfaceFormat.Bgr565);
                        int    j  = 0;
                        byte[] px = new byte[2];
                        for (int i = 0; i < pixels.Length; i += 2)
                        {
                            byte tmp = pixels[i + 1];
                            pixels[i + 1] = pixels[i];
                            pixels[i]     = tmp;
                        }
                        //texture.SetData<byte>(pixels);
                        bitmap = ToImage(pixels, currentPix.Width, currentPix.Height, PixelFormats.Bgr565);
                    }
                    else if (bytesPerPixel == 3)
                    {
                        //texture = new Texture2D(Engine.Device, currentPix.Width, currentPix.Height, 1, TextureUsage.None, SurfaceFormat.Color);
                        int    j   = 0;
                        byte[] px2 = new byte[pixels.Length * 4];
                        for (int i = 0; i < pixels.Length; i += 3)
                        {
                            px2[j++] = pixels[i];
                            px2[j++] = pixels[i + 1];
                            px2[j++] = pixels[i + 2];
                            px2[j++] = 255;
                        }
                        bitmap = ToImage(px2, currentPix.Width, currentPix.Height, PixelFormats.Bgra32);
                        //texture.SetData<byte>(px2);
                    }
                    currentPix.BitmapSource = bitmap;
                    break;

                case PixBlockType.Null:
                    break;

                default:
                    reader.Seek(blockLength, SeekOrigin.Current);
                    break;
                }
                if (reader.BaseStream.Position + 3 >= reader.BaseStream.Length)
                {
                    break;
                }
            }

            reader.Close();
        }
Пример #14
0
        private void bImportPalette_Click(object sender, EventArgs e)
        {
            int index = lboxItems.SelectedIndex;

            if (_resourceFile == null)
            {
                return;
            }
            if (index < 0 || index >= _resourceFile.Resources.Count)
            {
                return;
            }

            if (_resourceFile.Resources[index].PaletteType == PaletteType.EMPTY_ENTRY || _resourceFile.Resources[index].PaletteType == PaletteType.INVALID)
            {
                MessageBox.Show("The resource entry is empty and cannot be assigned a palette.");
                return;
            }
            else if (_resourceFile.Resources[index].PaletteType == PaletteType.HIGH_COLOR)
            {
                MessageBox.Show("The resource entry is in 15-bit HighColor mode and cannot be assigned a palette.");
                return;
            }
            else if (_resourceFile.Resources[index].PaletteType == PaletteType.BASE_PALETTE)
            {
                if (MessageBox.Show("The resource entry currently uses the game's base palette. Replace with an embedded palette?", "Confirm Import Palette", MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    return;
                }
            }

            if (ofdImportPalette.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    PaletteFile paletteFile = new PaletteFile();
                    paletteFile.ReadFromFile(ofdImportPalette.FileName);

                    _resourceFile.Resources[index].Palette.Import(paletteFile.Palette);
                    if (_resourceFile.Resources[index].Palette.HasNonUniqueSpecialIndices(out byte[] affected))
                    {
                        MessageBox.Show("The palette has some special indices that are mapped to the same colors as other indices. This may give incorrect results when importing images with this palette.\n\n" +
                                        "Affected indices: {0}".F(string.Join(",", affected)));
                    }

                    if (_resourceFile.Resources[index].PaletteType == PaletteType.BASE_PALETTE)
                    {
                        _resourceFile.Resources[index].PaletteHandle  = 1; // any non-zero number
                        _resourceFile.Resources[index].Memory         = 1; // any non-zero number
                        _resourceFile.Resources[index].PaletteHandle2 = 1; // any non-zero number
                    }

                    _resourceFile.Resources[index].FirstByte = 1; // embedded
                    MessageBox.Show("Palette imported successfully.");
                }
                catch
                {
                    MessageBox.Show("Unable to load new palette.");
                }
                _dirty = true;
                ReloadEntry();
            }
        }