Example #1
0
 new public DialogResult ShowDialog(IWin32Window owner)
 {
     _parent          = null;
     _original        = null;
     _originalPalette = null;
     _paletteData     = _textureData = null;
     DialogResult     = DialogResult.Cancel;
     try { return(base.ShowDialog(owner)); }
     catch (Exception x) { MessageBox.Show(x.ToString()); return(DialogResult.Cancel); }
     finally { DisposeImages(); }
 }
Example #2
0
        //internal void Attach(Bitmap bmp, string name)
        //{
        //    if (name.Equals(_name))
        //    {
        //        _bmp = bmp;
        //        _remake = true;
        //    }
        //}

        internal unsafe void Attach(TEX0Node tex)
        {
            ClearImages();

            _textures = new Bitmap[tex.LevelOfDetail];
            for (int i = 0; i < tex.LevelOfDetail; i++)
            {
                _textures[i] = tex.GetImage(i);
            }

            _remake = true;
        }
 public DialogResult ShowDialog(IWin32Window owner, REFTEntryNode original)
 {
     _parent          = null;
     _originalREFT    = original;
     _original        = null;
     _originalPalette = null;
     _paletteData     = _textureData = null;
     //cboFormat.Items.RemoveAt(9);
     //cboFormat.Items.RemoveAt(9);
     DialogResult = DialogResult.Cancel;
     try { return(base.ShowDialog(owner)); }
     catch (Exception x) { MessageBox.Show(x.ToString()); return(DialogResult.Cancel); }
     finally { DisposeImages(); }
 }
Example #4
0
        public static void Replace(this TEX0Node tex0, Bitmap bmp, int paletteSize)
        {
            FileMap tMap, pMap;

            if (tex0.HasPalette)
            {
                PLT0Node pn = tex0.GetPaletteNode();
                tMap = TextureConverter.Get(tex0.Format).EncodeTextureIndexed(bmp, tex0.LevelOfDetail, paletteSize, pn.Format, QuantizationAlgorithm.MedianCut, out pMap);
                pn.ReplaceRaw(pMap);
            }
            else
            {
                tMap = TextureConverter.Get(tex0.Format).EncodeTEX0Texture(bmp, tex0.LevelOfDetail);
            }
            tex0.ReplaceRaw(tMap);
        }
Example #5
0
 private void exportToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if ((_selectedTexture != null) && (_selectedTexture.Source is TEX0Node))
     {
         TEX0Node node = _selectedTexture.Source as TEX0Node;
         using (SaveFileDialog dlgSave = new SaveFileDialog())
         {
             dlgSave.FileName = node.Name;
             dlgSave.Filter   = ExportFilters.TEX0;
             if (dlgSave.ShowDialog(this) == DialogResult.OK)
             {
                 node.Export(dlgSave.FileName);
             }
         }
     }
 }
Example #6
0
        /// <summary>
        /// Replace the MenSelmapMark texture in toReplace with the image in newBitmap, flipping the channels if the image has solid black in all four corners.
        /// </summary>
        /// <param name="newBitmap">The new texture to use</param>
        /// <param name="toReplace">The TEX0 to insert the texture in</param>
        /// <param name="createNew">If true, the format of the existing texture will not be used as a fallback, even if useExistingAsFallback is true</param>
        private void ReplaceSelmapMark(Bitmap newBitmap, TEX0Node toReplace, bool createNew)
        {
            WiiPixelFormat format =
                selmapMarkFormat != null
                                        ? selmapMarkFormat.Value
                                : useExistingAsFallback && !createNew
                                        ? toReplace.Format
                                : BitmapUtilities.HasAlpha(newBitmap)
                                        ? WiiPixelFormat.IA4
                                        : WiiPixelFormat.I4;

            Console.WriteLine(format);
            Bitmap toEncode = BitmapUtilities.HasSolidCorners(newBitmap) ? BitmapUtilities.AlphaSwap(newBitmap) : newBitmap;

            BrawlLib.IO.FileMap tMap = TextureConverter.Get(format).EncodeTEX0Texture(toEncode, 1);
            toReplace.ReplaceRaw(tMap);
        }
        public unsafe void Attach(TEX0Node tex)
        {
            ClearImages();

            _textures = new Bitmap[tex.LevelOfDetail];
            for (int i = 0; i < tex.LevelOfDetail; i++)
                _textures[i] = tex.GetImage(i);

            if (_textures.Length != 0 && _textures[0] != null)
            {
                _width = _textures[0].Width;
                _height = _textures[0].Height;
            }

            _remake = true;
            Initialize();
        }
Example #8
0
        public unsafe void Attach(TEX0Node tex, PLT0Node plt)
        {
            ClearImages();

            _textures = new Bitmap[tex.LevelOfDetail];
            for (int i = 0; i < tex.LevelOfDetail; i++)
            {
                _textures[i] = tex.GetImage(i, plt);
            }

            if (_textures.Length != 0)
            {
                _width  = _textures[0].Width;
                _height = _textures[0].Height;
            }

            _remake = true;
            Initialize();
        }
Example #9
0
        public static void ColorSmashTex0(object sender, EventArgs e)
        {
            // If this was selected via keycode when it's invalid, return without error
            if (!CanRunColorSmash || MainForm.Instance.resourceTree.SelectedNodes.Count <= 1)
            {
                return;
            }

            short paletteCount = 0;

            foreach (TreeNode n in MainForm.Instance.resourceTree.SelectedNodes)
            {
                if (n is TEX0Wrapper tw)
                {
                    TEX0Node t = (TEX0Node)tw.Resource;
                    if (paletteCount < 256)
                    {
                        if (!t.HasPalette || t.GetPaletteNode() == null)
                        {
                            paletteCount = 256;
                        }
                        else if (t.HasPalette && t.GetPaletteNode() != null &&
                                 t.GetPaletteNode().Palette.Entries.Length > paletteCount)
                        {
                            paletteCount = (short)Math.Min(t.GetPaletteNode().Palette.Entries.Length, 256);
                        }
                    }
                }
            }

            if (paletteCount == 0)
            {
                paletteCount = 256;
            }

            using (NumericInputForm frm = new NumericInputForm())
            {
                if (frm.ShowDialog("Color Smasher", "How many colors?", paletteCount) == DialogResult.OK)
                {
                    ColorSmashTex0(frm.NewValue);
                }
            }
        }
Example #10
0
        public static void Copy(string kirbypath, string hatpath)
        {
            ResourceNode kirby   = NodeFactory.FromFile(null, kirbypath);
            string       temphat = Path.GetTempFileName();

            File.Copy(hatpath, temphat, true);
            ResourceNode hat = NodeFactory.FromFile(null, temphat);

            TEX0Node skin = (TEX0Node)kirby.FindChildByType("PlyKirby5KSkin", true, ResourceType.TEX0);

            if (skin == null)
            {
                MessageBox.Show(null, "Could not find the texture PlyKirby5KSkin in " + kirbypath, "Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string temptex = Path.GetTempFileName();

            skin.Export(temptex);

            TEX0Node hatskin = (TEX0Node)hat.FindChildByType("WpnKirbyKirbyMewtwoCap", true, ResourceType.TEX0);

            if (hatskin == null)
            {
                MessageBox.Show(null, "Could not find the texture WpnKirbyKirbyMewtwoCap in " + hatpath, "Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            hatskin.Replace(temptex);
            hat.Merge();
            hat.Export(hatpath);

            hat.Dispose();
            kirby.Dispose();

            File.Delete(temphat);
            File.Delete(temptex);

            MessageBox.Show(Path.GetFileName(hatpath) + " has been updated.");
        }
Example #11
0
        public void Replace()
        {
            TEX0Node tNode = Node as TEX0Node;

            string path;
            Bitmap bmp = null;

            switch (Program.OpenFile(Filters.TextureReplaceFilter, out path))
            {
            case 2:
            case 4:
            case 5:
            case 6:
            case 7:
                bmp = Bitmap.FromFile(path) as Bitmap; break;

            case 3:
                bmp = TGA.FromFile(path); break;

            case 8:
                tNode.Replace(path); return;

            default: return;
            }

            try
            {
                //if ((bmp.Width != tNode.Width) || (bmp.Height != tNode.Height))
                //    MessageBox.Show(String.Format("Texture size does not match original! ({0} x {1})", tNode.Width, tNode.Height));
                //else
                tNode.Replace(bmp);

                //automatically replace multiple nodes
                //if (_nodePath.Contains("Type1[90]/Textures(NW4R)/InfStc."))
                //{
                //    string id = _nodePath.Substring(_nodePath.LastIndexOf('.'));
                //    ResourceNode node = ResourceCache.FindNode("stage\\melee\\STGRESULT.PAC", "2/Type1[120]/Textures(NW4R)/InfStc" + id);
                //    ((TEX0Node)node).Replace(bmp);
                //}
            }
            finally { bmp.Dispose(); }
        }
Example #12
0
        public void changeBorder()
        {
            TEX0Node tex0    = getPVParent().GetTexInfoFor(this).tex0;
            Bitmap   icon    = tex0.GetImage(0);
            Bitmap   newIcon = replaceBorder(icon);

            if (newIcon == null)
            {
                return;
            }

            using (var dialog = new ConfirmIconReplaceDialog()) {
                dialog.CurrentImage = icon;
                dialog.NewImage     = newIcon;
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    tex0.Replace(newIcon);
                    getPVParent().UpdateImage();
                }
            }
        }
Example #13
0
        public unsafe void Attach(TEX0Node tex, PLT0Node plt)
        {
            ClearImages();

            _source = tex;

            _textures = new Bitmap[tex.LevelOfDetail];
            for (int i = 0; i < tex.LevelOfDetail; i++)
            {
                _textures[i] = tex.GetImage(i, plt);
            }

            if (_textures.Length != 0 && _textures[0] != null)
            {
                _width  = _textures[0].Width;
                _height = _textures[0].Height;
            }

            switch (tex.Format)
            {
            case WiiPixelFormat.I4:
            case WiiPixelFormat.I8:
                ifmt = PixelInternalFormat.Intensity;
                break;

            case WiiPixelFormat.IA4:
            case WiiPixelFormat.IA8:
                ifmt = PixelInternalFormat.Luminance8Alpha8;
                break;

            default:
                ifmt = PixelInternalFormat.Four;
                break;
            }

            _remake = true;
            Initialize();
        }
Example #14
0
        private void replaceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int index = lstTextures.SelectedIndex;

            if ((_selectedTexture != null) && (_selectedTexture.Source is TEX0Node))
            {
                TEX0Node node = _selectedTexture.Source as TEX0Node;
                using (TextureConverterDialog dlg = new TextureConverterDialog())
                    if (dlg.ShowDialog(this, node) == DialogResult.OK)
                    {
                        _updating = true;
                        _selectedTexture.Reload();
                        lstTextures.SetItemCheckState(index, CheckState.Checked);
                        lstTextures.SetSelected(index, false);
                        _updating = false;

                        if (RenderStateChanged != null)
                        {
                            RenderStateChanged(this, null);
                        }
                    }
            }
        }
Example #15
0
        public bool AddMenSelmapMark(string path, bool ask)
        {
            string tmp = null;

            if (path.EndsWith(".tex0", StringComparison.InvariantCultureIgnoreCase))
            {
                tmp = TempFiles.Create(".png");
                NodeFactory.FromFile(null, path).Export(tmp);
            }
            Bitmap bitmap = new Bitmap(tmp ?? path);

            if (BitmapUtilities.HasSolidCorners(bitmap))
            {
                bitmap = BitmapUtilities.AlphaSwap(bitmap);
            }
            string name = Path.GetFileNameWithoutExtension(path);

            if (ask)
            {
                using (var nameDialog = new AskNameDialog(bitmap)) {
                    nameDialog.Text = name;
                    if (nameDialog.ShowDialog() != DialogResult.OK)
                    {
                        return(false);
                    }
                    else
                    {
                        name = nameDialog.NameText;
                    }
                }
            }
            BRRESNode bres = sc_selmap.FindChild("MiscData[80]", false) as BRRESNode;
            TEX0Node  tex0 = bres.CreateResource <TEX0Node>(name);

            ReplaceSelmapMark(bitmap, tex0, true);
            return(true);
        }
Example #16
0
        private unsafe void Load()
        {
            if (_context == null)
            {
                return;
            }

            Source = null;

            if (Texture != null)
            {
                Texture.Delete();
            }
            Texture = new GLTexture(_context, 0, 0);
            Texture.Bind();

            //ctx._states[String.Format("{0}_TexRef", Name)] = Texture;

            Bitmap   bmp   = null;
            TEX0Node tNode = null;

            if (_context._states.ContainsKey("_Node_Refs"))
            {
                List <ResourceNode> nodes    = _context._states["_Node_Refs"] as List <ResourceNode>;
                List <ResourceNode> searched = new List <ResourceNode>(nodes.Count);

                foreach (ResourceNode n in nodes)
                {
                    ResourceNode node = n.RootNode;
                    if (searched.Contains(node))
                    {
                        continue;
                    }
                    searched.Add(node);

                    //Search node itself first
                    if ((tNode = node.FindChild("Textures(NW4R)/" + Name, true) as TEX0Node) != null)
                    {
                        Source = tNode;
                        bmp    = tNode.GetImage(0);
                    }
                    else
                    {
                        //Then search node directory
                        string path = node._origPath;
                        if (path != null)
                        {
                            DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(path));
                            foreach (FileInfo file in dir.GetFiles(Name + ".*"))
                            {
                                if (file.Name.EndsWith(".tga"))
                                {
                                    Source = file.FullName;
                                    bmp    = TGA.FromFile(file.FullName);
                                    break;
                                }
                                else if (file.Name.EndsWith(".png") || file.Name.EndsWith(".tiff") || file.Name.EndsWith(".tif"))
                                {
                                    Source = file.FullName;
                                    bmp    = (Bitmap)Bitmap.FromFile(file.FullName);
                                    break;
                                }
                            }
                        }
                    }
                    if (bmp != null)
                    {
                        break;
                    }
                }
                searched.Clear();

                if (bmp != null)
                {
                    int w = bmp.Width, h = bmp.Height, size = w * h;

                    Texture._width  = w;
                    Texture._height = h;
                    _context.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.MagFilter, (int)GLTextureMagFilter.LINEAR);
                    _context.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.MinFilter, (int)GLTextureMinFilter.NEAREST_MIPMAP_LINEAR);
                    //_context.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.BaseLevel, 0);

                    //if (tNode != null)
                    //    _context.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.MaxLevel, tNode.LevelOfDetail);
                    //else
                    //    _context.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.MaxLevel, 0);

                    BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                    try
                    {
                        using (UnsafeBuffer buffer = new UnsafeBuffer(size << 2))
                        {
                            ARGBPixel *sPtr = (ARGBPixel *)data.Scan0;
                            ABGRPixel *dPtr = (ABGRPixel *)buffer.Address;

                            for (int i = 0; i < size; i++)
                            {
                                *dPtr++ = (ABGRPixel)(*sPtr++);
                            }

                            int res = _context.gluBuild2DMipmaps(GLTextureTarget.Texture2D, GLInternalPixelFormat._4, w, h, GLPixelDataFormat.RGBA, GLPixelDataType.UNSIGNED_BYTE, buffer.Address);
                            if (res != 0)
                            {
                            }
                        }
                    }
                    finally
                    {
                        bmp.UnlockBits(data);
                        bmp.Dispose();
                    }
                }
            }
        }
        public void EncodeSource()
        {
            TextureConverter format = TextureConverter.Get((WiiPixelFormat)cboFormat.SelectedItem);
            if (format.IsIndexed)
            {
                if (_origTEX0 != null || _bresParent != null)
                    _textureData = format.EncodeTextureIndexed(_indexed, (int)numLOD.Value, (WiiPaletteFormat)cboPaletteFormat.SelectedItem, out _paletteData);
                else if (_origREFT != null || _reftParent != null)
                    _textureData = format.EncodeREFTTextureIndexed(_indexed, (int)numLOD.Value, (WiiPaletteFormat)cboPaletteFormat.SelectedItem);
                else if (_origTPL != null || _tplParent != null)
                    _textureData = format.EncodeTPLTextureIndexed(_indexed, (int)numLOD.Value, (WiiPaletteFormat)cboPaletteFormat.SelectedItem, out _paletteData);
            }
            else
            {
                if ((format.RawFormat == WiiPixelFormat.CMPR) && (_cmprBuffer != null))
                {
                    if (_origTEX0 != null || _bresParent != null)
                        _textureData = ((CMPR)format).EncodeTextureCached(_source, (int)numLOD.Value, _cmprBuffer);
                    else if (_origREFT != null || _reftParent != null)
                        _textureData = ((CMPR)format).EncodeREFTTextureCached(_source, (int)numLOD.Value, _cmprBuffer);
                    else if (_origTPL != null || _tplParent != null)
                        _textureData = ((CMPR)format).EncodeTPLTextureCached(_source, (int)numLOD.Value, _cmprBuffer);
                }
                else if (_origTEX0 != null || _bresParent != null)
                    _textureData = format.EncodeTEX0Texture(_source, (int)numLOD.Value);
                else if (_origREFT != null || _reftParent != null)
                    _textureData = format.EncodeREFTTexture(_source, (int)numLOD.Value, WiiPaletteFormat.IA8);
                else if (_origTPL != null || _tplParent != null)
                    _textureData = format.EncodeTPLTexture(_source, (int)numLOD.Value);
            }

            if (_bresParent != null)
            {
                _origTEX0 = _bresParent.CreateResource<TEX0Node>(Path.GetFileNameWithoutExtension(_imageSource));
                if (_paletteData != null)
                {
                    _origPLT0 = _bresParent.CreateResource<PLT0Node>(_origTEX0.Name);
                    _origPLT0.Name = _origTEX0.Name;
                    _origPLT0.ReplaceRaw(_paletteData);
                }
                _origTEX0.ReplaceRaw(_textureData);
            }
            else if (_tplParent != null)
            {
                _origTPL = new TPLTextureNode() { Name = "Texture" };
                _tplParent.AddChild(_origTPL);
                _origTPL.ReplaceRaw(_textureData);
                if (_paletteData != null)
                {
                    _origTPLPlt = new TPLPaletteNode() { Name = "Palette" };
                    _origTPL.AddChild(_origTPLPlt);
                    _origTPLPlt.ReplaceRaw(_paletteData);
                }
            }
            else if (_reftParent != null)
            {
                _reftParent.AddChild(_origREFT = new REFTEntryNode() { Name = Path.GetFileNameWithoutExtension(_imageSource) });
                _origREFT.ReplaceRaw(_textureData);
            }
            else if (_origTEX0 != null)
            {
                if (_origPLT0 != null)
                {
                    if (_paletteData != null)
                        _origPLT0.ReplaceRaw(_paletteData);
                    else
                    {
                        _origPLT0.Remove();
                        _origPLT0.Dispose();
                    }
                }
                else if (_paletteData != null)
                {
                    if ((_origTEX0.Parent == null) || (_origTEX0.Parent.Parent == null))
                    {
                        _paletteData.Dispose();
                        _paletteData = null;
                    }
                    else
                    {
                        _bresParent = _origTEX0.Parent.Parent as BRESNode;
                        _origPLT0 = _bresParent.CreateResource<PLT0Node>(_origTEX0.Name);
                        _origPLT0.Name = _origTEX0.Name;
                        _origPLT0.ReplaceRaw(_paletteData);
                    }
                }
                _origTEX0.ReplaceRaw(_textureData);
            }
            else if (_origREFT != null)
                _origREFT.ReplaceRaw(_textureData);
            else if (_origTPL != null)
            {
                _origTPL.ReplaceRaw(_textureData);
                if (_origTPLPlt != null)
                {
                    if (_paletteData != null)
                    {
                        _origTPL.AddChild(_origTPLPlt);
                        _origTPLPlt.ReplaceRaw(_paletteData);
                    }
                    else
                    {
                        _origTPLPlt.Remove();
                        _origTPLPlt.Dispose();
                    }
                }
                else if (_paletteData != null)
                {
                    if (_origTPL.Parent == null)
                    {
                        _paletteData.Dispose();
                        _paletteData = null;
                    }
                    else
                    {
                        _origTPLPlt = new TPLPaletteNode() { _name = "Palette" };
                        _origTPL.AddChild(_origTPLPlt);
                        _origTPLPlt.ReplaceRaw(_paletteData);
                    }
                }
            }
        }
Example #18
0
 /// <summary>
 /// Replace the MenSelmapMark texture in toReplace with the image in newBitmap, flipping the channels if the image has solid black in all four corners.
 /// </summary>
 /// <param name="newBitmap">The new texture to use</param>
 /// <param name="toReplace">The TEX0 to insert the texture in</param>
 /// <param name="createNew">If true, the format of the existing texture will not be used as a fallback, even if useExistingAsFallback is true</param>
 private void ReplaceSelmapMark(Bitmap newBitmap, TEX0Node toReplace, bool createNew)
 {
     WiiPixelFormat format =
         selmapMarkFormat != null
             ? selmapMarkFormat.Value
         : useExistingAsFallback && !createNew
             ? toReplace.Format
         : BitmapUtilities.HasAlpha(newBitmap)
             ? WiiPixelFormat.IA4
             : WiiPixelFormat.I4;
     Console.WriteLine(format);
     Bitmap toEncode = BitmapUtilities.HasSolidCorners(newBitmap) ? BitmapUtilities.AlphaSwap(newBitmap) : newBitmap;
     BrawlLib.IO.FileMap tMap = TextureConverter.Get(format).EncodeTEX0Texture(toEncode, 1);
     toReplace.ReplaceRaw(tMap);
 }
Example #19
0
        private void btnOkay_Click(object sender, EventArgs e)
        {
            TextureConverter format = TextureConverter.Get((WiiPixelFormat)cboFormat.SelectedItem);

            if (format.IsIndexed)
            {
                _textureData = format.EncodeTextureIndexed(_indexed, (int)numLOD.Value, (WiiPaletteFormat)cboPaletteFormat.SelectedItem, out _paletteData);
            }
            else
            {
                if ((format.RawFormat == WiiPixelFormat.CMPR) && (_cmprBuffer != null))
                {
                    _textureData = ((CMPR)format).EncodeTextureCached(_source, (int)numLOD.Value, _cmprBuffer);
                }
                else
                {
                    _textureData = format.EncodeTexture(_source, (int)numLOD.Value);
                }
            }

            if (_parent != null)
            {
                _original = _parent.CreateResource <TEX0Node>(Path.GetFileNameWithoutExtension(_imageSource));
                if (_paletteData != null)
                {
                    _originalPalette      = _parent.CreateResource <PLT0Node>(_original.Name);
                    _originalPalette.Name = _original.Name;
                    _originalPalette.ReplaceRaw(_paletteData);
                }
                _original.ReplaceRaw(_textureData);
            }
            else if (_original != null)
            {
                if (_originalPalette != null)
                {
                    if (_paletteData != null)
                    {
                        _originalPalette.ReplaceRaw(_paletteData);
                    }
                    else
                    {
                        _originalPalette.Remove();
                        _originalPalette.Dispose();
                    }
                }
                else if (_paletteData != null)
                {
                    if ((_original.Parent == null) || (_original.Parent.Parent == null))
                    {
                        _paletteData.Dispose();
                        _paletteData = null;
                    }
                    else
                    {
                        _parent               = _original.Parent.Parent as BRESNode;
                        _originalPalette      = _parent.CreateResource <PLT0Node>(_original.Name);
                        _originalPalette.Name = _original.Name;
                        _originalPalette.ReplaceRaw(_paletteData);
                    }
                }
                _original.ReplaceRaw(_textureData);
            }

            DialogResult = DialogResult.OK;
            Close();
        }
Example #20
0
        public void UpdateDirectory()
        {
            Console.WriteLine(System.Environment.CurrentDirectory);
            if (sc_selmap != null)
            {
                sc_selmap.Dispose();
            }
            if (common5 != null)
            {
                common5.Dispose();
            }
            _openFilePath       = null;
            fileSizeBar.Maximum = 1214283;
            if (File.Exists("../../menu2/sc_selmap.pac"))
            {
                common5       = null;
                sc_selmap     = TempFiles.MakeTempNode("../../menu2/sc_selmap.pac");
                _openFilePath = "../../menu2/sc_selmap.pac";
            }
            else if (File.Exists("../../menu2/sc_selmap_en.pac"))
            {
                common5       = null;
                sc_selmap     = TempFiles.MakeTempNode("../../menu2/sc_selmap_en.pac");
                _openFilePath = "../../menu2/sc_selmap_en.pac";
            }
            else if (File.Exists("../../system/common5.pac"))
            {
                common5       = TempFiles.MakeTempNode("../../system/common5.pac");
                sc_selmap     = common5.FindChild("sc_selmap_en", false);
                _openFilePath = "../../system/common5.pac";
            }
            else if (File.Exists("../../system/common5_en.pac"))
            {
                common5       = TempFiles.MakeTempNode("../../system/common5_en.pac");
                sc_selmap     = common5.FindChild("sc_selmap_en", false);
                _openFilePath = "../../system/common5_en.pac";
            }
            else
            {
                common5     = null;
                sc_selmap   = null;
                label1.Text = "Could not load sc_selmap(_en) or common5(_en).";
            }
            if (_openFilePath != null)
            {
                updateFileSize();
                TEX0Node tex0 = sc_selmap.FindChild("MiscData[80]/Textures(NW4R)/MenSelmapFrontBg", false) as TEX0Node;
                if (tex0 != null)
                {
                    scribble = tex0.GetImage(0);
                }
                FindMuMenumain();
            }
            else
            {
                fileSizeBar.Value  = 0;
                fileSizeLabel.Text = "";
            }

            // Find and load GCT, if it exists
            AutoSSS = null;
            DirectoryInfo directory = new DirectoryInfo(Environment.CurrentDirectory);

            while (directory != null)
            {
                Console.WriteLine(directory);
                if (File.Exists(directory.FullName + "/data/gecko/codes/RSBE01.gct"))
                {
                    AutoSSS = new CustomSSSCodeset(File.ReadAllBytes(directory.FullName + "/data/gecko/codes/RSBE01.gct"));
                    break;
                }
                else if (File.Exists(directory.FullName + "/codes/RSBE01.gct"))
                {
                    AutoSSS = new CustomSSSCodeset(File.ReadAllBytes(directory.FullName + "/codes/RSBE01.gct"));
                    break;
                }
                directory = directory.Parent;
            }
        }
Example #21
0
        public void ConvertToStockDefault()
        {
            string          matchName  = _resource.Name.Substring(0, _resource.Name.LastIndexOf(".")) + ".";
            string          matchNameX = _resource.Name.Substring(0, _resource.Name.LastIndexOf(".")) + "X.";
            List <TEX0Node> texList    = new List <TEX0Node>();

            for (int i = 0; i < _resource.Parent.Children.Count; i++)
            {
                if (!(_resource.Parent.Children[i] is TEX0Node))
                {
                    continue;
                }

                TEX0Node tx0 = (TEX0Node)_resource.Parent.Children[i];
                if (tx0.Name.StartsWith(matchName) && tx0.Name.LastIndexOf(".") > 0 &&
                    tx0.Name.LastIndexOf(".") < tx0.Name.Length &&
                    int.TryParse(
                        tx0.Name.Substring(tx0.Name.LastIndexOf(".") + 1,
                                           tx0.Name.Length - (tx0.Name.LastIndexOf(".") + 1)), out int x) && x >= 0)
                {
                    tx0.texSortNum = x;
                    if (x <= 0) // 0 edge case
                    {
                        tx0.texSortNum = 0;
                        if (tx0.HasPalette)
                        {
                            tx0.GetPaletteNode().Name = "InfStc." + tx0.texSortNum.ToString("000");
                        }

                        tx0.Name = "InfStc." + tx0.texSortNum.ToString("000");
                        if (((BRRESNode)_resource.Parent.Parent).GetFolder <PLT0Node>()
                            .FindChildrenByName("InfStc." + x.ToString("0000"))
                            .Count() > 0)
                        {
                            foreach (PLT0Node p in ((BRRESNode)_resource.Parent.Parent).GetFolder <PLT0Node>()
                                     .FindChildrenByName(
                                         "InfStc." + x.ToString(
                                             "0000")))
                            {
                                p.Remove();
                            }
                        }
                    }
                    else if (x == 9001) // WarioMan edge case (should pre-program)
                    {
                        tx0.texSortNum = 475 + x % 9001;
                        if (tx0.HasPalette)
                        {
                            tx0.GetPaletteNode().Name = "InfStc." + tx0.texSortNum.ToString("000");
                        }

                        tx0.Name = "InfStc." + tx0.texSortNum.ToString("000");
                        if (((BRRESNode)_resource.Parent.Parent).GetFolder <PLT0Node>()
                            .FindChildrenByName("InfStc." + x.ToString("0000"))
                            .Count() > 0)
                        {
                            foreach (PLT0Node p in ((BRRESNode)_resource.Parent.Parent).GetFolder <PLT0Node>()
                                     .FindChildrenByName(
                                         "InfStc." + x.ToString(
                                             "0000")))
                            {
                                p.Remove();
                            }
                        }
                    }
                    else if (x % 50 <= 10 && x % 50 != 0 ||
                             x >= 0961 && x <= 0965 || // Ganon Edge Case
                             x >= 1711 && x <= 1715 || // ROB Edge Case
                             x >= 1861 && x <= 1864 || // Wario Edge Case
                             x >= 2011 && x <= 2015 || // Toon Link Edge Case
                             x >= 2311 && x <= 2314)   // Sonic Edge Case
                    {
                        tx0.texSortNum = (int)Math.Floor(((double)x + 1) / 50.0) * 10 + x % 10;

                        if (x % 10 == 0 ||
                            x >= 0961 && x <= 0965 || // Ganon Edge Case
                            x >= 1711 && x <= 1715 || // ROB Edge Case
                            x >= 1861 && x <= 1864 || // Wario Edge Case
                            x >= 2011 && x <= 2015 || // Toon Link Edge Case
                            x >= 2311 && x <= 2314)   // Sonic Edge Case
                        {
                            tx0.texSortNum += 10;
                        }

                        if (tx0.HasPalette)
                        {
                            tx0.GetPaletteNode().Name = "InfStc." + tx0.texSortNum.ToString("000");
                        }

                        tx0.Name = "InfStc." + tx0.texSortNum.ToString("000");
                        if (((BRRESNode)_resource.Parent.Parent).GetFolder <PLT0Node>()
                            .FindChildrenByName("InfStc." + x.ToString("0000"))
                            .Count() > 0)
                        {
                            foreach (PLT0Node p in ((BRRESNode)_resource.Parent.Parent).GetFolder <PLT0Node>()
                                     .FindChildrenByName(
                                         "InfStc." + x.ToString(
                                             "0000")))
                            {
                                p.Remove();
                            }
                        }
                    }
                    else
                    {
                        if (tx0.HasPalette)
                        {
                            tx0.GetPaletteNode().Name = "InfStcX." + tx0.texSortNum.ToString("0000");
                        }

                        tx0.Name = "InfStcX." + tx0.texSortNum.ToString("0000");
                        if (((BRRESNode)_resource.Parent.Parent).GetFolder <PLT0Node>()
                            .FindChildrenByName("InfStc." + x.ToString("0000"))
                            .Count() > 0)
                        {
                            foreach (PLT0Node p in ((BRRESNode)_resource.Parent.Parent).GetFolder <PLT0Node>()
                                     .FindChildrenByName(
                                         "InfStc." + x.ToString(
                                             "0000")))
                            {
                                p.Remove();
                            }
                        }
                    }
                }
            }

            PAT0Node newPat0 = GeneratePAT0(true);

            if (((BRRESNode)_resource.Parent.Parent).GetFolder <CHR0Node>() != null)
            {
                ResourceNode[] temp = ((BRRESNode)_resource.Parent.Parent).GetFolder <CHR0Node>()
                                      .FindChildrenByName(newPat0.Name);
                if (temp.Length > 0)
                {
                    foreach (CHR0Node cn in temp)
                    {
                        cn.FrameCount = newPat0.FrameCount;
                    }
                }
            }

            if (((BRRESNode)_resource.Parent.Parent).GetFolder <CLR0Node>() != null)
            {
                ResourceNode[] temp = ((BRRESNode)_resource.Parent.Parent).GetFolder <CLR0Node>()
                                      .FindChildrenByName(newPat0.Name);
                if (temp.Length > 0)
                {
                    foreach (CLR0Node cn in temp)
                    {
                        cn.FrameCount = newPat0.FrameCount;
                    }
                }
            }

            if (MessageBox.Show(
                    "Would you like to convert the InfFace portraits to the new system as well at this time?",
                    "Convert InfFace?", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                string infFaceFolder   = "";
                bool   autoFoundFolder = false;
                if (Program.RootPath.EndsWith("\\info2\\info.pac", StringComparison.OrdinalIgnoreCase))
                {
                    string autoFolder =
                        Program.RootPath.Substring(0, Program.RootPath.LastIndexOf("\\info2\\info.pac")) +
                        "\\info\\portrite";
                    if (Directory.Exists(autoFolder))
                    {
                        if (MessageBox.Show(
                                "The folder for InfFace was autodetected to be: \n" + autoFolder +
                                "\n\nIs this correct?", "InfFace Converter", MessageBoxButtons.YesNo) ==
                            DialogResult.Yes)
                        {
                            infFaceFolder   = autoFolder;
                            autoFoundFolder = true;
                        }
                    }
                }

                if (!autoFoundFolder)
                {
                    FolderBrowserDialog f = new FolderBrowserDialog
                    {
                        Description = "Select the \"portrite\" folder"
                    };
                    DialogResult dr = f.ShowDialog();
                    infFaceFolder = f.SelectedPath;
                    if (dr != DialogResult.OK || infFaceFolder == null || infFaceFolder == "")
                    {
                        return;
                    }
                }

                try
                {
                    DirectoryInfo d  = Directory.CreateDirectory(infFaceFolder);
                    DirectoryInfo d2 = Directory.CreateDirectory(infFaceFolder + '\\' + "temp");
                    Console.WriteLine(infFaceFolder);
                    int count = 0;
                    foreach (FileInfo infFace in d.GetFiles().Reverse())
                    {
                        Console.WriteLine(infFaceFolder + '\\' + infFace.Name);
                        int properlength = infFace.Name.EndsWith(".brres", StringComparison.OrdinalIgnoreCase)
                            ? infFace.Name.Length - ".brres".Length
                            : infFace.Name.Length;

                        if (infFace.Name.StartsWith("InfFace") && !infFace.Name.StartsWith("InfFaceX") &&
                            infFace.Name.EndsWith(".brres", StringComparison.CurrentCultureIgnoreCase) &&
                            int.TryParse(infFace.Name.Substring(7, properlength - 7), out int x) && x >= 0)
                        {
                            int n = x;
                            if (x <= 0) // 0 edge case
                            {
                                n = 0;
                                infFace.MoveTo(infFaceFolder + '\\' + "temp" + '\\' + "InfFace" + n.ToString("000") +
                                               ".brres");
                            }
                            else if (x >= 9001 && x <= 9014) // WarioMan edge case (should pre-program)
                            {
                                n = 661 + x % 9001;
                                infFace.MoveTo(infFaceFolder + '\\' + "temp" + '\\' + "InfFace" + n.ToString("000") +
                                               ".brres");
                            }
                            else if (x % 50 <= 10 && x % 50 != 0 ||
                                     x >= 0961 && x <= 0965 || // Ganon Edge Case
                                     x >= 1711 && x <= 1715 || // ROB Edge Case
                                     x >= 1861 && x <= 1864 || // Wario Edge Case
                                     x >= 2011 && x <= 2015 || // Toon Link Edge Case
                                     x >= 2311 && x <= 2314)   // Sonic Edge Case
                            {
                                n = (int)Math.Floor(((double)x + 1) / 50.0) * 10 + x % 10;

                                if (x % 10 == 0 ||
                                    x >= 0961 && x <= 0965 || // Ganon Edge Case
                                    x >= 1711 && x <= 1715 || // ROB Edge Case
                                    x >= 1861 && x <= 1864 || // Wario Edge Case
                                    x >= 2011 && x <= 2015 || // Toon Link Edge Case
                                    x >= 2311 && x <= 2314)   // Sonic Edge Case
                                {
                                    n += 10;
                                }

                                infFace.MoveTo(infFaceFolder + '\\' + "temp" + '\\' + "InfFace" + n.ToString("000") +
                                               ".brres");
                                count++;
                            }
                            else
                            {
                                infFace.MoveTo(infFaceFolder + '\\' + "temp" + '\\' + "InfFaceX" + n.ToString("0000") +
                                               ".brres");
                                count++;
                            }
                        }
                    }

                    foreach (FileInfo infFace in d2.GetFiles())
                    {
                        infFace.MoveTo(infFaceFolder + '\\' + infFace.Name +
                                       (infFace.Name.EndsWith(".brres", StringComparison.OrdinalIgnoreCase)
                                           ? ""
                                           : ".brres"));
                    }

                    d2.Delete();
                    if (count > 0)
                    {
                        MessageBox.Show("InfFace conversion successful!");
                    }
                    else
                    {
                        MessageBox.Show("No convertable InfFace portraits found in " + infFaceFolder);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }
 public void TextureFrom(ResourceNode node, int charNum, int costumeNum)
 {
     Texture = node == null ? null : GetTEX0Func(node, charNum, costumeNum) as TEX0Node;
 }
 public void TextureFrom(ResourceNode node, int charNum, int costumeNum)
 {
     Texture = node == null ? null : GetTEX0Func(node, charNum, costumeNum) as TEX0Node;
 }
Example #24
0
        public void Replace(object sender, string filename)
        {
            var ig = StringComparison.CurrentCultureIgnoreCase;

            if (filename.EndsWith(".tex0", ig))
            {
                TEX0Node tex0 = GetTexInfoFor(sender).tex0;
                if (tex0 == null)
                {
                    return;
                }
                tex0.Replace(filename);
                tex0.IsDirty = true;
                UpdateImage();
            }
            else if (filename.EndsWith(".brres", ig))
            {
                using (ResourceNode node = NodeFactory.FromFile(null, filename)) {
                    TEX0Node tex0;
                    if (node is TEX0Node)
                    {
                        tex0 = (TEX0Node)node;
                    }
                    else
                    {
                        tex0 = (TEX0Node)node.FindChild("Textures(NW4R)", false).Children[0];
                    }
                    string tempFile = TempFiles.Create(".png");
                    tex0.Export(tempFile);
                    Replace(sender, tempFile);                     // call self with new file
                }
            }
            else
            {
                TEX0Node tex0 = GetTexInfoFor(sender).tex0;
                if (tex0 == null)
                {
                    AddNewTEX0(sender, filename);
                    return;
                }
                else if (useTextureConverter)
                {
                    using (TextureConverterDialog dlg = new TextureConverterDialog()) {
                        dlg.ImageSource = filename;
                        dlg.InitialSize =
                            sender == prevbase ? prevbaseResizeTo
                                                        : sender == frontstname ? frontstnameResizeTo
                                                        : sender == selmap_mark ? selmapMarkResizeTo
                                                        : null;
                        dlg.FormBorderStyle = FormBorderStyle.FixedSingle;
                        dlg.ShowInTaskbar   = true;
                        if (dlg.ShowDialog(null, tex0) == DialogResult.OK)
                        {
                            tex0.IsDirty = true;
                            UpdateImage();
                        }
                    }
                }
                else
                {
                    Bitmap bmp = new Bitmap(filename);
                    if (sender == prevbase && prevbaseResizeTo != null)
                    {
                        bmp = BitmapUtilities.Resize(bmp, prevbaseResizeTo.Value);
                    }
                    else if (sender == frontstname && frontstnameResizeTo != null)
                    {
                        bmp = BitmapUtilities.Resize(bmp, frontstnameResizeTo.Value);
                    }
                    else if (sender == selmap_mark && selmapMarkResizeTo != null)
                    {
                        bmp = BitmapUtilities.Resize(bmp, selmapMarkResizeTo.Value);
                    }
                    if (sender == selmap_mark)
                    {
                        ReplaceSelmapMark(bmp, tex0, false);
                    }
                    else
                    {
                        int colorCount = BitmapUtilities.CountColors(bmp, 256).Align(16);
                        tex0.Replace(bmp, colorCount);
                    }
                    tex0.IsDirty = true;
                    UpdateImage();
                }
            }
        }
Example #25
0
        /// <summary>
        /// Adds PAT0 entries for each stage to the given PAT0TextureNode.
        /// </summary>
        /// <param name="pathToPAT0TextureNode">Path relative to sc_selmap_en</param>
        /// <param name="defaultName">The texture name to be used for new PAT0 entries. If null, the name will be taken from the first entry, with the number at the end replaced with the icon number.</param>
        public void AddPAT0(string pathToPAT0TextureNode, string defaultName = null)
        {
            var look = sc_selmap.FindChild(pathToPAT0TextureNode, false).Children[0];

            if (!(look is PAT0TextureNode))
            {
                throw new FormatException(look.Name);
            }

            bool icon = look.Parent.Name == "iconM";

            PAT0TextureNode tn = look as PAT0TextureNode;

            List <PAT0TextureEntryNode> childrenList = (from c in tn.Children
                                                        where c is PAT0TextureEntryNode
                                                        select(PAT0TextureEntryNode) c).ToList();

            if ((from c in childrenList where c.FrameIndex >= 40 && c.FrameIndex < 50 select c).Count() >= 10)
            {
                MessageBox.Show("Skipping " + pathToPAT0TextureNode.Substring(pathToPAT0TextureNode.LastIndexOf('/') + 1) +
                                " - mappings for icon numbers 40-49 already exist.");
                return;
            }

            string texToCopyName = null;
            List <Tuple <string, float> > entries = new List <Tuple <string, float> >();

            foreach (var entry in childrenList)
            {
                if (entry.Texture == null)
                {
                    MessageBox.Show("BrawlLib cannot read PAT0 texture name(s) from " + pathToPAT0TextureNode);
                    return;
                }
                entries.Add(new Tuple <string, float>(entry.Texture, entry.FrameIndex));
                if (entry.FrameIndex == 1)
                {
                    texToCopyName = entry.Texture;
                }
                if (entry.FrameIndex != 0)
                {
                    tn.RemoveChild(entry);
                }
            }

            string basename = (from e in entries
                               where e.Item1.Contains('.')
                               select e.Item1).First();

            basename = basename.Substring(0, basename.LastIndexOf('.'));

            Func <int, string> getTexStringByIconNumber = iconNum => {
                if (iconNum < 32 || (iconNum >= 50 && iconNum < 60) || iconNum == 80)
                {
                    string previousTexture = null;
                    foreach (var entry in entries)
                    {
                        if (entry.Item2 > iconNum)
                        {
                            break;
                        }
                        previousTexture = entry.Item1;
                    }
                    return(previousTexture);
                }
                else
                {
                    return(defaultName ?? basename + "." + iconNum.ToString("D2"));
                }
            };

            for (int i = 1; i <= 80; i++)
            {
                string texname = getTexStringByIconNumber(i);
                var    entry   = new PAT0TextureEntryNode();
                tn.AddChild(entry);
                entry.FrameIndex = i;
                entry.Texture    = texname;
                if (icon)
                {
                    entry.Palette = entry.Texture;
                }
            }

            var moreThan79query = from e in entries
                                  where e.Item2 > 80
                                  orderby e.Item2 ascending
                                  select e;

            foreach (var tuple in moreThan79query)
            {
                var entry = new PAT0TextureEntryNode();
                tn.AddChild(entry);
                entry.FrameIndex = tuple.Item2;
                entry.Texture    = tuple.Item1;
                if (icon)
                {
                    entry.Palette = entry.Texture;
                }
            }

            ResourceNode brres = tn;

            while (brres != null && !(brres is BRRESNode))
            {
                brres = brres.Parent;
            }

            if (brres != null)
            {
                var      folder    = brres.FindChild("Textures(NW4R)", false);
                TEX0Node texToCopy = texToCopyName == null
                                        ? null
                                        : folder.FindChild(texToCopyName, false) as TEX0Node;
                PLT0Node pltToCopy = texToCopyName == null
                                        ? null
                                        : brres.FindChild("Palettes(NW4R)", false).FindChild(texToCopyName, false) as PLT0Node;

                foreach (ResourceNode c in tn.Children)
                {
                    PAT0TextureEntryNode p = c as PAT0TextureEntryNode;
                    if (p == null)
                    {
                        continue;
                    }

                    var texture = folder.FindChild(p.Texture, false);
                    if (texture == null)
                    {
                        if (texToCopy != null)
                        {
                            TEX0Node tex0 = ((BRRESNode)brres).CreateResource <TEX0Node>(p.Texture);
                            tex0.ReplaceRaw(texToCopy.WorkingUncompressed.Address, texToCopy.WorkingUncompressed.Length);
                        }
                        if (pltToCopy != null)
                        {
                            PLT0Node plt0 = ((BRRESNode)brres).CreateResource <PLT0Node>(p.Texture);
                            plt0.ReplaceRaw(pltToCopy.WorkingUncompressed.Address, pltToCopy.WorkingUncompressed.Length);
                        }
                    }
                    else if (texture.Index == 1)
                    {
                        texToCopy = texture as TEX0Node;
                    }
                }
            }
        }
 public new DialogResult ShowDialog(IWin32Window owner)
 {
     _bresParent = null;
     _origTEX0 = null;
     _origPLT0 = null;
     _origREFT = null;
     _origTPL = null;
     _origTPLPlt = null;
     _paletteData = _textureData = null;
     DialogResult = DialogResult.Cancel;
     try { return base.ShowDialog(owner); }
     //catch (Exception x) { MessageBox.Show(x.ToString()); return DialogResult.Cancel; }
     finally { DisposeImages(); }
 }
Example #27
0
        public static void ColorSmashTex0(object sender, EventArgs e)
        {
            // If this was selected via keycode when it's invalid, return without error
            if (!CanRunColorSmash || MainForm.Instance.resourceTree.SelectedNodes.Count <= 1)
            {
                return;
            }

            DirectoryInfo inputDir  = Directory.CreateDirectory(Program.AppPath + "\\cs\\");
            DirectoryInfo outputDir = Directory.CreateDirectory(Program.AppPath + "\\cs\\out\\");

            try
            {
                // Clear the directories. If they aren't empty, the implementation WILL NOT work
                foreach (FileInfo f in outputDir.GetFiles())
                {
                    try
                    {
                        f.Delete();
                    }
                    catch
                    {
                        // ignored
                    }
                }

                foreach (FileInfo f in inputDir.GetFiles())
                {
                    try
                    {
                        f.Delete();
                    }
                    catch
                    {
                        // ignored
                    }
                }

                // Throw error if color smash directory isn't empty
                if (inputDir.GetFiles().Length > 0 || outputDir.GetFiles().Length > 0)
                {
                    MessageBox.Show(
                        "One or more files exist in the required Color Smash folder. Please delete these nodes manually and try again",
                        "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                short                    paletteCount = 0;
                List <TEX0Node>          textureList  = new List <TEX0Node>();
                Dictionary <int, string> names        = new Dictionary <int, string>();
                BRRESNode                b            = (((TEX0Wrapper)MainForm.Instance.resourceTree.SelectedNodes[0]).Resource as TEX0Node)?
                                                        .BRESNode;
                if (b == null)
                {
                    MessageBox.Show(
                        "The BRRES could not be found. Color Smashing is only supported for TEX0 nodes in BRRES groups",
                        "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                int index = int.MaxValue;
                foreach (TreeNode n in MainForm.Instance.resourceTree.SelectedNodes)
                {
                    // If this was selected via keycode when it's invalid, return without error
                    if (!(n is TEX0Wrapper))
                    {
                        return;
                    }

                    if (((TEX0Wrapper)n).Resource is TEX0Node t)
                    {
                        if (t.BRESNode != b)
                        {
                            MessageBox.Show("Color Smash is only supported for nodes in the same BRRES", "Error",
                                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        textureList.Add(t);
                        int placement = t.Parent.Children.IndexOf(t);
                        names.Add(placement, t.Name);
                        if (placement < index)
                        {
                            index = placement;
                        }

                        t.Export($"{inputDir.FullName}\\{placement:D5}.png");

                        if (paletteCount < 256)
                        {
                            if (!t.HasPalette || t.GetPaletteNode() == null)
                            {
                                paletteCount = 256;
                            }
                            else if (t.HasPalette && t.GetPaletteNode() != null &&
                                     t.GetPaletteNode().Palette.Entries.Length > paletteCount)
                            {
                                paletteCount = (short)Math.Min(t.GetPaletteNode().Palette.Entries.Length, 256);
                            }
                        }
                    }
                }

                if (index == int.MaxValue)
                {
                    MessageBox.Show("Could not properly get the index of the images", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (paletteCount == 0)
                {
                    paletteCount = 256;
                }

                foreach (TEX0Node t in textureList)
                {
                    if (t.HasPalette && t.GetPaletteNode() != null)
                    {
                        t.GetPaletteNode().Remove();
                    }

                    t.Remove();
                }

                Process cSmash = Process.Start(new ProcessStartInfo
                {
                    FileName    = Program.AppPath + "\\color_smash.exe",
                    WindowStyle = ProcessWindowStyle.Hidden,
                    Arguments   = $"-c RGB5A3 -n {paletteCount}"
                });
                cSmash?.WaitForExit();

                textureList = new List <TEX0Node>();
                int           count    = 0;
                BRESGroupNode texGroup = b.GetOrCreateFolder <TEX0Node>();
                foreach (FileInfo f in outputDir.GetFiles())
                {
                    FileInfo f2 = new FileInfo($"{inputDir.FullName}\\{f.Name}");
                    int      i  = int.Parse(f.Name.Substring(0, f.Name.IndexOf(".", StringComparison.Ordinal)));
                    using (TextureConverterDialog dlg = new TextureConverterDialog())
                    {
                        dlg.ImageSource = f.FullName;
                        dlg.ChkImportPalette.Checked = true;
                        dlg.Automatic      = true;
                        dlg.StartingFormat = WiiPixelFormat.CI8;

                        if (dlg.ShowDialog(MainForm.Instance, b) != DialogResult.OK)
                        {
                            continue;
                        }

                        TEX0Node t = dlg.TEX0TextureNode;
                        t.Name = names[i];
                        textureList.Add(t);
                        dlg.Dispose();
                        t.OriginalPath = "";
                        if (texGroup.Children.Count > count + 1)
                        {
                            texGroup.RemoveChild(t);
                            texGroup.InsertChild(t, false, index + count);
                        }
                        count++;
                    }

                    f2.Delete();
                }

                if (textureList.Count > 0)
                {
                    textureList.Remove(textureList.Last());
                    foreach (TEX0Node t in textureList)
                    {
                        t.SharesData = true;
                    }
                }

                if (inputDir.GetFiles().Length > 0)
                {
                    MessageBox.Show(
                        "One or more files threw an error. Please ensure all relevant textures can be Color Smashed together.",
                        "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    foreach (FileInfo f in inputDir.GetFiles())
                    {
                        int i = int.Parse(f.Name.Substring(0, f.Name.IndexOf(".", StringComparison.Ordinal)));
                        using (TextureConverterDialog dlg = new TextureConverterDialog())
                        {
                            dlg.ImageSource = f.FullName;
                            dlg.Automatic   = true;

                            if (dlg.ShowDialog(MainForm.Instance, b) != DialogResult.OK)
                            {
                                continue;
                            }

                            TEX0Node t = dlg.TEX0TextureNode;
                            t.Name = names[i];

                            dlg.Dispose();
                            t.OriginalPath = "";
                            if (texGroup.Children.Count > count + 1)
                            {
                                texGroup.RemoveChild(t);
                                texGroup.InsertChild(t, false, index + count);
                            }
                            count++;
                        }
                    }
                }
            }
            finally
            {
                foreach (FileInfo f in outputDir.GetFiles())
                {
                    try
                    {
                        f.Delete();
                    }
                    catch
                    {
                        // ignored
                    }
                }

                try
                {
                    outputDir.Delete();
                }
                catch
                {
                    // ignored
                }

                foreach (FileInfo f in inputDir.GetFiles())
                {
                    try
                    {
                        f.Delete();
                    }
                    catch
                    {
                        // ignored
                    }
                }

                try
                {
                    inputDir.Delete();
                }
                catch
                {
                    // ignored
                }
            }
        }
Example #28
0
        public void copyIconsToSelcharacter2()
        {
            string fileToSaveTo = null;

            ResourceNode s2 = null;

            if (common5 != null)
            {
                s2 = common5.FindChild("sc_selcharacter2_en", false);
            }
            else if (sc_selmap != null)
            {
                if (File.Exists("../../menu2/sc_selcharacter2.pac"))
                {
                    fileToSaveTo = "../../menu2/sc_selcharacter2.pac";
                    s2           = TempFiles.MakeTempNode(fileToSaveTo);
                }
                else if (File.Exists("../../menu2/sc_selcharacter2_en.pac"))
                {
                    fileToSaveTo = "../../menu2/sc_selcharacter2_en.pac";
                    s2           = TempFiles.MakeTempNode(fileToSaveTo);
                }
            }

            if (s2 == null)
            {
                return;
            }

            ResourceNode md0  = s2.FindChild("MenuRule_en/ModelData[0]", false);
            MSBinNode    md1  = s2.FindChild("MenuRule_en/MiscData[1]", false) as MSBinNode;
            ResourceNode md80 = sc_selmap.FindChild("MiscData[80]", false);

            if (md0 == null || md80 == null)
            {
                return;
            }

            Image[] icons        = new Image[41];
            Image[] frontstnames = new Image[41];
            for (int i = 1; i < 60; i++)
            {
                if (i == 32)
                {
                    i = 50;
                }
                int    sssPos     = StageIDMap.sssPositionForSelcharacter2Icon(i);
                string nameSelmap = BestSSS[sssPos].Item2.ToString("D2");
                icons[sssPos]        = ((md80.FindChild("Textures(NW4R)/MenSelmapIcon." + nameSelmap, false) as TEX0Node).GetImage(0));
                frontstnames[sssPos] = ((md80.FindChild("Textures(NW4R)/MenSelmapFrontStname." + nameSelmap, false) as TEX0Node).GetImage(0));
            }

            var d = new RandomSelectEditNamesDialog(md1._strings, icons, frontstnames);

            d.Message = "When finished, press OK to continue.";
            if (d.ShowDialog() == DialogResult.OK)
            {
                for (int i = 0; i < md1._strings.Count; i++)
                {
                    md1._strings[i] = d[i].ToString();
                }
            }
            else
            {
                return;
            }

            using (ProgressWindow w = new ProgressWindow()
            {
                CanCancel = false
            }) {
                w.Begin(0, 60, 0);
                for (int i = 1; i < 60; i++)
                {
                    if (i == 32)
                    {
                        i = 50;
                    }

                    int      sssPos            = StageIDMap.sssPositionForSelcharacter2Icon(i);
                    string   tempFile1         = TempFiles.Create(".tex0");
                    string   tempFile2         = TempFiles.Create(".plt0");
                    string   nameSelcharacter2 = i.ToString("D2");
                    string   nameSelmap        = BestSSS[sssPos].Item2.ToString("D2");
                    TEX0Node iconFrom          = md80.FindChild("Textures(NW4R)/MenSelmapIcon." + nameSelmap, false) as TEX0Node;
                    TEX0Node iconTo            = md0.FindChild("Textures(NW4R)/MenSelmapIcon." + nameSelcharacter2, false) as TEX0Node;
                    var      palFrom           = md80.FindChild("Palettes(NW4R)/MenSelmapIcon." + nameSelmap, false);
                    var      palTo             = md0.FindChild("Palettes(NW4R)/MenSelmapIcon." + nameSelcharacter2, false);
                    if (iconFrom != null && iconTo != null && palFrom != null && palTo != null)
                    {
                        iconFrom.Export(tempFile1);
                        iconTo.Replace(tempFile1);
                        palFrom.Export(tempFile2);
                        palTo.Replace(tempFile2);
                    }

                    TEX0Node prevbase    = md80.FindChild("Textures(NW4R)/MenSelmapPrevbase." + nameSelmap, false) as TEX0Node;
                    TEX0Node stageswitch = md0.FindChild("Textures(NW4R)/MenStageSwitch." + nameSelcharacter2, false) as TEX0Node;
                    if (prevbase != null && stageswitch != null)
                    {
                        Bitmap thumbnail = new Bitmap(112, 56);
                        using (Graphics g = Graphics.FromImage(thumbnail)) {
                            g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                            g.DrawImage(prevbase.GetImage(0), 0, -28, 112, 112);
                        }
                        stageswitch.Replace(thumbnail);
                    }

                    w.Update(i);
                }
            }

            if (fileToSaveTo != null)
            {
                s2.Export(fileToSaveTo);
            }
        }