Skip to content

Commit

Permalink
Improve texture loading performance, clean up code
Browse files Browse the repository at this point in the history
  • Loading branch information
iMrShadow committed Oct 10, 2024
1 parent db27255 commit fcbffcb
Show file tree
Hide file tree
Showing 4 changed files with 109 additions and 100 deletions.
6 changes: 2 additions & 4 deletions TelltaleTextureTool/TelltaleTextureTool/Converter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ public static void ConvertTextureFromD3DtxToOthers(string sourceFilePath, string

Texture texture = new(array, TextureType.D3DTX);

texture.ChangePreviewImage(options, true);
texture.TransformTexture(options, true, false);
texture.SaveTexture(Path.Combine(destinationDirectory, Path.GetFileNameWithoutExtension(sourceFilePath)), newTextureType);
texture.Release();

Expand Down Expand Up @@ -249,7 +249,7 @@ public static void ConvertTextureFromOthersToD3Dtx(string sourceFilePath, string
options.IsSRGB = true;
}

texture.ChangePreviewImage(options, true);
texture.TransformTexture(options, true, false);

// Get the image
texture.GetDDSInformation(out D3DTXMetadata metadata, out ImageSection[] sections, flags);
Expand All @@ -259,8 +259,6 @@ public static void ConvertTextureFromOthersToD3Dtx(string sourceFilePath, string
metadata.Platform = options.PlatformType;
}

Console.WriteLine("DXGI: " + texture.Metadata.Format);
Console.WriteLine(metadata.Format);
// Modify the d3dtx file using our dds data
d3dtxMaster.ModifyD3DTX(metadata, sections);

Expand Down
44 changes: 21 additions & 23 deletions TelltaleTextureTool/TelltaleTextureTool/GUI/Image/ImageData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,22 @@
using System.Runtime.InteropServices;
using TelltaleTextureTool.TelltaleEnums;
using TelltaleTextureTool.Graphics;
using Avalonia;
using Avalonia.Platform;

namespace TelltaleTextureTool;

public class ImageData
{
public ImageProperties ImageProperties { get; set; } = new ImageProperties();
public Texture DDSImage { get; set; } = new Texture();

public TextureType CurrentTextureType { get; set; }
public uint MaxMip { get; set; }
public uint MaxFace { get; set; }

private string CurrentFilePath { get; set; } = string.Empty;
private bool IsSamePath { get; set; }
private bool HasPixelData { get; set; }
private TextureType CurrentTextureType { get; set; }

private TelltaleToolGame Game { get; set; }
private bool IsLegacyConsole { get; set; }

Expand Down Expand Up @@ -70,7 +70,7 @@ public void ApplyEffects(ImageAdvancedOptions options)
{
try
{
DDSImage.ChangePreviewImage(options);
DDSImage.TransformTexture(options, false, true);

DDSImage.GetBounds(out uint maxMip, out uint maxFace);
MaxMip = maxMip;
Expand Down Expand Up @@ -188,11 +188,11 @@ private void GetImageDataFromCommon(out ImageProperties imageProperties)
/// <param name="mip"></param>
/// <param name="face"></param>
/// <returns>The bitmap from the mip and face. </returns>
public Bitmap GetBitmapFromScratchImage(uint mip = 0, uint face = 0)
public WriteableBitmap GetBitmapFromScratchImage(uint mip = 0, uint face = 0)
{
if (TextureType.Unknown == CurrentTextureType)
{
return new Bitmap(MemoryStream.Null);
return null;
}

DDSImage.GetBounds(out uint maxMip, out uint maxFace);
Expand All @@ -210,26 +210,24 @@ public Bitmap GetBitmapFromScratchImage(uint mip = 0, uint face = 0)

DDSImage.GetData(mip, face, out ulong width, out ulong height, out ulong pitch, out ulong length, out byte[] pixelData);

// Converts the data into writeableBitmap. (TODO Insert a link to the code)
var imageInfo = new SKImageInfo((int)width, (int)height, SKColorType.Rgba8888);
var handle = GCHandle.Alloc(pixelData, GCHandleType.Pinned);
var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(pixelData, 0);
using var data = SKData.Create(ptr, (int)length, (_, _) => handle.Free());
using var skImage = SKImage.FromPixels(imageInfo, data, (int)pitch);
using var bitmap = SKBitmap.FromImage(skImage);

// Create a memory stream to hold the PNG data
var memoryStream = new MemoryStream();
// Create a WriteableBitmap in RGBA8888 format
var bitmap = new WriteableBitmap(
new PixelSize((int)width, (int)height),
new Vector(96, 96), // Set DPI as necessary
PixelFormat.Rgba8888,
AlphaFormat.Unpremul);

// Encode the bitmap to PNG and write it to the memory stream
var wstream = new SKManagedWStream(memoryStream);

var success = bitmap.Encode(wstream, SKEncodedImageFormat.Png, 95);
Console.WriteLine(success ? "Image converted successfully" : "Image conversion failed");
// Lock the WriteableBitmap's back buffer to write pixel data
using (var framebuffer = bitmap.Lock())
{
IntPtr framebufferPtr = framebuffer.Address;
int framebufferRowBytes = framebuffer.RowBytes;

memoryStream.Position = 0;
// Copy pixelData to the WriteableBitmap's memory
Marshal.Copy(pixelData, 0, framebufferPtr, (int)length);
}

return new Bitmap(memoryStream);
return bitmap;
}

private static void GetImageDataFromInvalid(out ImageProperties imageProperties)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class EnumDisplayNameConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)

Check warning on line 34 in TelltaleTextureTool/TelltaleTextureTool/GUI/ViewModels/MainViewModel.cs

View workflow job for this annotation

GitHub Actions / build

Nullability of reference types in type of parameter 'value' of 'object EnumDisplayNameConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)' doesn't match implicitly implemented member 'object? IValueConverter.Convert(object? value, Type targetType, object? parameter, CultureInfo culture)' (possibly because of nullability attributes).

Check warning on line 34 in TelltaleTextureTool/TelltaleTextureTool/GUI/ViewModels/MainViewModel.cs

View workflow job for this annotation

GitHub Actions / build

Nullability of reference types in type of parameter 'parameter' of 'object EnumDisplayNameConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)' doesn't match implicitly implemented member 'object? IValueConverter.Convert(object? value, Type targetType, object? parameter, CultureInfo culture)' (possibly because of nullability attributes).
{
if (value == null)
if (value is null)
return string.Empty;

// Get the field in the enum type that matches the current enum value
Expand Down Expand Up @@ -395,7 +395,7 @@ public async Task DeleteFileButton_Click()
var result = await MessageBoxManager.GetMessageBoxStandard(messageBox)
.ShowWindowDialogAsync(mainWindow);

if (result != ButtonResult.Yes) return;
if (result is not ButtonResult.Yes) return;

Directory.Delete(textureFilePath);
}
Expand Down Expand Up @@ -489,7 +489,7 @@ public async Task ContextMenuOpenFileCommand()
{
try
{
if (DataGridSelectedItem == null)
if (DataGridSelectedItem is null)
return;

var workingDirectoryFile =
Expand All @@ -514,7 +514,7 @@ public async Task ContextMenuOpenFolderCommand()
try
{
// if there is no valid item selected, don't continue
if (DataGridSelectedItem == null)
if (DataGridSelectedItem is null)
return;

// get our selected file object from the working directory
Expand All @@ -540,9 +540,9 @@ public async Task ContextMenuOpenFileExplorerCommand()
{
try
{
if (DirectoryPath == null) return;
if (DirectoryPath is null) return;

if (DataGridSelectedItem == null)
if (DataGridSelectedItem is null)
{
if (Directory.Exists(DirectoryPath))
await OpenFileExplorer(DirectoryPath);
Expand All @@ -564,7 +564,7 @@ public async Task ContextMenuOpenFileExplorerCommand()
[RelayCommand]
public async Task RefreshDirectoryButton_Click()
{
if (DirectoryPath != null && DirectoryPath != string.Empty)
if (DirectoryPath is not null && DirectoryPath != string.Empty)
{
await RefreshUiAsync();
}
Expand Down Expand Up @@ -601,7 +601,7 @@ public async Task ConvertButton_Click()
{
try
{
if (DataGridSelectedItem == null) return;
if (DataGridSelectedItem is null) return;

var workingDirectoryFile =
DataGridSelectedItem;
Expand All @@ -624,7 +624,7 @@ public async Task ConvertButton_Click()
AllowMultiple = false,
});

if (folderPath is null || folderPath.Count == 0)
if (folderPath is null || folderPath.Count is 0)
{
return;
}
Expand Down Expand Up @@ -697,7 +697,7 @@ public async Task DebugButton_Click()
{
try
{
if (DataGridSelectedItem == null) return;
if (DataGridSelectedItem is null) return;

var workingDirectoryFile =
DataGridSelectedItem;
Expand All @@ -706,7 +706,7 @@ public async Task DebugButton_Click()

string debugInfo = string.Empty;

if (workingDirectoryFile.FileType == ".d3dtx")
if (workingDirectoryFile.FileType is ".d3dtx")
{
var d3dtx = new D3DTX_Master();
d3dtx.ReadD3DTXFile(textureFilePath, ImageAdvancedOptions.GameID, ImageAdvancedOptions.IsLegacyConsole);
Expand Down Expand Up @@ -777,7 +777,7 @@ public async Task ReturnDirectory_Click()
{
try
{
if (Directory.GetParent(DirectoryPath) == null) return;
if (Directory.GetParent(DirectoryPath) is null) return;
WorkingDirectoryFiles.Clear();
await mainManager.SetWorkingDirectoryPath(Directory.GetParent(DirectoryPath).ToString());
DataGridSelectedItem = null;
Expand Down Expand Up @@ -828,7 +828,7 @@ private void ChangeComboBoxItemsByItemExtension(string itemExtension)
{string.Empty, _folderTypes}
};

if (itemExtension == null)
if (itemExtension is null)
{
FromFormatsList = null;
ToFormatsList = null;
Expand Down Expand Up @@ -908,7 +908,7 @@ public async void RowDoubleTappedCommand(object? sender, TappedEventArgs args)
if (source is null) return;
if (source is Border)
{
if (DataGridSelectedItem == null)
if (DataGridSelectedItem is null)
return;

var workingDirectoryFile =
Expand Down Expand Up @@ -946,7 +946,7 @@ public async void RowDoubleTappedCommand(object? sender, TappedEventArgs args)

private void UpdateUIElementsAsync()
{
if (DataGridSelectedItem != null)
if (DataGridSelectedItem is not null)
{
var workingDirectoryFile = DataGridSelectedItem;
var path = workingDirectoryFile.FilePath;
Expand All @@ -960,7 +960,7 @@ private void UpdateUIElementsAsync()
throw new Exception("File or directory do not exist anymore! Refreshing the directory.");
}

DebugButtonStatus = extension == ".d3dtx" || extension == ".dds";
DebugButtonStatus = extension is ".d3dtx" || extension is ".dds";
SaveButtonStatus = File.Exists(path);
DeleteButtonStatus = true;
ContextOpenFolderStatus = Directory.Exists(path);
Expand Down Expand Up @@ -1029,7 +1029,7 @@ public async Task PreviewImage()
{
UpdateUIElementsAsync();

if (DataGridSelectedItem == null)
if (DataGridSelectedItem is null)
return;

var workingDirectoryFile = DataGridSelectedItem;
Expand All @@ -1049,9 +1049,14 @@ public async Task PreviewImage()

ImageData.Initialize(filePath, textureType, ImageAdvancedOptions.GameID, ImageAdvancedOptions.IsLegacyConsole);

if (textureType is TextureType.Unknown)
{
ImageData.Reset();
}

ImageAdvancedOptions = ImageData.GetImageAdvancedOptions(ImageAdvancedOptions);

if (textureType != TextureType.Unknown)
if (textureType is not TextureType.Unknown)
{
ImageData.ApplyEffects(ImageAdvancedOptions);
}
Expand All @@ -1068,7 +1073,7 @@ public async Task PreviewImage()

ImageProperties = ImageData.ImageProperties;

if (textureType != TextureType.Unknown)
if (textureType is not TextureType.Unknown)
{
ImagePreview = ImageData.GetBitmapFromScratchImage(MipValue, FaceValue);
}
Expand All @@ -1092,7 +1097,7 @@ public async Task UpdateBitmap()
{
try
{
if (DataGridSelectedItem == null)
if (DataGridSelectedItem is null)
return;

var workingDirectoryFile = DataGridSelectedItem;
Expand All @@ -1103,7 +1108,7 @@ public async Task UpdateBitmap()
if (extension != string.Empty)
textureType = GetTextureTypeFromItem(extension.ToUpperInvariant().Remove(0, 1));

if (textureType == TextureType.Unknown)
if (textureType is TextureType.Unknown)
{
return;
}
Expand All @@ -1118,7 +1123,10 @@ public async Task UpdateBitmap()

ImageProperties = ImageData.ImageProperties;

ImagePreview = ImageData.GetBitmapFromScratchImage(MipValue, FaceValue);
if (textureType is not TextureType.Unknown)
{
ImagePreview = ImageData.GetBitmapFromScratchImage(MipValue, FaceValue);
}
}
catch (Exception ex)
{
Expand All @@ -1130,11 +1138,13 @@ public async Task UpdateBitmap()
protected override async void OnPropertyChanged(PropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (e.PropertyName == nameof(MipValue) || e.PropertyName == nameof(FaceValue))
if (e.PropertyName is nameof(MipValue) || e.PropertyName is nameof(FaceValue))
{
ImagePreview = ImageData.GetBitmapFromScratchImage(MipValue, FaceValue);
if (ImageData.CurrentTextureType is not TextureType.Unknown)
ImagePreview = ImageData.GetBitmapFromScratchImage(MipValue, FaceValue);
else { ImagePreview = new SvgImage { Source = SvgSource.Load(ErrorSvgFilename, _assetsUri) }; }
}
if (e.PropertyName == nameof(ImageAdvancedOptions))
if (e.PropertyName is nameof(ImageAdvancedOptions))
{
await UpdateBitmap();
}
Expand Down
Loading

0 comments on commit fcbffcb

Please sign in to comment.