Format code to conform with code style guide lines

This commit is contained in:
miku-666
2024-07-16 20:07:34 +02:00
parent 2dcc2c80c3
commit c41fecde90
51 changed files with 533 additions and 443 deletions

View File

@@ -47,7 +47,7 @@ namespace PckStudio.FileFormats
public CSMBParentPart Parent = 0;
public float posX, posY, posZ = 0.0f;
public float sizeX, sizeY, sizeZ = 0.0f;
public int uvX, uvY = 0;
public int uvX, uvY = 0;
public bool HideWArmour, MirrorTexture = false;
public float Inflation = 0.0f;
}

View File

@@ -72,7 +72,7 @@ namespace PckStudio.FileFormats
/// </summary>
public void ApplyCredits(LOCFile locFile)
{
foreach (var credit in Credits)
foreach (KeyValuePair<string, string> credit in Credits)
{
locFile.SetLocEntry(credit.Key, credit.Value);
}
@@ -135,7 +135,8 @@ namespace PckStudio.FileFormats
category > AudioCategory.EAudioType.Unused)
throw new InvalidCategoryException(nameof(category));
bool exists = HasCategory(category);
if (!exists) _categories[(int)category] = new AudioCategory(name, parameterType, category);
if (!exists)
_categories[(int)category] = new AudioCategory(name, parameterType, category);
return !exists;
}
@@ -149,7 +150,8 @@ namespace PckStudio.FileFormats
public bool RemoveCategory(AudioCategory.EAudioType category)
{
bool exists = HasCategory(category);
if (exists) _categories[(int)category] = null;
if (exists)
_categories[(int)category] = null;
return exists;
}

View File

@@ -185,7 +185,7 @@ namespace PckStudio.Forms.Additional_Popups
{
if (ofd.FileName.EndsWith(".3dst"))
{
using (var fs = File.OpenRead(ofd.FileName))
using (FileStream fs = File.OpenRead(ofd.FileName))
{
var reader = new _3DSTextureReader();
CheckImage(reader.FromStream(fs));

View File

@@ -60,9 +60,9 @@ namespace PckStudio.Forms.Additional_Popups.Animation
ResourceCategory.ItemAnimation => (Tiles.ItemTileInfos, Tiles.ItemImageList, "Items"),
_ => throw new InvalidOperationException(nameof(key))
};
var view = filterPrompt.AddFilterPage(name, null, filterPredicate);
TreeView view = filterPrompt.AddFilterPage(name, null, filterPredicate);
view.ImageList = imgList;
foreach ((int i, var tileData) in textureInfos?.enumerate())
foreach ((int i, JsonTileInfo tileData) in textureInfos?.enumerate())
{
if (string.IsNullOrEmpty(tileData.InternalName) || view.Nodes.ContainsKey(tileData.InternalName))
continue;

View File

@@ -1,7 +1,6 @@
using System;
using MetroFramework.Forms;
using System.Windows.Forms;
using System.Diagnostics;
namespace PckStudio.Forms.Additional_Popups.Animation
{

View File

@@ -1,6 +1,6 @@
using System;
using MetroFramework.Forms;
using System.Windows.Forms;
using MetroFramework.Forms;
namespace PckStudio.Forms.Additional_Popups.Animation
{

View File

@@ -19,14 +19,14 @@ namespace PckStudio.Forms.Additional_Popups.EntityForms
{
filterPrompt = new FilterPrompt();
filterPrompt.OnSelectedItemChanged += FilterPrompt_OnSelectedItemChanged;
var treeViewEntity = filterPrompt.AddFilterPage("Entities", null, filterPredicate);
TreeView treeViewEntity = filterPrompt.AddFilterPage("Entities", null, filterPredicate);
ImageList entities = new ImageList();
entities.ColorDepth = ColorDepth.Depth32Bit;
entities.ImageSize = new System.Drawing.Size(32, 32);
entities.Images.AddRange(entityImages);
treeViewEntity.ImageList = entities;
var entityInfos = dataType switch
List<EntityInfo> entityInfos = dataType switch
{
"models" => Entities.ModelInfos,
"materials" => Entities.MaterialInfos,
@@ -36,7 +36,7 @@ namespace PckStudio.Forms.Additional_Popups.EntityForms
int i = 0;
foreach(var entity in entityInfos)
foreach(EntityInfo entity in entityInfos)
{
TreeNode entityNode = new TreeNode(entity.DisplayName)
{

View File

@@ -17,7 +17,6 @@
**/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using MetroFramework.Forms;
@@ -31,8 +30,8 @@ namespace PckStudio.Forms.Additional_Popups.Animation
public Color PageBackColor { get; set; } = Color.FromArgb(64, 64, 64);
private object selectedItem;
public object SelectedItem => selectedItem;
private object _selectedItem;
public object SelectedItem => _selectedItem;
public int SelectedTabIndex => tabController.SelectedIndex;
@@ -62,7 +61,7 @@ namespace PckStudio.Forms.Additional_Popups.Animation
};
pageView.AfterSelect += (sender, e) =>
{
selectedItem = e.Node.Tag;
_selectedItem = e.Node.Tag;
Events[nameof(OnSelectedItemChanged)]?.DynamicInvoke(this, EventArgs.Empty);
};
pageView.Tag = new List<TreeNode>(4);
@@ -114,7 +113,7 @@ namespace PckStudio.Forms.Additional_Popups.Animation
private void AcceptBtn_Click(object sender, EventArgs e)
{
DialogResult = selectedItem is null ? DialogResult.Cancel : DialogResult.OK;
DialogResult = _selectedItem is null ? DialogResult.Cancel : DialogResult.OK;
}
}
}

View File

@@ -40,7 +40,8 @@ namespace PckStudio
{
MessageBox.Show(this, "Please insert a value in the text box.", "Empty string");
}
else DialogResult = DialogResult.OK;
else
DialogResult = DialogResult.OK;
}
private void RenamePrompt_Load(object sender, EventArgs e)

View File

@@ -14,9 +14,6 @@ namespace PckStudio.Forms
public ContributorsForm()
{
InitializeComponent();
#if false
Task.Run(GetContributors);
#endif
string buildConfig = "";
#if BETA
buildConfig = "Beta";
@@ -33,7 +30,7 @@ namespace PckStudio.Forms
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
foreach (var contributorsName in ApplicationScope.Contributors)
foreach (Octokit.RepositoryContributor contributorsName in ApplicationScope.Contributors)
{
if (InvokeRequired)
Invoke(() => contributorsLayoutPanel.Controls.Add(new GithubUserPanel(contributorsName)));

View File

@@ -20,7 +20,7 @@ namespace PckStudio.Forms.Editor
sealed class ANIMRuleSet
{
public SkinANIM Value => anim;
public SkinANIM Value => _anim;
public Action<SkinANIM> OnCheckboxChanged;
private class Bictionary<T1, T2> : Dictionary<T1, T2>
@@ -41,15 +41,15 @@ namespace PckStudio.Forms.Editor
internal void AddRange(IEnumerable<(T1, T2)> range)
{
foreach (var (key, value) in range)
foreach ((T1 key, T2 value) in range)
{
Add(key, value);
}
}
}
private Bictionary<CheckBox, SkinAnimFlag> checkBoxLinkage;
private SkinANIM anim;
private bool ignoreCheckChanged = false;
private SkinANIM _anim;
private bool _ignoreCheckChanged = false;
public ANIMRuleSet(params (CheckBox, SkinAnimFlag)[] linkage)
{
@@ -58,7 +58,7 @@ namespace PckStudio.Forms.Editor
Debug.WriteLine($"Not all {nameof(SkinAnimFlag)} are mapped to a given checkbox.");
checkBoxLinkage.AddRange(linkage);
foreach (var (checkbox, _) in linkage)
foreach ((CheckBox checkbox, SkinAnimFlag _) in linkage)
{
checkbox.CheckedChanged += checkedChanged;
}
@@ -66,7 +66,7 @@ namespace PckStudio.Forms.Editor
internal void SetAll(bool state)
{
foreach (var item in checkBoxLinkage)
foreach (KeyValuePair<CheckBox, SkinAnimFlag> item in checkBoxLinkage)
{
IgnoreAndDo(item.Key, checkbox =>
{
@@ -84,25 +84,28 @@ namespace PckStudio.Forms.Editor
break;
case SkinAnimFlag.RESOLUTION_64x64:
checkbox.Enabled = !state;
if(state) checkbox.Checked = false; // Prioritize slim model > classic model, LCE would
// Prioritize slim model > classic model, LCE would
if(state)
checkbox.Checked = false;
break;
}
anim.SetFlag(item.Value, checkbox.Checked);
_anim.SetFlag(item.Value, checkbox.Checked);
});
}
OnCheckboxChanged?.Invoke(anim);
OnCheckboxChanged?.Invoke(_anim);
}
internal void ApplyAnim(SkinANIM anim)
{
this.anim = anim;
foreach (var item in checkBoxLinkage)
this._anim = anim;
foreach (KeyValuePair<CheckBox, SkinAnimFlag> item in checkBoxLinkage)
{
/*
* not the best way to do this but whatever lol
* fix for both model flags being unset when both are set to true, with slim model prioritized of course
*/
if (item.Value == SkinAnimFlag.RESOLUTION_64x64 && anim.GetFlag(SkinAnimFlag.SLIM_MODEL)) continue;
if (item.Value == SkinAnimFlag.RESOLUTION_64x64 && anim.GetFlag(SkinAnimFlag.SLIM_MODEL))
continue;
item.Key.Checked = anim.GetFlag(item.Value);
}
@@ -110,7 +113,7 @@ namespace PckStudio.Forms.Editor
private void checkedChanged(object sender, EventArgs e)
{
if (!ignoreCheckChanged && sender is CheckBox checkBox && checkBoxLinkage.ContainsKey(checkBox))
if (!_ignoreCheckChanged && sender is CheckBox checkBox && checkBoxLinkage.ContainsKey(checkBox))
{
switch (checkBoxLinkage[checkBox])
{
@@ -151,8 +154,8 @@ namespace PckStudio.Forms.Editor
default:
break;
}
anim.SetFlag(checkBoxLinkage[checkBox], checkBox.Checked && checkBox.Enabled);
OnCheckboxChanged?.Invoke(anim);
_anim.SetFlag(checkBoxLinkage[checkBox], checkBox.Checked && checkBox.Enabled);
OnCheckboxChanged?.Invoke(_anim);
}
}
@@ -163,9 +166,9 @@ namespace PckStudio.Forms.Editor
private void IgnoreAndDo(CheckBox checkBox, Action<CheckBox> action)
{
ignoreCheckChanged = true;
_ignoreCheckChanged = true;
action.Invoke(checkBox);
ignoreCheckChanged = false;
_ignoreCheckChanged = false;
}
}
@@ -176,14 +179,14 @@ namespace PckStudio.Forms.Editor
saveButton.Visible = !Settings.Default.AutoSaveChanges;
}
public ANIMEditor(string ANIM) : this()
public ANIMEditor(string animString) : this()
{
if (!SkinANIM.IsValidANIM(ANIM))
if (!SkinANIM.IsValidANIM(animString))
{
DialogResult = DialogResult.Abort;
Close();
}
var anim = initialANIM = SkinANIM.FromString(ANIM);
SkinANIM anim = initialANIM = SkinANIM.FromString(animString);
setDisplayAnim(anim);
ruleset.ApplyAnim(anim);
}
@@ -254,7 +257,8 @@ namespace PckStudio.Forms.Editor
string value = string.Empty;
while (!SkinANIM.IsValidANIM(value))
{
if (!string.IsNullOrWhiteSpace(value)) MessageBox.Show(this, $"The following value \"{value}\" is not valid. Please try again.");
if (!string.IsNullOrWhiteSpace(value))
MessageBox.Show(this, $"The following value \"{value}\" is not valid. Please try again.");
TextPrompt diag = new TextPrompt(value);
diag.LabelText = "ANIM";
diag.OKButtonText = "Ok";
@@ -262,7 +266,8 @@ namespace PckStudio.Forms.Editor
{
value = diag.NewText;
}
else return;
else
return;
}
ruleset.ApplyAnim(SkinANIM.FromString(value));
}
@@ -306,15 +311,24 @@ namespace PckStudio.Forms.Editor
graphic.FillRectangle(Brushes.Magenta, new Rectangle(16, 16, 24, 16));
if (img.Height == 64)
{
if (ruleset.Value.GetFlag(SkinAnimFlag.RIGHT_ARM_DISABLED)) graphic.FillRectangle(Brushes.Magenta, new Rectangle(40, 16, 16, 16));
if (ruleset.Value.GetFlag(SkinAnimFlag.RIGHT_LEG_DISABLED)) graphic.FillRectangle(Brushes.Magenta, new Rectangle(0, 16, 16, 16));
if (ruleset.Value.GetFlag(SkinAnimFlag.BODY_OVERLAY_DISABLED)) graphic.FillRectangle(Brushes.Magenta, new Rectangle(16, 32, 24, 16));
if (ruleset.Value.GetFlag(SkinAnimFlag.RIGHT_ARM_OVERLAY_DISABLED)) graphic.FillRectangle(Brushes.Magenta, new Rectangle(40, 32, 16, 16));
if (ruleset.Value.GetFlag(SkinAnimFlag.RIGHT_LEG_OVERLAY_DISABLED)) graphic.FillRectangle(Brushes.Magenta, new Rectangle(0, 32, 16, 16));
if (ruleset.Value.GetFlag(SkinAnimFlag.LEFT_LEG_OVERLAY_DISABLED)) graphic.FillRectangle(Brushes.Magenta, new Rectangle(0, 48, 16, 16));
if (ruleset.Value.GetFlag(SkinAnimFlag.LEFT_LEG_DISABLED)) graphic.FillRectangle(Brushes.Magenta, new Rectangle(16, 48, 16, 16));
if (ruleset.Value.GetFlag(SkinAnimFlag.LEFT_ARM_DISABLED)) graphic.FillRectangle(Brushes.Magenta, new Rectangle(32, 48, 16, 16));
if (ruleset.Value.GetFlag(SkinAnimFlag.LEFT_ARM_OVERLAY_DISABLED)) graphic.FillRectangle(Brushes.Magenta, new Rectangle(48, 48, 16, 16));
if (ruleset.Value.GetFlag(SkinAnimFlag.RIGHT_ARM_DISABLED))
graphic.FillRectangle(Brushes.Magenta, new Rectangle(40, 16, 16, 16));
if (ruleset.Value.GetFlag(SkinAnimFlag.RIGHT_LEG_DISABLED))
graphic.FillRectangle(Brushes.Magenta, new Rectangle(0, 16, 16, 16));
if (ruleset.Value.GetFlag(SkinAnimFlag.BODY_OVERLAY_DISABLED))
graphic.FillRectangle(Brushes.Magenta, new Rectangle(16, 32, 24, 16));
if (ruleset.Value.GetFlag(SkinAnimFlag.RIGHT_ARM_OVERLAY_DISABLED))
graphic.FillRectangle(Brushes.Magenta, new Rectangle(40, 32, 16, 16));
if (ruleset.Value.GetFlag(SkinAnimFlag.RIGHT_LEG_OVERLAY_DISABLED))
graphic.FillRectangle(Brushes.Magenta, new Rectangle(0, 32, 16, 16));
if (ruleset.Value.GetFlag(SkinAnimFlag.LEFT_LEG_OVERLAY_DISABLED))
graphic.FillRectangle(Brushes.Magenta, new Rectangle(0, 48, 16, 16));
if (ruleset.Value.GetFlag(SkinAnimFlag.LEFT_LEG_DISABLED))
graphic.FillRectangle(Brushes.Magenta, new Rectangle(16, 48, 16, 16));
if (ruleset.Value.GetFlag(SkinAnimFlag.LEFT_ARM_DISABLED))
graphic.FillRectangle(Brushes.Magenta, new Rectangle(32, 48, 16, 16));
if (ruleset.Value.GetFlag(SkinAnimFlag.LEFT_ARM_OVERLAY_DISABLED))
graphic.FillRectangle(Brushes.Magenta, new Rectangle(48, 48, 16, 16));
}
else
{

View File

@@ -32,7 +32,6 @@ using PckStudio.Forms.Additional_Popups.Animation;
using PckStudio.Extensions;
using PckStudio.Properties;
using PckStudio.Internal;
using AnimatedGif;
using PckStudio.Internal.Deserializer;
namespace PckStudio.Forms.Editor
@@ -157,7 +156,8 @@ namespace PckStudio.Forms.Editor
{
foreach (TreeNode node in treeNode.Nodes)
{
if (node.Text.ToLower() == name.ToLower()) return node;
if (node.Text.ToLower() == name.ToLower())
return node;
return FindNodeByName(node, name);
}
return null;
@@ -241,8 +241,10 @@ namespace PckStudio.Forms.Editor
private bool ContainsNode(TreeNode node1, TreeNode node2)
{
// Check the parent node of the second node.
if (node2.Parent == null) return false;
if (node2.Parent.Equals(node1)) return true;
if (node2.Parent == null)
return false;
if (node2.Parent.Equals(node1))
return true;
// If the parent node is not null or equal to the first node,
// call the ContainsNode method recursively using the parent of
@@ -252,7 +254,7 @@ namespace PckStudio.Forms.Editor
private void treeView1_doubleClick(object sender, EventArgs e)
{
var frame = _animation.GetFrame(frameTreeView.SelectedNode.Index);
Animation.Frame frame = _animation.GetFrame(frameTreeView.SelectedNode.Index);
using FrameEditor diag = new FrameEditor(frame.Ticks, _animation.GetTextureIndex(frame.Texture), TextureIcons);
if (diag.ShowDialog(this) == DialogResult.OK)
{
@@ -319,7 +321,8 @@ namespace PckStudio.Forms.Editor
// -MattNL
Filter = "Animation Scripts (*.mcmeta)|*.png.mcmeta"
};
if (fileDialog.ShowDialog(this) != DialogResult.OK) return;
if (fileDialog.ShowDialog(this) != DialogResult.OK)
return;
Debug.WriteLine("Selected Animation Script: " + fileDialog.FileName);
string textureFile = fileDialog.FileName.Substring(0, fileDialog.FileName.Length - ".mcmeta".Length);
@@ -355,7 +358,7 @@ namespace PckStudio.Forms.Editor
string jsondata = JsonConvert.SerializeObject(mcmeta, Formatting.Indented);
string filename = fileDialog.FileName;
File.WriteAllText(filename, jsondata);
var finalTexture = _animation.BuildTexture();
Image finalTexture = _animation.BuildTexture();
// removes ".mcmeta" from filename
string texturePath = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename));
finalTexture.Save(texturePath);
@@ -451,7 +454,7 @@ namespace PckStudio.Forms.Editor
if (ofd.ShowDialog(this) != DialogResult.OK)
return;
Image img = Image.FromFile(ofd.FileName);
var textures = img.Split(ImageLayoutDirection.Vertical);
IEnumerable<Image> textures = img.Split(ImageLayoutDirection.Vertical);
_animation = new Animation(textures, string.Empty);
LoadAnimationTreeView();
}

View File

@@ -82,7 +82,7 @@ namespace PckStudio.Forms.Editor
treeView1.BeginUpdate();
treeView1.Nodes.Clear();
foreach (var category in _audioFile.Categories)
foreach (PckAudioFile.AudioCategory category in _audioFile.Categories)
{
// fix songs with directories using backslash instead of forward slash
// Songs with a backslash instead of a forward slash would not play in RPCS3
@@ -116,7 +116,7 @@ namespace PckStudio.Forms.Editor
{
if (treeView1.SelectedNode == null || treeView2.SelectedNode == null)
return;
var entry = treeView2.SelectedNode;
TreeNode entry = treeView2.SelectedNode;
if (!parent.CreateDataFolder())
return;
@@ -151,11 +151,11 @@ namespace PckStudio.Forms.Editor
}
using ItemSelectionPopUp add = new ItemSelectionPopUp(available);
if (add.ShowDialog(this) == DialogResult.OK)
_audioFile.AddCategory(GetCategoryId(add.SelectedItem));
else return;
if (add.ShowDialog(this) != DialogResult.OK)
return;
var category = _audioFile.GetCategory(GetCategoryId(add.SelectedItem));
_audioFile.AddCategory(GetCategoryId(add.SelectedItem));
PckAudioFile.AudioCategory category = _audioFile.GetCategory(GetCategoryId(add.SelectedItem));
if (GetCategoryId(add.SelectedItem) == PckAudioFile.AudioCategory.EAudioType.Creative)
{
@@ -174,7 +174,8 @@ namespace PckStudio.Forms.Editor
{
if (treeView1.SelectedNode is TreeNode t && t.Tag is PckAudioFile.AudioCategory)
{
if (!parent.CreateDataFolder()) return;
if (!parent.CreateDataFolder())
return;
OpenFileDialog ofn = new OpenFileDialog();
ofn.Multiselect = true;
@@ -182,7 +183,9 @@ namespace PckStudio.Forms.Editor
ofn.Title = "Please choose WAV or BINKA files to add to your pack";
ofn.ShowDialog(this);
ofn.Dispose();
if (string.IsNullOrEmpty(ofn.FileName)) return; // Return if name is null or if the user cancels
// Return if name is null or if the user cancels
if (string.IsNullOrEmpty(ofn.FileName))
return;
ProcessEntries(ofn.FileNames);
}
@@ -224,7 +227,7 @@ namespace PckStudio.Forms.Editor
}
}
async void ProcessEntries(string[] FileList)
async void ProcessEntries(string[] fileList)
{
int success = 0;
int exitCode = 0;
@@ -235,7 +238,7 @@ namespace PckStudio.Forms.Editor
Directory.CreateDirectory(ApplicationScope.DataCacher.CacheDirectory); // create directory in case it doesn't exist
foreach (string file in FileList)
foreach (string file in fileList)
{
if (Path.GetExtension(file) == ".binka" || Path.GetExtension(file) == ".wav")
{
@@ -243,7 +246,8 @@ namespace PckStudio.Forms.Editor
songName = Regex.Replace(songName, @"[^\u0000-\u007F]+", "_"); // Replace UTF characters
string cacheSongFile = Path.Combine(ApplicationScope.DataCacher.CacheDirectory, songName + Path.GetExtension(file));
if(File.Exists(cacheSongFile)) File.Delete(cacheSongFile);
if (File.Exists(cacheSongFile))
File.Delete(cacheSongFile);
string new_loc = Path.Combine(parent.GetDataPath(), songName + ".binka");
bool is_duplicate_file = false; // To handle if a file already in the pack is dropped back in
@@ -264,13 +268,14 @@ namespace PckStudio.Forms.Editor
string diag_text = "A file named \"" + Path.GetFileNameWithoutExtension(file) + ".binka\" already exists in the Data folder.";
if (is_duplicate_file) diag_text = "\"" + Path.GetFileNameWithoutExtension(file) + ".binka\" has an identical copy present in the Data folder.";
if (is_duplicate_file)
diag_text = "\"" + Path.GetFileNameWithoutExtension(file) + ".binka\" has an identical copy present in the Data folder.";
diag_text += " Pressing yes will replace the existing file. By pressing no, the song entry will be added without affecting the file." +
"You can also cancel this operation and all files in queue.";
DialogResult user_prompt = MessageBox.Show(this, diag_text, "File already exists", MessageBoxButtons.YesNoCancel);
while (user_prompt == DialogResult.None) ; // Stops the editor from adding or processing the file until the user has made their choice
while (user_prompt == DialogResult.None) // Stops the editor from adding or processing the file until the user has made their choice
if (user_prompt == DialogResult.Cancel)
{
break;
@@ -290,7 +295,8 @@ namespace PckStudio.Forms.Editor
{
// deletes the file so that the copy function can happen safely
// and ignore duplicate files because well... they're duplicates lol
if (File.Exists(new_loc) && !is_duplicate_file) File.Delete(new_loc);
if (File.Exists(new_loc) && !is_duplicate_file)
File.Delete(new_loc);
}
}
@@ -314,7 +320,8 @@ namespace PckStudio.Forms.Editor
exitCode = Binka.ToBinka(cacheSongFile, new_loc, (int)compressionUpDown.Value);
});
if (!File.Exists(cacheSongFile)) MessageBox.Show(this, $"\"{songName}.wav\" failed to convert for some reason. Please report this on the communtiy Discord server, which can be found under \"More\" in the toolbar at the top of the program.", "Conversion failed");
if (!File.Exists(cacheSongFile))
MessageBox.Show(this, $"\"{songName}.wav\" failed to convert for some reason. Please report this on the communtiy Discord server, which can be found under \"More\" in the toolbar at the top of the program.", "Conversion failed");
else
{
success++;
@@ -323,7 +330,8 @@ namespace PckStudio.Forms.Editor
Cursor.Current = Cursors.Default;
if (exitCode != 0) continue;
if (exitCode != 0)
continue;
}
// if the file is NOT a .wav and doesn't exist, copy the file
@@ -344,7 +352,7 @@ namespace PckStudio.Forms.Editor
waitDiag.Close();
waitDiag.Dispose();
MessageBox.Show(this, $"Successfully processed and/or converted {success}/{FileList.Length} file{(FileList.Length != 1 ? "s" : "" )}", "Done!");
MessageBox.Show(this, $"Successfully processed and/or converted {success}/{fileList.Length} file{(fileList.Length != 1 ? "s" : "" )}", "Done!");
}
private void Binka_DragDrop(object sender, DragEventArgs e)
@@ -353,7 +361,8 @@ namespace PckStudio.Forms.Editor
// Gets the MainForm so we can access the Save Location
if (treeView1.SelectedNode != null)
{
if (!parent.CreateDataFolder()) return;
if (!parent.CreateDataFolder())
return;
ProcessEntries((string[])e.Data.GetData(DataFormats.FileDrop, false));
}
@@ -372,7 +381,7 @@ namespace PckStudio.Forms.Editor
PckAudioFile.AudioCategory overworldCategory = _audioFile.GetCategory(PckAudioFile.AudioCategory.EAudioType.Overworld);
bool songs_missing = false;
foreach (var category in _audioFile.Categories)
foreach (PckAudioFile.AudioCategory category in _audioFile.Categories)
{
if (category.SongNames.Count < 1)
{
@@ -432,7 +441,8 @@ namespace PckStudio.Forms.Editor
private void deleteUnusedBINKAsToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show(this, "This will delete all unused BINKA songs in the Data directory. This cannot be undone. Are you sure you want to continue?", "Warning", MessageBoxButtons.YesNo);
if (dr != DialogResult.Yes) return;
if (dr != DialogResult.Yes)
return;
var totalSongList = new List<string>();
foreach (string song in _audioFile.Categories.SelectMany(cat => cat.SongNames))
{
@@ -440,7 +450,8 @@ namespace PckStudio.Forms.Editor
totalSongList.Add(song);
}
if (!parent.CreateDataFolder()) return;
if (!parent.CreateDataFolder())
return;
int totalDeleted = 0;
foreach (string song in Directory.GetFiles(parent.GetDataPath(), "*.binka"))
{
@@ -500,19 +511,23 @@ namespace PckStudio.Forms.Editor
private void openDataFolderToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!parent.CreateDataFolder()) return;
if (!parent.CreateDataFolder())
return;
Process.Start("explorer.exe", parent.GetDataPath());
}
private void AudioEditor_Shown(object sender, EventArgs e)
{
if (Owner.Owner is MainForm p) parent = p;
else Close();
if (Owner.Owner is MainForm p)
parent = p;
else
Close();
}
private async void bulkReplaceExistingFilesToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!parent.CreateDataFolder()) return;
if (!parent.CreateDataFolder())
return;
int exitCode = 0;
@@ -523,7 +538,10 @@ namespace PckStudio.Forms.Editor
ofn.Title = "Please choose WAV or BINKA files to replace existing track files";
ofn.ShowDialog(this);
ofn.Dispose();
if (string.IsNullOrEmpty(ofn.FileName)) return; // Return if name is null or if the user cancels
// Return if name is null or if the user cancels
if (string.IsNullOrEmpty(ofn.FileName))
return;
var totalSongList = new List<string>();
foreach (string song in _audioFile.Categories.SelectMany(cat => cat.SongNames))
@@ -536,7 +554,8 @@ namespace PckStudio.Forms.Editor
string song_name = Path.GetFileNameWithoutExtension(file);
string file_ext = Path.GetExtension(file).ToLower();
string new_loc = Path.Combine(parent.GetDataPath(), Path.GetFileNameWithoutExtension(file) + ".binka");
if (!totalSongList.Contains(song_name) || file == new_loc) continue;
if (!totalSongList.Contains(song_name) || file == new_loc)
continue;
Console.WriteLine(file);
File.Delete(new_loc);
@@ -556,9 +575,11 @@ namespace PckStudio.Forms.Editor
waitDiag.Dispose();
Cursor.Current = Cursors.Default;
if (exitCode != 0) continue;
if (exitCode != 0)
continue;
}
else if(file_ext == ".binka") File.Copy(file, Path.Combine(parent.GetDataPath(), Path.GetFileName(file)));
else if(file_ext == ".binka")
File.Copy(file, Path.Combine(parent.GetDataPath(), Path.GetFileName(file)));
}
}
@@ -572,20 +593,22 @@ namespace PckStudio.Forms.Editor
private void setCategoryToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!(treeView1.SelectedNode is TreeNode t && t.Tag is PckAudioFile.AudioCategory category)) return;
if (!(treeView1.SelectedNode is TreeNode t && t.Tag is PckAudioFile.AudioCategory category))
return;
string[] available = Categories.FindAll(str => !_audioFile.HasCategory(GetCategoryId(str))).ToArray();
if (available.Length > 0)
{
using ItemSelectionPopUp add = new ItemSelectionPopUp(available);
add.ButtonText = "Save";
if (add.ShowDialog(this) != DialogResult.OK) return;
if (add.ShowDialog(this) != DialogResult.OK)
return;
_audioFile.RemoveCategory(category.AudioType);
_audioFile.AddCategory(category.parameterType, GetCategoryId(add.SelectedItem), category.AudioType == PckAudioFile.AudioCategory.EAudioType.Overworld && playOverworldInCreative.Checked ? "include_overworld" : "");
var newCategory = _audioFile.GetCategory(GetCategoryId(add.SelectedItem));
PckAudioFile.AudioCategory newCategory = _audioFile.GetCategory(GetCategoryId(add.SelectedItem));
category.SongNames.ForEach(c => newCategory.SongNames.Add(c));
@@ -601,10 +624,11 @@ namespace PckStudio.Forms.Editor
{
if(MessageBox.Show(this, "This function will move all binka files in the \"Data\" folder into a \"Music\" folder, to keep your data better organized. Would you like to continue?", "Move tracks?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
if (treeView1.Nodes.Count < 1 || !parent.CreateDataFolder()) return;
if (treeView1.Nodes.Count < 1 || !parent.CreateDataFolder())
return;
string musicdir = Path.Combine(parent.GetDataPath(), "Music");
Directory.CreateDirectory(musicdir);
foreach (var category in _audioFile.Categories)
foreach (PckAudioFile.AudioCategory category in _audioFile.Categories)
{
for (var i = 0; i < category.SongNames.Count; i++) // using standard for loop so the list can be modified
{

View File

@@ -23,7 +23,7 @@ namespace PckStudio.Forms.Editor
{
// Behaviours File Format research by Miku and MattNL
private readonly PckAsset _asset;
BehaviourFile behaviourFile;
BehaviourFile _behaviourFile;
private readonly List<EntityInfo> BehaviourData = Entities.BehaviourInfos;
@@ -31,7 +31,7 @@ namespace PckStudio.Forms.Editor
{
treeView1.BeginUpdate();
treeView1.Nodes.Clear();
foreach (var entry in behaviourFile.entries)
foreach (var entry in _behaviourFile.entries)
{
TreeNode EntryNode = new TreeNode(entry.name);
@@ -62,12 +62,7 @@ namespace PckStudio.Forms.Editor
saveToolStripMenuItem1.Visible = !Settings.Default.AutoSaveChanges;
_asset = asset;
using (var stream = new MemoryStream(asset.Data))
{
var reader = new BehavioursReader();
behaviourFile = reader.FromStream(stream);
}
_behaviourFile = asset.GetData(new BehavioursReader());
treeView1.ImageList = new ImageList();
treeView1.ImageList.Images.AddRange(ApplicationScope.EntityImages);
@@ -77,7 +72,8 @@ namespace PckStudio.Forms.Editor
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if (treeView1.SelectedNode is null) return;
if (treeView1.SelectedNode is null)
return;
bool isValidOverride = treeView1.SelectedNode.Tag is BehaviourFile.RiderPositionOverride.PositionOverride;
MobIsTamedCheckbox.Enabled = isValidOverride;
@@ -101,7 +97,8 @@ namespace PckStudio.Forms.Editor
private void removeToolStripMenuItem_Click(object sender, EventArgs e)
{
if (treeView1.SelectedNode is null) return;
if (treeView1.SelectedNode is null)
return;
treeView1.SelectedNode.Remove();
}
@@ -147,15 +144,18 @@ namespace PckStudio.Forms.Editor
private void changeToolStripMenuItem_Click(object sender, EventArgs e)
{
if (treeView1.SelectedNode == null) return;
if (!(treeView1.SelectedNode.Tag is BehaviourFile.RiderPositionOverride entry)) return;
if (treeView1.SelectedNode == null)
return;
if (!(treeView1.SelectedNode.Tag is BehaviourFile.RiderPositionOverride entry))
return;
var diag = new AddEntry("behaviours", ApplicationScope.EntityImages);
if (diag.ShowDialog(this) == DialogResult.OK)
{
if (String.IsNullOrEmpty(diag.SelectedEntity)) return;
if (behaviourFile.entries.FindAll(behaviour => behaviour.name == diag.SelectedEntity).Count() > 0)
if (string.IsNullOrEmpty(diag.SelectedEntity))
return;
if (_behaviourFile.entries.FindAll(behaviour => behaviour.name == diag.SelectedEntity).Count() > 0)
{
MessageBox.Show(this, "You cannot have two entries for one entity. Please use the \"Add New Position Override\" tool to add multiple overrides for entities", "Error", MessageBoxButtons.OK);
return;
@@ -164,7 +164,7 @@ namespace PckStudio.Forms.Editor
entry.name = diag.SelectedEntity;
treeView1.SelectedNode.Tag = entry;
var behaviour = BehaviourData.Find(b => b.InternalName == entry.name);
EntityInfo behaviour = BehaviourData.Find(b => b.InternalName == entry.name);
treeView1.SelectedNode.Text = behaviour.DisplayName;
treeView1.SelectedNode.ImageIndex = BehaviourData.IndexOf(behaviour);
@@ -183,7 +183,8 @@ namespace PckStudio.Forms.Editor
private void addNewPositionOverrideToolStripMenuItem_Click(object sender, EventArgs e)
{
if (treeView1.SelectedNode.Tag is BehaviourFile.RiderPositionOverride.PositionOverride) treeView1.SelectedNode = treeView1.SelectedNode.Parent;
if (treeView1.SelectedNode.Tag is BehaviourFile.RiderPositionOverride.PositionOverride)
treeView1.SelectedNode = treeView1.SelectedNode.Parent;
if (treeView1.SelectedNode.Tag is BehaviourFile.RiderPositionOverride)
{
@@ -201,8 +202,9 @@ namespace PckStudio.Forms.Editor
if(diag.ShowDialog(this) == DialogResult.OK)
{
if (string.IsNullOrEmpty(diag.SelectedEntity)) return;
if (behaviourFile.entries.FindAll(behaviour => behaviour.name == diag.SelectedEntity).Count() > 0)
if (string.IsNullOrEmpty(diag.SelectedEntity))
return;
if (_behaviourFile.entries.FindAll(behaviour => behaviour.name == diag.SelectedEntity).Count() > 0)
{
MessageBox.Show(this, "You cannot have two entries for one entity. Please use the \"Add New Position Override\" tool to add multiple overrides for entities", "Error", MessageBoxButtons.OK);
return;
@@ -212,7 +214,7 @@ namespace PckStudio.Forms.Editor
TreeNode NewOverrideNode = new TreeNode(NewOverride.name);
NewOverrideNode.Tag = NewOverride;
var behaviour = BehaviourData.Find(b => b.InternalName == NewOverride.name);
EntityInfo behaviour = BehaviourData.Find(b => b.InternalName == NewOverride.name);
NewOverrideNode.Text = behaviour.DisplayName;
NewOverrideNode.ImageIndex = BehaviourData.IndexOf(behaviour);
NewOverrideNode.SelectedImageIndex = NewOverrideNode.ImageIndex;
@@ -226,7 +228,8 @@ namespace PckStudio.Forms.Editor
private void treeView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete) removeToolStripMenuItem_Click(sender, e);
if (e.KeyCode == Keys.Delete)
removeToolStripMenuItem_Click(sender, e);
}
private void treeView1_MouseHover(object sender, EventArgs e)
@@ -236,7 +239,7 @@ namespace PckStudio.Forms.Editor
private void saveToolStripMenuItem1_Click(object sender, EventArgs e)
{
behaviourFile = new BehaviourFile();
_behaviourFile = new BehaviourFile();
foreach (TreeNode node in treeView1.Nodes)
{
if(node.Tag is BehaviourFile.RiderPositionOverride entry)
@@ -251,11 +254,11 @@ namespace PckStudio.Forms.Editor
}
}
behaviourFile.entries.Add(entry);
_behaviourFile.entries.Add(entry);
}
}
_asset.SetData(new BehavioursWriter(behaviourFile));
_asset.SetData(new BehavioursWriter(_behaviourFile));
DialogResult = DialogResult.OK;
}

View File

@@ -23,7 +23,7 @@ namespace PckStudio.Forms.Editor
throw new Exception("Failed to parse BOX value");
}
closeButton.Visible =!Settings.Default.AutoSaveChanges;
closeButton.Visible = !Settings.Default.AutoSaveChanges;
inflationUpDown.Enabled = hasInflation;

View File

@@ -15,9 +15,9 @@ namespace PckStudio.Forms.Editor
{
public partial class COLEditor : MetroForm
{
ColorContainer default_colourfile;
ColorContainer colourfile;
string clipboard_color = "#FFFFFF";
ColorContainer _defaultColourfile;
ColorContainer _colourfile;
string _clipboard_color = "#FFFFFF";
private readonly PckAsset _asset;
@@ -33,7 +33,7 @@ namespace PckStudio.Forms.Editor
saveToolStripMenuItem1.Visible = !Settings.Default.AutoSaveChanges;
_asset = asset;
colourfile = asset.GetData(new COLFileReader());
_colourfile = asset.GetData(new COLFileReader());
TU12ToolStripMenuItem.Click += (sender, e) => SetUpDefaultFile(sender, e, 0);
TU13ToolStripMenuItem.Click += (sender, e) => SetUpDefaultFile(sender, e, 1);
@@ -55,15 +55,16 @@ namespace PckStudio.Forms.Editor
colorTreeView.SelectedNode = colorTreeView.Nodes[0];
}
private void SetUpDefaultFile(object sender, EventArgs e, int ID, bool targetVersion = true)
private void SetUpDefaultFile(object sender, EventArgs e, int id, bool showMessageBox = true)
{
if(targetVersion)
if (showMessageBox)
{
var result = MessageBox.Show(this, "This function will set up your colour table to match that of the chosen version. You may lose some entries in the table. Are you sure you would like to continue?", "Target update version?", MessageBoxButtons.YesNo);
if (result == DialogResult.No) return;
DialogResult result = MessageBox.Show(this, "This function will set up your colour table to match that of the chosen version. You may lose some entries in the table. Are you sure you would like to continue?", "Target update version?", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
return;
}
byte[] colorData = ID switch
byte[] colorData = id switch
{
0 => Resources.tu12colours,
1 => Resources.tu13colours,
@@ -78,15 +79,15 @@ namespace PckStudio.Forms.Editor
10 => Resources.tu54colours,
11 => Resources.tu69colours,
12 => Resources._1_91_colours,
_ => throw new ArgumentOutOfRangeException(nameof(ID)),
_ => throw new ArgumentOutOfRangeException(nameof(id)),
};
var reader = new COLFileReader();
using (var stream = new MemoryStream(colorData))
{
default_colourfile = reader.FromStream(stream);
_defaultColourfile = reader.FromStream(stream);
}
SetUpTable(targetVersion);
SetUpTable(showMessageBox);
}
void AddEntry(TreeView treeView, List<TreeNode> cache, string name, object tag)
@@ -110,7 +111,7 @@ namespace PckStudio.Forms.Editor
underwaterTreeView.Nodes.Clear();
fogTreeView.Nodes.Clear();
ColorContainer temp = targetVersion ? default_colourfile : colourfile;
ColorContainer temp = targetVersion ? _defaultColourfile : _colourfile;
List<string> CurrentEntries = new List<string>();
@@ -122,19 +123,21 @@ namespace PckStudio.Forms.Editor
// fixes the duplicate entry bug
if (targetVersion)
{
foreach(var col in colourfile.Colors)
foreach(ColorContainer.Color col in _colourfile.Colors)
{
if (default_colourfile.Colors.Find(c => c.Name == col.Name) == null) continue;
if (_defaultColourfile.Colors.Find(c => c.Name == col.Name) == null)
continue;
CurrentEntries.Add(col.Name);
AddEntry(colorTreeView, colorCache, col.Name, col);
}
}
foreach (var col in temp.Colors)
foreach (ColorContainer.Color col in temp.Colors)
{
var entry = colourfile.Colors.Find(color => color.Name == col.Name);
if (CurrentEntries.Contains(col.Name)) continue;
var color = entry ?? col;
ColorContainer.Color entry = _colourfile.Colors.Find(color => color.Name == col.Name);
if (CurrentEntries.Contains(col.Name))
continue;
ColorContainer.Color color = entry ?? col;
AddEntry(colorTreeView, colorCache, color.Name, color);
}
CurrentEntries.Clear();
@@ -142,22 +145,24 @@ namespace PckStudio.Forms.Editor
// fixes the duplicate entry bug
if (targetVersion)
{
foreach (var col in colourfile.WaterColors)
foreach (ColorContainer.WaterColor col in _colourfile.WaterColors)
{
if (default_colourfile.WaterColors.Find(c => c.Name == col.Name) == null) continue;
var entry = colourfile.WaterColors.Find(color => color.Name == col.Name);
var color = entry ?? col;
if (_defaultColourfile.WaterColors.Find(c => c.Name == col.Name) == null)
continue;
ColorContainer.WaterColor entry = _colourfile.WaterColors.Find(color => color.Name == col.Name);
ColorContainer.WaterColor color = entry ?? col;
AddEntry(waterTreeView, waterCache, color.Name, color);
AddEntry(underwaterTreeView, underwaterCache, color.Name, color);
AddEntry(fogTreeView, fogCache, color.Name, color);
}
}
foreach (var col in temp.WaterColors)
foreach (ColorContainer.WaterColor col in temp.WaterColors)
{
var entry = colourfile.WaterColors.Find(color => color.Name == col.Name);
if (CurrentEntries.Contains(col.Name)) continue;
var color = entry ?? col;
ColorContainer.WaterColor entry = _colourfile.WaterColors.Find(color => color.Name == col.Name);
if (CurrentEntries.Contains(col.Name))
continue;
ColorContainer.WaterColor color = entry ?? col;
AddEntry(waterTreeView, waterCache, color.Name, color);
AddEntry(underwaterTreeView, underwaterCache, color.Name, color);
AddEntry(fogTreeView, fogCache, color.Name, color);
@@ -287,14 +292,14 @@ namespace PckStudio.Forms.Editor
private void saveToolStripMenuItem1_Click(object sender, EventArgs e)
{
_asset.SetData(new COLFileWriter(colourfile));
_asset.SetData(new COLFileWriter(_colourfile));
DialogResult = DialogResult.OK;
}
public void treeView1_KeyDown(object sender, KeyEventArgs e)
{
var node = colorTreeView.SelectedNode;
TreeNode node = colorTreeView.SelectedNode;
if (e.KeyCode == Keys.Delete && node.Tag is ColorContainer.Color)
{
restoreOriginalColorToolStripMenuItem_Click(sender, e);
@@ -311,7 +316,7 @@ namespace PckStudio.Forms.Editor
private void treeView2_KeyDown(object sender, KeyEventArgs e)
{
var node = waterTreeView.SelectedNode;
TreeNode node = waterTreeView.SelectedNode;
if (e.KeyCode == Keys.Delete && node.Tag is ColorContainer.WaterColor)
{
restoreOriginalColorToolStripMenuItem_Click(sender, e);
@@ -328,7 +333,7 @@ namespace PckStudio.Forms.Editor
private void treeView3_KeyDown(object sender, KeyEventArgs e)
{
var node = underwaterTreeView.SelectedNode;
TreeNode node = underwaterTreeView.SelectedNode;
if (e.KeyCode == Keys.Delete && node.Tag is ColorContainer.WaterColor)
{
restoreOriginalColorToolStripMenuItem_Click(sender, e);
@@ -345,7 +350,7 @@ namespace PckStudio.Forms.Editor
private void treeView4_KeyDown(object sender, KeyEventArgs e)
{
var node = fogTreeView.SelectedNode;
TreeNode node = fogTreeView.SelectedNode;
if (e.KeyCode == Keys.Delete && node.Tag is ColorContainer.WaterColor)
{
restoreOriginalColorToolStripMenuItem_Click(sender, e);
@@ -390,9 +395,12 @@ namespace PckStudio.Forms.Editor
{
var waterColorEntry = (tabControl.SelectedTab.Controls[0] as TreeView).SelectedNode.Tag as ColorContainer.WaterColor;
if (tabControl.SelectedTab == waterTab) waterColorEntry.SurfaceColor = color;
else if (tabControl.SelectedTab == underwaterTab) waterColorEntry.UnderwaterColor = color;
else waterColorEntry.FogColor = color;
if (tabControl.SelectedTab == waterTab)
waterColorEntry.SurfaceColor = color;
else if (tabControl.SelectedTab == underwaterTab)
waterColorEntry.UnderwaterColor = color;
else
waterColorEntry.FogColor = color;
}
pictureBox1.BackColor = color;
@@ -405,7 +413,8 @@ namespace PckStudio.Forms.Editor
colorPick.AllowFullOpen = true;
colorPick.AnyColor = true;
colorPick.SolidColorOnly = tabControl.SelectedTab == colorsTab;
if (colorPick.ShowDialog(this) != DialogResult.OK) return;
if (colorPick.ShowDialog(this) != DialogResult.OK)
return;
pictureBox1.BackColor = colorPick.Color;
if (tabControl.SelectedTab == waterTab && waterTreeView.SelectedNode != null &&
waterTreeView.SelectedNode.Tag != null && waterTreeView.SelectedNode.Tag is ColorContainer.WaterColor)
@@ -465,9 +474,10 @@ namespace PckStudio.Forms.Editor
if (tab == colorsTab)
{
ColorContainer.Color col_entry = default_colourfile.Colors.Find(color => color.Name == node.Text);
ColorContainer.Color col_entry = _defaultColourfile.Colors.Find(color => color.Name == node.Text);
if (col_entry == null) return;
if (col_entry == null)
return;
color = col_entry.ColorPallette;
@@ -475,9 +485,10 @@ namespace PckStudio.Forms.Editor
}
else
{
ColorContainer.WaterColor WaterEntry = default_colourfile.WaterColors.Find(color => color.Name == node.Text);
ColorContainer.WaterColor WaterEntry = _defaultColourfile.WaterColors.Find(color => color.Name == node.Text);
if (WaterEntry == null) return;
if (WaterEntry == null)
return;
color =
tab == waterTab ? WaterEntry.SurfaceColor :
@@ -569,12 +580,12 @@ namespace PckStudio.Forms.Editor
private void copyColorToolStripMenuItem_Click(object sender, EventArgs e)
{
clipboard_color = colorTextbox.Text;
_clipboard_color = colorTextbox.Text;
}
private void pasteColorToolStripMenuItem_Click(object sender, EventArgs e)
{
colorTextbox.Text = clipboard_color;
colorTextbox.Text = _clipboard_color;
}
private void COLEditor_FormClosing(object sender, FormClosingEventArgs e)
@@ -594,7 +605,7 @@ namespace PckStudio.Forms.Editor
private void stripPS4BiomesToolStripMenuItem_Click(object sender, EventArgs e)
{
if(colourfile.WaterColors.Count > 0)
if(_colourfile.WaterColors.Count > 0)
{
List<string> PS4Biomes = new List<string>
{
@@ -605,9 +616,10 @@ namespace PckStudio.Forms.Editor
"mega_taiga_mutated"
};
foreach (var col in colourfile.WaterColors.ToList())
foreach (ColorContainer.WaterColor col in _colourfile.WaterColors.ToList())
{
if (PS4Biomes.Contains(col.Name)) colourfile.WaterColors.Remove(col);
if (PS4Biomes.Contains(col.Name))
_colourfile.WaterColors.Remove(col);
}
SetUpTable(false);
@@ -628,12 +640,12 @@ namespace PckStudio.Forms.Editor
entry.Name = prompt.NewText;
entry.ColorPallette = Color.FromArgb(0xFFFFFF);
if(colourfile.Colors.Find(c => c.Name == entry.Name) != null)
if(_colourfile.Colors.Find(c => c.Name == entry.Name) != null)
{
MessageBox.Show(this, $"\"{entry.Name}\" already exists in this color table", "Color not added");
}
colourfile.Colors.Add(entry);
_colourfile.Colors.Add(entry);
AddEntry(colorTreeView, colorCache, entry.Name, entry);
}
}
@@ -647,7 +659,7 @@ namespace PckStudio.Forms.Editor
&& entry != null
&& entry.Tag is ColorContainer.Color color)
{
colourfile.Colors.Remove(color);
_colourfile.Colors.Remove(color);
RemoveEntry(entry, colorCache);
}
}

View File

@@ -17,19 +17,13 @@
**/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using PckStudio.Forms.Additional_Popups.Grf;
using PckStudio.Internal.Misc;
using OMI.Formats.GameRule;
using OMI.Workers.GameRule;
using System.Diagnostics;
using OMI.Formats.Pck;
using PckStudio.Forms.Additional_Popups;
using PckStudio.Properties;
using PckStudio.ToolboxItems;
using PckStudio.Extensions;
namespace PckStudio.Forms.Editor
{
@@ -58,7 +52,7 @@ namespace PckStudio.Forms.Editor
private void LoadGameRuleTree(TreeNodeCollection root, GameRuleFile.GameRule parentRule)
{
foreach (var rule in parentRule.ChildRules)
foreach (GameRuleFile.GameRule rule in parentRule.ChildRules)
{
TreeNode node = new TreeNode(rule.Name);
node.Tag = rule;
@@ -106,7 +100,7 @@ namespace PckStudio.Forms.Editor
{
GrfParametersTreeView.Nodes.Clear();
if (GrfTreeView.SelectedNode is TreeNode t && t.Tag is GameRuleFile.GameRule rule)
foreach (var param in rule.Parameters)
foreach (KeyValuePair<string, string> param in rule.Parameters)
{
GrfParametersTreeView.Nodes.Add(new TreeNode($"{param.Key}: {param.Value}") { Tag = param});
}
@@ -114,7 +108,8 @@ namespace PckStudio.Forms.Editor
private void addDetailContextMenuItem_Click(object sender, EventArgs e)
{
if (GrfTreeView.SelectedNode == null || !(GrfTreeView.SelectedNode.Tag is GameRuleFile.GameRule)) return;
if (GrfTreeView.SelectedNode == null || !(GrfTreeView.SelectedNode.Tag is GameRuleFile.GameRule))
return;
var grfTag = GrfTreeView.SelectedNode.Tag as GameRuleFile.GameRule;
AddParameter prompt = new AddParameter();
if (prompt.ShowDialog(this) == DialogResult.OK)
@@ -164,7 +159,7 @@ namespace PckStudio.Forms.Editor
private void addGameRuleToolStripMenuItem_Click(object sender, EventArgs e)
{
bool isValidNode = GrfTreeView.SelectedNode is TreeNode t && t.Tag is GameRuleFile.GameRule;
var parentRule = isValidNode
GameRuleFile.GameRule parentRule = isValidNode
? GrfTreeView.SelectedNode.Tag as GameRuleFile.GameRule
: _file.Root;
@@ -180,9 +175,9 @@ namespace PckStudio.Forms.Editor
prompt.ShowDialog(this) == DialogResult.OK &&
!string.IsNullOrWhiteSpace(prompt.NewText))
{
var tag = parentRule.AddRule(prompt.NewText);
TreeNode node = new TreeNode(tag.Name);
node.Tag = tag;
GameRuleFile.GameRule rule = parentRule.AddRule(prompt.NewText);
TreeNode node = new TreeNode(rule.Name);
node.Tag = rule;
root.Add(node);
}
}
@@ -190,15 +185,15 @@ namespace PckStudio.Forms.Editor
private void removeGameRuleToolStripMenuItem_Click(object sender, EventArgs e)
{
if (GrfTreeView.SelectedNode is TreeNode t && t.Tag is GameRuleFile.GameRule tag && removeTag(tag))
if (GrfTreeView.SelectedNode is TreeNode t && t.Tag is GameRuleFile.GameRule tag && RemoveTag(tag))
t.Remove();
}
private bool removeTag(GameRuleFile.GameRule rule)
private bool RemoveTag(GameRuleFile.GameRule rule)
{
_ = rule.Parent ?? throw new ArgumentNullException(nameof(rule.Parent));
foreach (var subTag in rule.ChildRules.ToList())
return removeTag(subTag);
foreach (GameRuleFile.GameRule subTag in rule.ChildRules.ToList())
return RemoveTag(subTag);
return rule.Parent.ChildRules.Remove(rule);
}

View File

@@ -17,29 +17,29 @@ namespace PckStudio.Forms.Editor
{
public partial class LOCEditor : MetroForm
{
LOCFile currentLoc;
LOCFile _currentLoc;
PckAsset _asset;
public LOCEditor(PckAsset asset)
{
InitializeComponent();
_asset = asset;
currentLoc = asset.GetData(new LOCFileReader());
_currentLoc = asset.GetData(new LOCFileReader());
saveToolStripMenuItem.Visible = !Settings.Default.AutoSaveChanges;
}
private void LOCEditor_Load(object sender, EventArgs e)
{
RPC.SetPresence("LOC Editor", "Editing localization File.");
foreach(string locKey in currentLoc.LocKeys.Keys)
foreach(string locKey in _currentLoc.LocKeys.Keys)
treeViewLocKeys.Nodes.Add(locKey);
}
private void treeViewLocKeys_AfterSelect(object sender, TreeViewEventArgs e)
{
var node = e.Node;
TreeNode node = e.Node;
if (node == null ||
!currentLoc.LocKeys.ContainsKey(node.Text))
!_currentLoc.LocKeys.ContainsKey(node.Text))
{
MessageBox.Show(this, "Selected Node does not seem to be in the loc file");
return;
@@ -53,7 +53,7 @@ namespace PckStudio.Forms.Editor
{
prompt.OKButtonText = "Add";
if (prompt.ShowDialog(this) == DialogResult.OK &&
currentLoc.AddLocKey(prompt.NewText, ""))
_currentLoc.AddLocKey(prompt.NewText, ""))
{
treeViewLocKeys.Nodes.Add(prompt.NewText);
}
@@ -62,7 +62,7 @@ namespace PckStudio.Forms.Editor
private void deleteDisplayIDToolStripMenuItem_Click(object sender, EventArgs e)
{
if (treeViewLocKeys.SelectedNode is TreeNode t && currentLoc.RemoveLocKey(t.Text))
if (treeViewLocKeys.SelectedNode is TreeNode t && _currentLoc.RemoveLocKey(t.Text))
{
treeViewLocKeys.SelectedNode.Remove();
ReloadTranslationTable();
@@ -77,11 +77,11 @@ namespace PckStudio.Forms.Editor
MessageBox.Show(this, "something went wrong");
return;
}
var row = dataGridViewLocEntryData.Rows[e.RowIndex];
DataGridViewRow row = dataGridViewLocEntryData.Rows[e.RowIndex];
string locKey = treeViewLocKeys.SelectedNode.Text;
string language = row.Cells[0].Value.ToString();
string value = row.Cells[1].Value.ToString();
currentLoc.SetLocEntry(locKey, language, value);
_currentLoc.SetLocEntry(locKey, language, value);
}
private void treeView1_KeyDown(object sender, KeyEventArgs e)
@@ -97,7 +97,7 @@ namespace PckStudio.Forms.Editor
dataGridViewLocEntryData.Rows[i].Cells[1].Value = textBoxReplaceAll.Text;
}
currentLoc.SetLocEntry(treeViewLocKeys.SelectedNode.Text, textBoxReplaceAll.Text);
_currentLoc.SetLocEntry(treeViewLocKeys.SelectedNode.Text, textBoxReplaceAll.Text);
}
private void ReloadTranslationTable()
@@ -105,15 +105,16 @@ namespace PckStudio.Forms.Editor
dataGridViewLocEntryData.Rows.Clear();
if (treeViewLocKeys.SelectedNode is null)
return;
foreach (var l in currentLoc.GetLocEntries(treeViewLocKeys.SelectedNode.Text))
dataGridViewLocEntryData.Rows.Add(l.Key, l.Value);
foreach (KeyValuePair<string, string> locEntry in _currentLoc.GetLocEntries(treeViewLocKeys.SelectedNode.Text))
dataGridViewLocEntryData.Rows.Add(locEntry.Key, locEntry.Value);
}
private IEnumerable<string> GetAvailableLanguages()
{
foreach (var lang in LOCFile.ValidLanguages)
{
if (currentLoc.Languages.Contains(lang)) continue;
if (_currentLoc.Languages.Contains(lang))
continue;
yield return lang;
}
yield break;
@@ -125,14 +126,14 @@ namespace PckStudio.Forms.Editor
using (var dialog = new AddLanguage(avalibleLang))
if (dialog.ShowDialog(this) == DialogResult.OK)
{
currentLoc.AddLanguage(dialog.SelectedLanguage);
_currentLoc.AddLanguage(dialog.SelectedLanguage);
ReloadTranslationTable();
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
_asset.SetData(new LOCFileWriter(currentLoc, 2));
_asset.SetData(new LOCFileWriter(_currentLoc, 2));
DialogResult = DialogResult.OK;
}

View File

@@ -21,7 +21,7 @@ namespace PckStudio.Forms.Editor
{
// Materials File Format research by PhoenixARC
private readonly PckAsset _asset;
MaterialContainer materialFile;
MaterialContainer _materialFile;
private readonly List<EntityInfo> MaterialData = Entities.BehaviourInfos;
@@ -34,11 +34,11 @@ namespace PckStudio.Forms.Editor
{
treeView1.BeginUpdate();
treeView1.Nodes.Clear();
foreach (var entry in materialFile)
foreach (MaterialContainer.Material entry in _materialFile)
{
TreeNode EntryNode = new TreeNode(entry.Name);
var material = MaterialData.Find(m => m.InternalName == entry.Name);
EntityInfo material = MaterialData.Find(m => m.InternalName == entry.Name);
if(material != null)
{
EntryNode.Text = material.DisplayName;
@@ -73,9 +73,9 @@ namespace PckStudio.Forms.Editor
using (var stream = new MemoryStream(asset.Data))
{
var reader = new MaterialFileReader();
materialFile = reader.FromStream(stream);
_materialFile = reader.FromStream(stream);
if (materialFile.hasInvalidEntries())
if (_materialFile.hasInvalidEntries())
{
DialogResult dr = MessageBox.Show(this, "Unsupported entities were found in this file. Would you like to display them?", "Invalid data found", MessageBoxButtons.YesNo);
@@ -91,7 +91,8 @@ namespace PckStudio.Forms.Editor
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if (e.Node == null) return;
if (e.Node == null)
return;
bool enable = e.Node.Tag is MaterialContainer.Material && treeView1.SelectedNode != null;
materialComboBox.Enabled = enable;
@@ -105,7 +106,8 @@ namespace PckStudio.Forms.Editor
}
private void removeToolStripMenuItem_Click(object sender, EventArgs e)
{
if (treeView1.SelectedNode == null) return;
if (treeView1.SelectedNode == null)
return;
treeView1.SelectedNode.Remove();
}
@@ -117,27 +119,28 @@ namespace PckStudio.Forms.Editor
private void treeView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete) removeToolStripMenuItem_Click(sender, e);
if (e.KeyCode == Keys.Delete)
removeToolStripMenuItem_Click(sender, e);
}
private void saveToolStripMenuItem1_Click(object sender, EventArgs e)
{
materialFile = new MaterialContainer();
_materialFile = new MaterialContainer();
foreach (TreeNode node in treeView1.Nodes)
{
if(node.Tag is MaterialContainer.Material entry)
{
materialFile.Add(entry);
_materialFile.Add(entry);
}
}
foreach (MaterialContainer.Material mat in hiddenInvalidEntries)
{
materialFile.Add(mat);
_materialFile.Add(mat);
}
_asset.SetData(new MaterialFileWriter(materialFile));
_asset.SetData(new MaterialFileWriter(_materialFile));
DialogResult = DialogResult.OK;
}
@@ -148,22 +151,23 @@ namespace PckStudio.Forms.Editor
if (diag.ShowDialog(this) == DialogResult.OK)
{
if (string.IsNullOrEmpty(diag.SelectedEntity)) return;
if (materialFile.FindAll(mat => mat.Name == diag.SelectedEntity).Count() > 0)
if (string.IsNullOrEmpty(diag.SelectedEntity))
return;
if (_materialFile.FindAll(mat => mat.Name == diag.SelectedEntity).Count() > 0)
{
MessageBox.Show(this, "You cannot have two entries for one entity. Please use the \"Add New Position Override\" tool to add multiple overrides for entities", "Error", MessageBoxButtons.OK);
return;
}
var NewEntry = new MaterialContainer.Material(diag.SelectedEntity, "entity_alphatest");
var newEntry = new MaterialContainer.Material(diag.SelectedEntity, "entity_alphatest");
TreeNode NewEntryNode = new TreeNode(NewEntry.Name);
NewEntryNode.Tag = NewEntry;
TreeNode newEntryNode = new TreeNode(newEntry.Name);
newEntryNode.Tag = newEntry;
var material = MaterialData.Find(m => m.InternalName == NewEntry.Name);
NewEntryNode.Text = material.DisplayName;
NewEntryNode.ImageIndex = MaterialData.IndexOf(material);
NewEntryNode.SelectedImageIndex = NewEntryNode.ImageIndex;
treeView1.Nodes.Add(NewEntryNode);
EntityInfo material = MaterialData.Find(m => m.InternalName == newEntry.Name);
newEntryNode.Text = material.DisplayName;
newEntryNode.ImageIndex = MaterialData.IndexOf(material);
newEntryNode.SelectedImageIndex = newEntryNode.ImageIndex;
treeView1.Nodes.Add(newEntryNode);
}
}

View File

@@ -110,7 +110,7 @@ namespace PckStudio.Forms.Editor
_rowCount = atlas.Width / _tileAreaSize.Width;
_columnCount = atlas.Height / _tileAreaSize.Height;
_resourceLocation = resourceLocation;
var tileInfos = resourceLocation.Category switch
List<JsonTileInfo> tileInfos = resourceLocation.Category switch
{
ResourceCategory.BlockAtlas => Tiles.BlockTileInfos,
ResourceCategory.ItemAtlas => Tiles.ItemTileInfos,
@@ -127,7 +127,7 @@ namespace PckStudio.Forms.Editor
originalPictureBox.Image = new Bitmap(atlas);
var images = atlas.Split(_tileAreaSize, _imageLayout);
IEnumerable<Image> images = atlas.Split(_tileAreaSize, _imageLayout);
AtlasTile MakeTile((int index, Image value) p)
{
@@ -168,7 +168,7 @@ namespace PckStudio.Forms.Editor
private bool AcquireColorTable(PckFile pckFile)
{
if (pckFile.TryGetAsset("colours.col", PckAssetType.ColourTableFile, out var colAsset) &&
if (pckFile.TryGetAsset("colours.col", PckAssetType.ColourTableFile, out PckAsset colAsset) &&
colAsset.Size > 0)
{
using var ms = new MemoryStream(colAsset.Data);
@@ -246,7 +246,7 @@ namespace PckStudio.Forms.Editor
// asset size check dont have to be done here the deserializer handles it. -Miku
if (playAnimationsToolStripMenuItem.Checked && hasAnimation)
{
var animation = animationAsset.GetDeserializedData(AnimationDeserializer.DefaultDeserializer);
Animation animation = animationAsset.GetDeserializedData(AnimationDeserializer.DefaultDeserializer);
selectTilePictureBox.Image = animation.CreateAnimationImage();
selectTilePictureBox.Start();
}
@@ -343,7 +343,7 @@ namespace PckStudio.Forms.Editor
default:
break;
};
}
return GetSelectedIndex(result.X, result.Y, rowCount, columnCount, imageLayout);
}
@@ -359,7 +359,7 @@ namespace PckStudio.Forms.Editor
private static Rectangle GetAtlasArea(int index, int tileWidth, int tileHeight, int rowCount, int columnCount, Size size, ImageLayoutDirection imageLayout)
{
var p = GetSelectedPoint(index, rowCount, columnCount, imageLayout);
Point p = GetSelectedPoint(index, rowCount, columnCount, imageLayout);
var ap = new Point(p.X * size.Width, p.Y * size.Height);
return new Rectangle(ap, new Size(size.Width * tileWidth, size.Height * tileHeight));
}
@@ -384,7 +384,7 @@ namespace PckStudio.Forms.Editor
g.DrawImage(texture, dataTile.Area);
}
var tile = _selectedTile != dataTile ? dataTile : _selectedTile;
AtlasTile tile = _selectedTile != dataTile ? dataTile : _selectedTile;
_tiles[tile.Index] = new AtlasTile(tile.Index, tile.Area, tile.Tile, texture);
selectTilePictureBox.Image = texture;
UpdateAtlasDisplay();
@@ -394,7 +394,7 @@ namespace PckStudio.Forms.Editor
{
if (dataTile.Tile.HasColourEntry && dataTile.Tile.ColourEntry is not null)
{
var col = FindBlendColorByKey(dataTile.Tile.ColourEntry.DefaultName);
Color col = FindBlendColorByKey(dataTile.Tile.ColourEntry.DefaultName);
return col;
}
@@ -518,14 +518,14 @@ namespace PckStudio.Forms.Editor
{
ResourceCategory animationResourceCategory = _resourceLocation.Category == ResourceCategory.ItemAtlas ? ResourceCategory.ItemAnimation : ResourceCategory.BlockAnimation;
string animationAssetPath = $"{ResourceLocation.GetPathFromCategory(animationResourceCategory)}/{_selectedTile.Tile.InternalName}.png";
var file = _pckFile.GetOrCreate(animationAssetPath, PckAssetType.TextureFile);
PckAsset asset = _pckFile.GetOrCreate(animationAssetPath, PckAssetType.TextureFile);
var animation = file.GetDeserializedData(AnimationDeserializer.DefaultDeserializer);
Animation animation = asset.GetDeserializedData(AnimationDeserializer.DefaultDeserializer);
var animationEditor = new AnimationEditor(animation, _selectedTile.Tile.DisplayName);
if (animationEditor.ShowDialog(this) == DialogResult.OK)
{
file.SetSerializedData(animationEditor.Result, AnimationSerializer.DefaultSerializer);
asset.SetSerializedData(animationEditor.Result, AnimationSerializer.DefaultSerializer);
// so animations can automatically update upon saving
SelectedIndex = _selectedTile.Index;
}
@@ -597,7 +597,8 @@ namespace PckStudio.Forms.Editor
colorPick.CustomColors = GameConstants.DyeColors.Select(c => c.ToBGR()).ToArray();
if (colorPick.ShowDialog(this) != DialogResult.OK) return;
if (colorPick.ShowDialog(this) != DialogResult.OK)
return;
selectTilePictureBox.BlendColor = colorPick.Color;
selectTilePictureBox.Image = dataTile.Texture;

View File

@@ -96,8 +96,8 @@ namespace PckStudio.Forms.Features
reader.ReadLine();
xml.Load(reader);
}
var configNode = xml.SelectSingleNode("config");
var mlcpathNode = configNode.SelectSingleNode("MlcPath");
XmlNode configNode = xml.SelectSingleNode("config");
XmlNode mlcpathNode = configNode.SelectSingleNode("MlcPath");
GameDirectoryTextBox.Text = mlcpathNode.InnerText;
GameDirectoryTextBox.Enabled = false;
BrowseDirectoryBtn.Enabled = false;
@@ -171,9 +171,9 @@ namespace PckStudio.Forms.Features
{
_basePckPath = directory.GetFiles().FirstOrDefault(f => f.Name.EndsWith(".pck")).FullName;
_ = _basePckPath ?? throw new NullReferenceException($"Could not find any '.pck' inside {directory.Name}");
if (TryGetDataDirectory(directory, out var dataDir))
if (TryGetDataDirectory(directory, out DirectoryInfo dataDir))
{
var tpFileInfo = dataDir.GetFiles().FirstOrDefault(f => !f.Name.Equals("audio.pck") && f.Name.EndsWith(".pck"));
FileInfo tpFileInfo = dataDir.GetFiles().FirstOrDefault(f => !f.Name.Equals("audio.pck") && f.Name.EndsWith(".pck"));
_hasTexturePack = tpFileInfo is not null;
_texturePackPath = _hasTexturePack ? tpFileInfo.FullName : string.Empty;
}
@@ -186,7 +186,7 @@ namespace PckStudio.Forms.Features
private bool TryGetDataDirectory(DirectoryInfo directory, out DirectoryInfo dataDirectory)
{
var dirs = directory.GetDirectories("Data", SearchOption.TopDirectoryOnly);
DirectoryInfo[] dirs = directory.GetDirectories("Data", SearchOption.TopDirectoryOnly);
dataDirectory = dirs.Length != 0 ? dirs[0] : null;
return dirs.Length != 0;
}
@@ -219,11 +219,11 @@ namespace PckStudio.Forms.Features
return;
}
foreach (var directoryInfo in dlcDirectory.GetDirectories())
foreach (DirectoryInfo directoryInfo in dlcDirectory.GetDirectories())
{
if (directoryInfo.GetFileSystemInfos().Length != 0)
{
var node = DLCTreeView.Nodes.Add(directoryInfo.Name);
TreeNode node = DLCTreeView.Nodes.Add(directoryInfo.Name);
node.Tag = new DLCDirectoryInfo(directoryInfo);
}
}
@@ -302,7 +302,7 @@ namespace PckStudio.Forms.Features
private void removePckToolStripMenuItem_Click(object sender, EventArgs e)
{
string pckName = DLCTreeView.SelectedNode.Text;
var result = MessageBox.Show(this, $"Are you sure you want to permanently delete '{pckName}'?", "Hold up!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
DialogResult result = MessageBox.Show(this, $"Are you sure you want to permanently delete '{pckName}'?", "Hold up!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
string directoryPath = GetContentSubDirectory("WiiU", "DLC", pckName);

View File

@@ -22,8 +22,8 @@ namespace PckStudio.Forms.Features
{
public partial class PckManager : MetroFramework.Forms.MetroForm
{
private Control currentlyShowingControl;
private string currentlyShowingControlName;
private Control _currentlyShowingControl;
private string _currentlyShowingControlName;
private const string CemU = "Cemu";
// TODO: Implement these Panels
@@ -47,29 +47,29 @@ namespace PckStudio.Forms.Features
protected override void OnGotFocus(EventArgs e)
{
currentlyShowingControl?.Focus();
_currentlyShowingControl?.Focus();
}
private void supportedPlatformComboBox_SelectionChangeCommitted(object sender, EventArgs e)
{
if (!supportedPlatformComboBox.SelectedItem.Equals(currentlyShowingControlName))
if (!supportedPlatformComboBox.SelectedItem.Equals(_currentlyShowingControlName))
{
mainPanel.Controls.Remove(currentlyShowingControl);
currentlyShowingControlName = supportedPlatformComboBox.Items[supportedPlatformComboBox.SelectedIndex].ToString();
mainPanel.Controls.Remove(_currentlyShowingControl);
_currentlyShowingControlName = supportedPlatformComboBox.Items[supportedPlatformComboBox.SelectedIndex].ToString();
try
{
currentlyShowingControl = currentlyShowingControlName switch
_currentlyShowingControl = _currentlyShowingControlName switch
{
CemU => new CemuPanel(),
//WiiU => throw new NotImplementedException($"{text}-Panel is currently not implemented."),
//PS3 => throw new NotImplementedException($"{text}-Panel is currently not implemented."),
//PSVita => throw new NotImplementedException($"{text}-Panel is currently not implemented."),
//RPCS3 => throw new NotImplementedException($"{text}-Panel is currently not implemented."),
_ => throw new Exception($"No Panel found for: {currentlyShowingControlName}"),
_ => throw new Exception($"No Panel found for: {_currentlyShowingControlName}"),
};
currentlyShowingControl.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right;
mainPanel.SetColumnSpan(currentlyShowingControl, 2);
mainPanel.Controls.Add(currentlyShowingControl, 0, 1);
_currentlyShowingControl.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right;
mainPanel.SetColumnSpan(_currentlyShowingControl, 2);
mainPanel.Controls.Add(_currentlyShowingControl, 0, 1);
}
catch (NotImplementedException ex)
{

View File

@@ -23,7 +23,7 @@ namespace PckStudio.Popups
_endianness = value ? Endianness.LittleEndian : Endianness.BigEndian;
}
}
private PckFile _pckFile;
private readonly PckFile _pckFile;
private Endianness _endianness;
public AdvancedOptions(PckFile pckFile)

View File

@@ -9,26 +9,26 @@ namespace PckStudio.Forms
{
public partial class SkinPreview : Form
{
Image Texture;
ModelBase Model;
Image _texture;
ModelBase _model;
public SkinPreview(Image img, SkinANIM anim, ModelBase model = null)
{
InitializeComponent();
Texture = img;
_texture = img;
Model = model ?? new Steve64x32Model(Texture);
_model = model ?? new Steve64x32Model(_texture);
if (img.Width == 64 && img.Height == 64)
{
Model = model ?? new Steve64x64Model(Texture, anim);
_model = model ?? new Steve64x64Model(_texture, anim);
}
}
private void SkinPreview_Load(object sender, EventArgs e) => RenderModel(Texture);
private void SkinPreview_Load(object sender, EventArgs e) => RenderModel(_texture);
public void RenderModel(Image source)
{
Model.AddToModelView(ModelView);
_model.AddToModelView(ModelView);
}
}
}

View File

@@ -24,7 +24,7 @@ namespace PckStudio.Forms
public partial class generateModel : MetroForm
{
[Obsolete("We don't need a full control to get an image")]
private PictureBox skinPreview = new PictureBox();
private PictureBox _skinPreview = new PictureBox();
private Image _previewImage;
public Image PreviewImage => _previewImage;
@@ -549,7 +549,7 @@ namespace PckStudio.Forms
using (Graphics graphics = Graphics.FromImage(uvPictureBox.Image))
{
graphics.ApplyConfig(_graphicsConfig);
foreach (var part in modelBoxes)
foreach (SkinBOX part in modelBoxes)
{
float width = part.Size.X * 2;
float height = part.Size.Y * 2;
@@ -874,9 +874,9 @@ namespace PckStudio.Forms
private void generateModel_Load(object sender, EventArgs e)
{
if (Screen.PrimaryScreen.Bounds.Height >= 780 && Screen.PrimaryScreen.Bounds.Width >= 1080) {
if (Screen.PrimaryScreen.Bounds.Height >= 780 && Screen.PrimaryScreen.Bounds.Width >= 1080)
return;
}
Rerender();
}
@@ -1092,7 +1092,7 @@ namespace PckStudio.Forms
// Creates Model Data and Finalizes
private void buttonDone_Click(object sender, EventArgs e)
{
foreach (var part in modelBoxes)
foreach (SkinBOX part in modelBoxes)
{
_asset.AddProperty("BOX", part);
}
@@ -1154,7 +1154,7 @@ namespace PckStudio.Forms
private void UpdateListView()
{
listViewBoxes.Items.Clear();
foreach (var part in modelBoxes)
foreach (SkinBOX part in modelBoxes)
{
ListViewItem listViewItem = new ListViewItem(part.Type);
listViewItem.Tag = part;
@@ -1209,15 +1209,15 @@ namespace PckStudio.Forms
reader.ReadLine();
string part = reader.ReadLine();
reader.ReadLine();
var PosX = reader.ReadLine();
var PosY = reader.ReadLine();
var PosZ = reader.ReadLine();
var SizeX = reader.ReadLine();
var SizeY = reader.ReadLine();
var SizeZ = reader.ReadLine();
var UvX = reader.ReadLine();
var UvY = reader.ReadLine();
modelBoxes.Add(SkinBOX.FromString($"{part} {PosX} {PosY} {PosZ} {SizeX} {SizeY} {SizeZ} {UvX} {UvY}"));
var posX = reader.ReadLine();
var posY = reader.ReadLine();
var posZ = reader.ReadLine();
var sizeX = reader.ReadLine();
var sizeY = reader.ReadLine();
var sizeZ = reader.ReadLine();
var uvX = reader.ReadLine();
var uvY = reader.ReadLine();
modelBoxes.Add(SkinBOX.FromString($"{part} {posX} {posY} {posZ} {sizeX} {sizeY} {sizeZ} {uvX} {uvY}"));
}
}
@@ -1231,7 +1231,7 @@ namespace PckStudio.Forms
try
{
ListViewItem listViewItem = new ListViewItem();
var selected = listViewBoxes.SelectedItems[0];
ListViewItem selected = listViewBoxes.SelectedItems[0];
listViewItem.Text = selected.Text;
listViewItem.Tag = selected.Tag;
int num = 0;
@@ -1423,26 +1423,26 @@ namespace PckStudio.Forms
}
[Obsolete("Just whyyyyy")]
public string JSONToCSM(string InputFilePath)
public string JSONToCSM(string inputFilePath)
{
CSMJObject jsonDe = JsonConvert.DeserializeObject<CSMJObject>(File.ReadAllText(InputFilePath));
CSMJObject jsonDe = JsonConvert.DeserializeObject<CSMJObject>(File.ReadAllText(inputFilePath));
StringBuilder sb = new StringBuilder();
foreach (CSMJObjectGroup group in jsonDe.Groups)
{
string PARENT = group.Name;
string parent = group.Name;
foreach (int i in group.children)
{
string name = jsonDe.Elements[i].Name;
float PosX = jsonDe.Elements[i].from[0] + group.origin[0];
float PosY = jsonDe.Elements[i].from[1] + group.origin[1];
float PosZ = jsonDe.Elements[i].from[2] + group.origin[2];
float SizeX = jsonDe.Elements[i].to[0] - jsonDe.Elements[i].from[0];
float SizeY = jsonDe.Elements[i].to[1] - jsonDe.Elements[i].from[1];
float SizeZ = jsonDe.Elements[i].to[2] - jsonDe.Elements[i].from[2];
float U = 0;
float V = 0;
float posX = jsonDe.Elements[i].from[0] + group.origin[0];
float posY = jsonDe.Elements[i].from[1] + group.origin[1];
float posZ = jsonDe.Elements[i].from[2] + group.origin[2];
float sizeX = jsonDe.Elements[i].to[0] - jsonDe.Elements[i].from[0];
float sizeY = jsonDe.Elements[i].to[1] - jsonDe.Elements[i].from[1];
float sizeZ = jsonDe.Elements[i].to[2] - jsonDe.Elements[i].from[2];
float u = 0;
float v = 0;
sb.AppendLine(name + "\n" + PARENT + "\n" + name + "\n" + PosX + "\n" + PosY + "\n" + PosZ + "\n" + SizeX + "\n" + SizeY + "\n" + SizeZ + "\n" + U + "\n" + V);
sb.AppendLine(name + "\n" + parent + "\n" + name + "\n" + posX + "\n" + posY + "\n" + posZ + "\n" + sizeX + "\n" + sizeY + "\n" + sizeZ + "\n" + u + "\n" + v);
}
}
return sb.ToString();

View File

@@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OMI.Formats.Pck;
using OMI.Formats.Pck;
namespace PckStudio.Interfaces
{

View File

@@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OMI.Formats.Pck;
using OMI.Formats.Pck;
namespace PckStudio.Interfaces
{

View File

@@ -29,21 +29,21 @@ namespace PckStudio.Internal
{
public const int MinimumFrameTime = 1;
public int FrameCount => frames.Count;
public int FrameCount => _frames.Count;
public int TextureCount => textures.Count;
public int TextureCount => _textures.Count;
public bool Interpolate { get; set; } = false;
private readonly List<Image> textures;
private readonly List<Image> _textures;
private readonly IList<Frame> frames = new List<Frame>();
private readonly IList<Frame> _frames = new List<Frame>();
private object _syncLock = new object();
public Animation(IEnumerable<Image> textures)
{
this.textures = new List<Image>(textures);
_textures = new List<Image>(textures);
}
public Animation(IEnumerable<Image> textures, string ANIM)
@@ -63,7 +63,7 @@ namespace PckStudio.Internal
}
set
{
lock(l_ticks)
lock(_syncObject)
{
_ticks = value;
}
@@ -71,7 +71,7 @@ namespace PckStudio.Internal
}
private int _ticks;
private object l_ticks = new object();
private object _syncObject = new object();
public Frame(Image texture) : this(texture, MinimumFrameTime)
{ }
@@ -119,7 +119,7 @@ namespace PckStudio.Internal
private void CheckTextureIndex(int index)
{
if (!textures.IndexInRange(index))
if (!_textures.IndexInRange(index))
throw new ArgumentOutOfRangeException(nameof(index));
}
@@ -127,8 +127,8 @@ namespace PckStudio.Internal
public Frame AddFrame(int textureIndex, int frameTime)
{
CheckTextureIndex(textureIndex);
Frame frame = new Frame(textures[textureIndex], frameTime);
frames.Add(frame);
Frame frame = new Frame(_textures[textureIndex], frameTime);
_frames.Add(frame);
return frame;
}
@@ -142,15 +142,15 @@ namespace PckStudio.Internal
public bool RemoveFrame(int frameIndex)
{
frames.RemoveAt(frameIndex);
_frames.RemoveAt(frameIndex);
return true;
}
public Frame GetFrame(int index) => frames[index];
public Frame GetFrame(int index) => _frames[index];
public IReadOnlyCollection<Frame> GetFrames()
{
return new ReadOnlyCollection<Frame>(frames);
return new ReadOnlyCollection<Frame>(_frames);
}
public IReadOnlyCollection<Frame> GetInterpolatedFrames()
@@ -166,10 +166,10 @@ namespace PckStudio.Internal
{
for (int i = 0; i < FrameCount; i++)
{
Frame currentFrame = frames[i];
Frame nextFrame = frames[0];
Frame currentFrame = _frames[i];
Frame nextFrame = _frames[0];
if (i + 1 < FrameCount)
nextFrame = frames[i + 1];
nextFrame = _frames[i + 1];
for (int tick = 0; tick < currentFrame.Ticks; tick++)
{
double delta = 1.0f - tick / (double)currentFrame.Ticks;
@@ -182,50 +182,50 @@ namespace PckStudio.Internal
public IReadOnlyCollection<Image> GetTextures()
{
return textures;
return _textures;
}
public int GetTextureIndex(Image frameTexture)
{
_ = frameTexture ?? throw new ArgumentNullException(nameof(frameTexture));
return textures.IndexOf(frameTexture);
return _textures.IndexOf(frameTexture);
}
public void SetFrame(int frameIndex, Frame frame)
{
lock(_syncLock)
{
frames[frameIndex] = frame;
_frames[frameIndex] = frame;
}
}
public void SetFrame(int frameIndex, int textureIndex, int frameTime = MinimumFrameTime)
{
CheckTextureIndex(textureIndex);
SetFrame(frameIndex, new Frame(textures[textureIndex], frameTime));
SetFrame(frameIndex, new Frame(_textures[textureIndex], frameTime));
}
public string BuildAnim()
{
StringBuilder stringBuilder = new StringBuilder(Interpolate ? "#" : string.Empty);
foreach (var frame in frames)
foreach (Frame frame in _frames)
stringBuilder.Append($"{GetTextureIndex(frame.Texture)}*{frame.Ticks},");
return stringBuilder.ToString(0, stringBuilder.Length - 1);
}
public Image BuildTexture()
{
if (textures[0].Width != textures[0].Height)
if (_textures[0].Width != _textures[0].Height)
throw new Exception("Invalid size");
return textures.Combine(ImageLayoutDirection.Vertical);
return _textures.Combine(ImageLayoutDirection.Vertical);
}
internal void SetFrameTicks(int ticks)
{
lock(_syncLock)
{
foreach (var frame in frames)
foreach (Frame frame in _frames)
{
frame.Ticks = ticks;
}
@@ -236,7 +236,7 @@ namespace PckStudio.Internal
{
lock(_syncLock)
{
frames.Swap(sourceIndex, destinationIndex);
_frames.Swap(sourceIndex, destinationIndex);
}
}

View File

@@ -1,5 +1,5 @@
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using PckStudio.Properties;
@@ -55,7 +55,7 @@ namespace PckStudio.Internal.App
internal static void GetContributors()
{
var ghClient = new Octokit.GitHubClient(new Octokit.ProductHeaderValue(Application.ProductName + "Credits"));
var allContributorsAct = ghClient.Repository.GetAllContributors("PhoenixARC", "-PCK-Studio");
Task<IReadOnlyList<Octokit.RepositoryContributor>> allContributorsAct = ghClient.Repository.GetAllContributors("PhoenixARC", "-PCK-Studio");
allContributorsAct.Wait();
Contributors = allContributorsAct.Result.ToArray();
}

View File

@@ -15,13 +15,8 @@
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace PckStudio.Internal.App
{

View File

@@ -21,8 +21,8 @@ namespace PckStudio.Internal.Deserializer
_ = asset ?? throw new ArgumentNullException(nameof(asset));
if (asset.Size > 0)
{
var texture = asset.GetTexture();
var frameTextures = texture.Split(ImageLayoutDirection.Vertical);
Image texture = asset.GetTexture();
IEnumerable<Image> frameTextures = texture.Split(ImageLayoutDirection.Vertical);
var _animation = new Animation(frameTextures, asset.GetProperty("ANIM"));
return _animation;
}
@@ -31,7 +31,7 @@ namespace PckStudio.Internal.Deserializer
public Animation DeserializeJavaAnimation(JObject jsonObject, Image texture)
{
var textures = texture.Split(ImageLayoutDirection.Vertical);
IEnumerable<Image> textures = texture.Split(ImageLayoutDirection.Vertical);
Animation result = new Animation(textures);
if (jsonObject["animation"] is not JToken animation)
return result;

View File

@@ -17,7 +17,7 @@ namespace PckStudio.Internal.IO._3DST
if (File.Exists(filename))
{
Image img = null;
using (var fs = File.OpenRead(filename))
using (FileStream fs = File.OpenRead(filename))
{
img = FromStream(fs);
}

View File

@@ -19,7 +19,7 @@ namespace PckStudio.Internal.IO._3DST
public void WriteToFile(string filename)
{
using(var fs = File.OpenWrite(filename))
using(FileStream fs = File.OpenWrite(filename))
{
WriteToStream(fs);
}

View File

@@ -346,20 +346,24 @@ namespace PckStudio.Internal.IO._3DST
int[] etc1Order = etc1Scramble(width, height);
int i = 0;
for (int tY = 0; tY < height / 4; tY++) {
for (int tX = 0; tX < width / 4; tX++) {
for (int tY = 0; tY < height / 4; tY++)
{
for (int tX = 0; tX < width / 4; tX++)
{
int TX = etc1Order[i] % (width / 4);
int TY = (etc1Order[i] - TX) / (width / 4);
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
dataOffset = ((TX * 4) + x + (((TY * 4) + y) * width)) * 4;
for (int y = 0; y < 4; y++)
{
for (int x = 0; x < 4; x++)
{
dataOffset = ((TX * 4) + x + (((TY * 4) + y) * width)) * 4;
long outputOffset = ((tX * 4) + x + (((tY * 4 + y)) * width)) * 4;
Buffer.BlockCopy(decodedData, (int)dataOffset, output, (int)outputOffset, 4);
}
}
i += 1;
}
}
}
break;
@@ -577,8 +581,10 @@ namespace PckStudio.Internal.IO._3DST
private static byte saturate(int value)
{
if (value > 0xff) return 0xff;
if (value < 0) return 0;
if (value > 0xff)
return 0xff;
if (value < 0)
return 0;
return (byte)(value & 0xff);
}

View File

@@ -17,7 +17,7 @@ namespace PckStudio.Internal.IO.CSMB
public void WriteToFile(string filename)
{
using(var fs = File.OpenWrite(filename))
using (FileStream fs = File.OpenWrite(filename))
{
WriteToStream(fs);
}

View File

@@ -3,7 +3,6 @@ using OMI.Workers;
using PckStudio.FileFormats;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
@@ -34,7 +33,7 @@ namespace PckStudio.Internal.IO.PckAudio
if(File.Exists(filename))
{
PckAudioFile file;
using(var fs = File.OpenRead(filename))
using(FileStream fs = File.OpenRead(filename))
{
file = FromStream(fs);
}
@@ -95,7 +94,7 @@ namespace PckStudio.Internal.IO.PckAudio
{
List<string> credits = new List<string>();
List<string> creditIds = new List<string>();
foreach (var c in _OriginalAudioTypeOrder)
foreach (PckAudioFile.AudioCategory.EAudioType c in _OriginalAudioTypeOrder)
{
int audioCount = reader.ReadInt32();
for (; 0 < audioCount; audioCount--)
@@ -118,8 +117,8 @@ namespace PckStudio.Internal.IO.PckAudio
throw new InvalidDataException(nameof(key));
}
}
};
foreach (var credit in credits.Zip(creditIds, (str, id) => (str, id)))
}
foreach ((string str, string id) credit in credits.Zip(creditIds, (str, id) => (str, id)))
{
_file.SetCredit(credit.id, credit.str);
}

View File

@@ -27,7 +27,7 @@ namespace PckStudio.Internal.IO.PckAudio
public void WriteToFile(string filename)
{
using(var fs = File.OpenWrite(filename))
using (FileStream fs = File.OpenWrite(filename))
{
WriteToStream(fs);
}
@@ -68,7 +68,7 @@ namespace PckStudio.Internal.IO.PckAudio
private void WriteCategories(EndiannessAwareBinaryWriter writer)
{
writer.Write(_file.Categories.Length);
foreach (var category in _file.Categories)
foreach (PckAudioFile.AudioCategory category in _file.Categories)
{
writer.Write((int)category.parameterType);
writer.Write((int)category.AudioType);
@@ -79,7 +79,7 @@ namespace PckStudio.Internal.IO.PckAudio
private void WriteCategorySongs(EndiannessAwareBinaryWriter writer)
{
bool addCredit = true;
foreach (var category in _file.Categories)
foreach (PckAudioFile.AudioCategory category in _file.Categories)
{
writer.Write(category.SongNames.Count + (addCredit ? _file.Credits.Count * 2 : 0));
foreach (var name in category.SongNames)
@@ -89,7 +89,7 @@ namespace PckStudio.Internal.IO.PckAudio
}
if (addCredit)
{
foreach (var credit in _file.Credits)
foreach (KeyValuePair<string, string> credit in _file.Credits)
{
writer.Write(LUT.IndexOf("CREDIT"));
WriteString(writer, credit.Value);

View File

@@ -22,11 +22,11 @@ namespace PckStudio.Internal.IO.TGA
{
internal static class TGADeserializer
{
private static TGAReader reader = new TGAReader();
private static TGAReader _reader = new TGAReader();
public static Image DeserializeFromStream(Stream stream)
{
TGAFileData tgaImg = reader.FromStream(stream);
TGAFileData tgaImg = _reader.FromStream(stream);
return tgaImg.Bitmap;
}
}

View File

@@ -17,7 +17,6 @@
**/
using System.IO;
using System.Drawing;
using System;
namespace PckStudio.Internal.IO.TGA
{

View File

@@ -38,7 +38,7 @@ namespace PckStudio.Internal.IO.TGA
{
if (File.Exists(filename))
{
using( var fs = File.OpenRead(filename) )
using(FileStream fs = File.OpenRead(filename) )
{
return FromStream(fs);
}

View File

@@ -22,11 +22,11 @@ namespace PckStudio.Internal.IO.TGA
{
internal static class TGASerializer
{
private static TGAWriter writer = new TGAWriter();
private static TGAWriter _writer = new TGAWriter();
public static void SerializeToStream(Stream stream, Image image)
{
writer.WriteToStream(stream, image);
_writer.WriteToStream(stream, image);
}
}
}

View File

@@ -134,7 +134,7 @@ namespace PckStudio.Internal.IO.TGA
public void WriteToFile(string filename, Image image)
{
using (var fs = File.OpenWrite(filename))
using (FileStream fs = File.OpenWrite(filename))
{
WriteToStream(fs, image);
}

View File

@@ -58,10 +58,8 @@ namespace PckStudio.Internal.Misc
string destinationFilepath = Path.Combine(_cacheDirectory, filename);
if (!File.Exists(destinationFilepath))
{
using (FileStream fsDst = File.OpenWrite(destinationFilepath))
{
fsDst.Write(data, 0, data.Length);
}
using FileStream fsDst = File.OpenWrite(destinationFilepath);
fsDst.Write(data, 0, data.Length);
}
}
}

View File

@@ -2,15 +2,15 @@
* Source by: Simon Mourier(https://stackoverflow.com/users/403671/simon-mourier)
*/
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Windows; // for WPF support
using System.Windows.Interop; // for WPF support
namespace PckStudio.Internal.Misc
{
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Windows; // for WPF support
using System.Windows.Interop; // for WPF support
public class OpenFolderDialog
{
public virtual string ResultPath { get; protected set; }
@@ -43,13 +43,13 @@ namespace PckStudio.Internal.Misc
var dialog = (IFileOpenDialog)new FileOpenDialog();
if (!string.IsNullOrEmpty(InputPath))
{
if (CheckHr(SHCreateItemFromParsingName(InputPath, null, typeof(IShellItem).GUID, out var item), throwOnError) != 0)
if (CheckHr(SHCreateItemFromParsingName(InputPath, null, typeof(IShellItem).GUID, out IShellItem item), throwOnError) != 0)
return null;
dialog.SetFolder(item);
}
var options = FOS.FOS_PICKFOLDERS;
FOS options = FOS.FOS_PICKFOLDERS;
options = (FOS)SetOptions((int)options);
dialog.SetOptions(options);
@@ -84,7 +84,7 @@ namespace PckStudio.Internal.Misc
if (CheckHr(hr, throwOnError) != 0)
return null;
if (CheckHr(dialog.GetResult(out var result), throwOnError) != 0)
if (CheckHr(dialog.GetResult(out IShellItem result), throwOnError) != 0)
return null;
if (CheckHr(result.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEPARSING, out var path), throwOnError) != 0)

View File

@@ -1,9 +1,23 @@
using System;
/* Copyright (c) 2024-present miku-666
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1.The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PckStudio.Internal
{

View File

@@ -1,12 +1,21 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
/* Copyright (c) 2024-present miku-666
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1.The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using OMI.Formats.Pck;
using PckStudio.Extensions;
using PckStudio.Interfaces;
@@ -21,7 +30,7 @@ namespace PckStudio.Internal.Serializer
{
string anim = animation.BuildAnim();
asset.SetProperty("ANIM", anim);
var texture = animation.BuildTexture();
Image texture = animation.BuildTexture();
asset.SetTexture(texture);
}
}

View File

@@ -1,12 +1,25 @@
using System;
using System.Collections.Generic;
/* Copyright (c) 2024-present miku-666
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1.The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OMI.Formats.Pck;
using PckStudio.Interfaces;
using PckStudio.Internal.IO.TGA;

View File

@@ -15,7 +15,6 @@
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
using System;
namespace PckStudio.Internal
{

View File

@@ -1,9 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PckStudio.Internal
{
[Flags]

View File

@@ -51,10 +51,10 @@ namespace PckStudio.Internal
{
throw new ArgumentException("Arguments must have at least a length of 9");
}
var type = arguments[0];
var pos = TryGetVector3(arguments, 1);
var size = TryGetVector3(arguments, 4);
var uv = TryGetVector2(arguments, 7);
string type = arguments[0];
Vector3 pos = TryGetVector3(arguments, 1);
Vector3 size = TryGetVector3(arguments, 4);
Vector2 uv = TryGetVector2(arguments, 7);
var skinBox = new SkinBOX(type, pos, size, uv);
if (arguments.Length >= 10)
skinBox.HideWithArmor = arguments[9] == "1";
@@ -86,9 +86,9 @@ namespace PckStudio.Internal
private static Vector3 TryGetVector3(string[] arguments, int startIndex)
{
var vec2 = TryGetVector2(arguments, startIndex);
Vector2 xy = TryGetVector2(arguments, startIndex);
float.TryParse(arguments[startIndex + 2], out float z);
return new Vector3(vec2, z);
return new Vector3(xy, z);
}
public override int GetHashCode()

View File

@@ -403,7 +403,8 @@ namespace PckStudio
bool alreadyExists = root.ContainsKey(nodeText);
TreeNode subNode = alreadyExists ? root[nodeText] : CreateNode(nodeText);
if (!alreadyExists) root.Add(subNode);
if (!alreadyExists)
root.Add(subNode);
return BuildNodeTreeBySeperator(subNode.Nodes, subPath, seperator);
}
@@ -417,7 +418,7 @@ namespace PckStudio
TreeNode node = BuildNodeTreeBySeperator(root, asset.Filename, '/');
node.Tag = asset;
SetNodeIcon(node, asset.Type);
};
}
}
private void BuildMainTreeView()
@@ -484,7 +485,7 @@ namespace PckStudio
Animation animation = asset.GetDeserializedData(AnimationDeserializer.DefaultDeserializer);
string internalName = Path.GetFileNameWithoutExtension(asset.Filename);
var textureInfos = resourceLocation.Category switch
IList<JsonTileInfo> textureInfos = resourceLocation.Category switch
{
ResourceCategory.BlockAnimation => Tiles.BlockTileInfos,
ResourceCategory.ItemAnimation => Tiles.ItemTileInfos,
@@ -516,8 +517,8 @@ namespace PckStudio
dialog.ButtonText = "Ok";
if (dialog.ShowDialog() != DialogResult.OK)
return;
var compressiontype = dialog.SelectedItem switch
GameRuleFile.CompressionType compressiontype = dialog.SelectedItem switch
{
use_deflate => GameRuleFile.CompressionType.Deflate,
use_xmem => GameRuleFile.CompressionType.XMem,
@@ -722,7 +723,8 @@ namespace PckStudio
abbPath = abbPath.Substring(startIndex, abbPath.Length - startIndex);
string finalPath = ($"{outPath}/{abbPath}/").Replace('\\', '/');
if (!Directory.Exists(finalPath)) Directory.CreateDirectory(finalPath);
if (!Directory.Exists(finalPath))
Directory.CreateDirectory(finalPath);
extractFile(finalPath + "/" + Path.GetFileName(asset.Filename), asset);
}
@@ -746,13 +748,13 @@ namespace PckStudio
}
else
{
foreach (PckAsset _asset in currentPCK.GetAssets())
foreach (PckAsset asset in currentPCK.GetAssets())
{
if (_asset.Filename.StartsWith(selectedFolder))
if (asset.Filename.StartsWith(selectedFolder))
{
extractFolderFile(outPath, _asset);
extractFolderFile(outPath, asset);
}
};
}
}
}
@@ -918,10 +920,11 @@ namespace PckStudio
private void renameFileToolStripMenuItem_Click(object sender, EventArgs e)
{
TreeNode node = treeViewMain.SelectedNode;
if (node == null) return;
if (node == null)
return;
string path = node.FullPath;
bool isFile = node.TryGetTagData<PckAsset>(out var asset);
bool isFile = node.TryGetTagData(out PckAsset asset);
using TextPrompt diag = new TextPrompt(isFile ? asset.Filename : Path.GetFileName(node.FullPath));
@@ -943,7 +946,8 @@ namespace PckStudio
{
if (childNode.Tag is PckAsset folderAsset)
{
if (folderAsset.Filename == diag.NewText) continue;
if (folderAsset.Filename == diag.NewText)
continue;
folderAsset.Filename = childNode.FullPath;
}
}
@@ -974,7 +978,8 @@ namespace PckStudio
//}
//else
{
if (treeViewMain.Nodes.ContainsKey("Skins")) add.SkinAsset.Filename = add.SkinAsset.Filename.Insert(0, "Skins/"); // Then Skins folder
if (treeViewMain.Nodes.ContainsKey("Skins"))
add.SkinAsset.Filename = add.SkinAsset.Filename.Insert(0, "Skins/"); // Then Skins folder
currentPCK.AddAsset(add.SkinAsset);
}
if (add.HasCape)
@@ -992,7 +997,8 @@ namespace PckStudio
//}
//else
{
if (treeViewMain.Nodes.ContainsKey("Skins")) add.CapeAsset.Filename = add.CapeAsset.Filename.Insert(0, "Skins/"); // Then Skins folder
if (treeViewMain.Nodes.ContainsKey("Skins"))
add.CapeAsset.Filename = add.CapeAsset.Filename.Insert(0, "Skins/"); // Then Skins folder
currentPCK.AddAsset(add.CapeAsset);
}
}
@@ -1067,7 +1073,8 @@ namespace PckStudio
bool IsSubPCKNode(string nodePath, string extention = ".pck")
{
// written by miku, implemented and modified by MattNL
if (nodePath.EndsWith(extention)) return false;
if (nodePath.EndsWith(extention))
return false;
string[] subpaths = nodePath.Split('/');
@@ -1116,11 +1123,13 @@ namespace PckStudio
{
// Support for if a file is edited within a nested PCK File (AKA SubPCK)
if (!IsSubPCKNode(childPath)) return;
if (!IsSubPCKNode(childPath))
return;
TreeNode parent = GetSubPCK(childPath);
Debug.WriteLine(parent.Name);
if (parent == null) return;
if (parent == null)
return;
PckAsset parentAsset = parent.Tag as PckAsset;
PckFile parentAssetPck =
@@ -1142,8 +1151,9 @@ namespace PckStudio
{
PckAsset newAsset = newPCKFile.CreateNewAsset(asset.Filename, asset.Type);
// check for skins folder so files are placed consistently in final pck
if (asset.Filename.StartsWith("Skins/") && parentAsset.Type is PckAssetType.SkinDataFile) hasSkinsFolder = true;
foreach (var prop in asset.GetProperties())
if (asset.Filename.StartsWith("Skins/") && parentAsset.Type is PckAssetType.SkinDataFile)
hasSkinsFolder = true;
foreach (KeyValuePair<string, string> prop in asset.GetProperties())
newAsset.AddProperty(prop);
newAsset.SetData(asset.Data);
}
@@ -1155,7 +1165,7 @@ namespace PckStudio
PckAsset newAsset = newPCKFile.CreateNewAsset(
(hasSkinsFolder ? "Skins/" : String.Empty)
+ nodeAsset.Filename.Replace(parentAsset.Filename + "/", String.Empty), nodeAsset.Type);
foreach (var prop in nodeAsset.GetProperties())
foreach (KeyValuePair<string, string> prop in nodeAsset.GetProperties())
newAsset.AddProperty(prop);
newAsset.SetData(nodeAsset.Data);
}
@@ -1171,9 +1181,9 @@ namespace PckStudio
MessageBox.Show(this, $"Files added successfully to {parentAsset.Filename}");
}
}
}
private void treeViewMain_DoubleClick(object sender, EventArgs e)
private void treeViewMain_DoubleClick(object sender, EventArgs e)
{
if (treeViewMain.SelectedNode.TryGetTagData(out PckAsset asset))
{
@@ -1283,7 +1293,7 @@ namespace PckStudio
TreeNode newNode = new TreeNode();
newNode.Text = Path.GetFileName(diag.NewText);
var newFile = new PckAsset(diag.NewText, asset.Type);
foreach (var property in asset.GetProperties())
foreach (KeyValuePair<string, string> property in asset.GetProperties())
{
newFile.AddProperty(property);
}
@@ -1303,11 +1313,17 @@ namespace PckStudio
return;
}
if (node.Parent == null) treeViewMain.Nodes.Insert(node.Index + 1, newNode); //adds generated file node
else node.Parent.Nodes.Insert(node.Index + 1, newNode);//adds generated file node to selected folder
// adds generated file node
if (node.Parent == null)
treeViewMain.Nodes.Insert(node.Index + 1, newNode);
// adds generated file node to selected folder
else
node.Parent.Nodes.Insert(node.Index + 1, newNode);
if (!IsSubPCKNode(node.FullPath)) currentPCK.InsertAsset(node.Index + 1, newFile);
else RebuildSubPCK(node.FullPath);
if (!IsSubPCKNode(node.FullPath))
currentPCK.InsertAsset(node.Index + 1, newFile);
else
RebuildSubPCK(node.FullPath);
BuildMainTreeView();
wasModified = true;
}
@@ -1332,7 +1348,7 @@ namespace PckStudio
if (treeViewMain.SelectedNode is TreeNode node &&
node.Tag is PckAsset asset)
{
foreach (var property in asset.GetProperties())
foreach (KeyValuePair<string, string> property in asset.GetProperties())
{
treeMeta.Nodes.Add(CreateNode(property.Key, property));
}
@@ -1468,7 +1484,7 @@ namespace PckStudio
List<PckAsset> pckFiles = GetEndingNodes(draggedNode.Nodes).Where(t => t.IsTagOfType<PckAsset>()).Select(t => t.Tag as PckAsset).ToList();
string oldPath = draggedNode.FullPath;
string newPath = Path.Combine(isTargetPckFile ? Path.GetDirectoryName(targetNode.FullPath) : targetNode.FullPath, draggedNode.Text).Replace('\\', '/');
foreach (var pckFile in pckFiles)
foreach (PckAsset pckFile in pckFiles)
{
pckFile.Filename = Path.Combine(newPath, pckFile.Filename.Substring(oldPath.Length + 1)).Replace('\\', '/');
}
@@ -1506,11 +1522,11 @@ namespace PckStudio
MessageBox.Show(this, $"'{addFile.Filepath}' of type {addFile.Filetype} already exists.", "Import failed", MessageBoxButtons.OK, MessageBoxIcon.Warning);
continue;
}
var importedFile = currentPCK.CreateNewAsset(addFile.Filepath, addFile.Filetype, () => File.ReadAllBytes(filepath));
PckAsset importedAsset = currentPCK.CreateNewAsset(addFile.Filepath, addFile.Filetype, () => File.ReadAllBytes(filepath));
string propertyFile = filepath + ".txt";
if (File.Exists(propertyFile))
{
importedFile.DeserializePropertiesFromString(File.ReadAllText(propertyFile));
importedAsset.DeserializePropertiesFromString(File.ReadAllText(propertyFile));
}
addedCount++;
@@ -1845,15 +1861,16 @@ namespace PckStudio
if (treeViewMain.SelectedNode is TreeNode node)
{
if (node.Tag is PckAsset asset &&
(asset.Type != PckAssetType.TexturePackInfoFile &&
asset.Type != PckAssetType.SkinDataFile))
asset.Type != PckAssetType.TexturePackInfoFile &&
asset.Type != PckAssetType.SkinDataFile)
{
if (node.Parent is TreeNode parentNode)
{
nodeCollection = parentNode.Nodes;
}
}
else nodeCollection = node.Nodes;
else
nodeCollection = node.Nodes;
}
nodeCollection.Add(folerNode);
}
@@ -1954,10 +1971,10 @@ namespace PckStudio
private void OpenPck_DragDrop(object sender, DragEventArgs e)
{
string[] Filepaths = (string[])e.Data.GetData(DataFormats.FileDrop, false);
if (Filepaths.Length > 1)
string[] filepaths = (string[])e.Data.GetData(DataFormats.FileDrop, false);
if (filepaths.Length > 1)
MessageBox.Show(this, "Only one pck file at a time is currently supported");
LoadPckFromFile(Filepaths[0]);
LoadPckFromFile(filepaths[0]);
}
private void OpenPck_DragLeave(object sender, EventArgs e)