97 Commits

Author SHA1 Message Date
VaDiM
43fa0ac820 Fix(?) for crunched cubemaps 2023-04-23 03:57:14 +03:00
VaDiM
4bae98813b [GUI] One more bugfix
- bugfix for 44a1240f5f
2023-04-13 22:08:01 +03:00
VaDiM
90ec395b2a Block alignment fix for Unity 2019.4.X
- src: 10346b4f02
2023-04-09 15:40:34 +03:00
VaDiM
af3684bab8 [GUI] Bugfix
- bugfix for ea09a8de64
2023-04-06 02:14:53 +03:00
VaDiM
1da51ac95b Add error message on incorrect format of specified unity ver 2023-03-20 19:32:00 +03:00
VaDiM
9e14f1ef00 Add error message for bundles with CN encryption 2023-03-20 19:31:49 +03:00
VaDiM
4edadb19f8 Disable Shader support for Unity > 2020 2023-03-20 06:13:08 +03:00
VaDiM
44a1240f5f [GUI] Improve memory usage of image previews
- also a bit increased performance of alpha mask resizing for previews
2023-03-14 04:10:48 +03:00
VaDiM
01957a9443 [CLI] Add draft readme 2023-03-10 21:18:29 +03:00
VaDiM
ad1b3b4911 [CLI] Some fixes for logging 2023-03-10 21:01:12 +03:00
VaDiM
0925751776 [CLI] Add MovieTexture support 2023-03-10 19:37:53 +03:00
VaDiM
b59ba3ba94 [GUI] Add some videoClip info to preview tab 2023-03-10 11:53:38 +03:00
VaDiM
67898c72ca Update projects files
- Fixed build options
2023-03-10 09:01:27 +03:00
VaDiM
0425423ca9 [CLI] Add debugging info for video 2023-03-08 19:59:19 +03:00
VaDiM
16a7107d4e [CLI] Partial assets reading 2023-03-08 18:28:50 +03:00
VaDiM
10b7e84ffb [CLI] More debugging info for audio 2023-03-08 17:31:34 +03:00
VaDiM
679e7041a6 [GUI] A bit better(?) error handling 2023-03-08 17:12:59 +03:00
VaDiM
629c6248a4 [GUI] Use blocking call to show messages in correct order 2023-03-08 12:11:45 +03:00
VaDiM
7674081df7 [GUI] Add context menu to the Scene Hierarchy tab
- Added context menu with "Select all", "Select none", "Expand all", "Collapse all" options to the "Scene Hierarchy" tab.
https://github.com/aelurum/AssetStudio/issues/1
2023-03-07 18:21:34 +03:00
VaDiM
fb574064c9 [GUI] Avoid overflow in alphanum sorting 2023-03-07 06:55:45 +03:00
VaDiM
c52940abc4 Add AssetStudioCLI project
- Updated projects and dependencies
2023-03-07 06:52:33 +03:00
VaDiM
5c662d64e4 Add exclude mode to asset list filter 2023-02-05 00:47:04 +03:00
VaDiM
b9cf95616b SwapBytesForXbox refactor 2023-01-27 13:46:55 +03:00
VaDiM
39490d4e03 Update fmod to 0.2.0.22 (CLI Preparation) 2023-01-27 13:17:01 +03:00
VaDiM
a96d1a5d5d Fix bug in alphanum sorting 2022-12-27 05:21:42 +03:00
VaDiM
568daafc7f Add progress info to LoadZipFile()
Displays the progress of loading zip(apk) files on the progress bar
2022-12-15 17:43:28 +03:00
VaDiM
2a2216e2bf Update projects and dependencies 2022-12-10 20:23:45 +03:00
VaDiM
dfbe46e1e5 Improve sorting performance
Improved performance of AlphanumComparatorFast sorting for names, as well as the default sorting for containers
2022-12-03 05:16:19 +03:00
VaDiM
6a9aad510c Add image export in WebP format 2022-11-22 03:33:47 +03:00
VaDiM
fd21cafd29 Merge branch 'Perfare_master' into AssetStudio-mod 2022-11-21 02:37:02 +03:00
VaDiM
ea09a8de64 Add support for sprites with alpha mask
- Sprites with alpha mask can now be viewed and exported with transparency
- Added hotkeys to control display of an alpha mask  on the preview tab
- Added an option to the export settings to enable/disable export with alpha mask as well
- Prevented texture2D preview options from being changed with hotkeys outside of texture preview (e.g. when some other asset is selected)
2022-11-21 01:59:16 +03:00
VaDiM
7fa5b4f355 Update ImageSharp.Drawing version
- migrate to ImageSharp v2+
2022-11-18 06:33:26 +03:00
VaDiM
c22d92009a Update project files 2022-11-17 04:39:49 +03:00
Perfare
53f3e8232a support 2022.1 2022-11-17 04:32:05 +03:00
Perfare
2fe57a1c5d update enum 2022-11-17 04:31:30 +03:00
Perfare
ded2dcd54e Fixed #962 2022-11-17 04:31:16 +03:00
Perfare
8ae3df6197 minor improvements 2022-11-17 04:30:52 +03:00
Kanglai Qian
64d9718c34 avoid useless search for non exist files (#967) 2022-11-17 04:30:39 +03:00
Perfare
220004c976 support 2021.3 2022-11-17 04:30:27 +03:00
Perfare
a324366be9 BundleFile fix 2022-11-17 04:30:17 +03:00
Perfare
06b4ae9ffe Fix type conversion bug 2022-11-17 04:29:55 +03:00
Perfare
77b056de5e update project file 2022-11-17 04:29:02 +03:00
Perfare
344edb722f revert 2022-11-17 04:23:17 +03:00
Perfare
98c4d0c3ab minor fixes and improvements 2022-11-17 04:23:00 +03:00
Perfare
23ac590648 Fixed #941 2022-11-17 04:22:31 +03:00
Perfare
54445475a3 Fix and improve Texture2D convert 2022-11-17 04:22:14 +03:00
Perfare
7299bcba6d Create build.yml 2022-11-17 04:22:06 +03:00
Perfare
5487ff4e60 Fixed #924 2022-11-17 04:21:13 +03:00
Perfare
b3621a75b0 Fixed #929 2022-11-17 04:20:20 +03:00
Perfare
8b048b9e1e improved Sprite export
Fixed #944
Fixed #923
2022-11-17 04:20:20 +03:00
Perfare
41a79f485f using IProgress 2022-11-17 04:18:40 +03:00
Perfare
a060a392e7 Fixed #919 2022-11-17 04:18:06 +03:00
Rudolf Kolbe
0798af7c5c fix apk loading issues (#913)
* fix apk loading issues

Someone contacted me some days ago and notified me that some problems showed up with my APK loading implementation.
Namely:

file reference registration (importFilesHash) was missing
split files weren't handled
external resource files weren't registered
This pr fixes those problems.

* revert weird changes

* fix missing }

* fix formatting

* use entry.FullName for the basePath instead of entry.Name
2022-11-17 04:17:33 +03:00
VaDiM
8ebfa16e19 Return to ImageSharp
coz the perfomance issue was fixed by Perfare in later commits
2022-11-17 03:59:59 +03:00
Perfare
d158e864b5 support 2022.1 2022-06-16 18:41:55 +08:00
Perfare
b70b5196e3 update enum 2022-06-16 17:45:54 +08:00
Perfare
4f88841026 Fixed #962 2022-06-01 15:33:01 +08:00
Perfare
dc9429feac minor improvements 2022-05-21 21:16:34 +08:00
Kanglai Qian
a3c16ed3d6 avoid useless search for non exist files (#967) 2022-05-21 21:10:02 +08:00
Perfare
5b83eebdda support 2021.3 2022-05-21 17:38:40 +08:00
Perfare
1fcf7a4364 BundleFile fix 2022-05-21 17:24:54 +08:00
Perfare
973d50ce8b Fix type conversion bug 2022-05-21 05:46:44 +08:00
Perfare
50485a9bd3 update project file 2022-03-24 10:38:52 +08:00
Perfare
dbb3d3fef7 revert 2022-03-24 09:47:36 +08:00
Perfare
e1cfff63c3 minor fixes and improvements 2022-03-23 01:41:59 +08:00
Perfare
44514a4e10 Fixed #941 2022-03-22 22:54:49 +08:00
Perfare
b1205808e2 Fix and improve Texture2D convert 2022-03-22 01:00:20 +08:00
Perfare
7d3a4a10fc Create build.yml 2022-03-20 02:36:32 +08:00
Perfare
b909857820 Fixed #924 2022-03-19 08:06:03 +08:00
Perfare
b674e66407 Fixed #929 2022-03-19 07:48:39 +08:00
Perfare
d7dcd3f405 improved Sprite export
Fixed #944
Fixed #923
2022-03-19 07:43:53 +08:00
Perfare
44145e0b9c using IProgress 2022-03-19 06:40:51 +08:00
Perfare
d4e21f824c Fixed #919 2022-02-17 01:07:24 +08:00
Rudolf Kolbe
e7a4604a65 fix apk loading issues (#913)
* fix apk loading issues

Someone contacted me some days ago and notified me that some problems showed up with my APK loading implementation.
Namely:

file reference registration (importFilesHash) was missing
split files weren't handled
external resource files weren't registered
This pr fixes those problems.

* revert weird changes

* fix missing }

* fix formatting

* use entry.FullName for the basePath instead of entry.Name
2022-02-15 11:19:50 +08:00
VaDiM
74f2c3190b Merge branch 'Perfare_master' into AssetStudio-mod 2022-01-13 18:10:31 +02:00
Rudolf Kolbe
8d193a63cd Zip (including APK) Loading (#902)
* load ZipFile

makes it possible to directly load apk files

* use LoadFile for recursive zip opening

* set System.IO.Compression version

* keep identical format in AssetStudio.csproj

* try/catch the loading of each zip entry

* remove extra new line in FileReader.cs

* apply requested changes
2021-12-27 15:59:18 +08:00
brianpow
e61a317185 use FullPath instead of FileName for easier identification of broken file (#900)
* use FullPath instead of FileName for easier identification of broken file.

* use FullPath instead of FileName for easier identification of broken file
2021-12-24 13:23:09 +08:00
VaDiM
f67965b1dd Texture2DDecoderNative - Linux/macOS compatibility fix
+ CMakeLists.txt
2021-12-15 02:49:28 +02:00
VaDiM
07a81d9bfe Update projects 2021-12-15 00:35:46 +02:00
VaDiM
95fd1823c8 Merge branch 'Perfare_master' into AssetStudio-mod 2021-12-13 04:45:41 +02:00
VaDiM
d25451d5b9 Merge branch 'Perfare_master' into AssetStudio-mod 2021-12-13 00:43:49 +02:00
scriptkitz
0e1a886e0b 修正UV导出计算错误问题。 (#891) 2021-12-11 15:48:54 +08:00
Perfare
97b5f51f3a Fix build 2021-12-09 20:23:25 +08:00
Perfare
7295feda72 Update README.md 2021-12-09 19:16:13 +08:00
Perfare
fe95c91759 Add net6.0 target framework 2021-12-09 19:00:59 +08:00
Perfare
d220315d9b Add detailed export progress in the status bar 2021-12-09 18:08:56 +08:00
Perfare
a94caa5e34 Update project 2021-12-09 17:21:44 +08:00
Perfare
3660b4ed67 Some improvements 2021-12-09 17:13:21 +08:00
Perfare
3370f93037 Fixed bug 2021-12-06 17:37:59 +08:00
Perfare
80653711cd Performance improvement 2021-12-06 13:36:22 +08:00
VaDiM
f0b23bbfe7 Merge branch 'Perfare_master' into AssetStudio-mod 2021-12-05 02:41:24 +02:00
Perfare
88c5804586 Fixed #886 2021-12-04 09:23:41 +08:00
Perfare
e501940f03 Use a better way to crop Sprite 2021-12-04 08:44:33 +08:00
Perfare
d4060cde6d Fixed bug 2021-12-04 02:05:35 +08:00
Perfare
582a779441 Update project file 2021-12-03 19:46:20 +08:00
Perfare
5fa4934787 Add net5.0 target framework 2021-12-03 17:21:24 +08:00
Perfare
18277fbea8 fixed bug 2021-12-03 17:05:06 +08:00
104 changed files with 7196 additions and 12190 deletions

57
.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,57 @@
name: AssetStudioBuild
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
workflow_dispatch:
jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- uses: microsoft/setup-msbuild@v1.1
- name: Download FBX SDK
run: |
md fbx
cd fbx
Invoke-WebRequest "https://damassets.autodesk.net/content/dam/autodesk/www/adn/fbx/2020-2-1/fbx202021_fbxsdk_vs2019_win.exe" -OutFile "fbxsdk.exe"
Start-Process -FilePath "fbxsdk.exe" /S -Wait
Invoke-WebRequest "https://damassets.autodesk.net/content/dam/autodesk/www/adn/fbx/2020-2-1/fbx202021_fbxsdk_vs2019_pdbs.exe" -OutFile "fbxpdb.exe"
Start-Process -FilePath "fbxpdb.exe" /S -Wait
cd ..
- name: Nuget Restore
run: nuget restore
- name: Build .Net472
run: msbuild /p:Configuration=Release /p:TargetFramework=net472 /verbosity:minimal
- name: Build .Net5
run: msbuild /t:AssetStudioGUI:publish /p:Configuration=Release /p:TargetFramework=net5.0-windows /p:SelfContained=false /verbosity:minimal
- name: Build .Net6
run: msbuild /t:AssetStudioGUI:publish /p:Configuration=Release /p:TargetFramework=net6.0-windows /p:SelfContained=false /verbosity:minimal
- name: Upload .Net472 Artifact
uses: actions/upload-artifact@v2
with:
name: AssetStudio.net472
path: AssetStudioGUI/bin/Release/net472
- name: Upload .Net5 Artifact
uses: actions/upload-artifact@v2
with:
name: AssetStudio.net5
path: AssetStudioGUI/bin/Release/net5.0-windows/publish
- name: Upload .Net6 Artifact
uses: actions/upload-artifact@v2
with:
name: AssetStudio.net6
path: AssetStudioGUI/bin/Release/net6.0-windows/publish

3
.gitignore vendored
View File

@@ -35,6 +35,9 @@ bld/
# Visual Studio 2017 auto generated files
Generated\ Files/
# Launch Settings
*launchSettings.json
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*

View File

@@ -1,17 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net472;netstandard2.0</TargetFrameworks>
<TargetFrameworks>net472;net6.0;net6.0-windows;net7.0;net7.0-windows</TargetFrameworks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Version>0.16.8.1</Version>
<AssemblyVersion>0.16.8.1</AssemblyVersion>
<FileVersion>0.16.8.1</FileVersion>
<Copyright>Copyright © Perfare 2020-2021; Copyright © hozuki 2020</Copyright>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net472|AnyCPU'">
<DebugType>none</DebugType>
<DebugSymbols>false</DebugSymbols>
<Version>0.16.48.1</Version>
<Copyright>Copyright © Perfare 2020-2022; Copyright © hozuki 2020</Copyright>
<DebugType>embedded</DebugType>
</PropertyGroup>
</Project>

View File

@@ -4,33 +4,29 @@ using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
#if NETFRAMEWORK
namespace AssetStudio.PInvoke
{
public static class DllLoader
{
public static void PreloadDll(string dllName)
{
var dllDir = GetDirectedDllDirectory();
var localPath = Process.GetCurrentProcess().MainModule.FileName;
var localDir = Path.GetDirectoryName(localPath);
// Not using OperatingSystem.Platform.
// See: https://www.mono-project.com/docs/faq/technical/#how-to-detect-the-execution-platform
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Win32.LoadDll(dllDir, dllName);
}
else
{
Posix.LoadDll(dllDir, dllName);
Win32.LoadDll(GetDirectedDllDirectory(localDir), dllName);
}
}
private static string GetDirectedDllDirectory()
private static string GetDirectedDllDirectory(string localDir)
{
var localPath = Process.GetCurrentProcess().MainModule.FileName;
var localDir = Path.GetDirectoryName(localPath);
var subDir = Environment.Is64BitProcess ? "x64" : "x86";
var win32Path = Path.Combine("runtimes", "win-x86", "native");
var win64Path = Path.Combine("runtimes", "win-x64", "native");
var subDir = Environment.Is64BitProcess ? win64Path : win32Path;
var directedDllDir = Path.Combine(localDir, subDir);
@@ -64,61 +60,7 @@ namespace AssetStudio.PInvoke
private const uint LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x1000;
private const uint LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR = 0x100;
}
private static class Posix
{
internal static void LoadDll(string dllDir, string dllName)
{
string dllExtension;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
dllExtension = ".so";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
dllExtension = ".dylib";
}
else
{
throw new NotSupportedException();
}
var dllFileName = $"lib{dllName}{dllExtension}";
var directedDllPath = Path.Combine(dllDir, dllFileName);
const int ldFlags = RTLD_NOW | RTLD_GLOBAL;
var hLibrary = DlOpen(directedDllPath, ldFlags);
if (hLibrary == IntPtr.Zero)
{
var pErrStr = DlError();
// `PtrToStringAnsi` always uses the specific constructor of `String` (see dotnet/core#2325),
// which in turn interprets the byte sequence with system default codepage. On OSX and Linux
// the codepage is UTF-8 so the error message should be handled correctly.
var errorMessage = Marshal.PtrToStringAnsi(pErrStr);
throw new DllNotFoundException(errorMessage);
}
}
// OSX and most Linux OS use LP64 so `int` is still 32-bit even on 64-bit platforms.
// void *dlopen(const char *filename, int flag);
[DllImport("libdl", EntryPoint = "dlopen")]
private static extern IntPtr DlOpen([MarshalAs(UnmanagedType.LPStr)] string fileName, int flags);
// char *dlerror(void);
[DllImport("libdl", EntryPoint = "dlerror")]
private static extern IntPtr DlError();
private const int RTLD_LAZY = 0x1;
private const int RTLD_NOW = 0x2;
private const int RTLD_GLOBAL = 0x100;
}
}
}
#endif

View File

@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31410.357
# Visual Studio Version 17
VisualStudioVersion = 17.5.33414.496
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AssetStudio", "AssetStudio\AssetStudio.csproj", "{422FEC21-EF60-4F29-AA56-95DFDA23C913}"
EndProject
@@ -25,6 +25,12 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AssetStudioFBXNative", "Ass
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Texture2DDecoderNative", "Texture2DDecoderNative\Texture2DDecoderNative.vcxproj", "{29356642-C46E-4144-83D8-22DC09D0D7FD}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AssetStudioCLI", "AssetStudioCLI\AssetStudioCLI.csproj", "{34B6329B-0E73-45AC-B8CC-015F119F63DC}"
ProjectSection(ProjectDependencies) = postProject
{422FEC21-EF60-4F29-AA56-95DFDA23C913} = {422FEC21-EF60-4F29-AA56-95DFDA23C913}
{65EAFFA3-01D3-4EF5-B092-8B4647E9A1FF} = {65EAFFA3-01D3-4EF5-B092-8B4647E9A1FF}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -131,6 +137,18 @@ Global
{29356642-C46E-4144-83D8-22DC09D0D7FD}.Release|x64.Build.0 = Release|x64
{29356642-C46E-4144-83D8-22DC09D0D7FD}.Release|x86.ActiveCfg = Release|Win32
{29356642-C46E-4144-83D8-22DC09D0D7FD}.Release|x86.Build.0 = Release|Win32
{34B6329B-0E73-45AC-B8CC-015F119F63DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{34B6329B-0E73-45AC-B8CC-015F119F63DC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{34B6329B-0E73-45AC-B8CC-015F119F63DC}.Debug|x64.ActiveCfg = Debug|Any CPU
{34B6329B-0E73-45AC-B8CC-015F119F63DC}.Debug|x64.Build.0 = Debug|Any CPU
{34B6329B-0E73-45AC-B8CC-015F119F63DC}.Debug|x86.ActiveCfg = Debug|Any CPU
{34B6329B-0E73-45AC-B8CC-015F119F63DC}.Debug|x86.Build.0 = Debug|Any CPU
{34B6329B-0E73-45AC-B8CC-015F119F63DC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{34B6329B-0E73-45AC-B8CC-015F119F63DC}.Release|Any CPU.Build.0 = Release|Any CPU
{34B6329B-0E73-45AC-B8CC-015F119F63DC}.Release|x64.ActiveCfg = Release|Any CPU
{34B6329B-0E73-45AC-B8CC-015F119F63DC}.Release|x64.Build.0 = Release|Any CPU
{34B6329B-0E73-45AC-B8CC-015F119F63DC}.Release|x86.ActiveCfg = Release|Any CPU
{34B6329B-0E73-45AC-B8CC-015F119F63DC}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -1,16 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net472;netstandard2.0</TargetFrameworks>
<Version>0.16.8.1</Version>
<AssemblyVersion>0.16.8.1</AssemblyVersion>
<FileVersion>0.16.8.1</FileVersion>
<Copyright>Copyright © Perfare 2018-2021</Copyright>
<TargetFrameworks>net472;net6.0;net6.0-windows;net7.0;net7.0-windows</TargetFrameworks>
<Version>0.16.48.1</Version>
<Copyright>Copyright © Perfare 2018-2022</Copyright>
<DebugType>embedded</DebugType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net472|AnyCPU'">
<DebugType>none</DebugType>
<DebugSymbols>false</DebugSymbols>
</PropertyGroup>
<ItemGroup Condition=" '$(TargetFramework)' != 'net472' ">
<PackageReference Include="K4os.Compression.LZ4" Version="1.3.5" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net472' ">
<PackageReference Include="System.Memory" Version="4.5.4" />
<PackageReference Include="System.IO.Compression" Version="4.0.0" />
<PackageReference Include="K4os.Compression.LZ4" Version="1.1.11" />
</ItemGroup>
</Project>

View File

@@ -1,6 +1,7 @@
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using static AssetStudio.ImportHelper;
@@ -11,17 +12,50 @@ namespace AssetStudio
{
public string SpecifyUnityVersion;
public List<SerializedFile> assetsFileList = new List<SerializedFile>();
private List<ClassIDType> filteredAssetTypesList = new List<ClassIDType>();
internal Dictionary<string, int> assetsFileIndexCache = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
internal Dictionary<string, BinaryReader> resourceFileReaders = new Dictionary<string, BinaryReader>(StringComparer.OrdinalIgnoreCase);
private List<string> importFiles = new List<string>();
private HashSet<string> importFilesHash = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private HashSet<string> noexistFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private HashSet<string> assetsFileListHash = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
public void SetAssetFilter(ClassIDType classIDType)
{
if (filteredAssetTypesList.Count == 0)
{
filteredAssetTypesList.AddRange(new List<ClassIDType>
{
ClassIDType.AssetBundle,
ClassIDType.ResourceManager,
});
}
if (classIDType == ClassIDType.MonoBehaviour)
{
filteredAssetTypesList.AddRange(new List<ClassIDType>
{
ClassIDType.MonoScript,
ClassIDType.MonoBehaviour
});
}
else
{
filteredAssetTypesList.Add(classIDType);
}
}
public void SetAssetFilter(List<ClassIDType> classIDTypeList)
{
foreach (ClassIDType classIDType in classIDTypeList)
SetAssetFilter(classIDType);
}
public void LoadFiles(params string[] files)
{
var path = Path.GetDirectoryName(files[0]);
var path = Path.GetDirectoryName(Path.GetFullPath(files[0]));
MergeSplitAssets(path);
var toReadFile = ProcessingSplitFiles(files.ToList());
Load(toReadFile);
@@ -53,6 +87,7 @@ namespace AssetStudio
importFiles.Clear();
importFilesHash.Clear();
noexistFiles.Clear();
assetsFileListHash.Clear();
ReadAssets();
@@ -84,6 +119,9 @@ namespace AssetStudio
case FileType.BrotliFile:
LoadFile(DecompressBrotli(reader));
break;
case FileType.ZipFile:
LoadZipFile(reader);
break;
}
}
@@ -91,7 +129,7 @@ namespace AssetStudio
{
if (!assetsFileListHash.Contains(reader.FileName))
{
Logger.Info($"Loading {reader.FileName}");
Logger.Info($"Loading {reader.FullPath}");
try
{
var assetsFile = new SerializedFile(reader, this);
@@ -106,31 +144,43 @@ namespace AssetStudio
if (!importFilesHash.Contains(sharedFileName))
{
var sharedFilePath = Path.Combine(Path.GetDirectoryName(reader.FullPath), sharedFileName);
if (!File.Exists(sharedFilePath))
if (!noexistFiles.Contains(sharedFilePath))
{
var findFiles = Directory.GetFiles(Path.GetDirectoryName(reader.FullPath), sharedFileName, SearchOption.AllDirectories);
if (findFiles.Length > 0)
if (!File.Exists(sharedFilePath))
{
sharedFilePath = findFiles[0];
var findFiles = Directory.GetFiles(Path.GetDirectoryName(reader.FullPath), sharedFileName, SearchOption.AllDirectories);
if (findFiles.Length > 0)
{
sharedFilePath = findFiles[0];
}
}
if (File.Exists(sharedFilePath))
{
importFiles.Add(sharedFilePath);
importFilesHash.Add(sharedFileName);
}
else
{
noexistFiles.Add(sharedFilePath);
}
}
if (File.Exists(sharedFilePath))
{
importFiles.Add(sharedFilePath);
importFilesHash.Add(sharedFileName);
}
}
}
}
catch (NotSupportedException e)
{
Logger.Error(e.Message);
reader.Dispose();
}
catch (Exception e)
{
Logger.Error($"Error while reading assets file {reader.FileName}", e);
Logger.Warning($"Error while reading assets file {reader.FullPath}\r\n{e}");
reader.Dispose();
}
}
else
{
Logger.Info($"Skipping {reader.FullPath}");
reader.Dispose();
}
}
@@ -143,7 +193,7 @@ namespace AssetStudio
{
var assetsFile = new SerializedFile(reader, this);
assetsFile.originalPath = originalPath;
if (!string.IsNullOrEmpty(unityVersion) && assetsFile.header.m_Version < SerializedFileFormatVersion.kUnknown_7)
if (!string.IsNullOrEmpty(unityVersion) && assetsFile.header.m_Version < SerializedFileFormatVersion.Unknown_7)
{
assetsFile.SetVersion(unityVersion);
}
@@ -151,20 +201,27 @@ namespace AssetStudio
assetsFileList.Add(assetsFile);
assetsFileListHash.Add(assetsFile.fileName);
}
catch (NotSupportedException e)
{
Logger.Error(e.Message);
resourceFileReaders.Add(reader.FileName, reader);
}
catch (Exception e)
{
Logger.Error($"Error while reading assets file {reader.FileName} from {Path.GetFileName(originalPath)}", e);
Logger.Warning($"Error while reading assets file {reader.FullPath} from {Path.GetFileName(originalPath)}\r\n{e}");
resourceFileReaders.Add(reader.FileName, reader);
}
}
else
Logger.Info($"Skipping {originalPath} ({reader.FileName})");
}
private void LoadBundleFile(FileReader reader, string originalPath = null)
{
Logger.Info("Loading " + reader.FileName);
Logger.Info("Loading " + reader.FullPath);
try
{
var bundleFile = new BundleFile(reader);
var bundleFile = new BundleFile(reader, SpecifyUnityVersion);
foreach (var file in bundleFile.fileList)
{
var dummyPath = Path.Combine(Path.GetDirectoryName(reader.FullPath), file.fileName);
@@ -179,14 +236,18 @@ namespace AssetStudio
}
}
}
catch (NotSupportedException e)
{
Logger.Error(e.Message);
}
catch (Exception e)
{
var str = $"Error while reading bundle file {reader.FileName}";
var str = $"Error while reading bundle file {reader.FullPath}";
if (originalPath != null)
{
str += $" from {Path.GetFileName(originalPath)}";
}
Logger.Error(str, e);
Logger.Warning($"{str}\r\n{e}");
}
finally
{
@@ -196,7 +257,7 @@ namespace AssetStudio
private void LoadWebFile(FileReader reader)
{
Logger.Info("Loading " + reader.FileName);
Logger.Info("Loading " + reader.FullPath);
try
{
var webFile = new WebFile(reader);
@@ -223,7 +284,111 @@ namespace AssetStudio
}
catch (Exception e)
{
Logger.Error($"Error while reading web file {reader.FileName}", e);
Logger.Error($"Error while reading web file {reader.FullPath}", e);
}
finally
{
reader.Dispose();
}
}
private void LoadZipFile(FileReader reader)
{
Logger.Info("Reading " + reader.FileName);
try
{
using (ZipArchive archive = new ZipArchive(reader.BaseStream, ZipArchiveMode.Read))
{
List<string> splitFiles = new List<string>();
// register all files before parsing the assets so that the external references can be found
// and find split files
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (entry.Name.Contains(".split"))
{
string baseName = Path.GetFileNameWithoutExtension(entry.Name);
string basePath = Path.Combine(Path.GetDirectoryName(entry.FullName), baseName);
if (!splitFiles.Contains(basePath))
{
splitFiles.Add(basePath);
importFilesHash.Add(baseName);
}
}
else
{
importFilesHash.Add(entry.Name);
}
}
// merge split files and load the result
foreach (string basePath in splitFiles)
{
try
{
Stream splitStream = new MemoryStream();
int i = 0;
while (true)
{
string path = $"{basePath}.split{i++}";
ZipArchiveEntry entry = archive.GetEntry(path);
if (entry == null)
break;
using (Stream entryStream = entry.Open())
{
entryStream.CopyTo(splitStream);
}
}
splitStream.Seek(0, SeekOrigin.Begin);
FileReader entryReader = new FileReader(basePath, splitStream);
LoadFile(entryReader);
}
catch (Exception e)
{
Logger.Warning($"Error while reading zip split file {basePath}\r\n{e}");
}
}
// load all entries
var progressCount = archive.Entries.Count;
int k = 0;
Progress.Reset();
foreach (ZipArchiveEntry entry in archive.Entries)
{
try
{
string dummyPath = Path.Combine(Path.GetDirectoryName(reader.FullPath), reader.FileName, entry.FullName);
// create a new stream
// - to store the deflated stream in
// - to keep the data for later extraction
Stream streamReader = new MemoryStream();
using (Stream entryStream = entry.Open())
{
entryStream.CopyTo(streamReader);
}
streamReader.Position = 0;
FileReader entryReader = new FileReader(dummyPath, streamReader);
LoadFile(entryReader);
if (entryReader.FileType == FileType.ResourceFile)
{
entryReader.Position = 0;
if (!resourceFileReaders.ContainsKey(entry.Name))
{
resourceFileReaders.Add(entry.Name, entryReader);
}
}
Progress.Report(++k, progressCount);
}
catch (Exception e)
{
Logger.Warning($"Error while reading zip entry {entry.FullName}\r\n{e}");
}
}
}
}
catch (Exception e)
{
Logger.Error($"Error while reading zip file {reader.FileName}", e);
}
finally
{
@@ -235,7 +400,7 @@ namespace AssetStudio
{
if (assetsFile.IsVersionStripped && string.IsNullOrEmpty(SpecifyUnityVersion))
{
throw new Exception("The Unity version has been stripped, please set the version in the options");
throw new NotSupportedException("The Unity version has been stripped, please set the version in the options");
}
if (!string.IsNullOrEmpty(SpecifyUnityVersion))
{
@@ -273,9 +438,13 @@ namespace AssetStudio
foreach (var objectInfo in assetsFile.m_Objects)
{
var objectReader = new ObjectReader(assetsFile.reader, assetsFile, objectInfo);
if (filteredAssetTypesList.Count > 0 && !filteredAssetTypesList.Contains(objectReader.type))
{
continue;
}
try
{
Object obj;
Object obj = null;
switch (objectReader.type)
{
case ClassIDType.Animation:
@@ -336,7 +505,8 @@ namespace AssetStudio
obj = new RectTransform(objectReader);
break;
case ClassIDType.Shader:
obj = new Shader(objectReader);
if (objectReader.version[0] < 2021)
obj = new Shader(objectReader);
break;
case ClassIDType.SkinnedMeshRenderer:
obj = new SkinnedMeshRenderer(objectReader);
@@ -366,17 +536,19 @@ namespace AssetStudio
obj = new Object(objectReader);
break;
}
assetsFile.AddObject(obj);
if (obj != null)
assetsFile.AddObject(obj);
}
catch (Exception e)
{
var sb = new StringBuilder();
sb.AppendLine("Unable to load object")
.AppendLine($"Assets {assetsFile.fileName}")
.AppendLine($"Path {assetsFile.originalPath}")
.AppendLine($"Type {objectReader.type}")
.AppendLine($"PathID {objectInfo.m_PathID}")
.Append(e);
Logger.Error(sb.ToString());
Logger.Warning(sb.ToString());
}
Progress.Report(++i, progressCount);
@@ -432,6 +604,14 @@ namespace AssetStudio
{
m_Sprite.m_SpriteAtlas.Set(m_SpriteAtlas);
}
else
{
m_Sprite.m_SpriteAtlas.TryGet(out var m_SpriteAtlaOld);
if (m_SpriteAtlaOld.m_IsVariant)
{
m_Sprite.m_SpriteAtlas.Set(m_SpriteAtlas);
}
}
}
}
}
@@ -439,4 +619,4 @@ namespace AssetStudio
}
}
}
}
}

View File

@@ -0,0 +1,10 @@
using System.Buffers;
namespace AssetStudio
{
public static class BigArrayPool<T>
{
private static readonly ArrayPool<T> s_shared = ArrayPool<T>.Create(64 * 1024 * 1024, 3);
public static ArrayPool<T> Shared => s_shared;
}
}

View File

@@ -8,7 +8,8 @@ namespace AssetStudio
public enum BuildTarget
{
NoTarget = -2,
DashboardWidget = 1,
AnyPlayer = -1,
ValidPlayer = 1,
StandaloneOSX = 2,
StandaloneOSXPPC = 3,
StandaloneOSXIntel = 4,
@@ -19,8 +20,10 @@ namespace AssetStudio
iOS = 9,
PS3,
XBOX360,
Broadcom = 12,
Android = 13,
StandaloneGLESEmu = 14,
StandaloneGLES20Emu = 15,
NaCl = 16,
StandaloneLinux = 17,
FlashPlayer = 18,
@@ -48,6 +51,8 @@ namespace AssetStudio
GameCoreXboxSeries,
GameCoreXboxOne,
PS5,
EmbeddedLinux,
QNX,
UnknownPlatform = 9999
}
}

View File

@@ -1,11 +1,43 @@
using System;
using System.Collections.Generic;
using K4os.Compression.LZ4;
using System;
using System.IO;
using System.Linq;
using Lz4;
namespace AssetStudio
{
[Flags]
public enum ArchiveFlags
{
CompressionTypeMask = 0x3f,
BlocksAndDirectoryInfoCombined = 0x40,
BlocksInfoAtTheEnd = 0x80,
OldWebPluginCompatibility = 0x100,
BlockInfoNeedPaddingAtStart = 0x200
}
[Flags]
public enum CnEncryptionFlags
{
OldFlag = 0x200,
NewFlag = 0x400
}
[Flags]
public enum StorageBlockFlags
{
CompressionTypeMask = 0x3f,
Streamed = 0x40
}
public enum CompressionType
{
None,
Lzma,
Lz4,
Lz4HC,
Lzham
}
public class BundleFile
{
public class Header
@@ -17,14 +49,14 @@ namespace AssetStudio
public long size;
public uint compressedBlocksInfoSize;
public uint uncompressedBlocksInfoSize;
public uint flags;
public ArchiveFlags flags;
}
public class StorageBlock
{
public uint compressedSize;
public uint uncompressedSize;
public ushort flags;
public StorageBlockFlags flags;
}
public class Node
@@ -41,7 +73,7 @@ namespace AssetStudio
public StreamFile[] fileList;
public BundleFile(FileReader reader)
public BundleFile(FileReader reader, string specUnityVer = "")
{
m_Header = new Header();
m_Header.signature = reader.ReadStringToNull();
@@ -67,7 +99,31 @@ namespace AssetStudio
break;
case "UnityFS":
ReadHeader(reader);
ReadBlocksInfoAndDirectory(reader);
bool isUnityCnEnc = false;
string unityVer = string.IsNullOrEmpty(specUnityVer) ? m_Header.unityRevision : specUnityVer;
int[] ver = new string(unityVer.SkipWhile(x => !char.IsDigit(x)).TakeWhile(x => char.IsDigit(x) || x == '.').ToArray()).Split('.').Select(x => int.Parse(x)).ToArray();
if (ver[0] != 0)
{
// https://issuetracker.unity3d.com/issues/files-within-assetbundles-do-not-start-on-aligned-boundaries-breaking-patching-on-nintendo-switch
if (ver[0] < 2020 ||
(ver[0] == 2020 && ver[1] <= 3 && ver[2] < 34) ||
(ver[0] == 2021 && ver[1] <= 3 && ver[2] < 2) ||
(ver[0] == 2022 && ver[1] <= 1 && ver[2] < 1))
{
isUnityCnEnc = ((CnEncryptionFlags)m_Header.flags & CnEncryptionFlags.OldFlag) != 0;
}
else
{
isUnityCnEnc = ((CnEncryptionFlags)m_Header.flags & CnEncryptionFlags.NewFlag) != 0;
}
}
if (isUnityCnEnc)
{
throw new NotSupportedException("Unsupported bundle file. UnityCN encryption was detected.");
}
ReadBlocksInfoAndDirectory(reader, ver);
using (var blocksStream = CreateBlocksStream(reader.FullPath))
{
ReadBlocks(reader, blocksStream);
@@ -79,7 +135,6 @@ namespace AssetStudio
private void ReadHeaderAndBlocksInfo(EndianBinaryReader reader)
{
var isCompressed = m_Header.signature == "UnityWeb";
if (m_Header.version >= 4)
{
var hash = reader.ReadBytes(16);
@@ -96,7 +151,6 @@ namespace AssetStudio
{
compressedSize = reader.ReadUInt32(),
uncompressedSize = reader.ReadUInt32(),
flags = (ushort)(isCompressed ? 1 : 0)
};
if (i == levelCount - 1)
{
@@ -133,10 +187,11 @@ namespace AssetStudio
private void ReadBlocksAndDirectory(EndianBinaryReader reader, Stream blocksStream)
{
var isCompressed = m_Header.signature == "UnityWeb";
foreach (var blockInfo in m_BlocksInfo)
{
var uncompressedBytes = reader.ReadBytes((int)blockInfo.compressedSize);
if (blockInfo.flags == 1)
if (isCompressed)
{
using (var memoryStream = new MemoryStream(uncompressedBytes))
{
@@ -196,59 +251,79 @@ namespace AssetStudio
m_Header.size = reader.ReadInt64();
m_Header.compressedBlocksInfoSize = reader.ReadUInt32();
m_Header.uncompressedBlocksInfoSize = reader.ReadUInt32();
m_Header.flags = reader.ReadUInt32();
m_Header.flags = (ArchiveFlags)reader.ReadUInt32();
if (m_Header.signature != "UnityFS")
{
reader.ReadByte();
}
}
private void ReadBlocksInfoAndDirectory(EndianBinaryReader reader)
private void ReadBlocksInfoAndDirectory(EndianBinaryReader reader, int[] unityVer)
{
byte[] blocksInfoBytes;
if (m_Header.version >= 7)
{
reader.AlignStream(16);
}
if ((m_Header.flags & 0x80) != 0) //kArchiveBlocksInfoAtTheEnd
else if (unityVer[0] >= 2019 && unityVer[1] >= 4)
{
//check if we need to align the reader
//- align to 16 bytes and check if all are 0
//- if not, reset the reader to the previous position
var preAlign = reader.Position;
var alignData = reader.ReadBytes((16 - (int)(preAlign % 16)) % 16);
if (alignData.Any(x => x != 0))
{
reader.Position = preAlign;
}
}
if ((m_Header.flags & ArchiveFlags.BlocksInfoAtTheEnd) != 0)
{
var position = reader.Position;
reader.Position = reader.BaseStream.Length - m_Header.compressedBlocksInfoSize;
blocksInfoBytes = reader.ReadBytes((int)m_Header.compressedBlocksInfoSize);
reader.Position = position;
}
else //0x40 kArchiveBlocksAndDirectoryInfoCombined
else //0x40 BlocksAndDirectoryInfoCombined
{
blocksInfoBytes = reader.ReadBytes((int)m_Header.compressedBlocksInfoSize);
}
var blocksInfoCompressedStream = new MemoryStream(blocksInfoBytes);
MemoryStream blocksInfoUncompresseddStream;
switch (m_Header.flags & 0x3F) //kArchiveCompressionTypeMask
var uncompressedSize = m_Header.uncompressedBlocksInfoSize;
var compressionType = (CompressionType)(m_Header.flags & ArchiveFlags.CompressionTypeMask);
switch (compressionType)
{
default: //None
case CompressionType.None:
{
blocksInfoUncompresseddStream = blocksInfoCompressedStream;
blocksInfoUncompresseddStream = new MemoryStream(blocksInfoBytes);
break;
}
case 1: //LZMA
case CompressionType.Lzma:
{
blocksInfoUncompresseddStream = new MemoryStream((int)(m_Header.uncompressedBlocksInfoSize));
SevenZipHelper.StreamDecompress(blocksInfoCompressedStream, blocksInfoUncompresseddStream, m_Header.compressedBlocksInfoSize, m_Header.uncompressedBlocksInfoSize);
blocksInfoUncompresseddStream.Position = 0;
blocksInfoCompressedStream.Close();
break;
}
case 2: //LZ4
case 3: //LZ4HC
{
var uncompressedBytes = new byte[m_Header.uncompressedBlocksInfoSize];
using (var decoder = new Lz4DecoderStream(blocksInfoCompressedStream))
blocksInfoUncompresseddStream = new MemoryStream((int)(uncompressedSize));
using (var blocksInfoCompressedStream = new MemoryStream(blocksInfoBytes))
{
decoder.Read(uncompressedBytes, 0, uncompressedBytes.Length);
SevenZipHelper.StreamDecompress(blocksInfoCompressedStream, blocksInfoUncompresseddStream, m_Header.compressedBlocksInfoSize, m_Header.uncompressedBlocksInfoSize);
}
blocksInfoUncompresseddStream.Position = 0;
break;
}
case CompressionType.Lz4:
case CompressionType.Lz4HC:
{
var uncompressedBytes = new byte[uncompressedSize];
var numWrite = LZ4Codec.Decode(blocksInfoBytes, uncompressedBytes);
if (numWrite != uncompressedSize)
{
throw new IOException($"Lz4 decompression error, write {numWrite} bytes but expected {uncompressedSize} bytes");
}
blocksInfoUncompresseddStream = new MemoryStream(uncompressedBytes);
break;
}
default:
throw new IOException($"Unsupported compression type {compressionType}");
}
using (var blocksInfoReader = new EndianBinaryReader(blocksInfoUncompresseddStream))
{
@@ -261,7 +336,7 @@ namespace AssetStudio
{
uncompressedSize = blocksInfoReader.ReadUInt32(),
compressedSize = blocksInfoReader.ReadUInt32(),
flags = blocksInfoReader.ReadUInt16()
flags = (StorageBlockFlags)blocksInfoReader.ReadUInt16()
};
}
@@ -278,34 +353,49 @@ namespace AssetStudio
};
}
}
if ((m_Header.flags & ArchiveFlags.BlockInfoNeedPaddingAtStart) != 0)
{
reader.AlignStream(16);
}
}
private void ReadBlocks(EndianBinaryReader reader, Stream blocksStream)
{
foreach (var blockInfo in m_BlocksInfo)
{
switch (blockInfo.flags & 0x3F) //kStorageBlockCompressionTypeMask
var compressionType = (CompressionType)(blockInfo.flags & StorageBlockFlags.CompressionTypeMask);
switch (compressionType)
{
default: //None
case CompressionType.None:
{
reader.BaseStream.CopyTo(blocksStream, blockInfo.compressedSize);
break;
}
case 1: //LZMA
case CompressionType.Lzma:
{
SevenZipHelper.StreamDecompress(reader.BaseStream, blocksStream, blockInfo.compressedSize, blockInfo.uncompressedSize);
break;
}
case 2: //LZ4
case 3: //LZ4HC
case CompressionType.Lz4:
case CompressionType.Lz4HC:
{
var compressedStream = new MemoryStream(reader.ReadBytes((int)blockInfo.compressedSize));
using (var lz4Stream = new Lz4DecoderStream(compressedStream))
var compressedSize = (int)blockInfo.compressedSize;
var compressedBytes = BigArrayPool<byte>.Shared.Rent(compressedSize);
reader.Read(compressedBytes, 0, compressedSize);
var uncompressedSize = (int)blockInfo.uncompressedSize;
var uncompressedBytes = BigArrayPool<byte>.Shared.Rent(uncompressedSize);
var numWrite = LZ4Codec.Decode(compressedBytes, 0, compressedSize, uncompressedBytes, 0, uncompressedSize);
if (numWrite != uncompressedSize)
{
lz4Stream.CopyTo(blocksStream, blockInfo.uncompressedSize);
throw new IOException($"Lz4 decompression error, write {numWrite} bytes but expected {uncompressedSize} bytes");
}
blocksStream.Write(uncompressedBytes, 0, uncompressedSize);
BigArrayPool<byte>.Shared.Return(compressedBytes);
BigArrayPool<byte>.Shared.Return(uncompressedBytes);
break;
}
default:
throw new IOException($"Unsupported compression type {compressionType}");
}
}
blocksStream.Position = 0;

View File

@@ -797,6 +797,7 @@ namespace AssetStudio
public ClassIDType typeID;
public byte customType;
public byte isPPtrCurve;
public byte isIntCurve;
public GenericBinding() { }
@@ -816,6 +817,10 @@ namespace AssetStudio
}
customType = reader.ReadByte();
isPPtrCurve = reader.ReadByte();
if (version[0] > 2022 || (version[0] == 2022 && version[1] >= 1)) //2022.1 and up
{
isIntCurve = reader.ReadByte();
}
reader.AlignStream();
}
}
@@ -909,9 +914,9 @@ namespace AssetStudio
public enum AnimationType
{
kLegacy = 1,
kGeneric = 2,
kHumanoid = 3
Legacy = 1,
Generic = 2,
Humanoid = 3
};
public sealed class AnimationClip : NamedObject
@@ -945,7 +950,7 @@ namespace AssetStudio
else if (version[0] >= 4)//4.0 and up
{
m_AnimationType = (AnimationType)reader.ReadInt32();
if (m_AnimationType == AnimationType.kLegacy)
if (m_AnimationType == AnimationType.Legacy)
m_Legacy = true;
}
else

View File

@@ -9,7 +9,7 @@ namespace AssetStudio
public sealed class AudioClip : NamedObject
{
public int m_Format;
public AudioType m_Type;
public FMODSoundType m_Type;
public bool m_3D;
public bool m_UseHardware;
@@ -36,7 +36,7 @@ namespace AssetStudio
if (version[0] < 5)
{
m_Format = reader.ReadInt32();
m_Type = (AudioType)reader.ReadInt32();
m_Type = (FMODSoundType)reader.ReadInt32();
m_3D = reader.ReadBoolean();
m_UseHardware = reader.ReadBoolean();
reader.AlignStream();
@@ -92,34 +92,51 @@ namespace AssetStudio
}
}
public enum AudioType
public enum FMODSoundType
{
UNKNOWN,
ACC,
AIFF,
UNKNOWN = 0,
ACC = 1,
AIFF = 2,
ASF = 3,
AT3 = 4,
CDDA = 5,
DLS = 6,
FLAC = 7,
FSB = 8,
GCADPCM = 9,
IT = 10,
MIDI = 11,
MOD = 12,
MPEG,
OGGVORBIS,
MPEG = 13,
OGGVORBIS = 14,
PLAYLIST = 15,
RAW = 16,
S3M = 17,
SF2 = 18,
USER = 19,
WAV = 20,
XM,
XMA,
VAG,
AUDIOQUEUE
XM = 21,
XMA = 22,
VAG = 23,
AUDIOQUEUE = 24,
XWMA = 25,
BCWAV = 26,
AT9 = 27,
VORBIS = 28,
MEDIA_FOUNDATION = 29
}
public enum AudioCompressionFormat
{
PCM,
Vorbis,
ADPCM,
MP3,
VAG,
HEVAG,
XMA,
AAC,
GCADPCM,
ATRAC9
PCM = 0,
Vorbis = 1,
ADPCM = 2,
MP3 = 3,
PSMVAG = 4,
HEVAG = 5,
XMA = 6,
AAC = 7,
GCADPCM = 8,
ATRAC9 = 9
}
}

View File

@@ -74,9 +74,18 @@ namespace AssetStudio
var m_ShaderKeywords = reader.ReadStringArray();
}
if (version[0] >= 5) //5.0 and up
if (version[0] > 2021 || (version[0] == 2021 && version[1] >= 3)) //2021.3 and up
{
var m_ValidKeywords = reader.ReadStringArray();
var m_InvalidKeywords = reader.ReadStringArray();
}
else if (version[0] >= 5) //5.0 ~ 2021.2
{
var m_ShaderKeywords = reader.ReadAlignedString();
}
if (version[0] >= 5) //5.0 and up
{
var m_LightmapFlags = reader.ReadUInt32();
}

View File

@@ -396,14 +396,14 @@ namespace AssetStudio
}
}
public enum GfxPrimitiveType : int
public enum GfxPrimitiveType
{
kPrimitiveTriangles = 0,
kPrimitiveTriangleStrip = 1,
kPrimitiveQuads = 2,
kPrimitiveLines = 3,
kPrimitiveLineStrip = 4,
kPrimitivePoints = 5,
Triangles = 0,
TriangleStrip = 1,
Quads = 2,
Lines = 3,
LineStrip = 4,
Points = 5
};
public class SubMesh
@@ -651,6 +651,11 @@ namespace AssetStudio
int m_MeshUsageFlags = reader.ReadInt32();
if (version[0] > 2022 || (version[0] == 2022 && version[1] >= 1)) //2022.1 and up
{
int m_CookingOptions = reader.ReadInt32();
}
if (version[0] >= 5) //5.0 and up
{
var m_BakedConvexCollisionMesh = reader.ReadUInt8Array();
@@ -729,7 +734,7 @@ namespace AssetStudio
}
}
if (reader.endian == EndianType.BigEndian && componentByteSize > 1) //swap bytes
if (reader.Endian == EndianType.BigEndian && componentByteSize > 1) //swap bytes
{
for (var i = 0; i < componentBytes.Length / componentByteSize; i++)
{
@@ -1060,7 +1065,7 @@ namespace AssetStudio
}
var indexCount = m_SubMesh.indexCount;
var topology = m_SubMesh.topology;
if (topology == GfxPrimitiveType.kPrimitiveTriangles)
if (topology == GfxPrimitiveType.Triangles)
{
for (int i = 0; i < indexCount; i += 3)
{
@@ -1069,7 +1074,7 @@ namespace AssetStudio
m_Indices.Add(m_IndexBuffer[firstIndex + i + 2]);
}
}
else if (version[0] < 4 || topology == GfxPrimitiveType.kPrimitiveTriangleStrip)
else if (version[0] < 4 || topology == GfxPrimitiveType.TriangleStrip)
{
// de-stripify :
uint triIndex = 0;
@@ -1100,7 +1105,7 @@ namespace AssetStudio
//fix indexCount
m_SubMesh.indexCount = triIndex;
}
else if (topology == GfxPrimitiveType.kPrimitiveQuads)
else if (topology == GfxPrimitiveType.Quads)
{
for (int q = 0; q < indexCount; q += 4)
{
@@ -1193,44 +1198,44 @@ namespace AssetStudio
{
public enum VertexChannelFormat
{
kChannelFormatFloat,
kChannelFormatFloat16,
kChannelFormatColor,
kChannelFormatByte,
kChannelFormatUInt32
Float,
Float16,
Color,
Byte,
UInt32
}
public enum VertexFormat2017
{
kVertexFormatFloat,
kVertexFormatFloat16,
kVertexFormatColor,
kVertexFormatUNorm8,
kVertexFormatSNorm8,
kVertexFormatUNorm16,
kVertexFormatSNorm16,
kVertexFormatUInt8,
kVertexFormatSInt8,
kVertexFormatUInt16,
kVertexFormatSInt16,
kVertexFormatUInt32,
kVertexFormatSInt32
Float,
Float16,
Color,
UNorm8,
SNorm8,
UNorm16,
SNorm16,
UInt8,
SInt8,
UInt16,
SInt16,
UInt32,
SInt32
}
public enum VertexFormat
{
kVertexFormatFloat,
kVertexFormatFloat16,
kVertexFormatUNorm8,
kVertexFormatSNorm8,
kVertexFormatUNorm16,
kVertexFormatSNorm16,
kVertexFormatUInt8,
kVertexFormatSInt8,
kVertexFormatUInt16,
kVertexFormatSInt16,
kVertexFormatUInt32,
kVertexFormatSInt32
Float,
Float16,
UNorm8,
SNorm8,
UNorm16,
SNorm16,
UInt8,
SInt8,
UInt16,
SInt16,
UInt32,
SInt32
}
public static VertexFormat ToVertexFormat(int format, int[] version)
@@ -1239,16 +1244,16 @@ namespace AssetStudio
{
switch ((VertexChannelFormat)format)
{
case VertexChannelFormat.kChannelFormatFloat:
return VertexFormat.kVertexFormatFloat;
case VertexChannelFormat.kChannelFormatFloat16:
return VertexFormat.kVertexFormatFloat16;
case VertexChannelFormat.kChannelFormatColor: //in 4.x is size 4
return VertexFormat.kVertexFormatUNorm8;
case VertexChannelFormat.kChannelFormatByte:
return VertexFormat.kVertexFormatUInt8;
case VertexChannelFormat.kChannelFormatUInt32: //in 5.x
return VertexFormat.kVertexFormatUInt32;
case VertexChannelFormat.Float:
return VertexFormat.Float;
case VertexChannelFormat.Float16:
return VertexFormat.Float16;
case VertexChannelFormat.Color: //in 4.x is size 4
return VertexFormat.UNorm8;
case VertexChannelFormat.Byte:
return VertexFormat.UInt8;
case VertexChannelFormat.UInt32: //in 5.x
return VertexFormat.UInt32;
default:
throw new ArgumentOutOfRangeException(nameof(format), format, null);
}
@@ -1257,31 +1262,31 @@ namespace AssetStudio
{
switch ((VertexFormat2017)format)
{
case VertexFormat2017.kVertexFormatFloat:
return VertexFormat.kVertexFormatFloat;
case VertexFormat2017.kVertexFormatFloat16:
return VertexFormat.kVertexFormatFloat16;
case VertexFormat2017.kVertexFormatColor:
case VertexFormat2017.kVertexFormatUNorm8:
return VertexFormat.kVertexFormatUNorm8;
case VertexFormat2017.kVertexFormatSNorm8:
return VertexFormat.kVertexFormatSNorm8;
case VertexFormat2017.kVertexFormatUNorm16:
return VertexFormat.kVertexFormatUNorm16;
case VertexFormat2017.kVertexFormatSNorm16:
return VertexFormat.kVertexFormatSNorm16;
case VertexFormat2017.kVertexFormatUInt8:
return VertexFormat.kVertexFormatUInt8;
case VertexFormat2017.kVertexFormatSInt8:
return VertexFormat.kVertexFormatSInt8;
case VertexFormat2017.kVertexFormatUInt16:
return VertexFormat.kVertexFormatUInt16;
case VertexFormat2017.kVertexFormatSInt16:
return VertexFormat.kVertexFormatSInt16;
case VertexFormat2017.kVertexFormatUInt32:
return VertexFormat.kVertexFormatUInt32;
case VertexFormat2017.kVertexFormatSInt32:
return VertexFormat.kVertexFormatSInt32;
case VertexFormat2017.Float:
return VertexFormat.Float;
case VertexFormat2017.Float16:
return VertexFormat.Float16;
case VertexFormat2017.Color:
case VertexFormat2017.UNorm8:
return VertexFormat.UNorm8;
case VertexFormat2017.SNorm8:
return VertexFormat.SNorm8;
case VertexFormat2017.UNorm16:
return VertexFormat.UNorm16;
case VertexFormat2017.SNorm16:
return VertexFormat.SNorm16;
case VertexFormat2017.UInt8:
return VertexFormat.UInt8;
case VertexFormat2017.SInt8:
return VertexFormat.SInt8;
case VertexFormat2017.UInt16:
return VertexFormat.UInt16;
case VertexFormat2017.SInt16:
return VertexFormat.SInt16;
case VertexFormat2017.UInt32:
return VertexFormat.UInt32;
case VertexFormat2017.SInt32:
return VertexFormat.SInt32;
default:
throw new ArgumentOutOfRangeException(nameof(format), format, null);
}
@@ -1297,20 +1302,20 @@ namespace AssetStudio
{
switch (format)
{
case VertexFormat.kVertexFormatFloat:
case VertexFormat.kVertexFormatUInt32:
case VertexFormat.kVertexFormatSInt32:
case VertexFormat.Float:
case VertexFormat.UInt32:
case VertexFormat.SInt32:
return 4u;
case VertexFormat.kVertexFormatFloat16:
case VertexFormat.kVertexFormatUNorm16:
case VertexFormat.kVertexFormatSNorm16:
case VertexFormat.kVertexFormatUInt16:
case VertexFormat.kVertexFormatSInt16:
case VertexFormat.Float16:
case VertexFormat.UNorm16:
case VertexFormat.SNorm16:
case VertexFormat.UInt16:
case VertexFormat.SInt16:
return 2u;
case VertexFormat.kVertexFormatUNorm8:
case VertexFormat.kVertexFormatSNorm8:
case VertexFormat.kVertexFormatUInt8:
case VertexFormat.kVertexFormatSInt8:
case VertexFormat.UNorm8:
case VertexFormat.SNorm8:
case VertexFormat.UInt8:
case VertexFormat.SInt8:
return 1u;
default:
throw new ArgumentOutOfRangeException(nameof(format), format, null);
@@ -1319,7 +1324,7 @@ namespace AssetStudio
public static bool IsIntFormat(VertexFormat format)
{
return format >= VertexFormat.kVertexFormatUInt8;
return format >= VertexFormat.UInt8;
}
public static float[] BytesToFloatArray(byte[] inputBytes, VertexFormat format)
@@ -1331,22 +1336,22 @@ namespace AssetStudio
{
switch (format)
{
case VertexFormat.kVertexFormatFloat:
case VertexFormat.Float:
result[i] = BitConverter.ToSingle(inputBytes, i * 4);
break;
case VertexFormat.kVertexFormatFloat16:
case VertexFormat.Float16:
result[i] = Half.ToHalf(inputBytes, i * 2);
break;
case VertexFormat.kVertexFormatUNorm8:
case VertexFormat.UNorm8:
result[i] = inputBytes[i] / 255f;
break;
case VertexFormat.kVertexFormatSNorm8:
case VertexFormat.SNorm8:
result[i] = Math.Max((sbyte)inputBytes[i] / 127f, -1f);
break;
case VertexFormat.kVertexFormatUNorm16:
case VertexFormat.UNorm16:
result[i] = BitConverter.ToUInt16(inputBytes, i * 2) / 65535f;
break;
case VertexFormat.kVertexFormatSNorm16:
case VertexFormat.SNorm16:
result[i] = Math.Max(BitConverter.ToInt16(inputBytes, i * 2) / 32767f, -1f);
break;
}
@@ -1363,16 +1368,16 @@ namespace AssetStudio
{
switch (format)
{
case VertexFormat.kVertexFormatUInt8:
case VertexFormat.kVertexFormatSInt8:
case VertexFormat.UInt8:
case VertexFormat.SInt8:
result[i] = inputBytes[i];
break;
case VertexFormat.kVertexFormatUInt16:
case VertexFormat.kVertexFormatSInt16:
case VertexFormat.UInt16:
case VertexFormat.SInt16:
result[i] = BitConverter.ToInt16(inputBytes, i * 2);
break;
case VertexFormat.kVertexFormatUInt32:
case VertexFormat.kVertexFormatSInt32:
case VertexFormat.UInt32:
case VertexFormat.SInt32:
result[i] = BitConverter.ToInt32(inputBytes, i * 4);
break;
}

View File

@@ -13,7 +13,7 @@ namespace AssetStudio
public PPtr(ObjectReader reader)
{
m_FileID = reader.ReadInt32();
m_PathID = reader.m_Version < SerializedFileFormatVersion.kUnknown_14 ? reader.ReadInt32() : reader.ReadInt64();
m_PathID = reader.m_Version < SerializedFileFormatVersion.Unknown_14 ? reader.ReadInt32() : reader.ReadInt64();
assetsFile = reader.assetsFile;
}

View File

@@ -56,15 +56,14 @@ namespace AssetStudio
}
public enum TextureDimension
{
kTexDimUnknown = -1,
kTexDimNone = 0,
kTexDimAny = 1,
kTexDim2D = 2,
kTexDim3D = 3,
kTexDimCUBE = 4,
kTexDim2DArray = 5,
kTexDimCubeArray = 6,
kTexDimForce32Bit = 2147483647
Unknown = -1,
None = 0,
Any = 1,
Tex2D = 2,
Tex3D = 3,
Cube = 4,
Tex2DArray = 5,
CubeArray = 6
};
public class SerializedTextureProperty
@@ -81,11 +80,12 @@ namespace AssetStudio
public enum SerializedPropertyType
{
kColor = 0,
kVector = 1,
kFloat = 2,
kRange = 3,
kTexture = 4
Color = 0,
Vector = 1,
Float = 2,
Range = 3,
Texture = 4,
Int = 5
};
public class SerializedProperty
@@ -195,11 +195,11 @@ namespace AssetStudio
public enum FogMode
{
kFogUnknown = -1,
kFogDisabled = 0,
kFogLinear = 1,
kFogExp = 2,
kFogExp2 = 3
Unknown = -1,
Disabled = 0,
Linear = 1,
Exp = 2,
Exp2 = 3
};
public class SerializedShaderState
@@ -428,6 +428,7 @@ namespace AssetStudio
if ((version[0] == 2020 && version[1] > 3) ||
(version[0] == 2020 && version[1] == 3 && version[2] >= 2) || //2020.3.2f1 and up
(version[0] > 2021) ||
(version[0] == 2021 && version[1] > 1) ||
(version[0] == 2021 && version[1] == 1 && version[2] >= 4)) //2021.1.4f1 and up
{
@@ -453,38 +454,39 @@ namespace AssetStudio
public enum ShaderGpuProgramType
{
kShaderGpuProgramUnknown = 0,
kShaderGpuProgramGLLegacy = 1,
kShaderGpuProgramGLES31AEP = 2,
kShaderGpuProgramGLES31 = 3,
kShaderGpuProgramGLES3 = 4,
kShaderGpuProgramGLES = 5,
kShaderGpuProgramGLCore32 = 6,
kShaderGpuProgramGLCore41 = 7,
kShaderGpuProgramGLCore43 = 8,
kShaderGpuProgramDX9VertexSM20 = 9,
kShaderGpuProgramDX9VertexSM30 = 10,
kShaderGpuProgramDX9PixelSM20 = 11,
kShaderGpuProgramDX9PixelSM30 = 12,
kShaderGpuProgramDX10Level9Vertex = 13,
kShaderGpuProgramDX10Level9Pixel = 14,
kShaderGpuProgramDX11VertexSM40 = 15,
kShaderGpuProgramDX11VertexSM50 = 16,
kShaderGpuProgramDX11PixelSM40 = 17,
kShaderGpuProgramDX11PixelSM50 = 18,
kShaderGpuProgramDX11GeometrySM40 = 19,
kShaderGpuProgramDX11GeometrySM50 = 20,
kShaderGpuProgramDX11HullSM50 = 21,
kShaderGpuProgramDX11DomainSM50 = 22,
kShaderGpuProgramMetalVS = 23,
kShaderGpuProgramMetalFS = 24,
kShaderGpuProgramSPIRV = 25,
kShaderGpuProgramConsoleVS = 26,
kShaderGpuProgramConsoleFS = 27,
kShaderGpuProgramConsoleHS = 28,
kShaderGpuProgramConsoleDS = 29,
kShaderGpuProgramConsoleGS = 30,
kShaderGpuProgramRayTracing = 31,
Unknown = 0,
GLLegacy = 1,
GLES31AEP = 2,
GLES31 = 3,
GLES3 = 4,
GLES = 5,
GLCore32 = 6,
GLCore41 = 7,
GLCore43 = 8,
DX9VertexSM20 = 9,
DX9VertexSM30 = 10,
DX9PixelSM20 = 11,
DX9PixelSM30 = 12,
DX10Level9Vertex = 13,
DX10Level9Pixel = 14,
DX11VertexSM40 = 15,
DX11VertexSM50 = 16,
DX11PixelSM40 = 17,
DX11PixelSM50 = 18,
DX11GeometrySM40 = 19,
DX11GeometrySM50 = 20,
DX11HullSM50 = 21,
DX11DomainSM50 = 22,
MetalVS = 23,
MetalFS = 24,
SPIRV = 25,
ConsoleVS = 26,
ConsoleFS = 27,
ConsoleHS = 28,
ConsoleDS = 29,
ConsoleGS = 30,
RayTracing = 31,
PS5NGGC = 32
};
public class SerializedProgramParameters
@@ -604,8 +606,9 @@ namespace AssetStudio
if ((version[0] == 2020 && version[1] > 3) ||
(version[0] == 2020 && version[1] == 3 && version[2] >= 2) || //2020.3.2f1 and up
(version[0] > 2021) ||
(version[0] == 2021 && version[1] > 1) ||
(version[0] == 2021 && version[1] == 1 && version[2] >= 4)) //2021.1.4f1 and up
(version[0] == 2021 && version[1] == 1 && version[2] >= 1)) //2021.1.1f1 and up
{
m_Parameters = new SerializedProgramParameters(reader);
}
@@ -689,6 +692,7 @@ namespace AssetStudio
{
public SerializedSubProgram[] m_SubPrograms;
public SerializedProgramParameters m_CommonParameters;
public ushort[] m_SerializedKeywordStateMask;
public SerializedProgram(ObjectReader reader)
{
@@ -703,19 +707,26 @@ namespace AssetStudio
if ((version[0] == 2020 && version[1] > 3) ||
(version[0] == 2020 && version[1] == 3 && version[2] >= 2) || //2020.3.2f1 and up
(version[0] > 2021) ||
(version[0] == 2021 && version[1] > 1) ||
(version[0] == 2021 && version[1] == 1 && version[2] >= 4)) //2021.1.4f1 and up
(version[0] == 2021 && version[1] == 1 && version[2] >= 1)) //2021.1.1f1 and up
{
m_CommonParameters = new SerializedProgramParameters(reader);
}
if (version[0] > 2022 || (version[0] == 2022 && version[1] >= 1)) //2022.1 and up
{
m_SerializedKeywordStateMask = reader.ReadUInt16Array();
reader.AlignStream();
}
}
}
public enum PassType
{
kPassTypeNormal = 0,
kPassTypeUse = 1,
kPassTypeGrab = 2
Normal = 0,
Use = 1,
Grab = 2
};
public class SerializedPass
@@ -794,7 +805,7 @@ namespace AssetStudio
m_Name = reader.ReadAlignedString();
m_TextureName = reader.ReadAlignedString();
m_Tags = new SerializedTagMap(reader);
if (version[0] > 2021 || (version[0] == 2021 && version[1] >= 2)) //2021.2 and up
if (version[0] == 2021 && version[1] >= 2) //2021.2 ~2021.x
{
m_SerializedKeywordStateMask = reader.ReadUInt16Array();
reader.AlignStream();
@@ -922,32 +933,32 @@ namespace AssetStudio
public enum ShaderCompilerPlatform
{
kShaderCompPlatformNone = -1,
kShaderCompPlatformGL = 0,
kShaderCompPlatformD3D9 = 1,
kShaderCompPlatformXbox360 = 2,
kShaderCompPlatformPS3 = 3,
kShaderCompPlatformD3D11 = 4,
kShaderCompPlatformGLES20 = 5,
kShaderCompPlatformNaCl = 6,
kShaderCompPlatformFlash = 7,
kShaderCompPlatformD3D11_9x = 8,
kShaderCompPlatformGLES3Plus = 9,
kShaderCompPlatformPSP2 = 10,
kShaderCompPlatformPS4 = 11,
kShaderCompPlatformXboxOne = 12,
kShaderCompPlatformPSM = 13,
kShaderCompPlatformMetal = 14,
kShaderCompPlatformOpenGLCore = 15,
kShaderCompPlatformN3DS = 16,
kShaderCompPlatformWiiU = 17,
kShaderCompPlatformVulkan = 18,
kShaderCompPlatformSwitch = 19,
kShaderCompPlatformXboxOneD3D12 = 20,
kShaderCompPlatformGameCoreXboxOne = 21,
kShaderCompPlatformGameCoreScarlett = 22,
kShaderCompPlatformPS5 = 23,
kShaderCompPlatformPS5NGGC = 24,
None = -1,
GL = 0,
D3D9 = 1,
Xbox360 = 2,
PS3 = 3,
D3D11 = 4,
GLES20 = 5,
NaCl = 6,
Flash = 7,
D3D11_9x = 8,
GLES3Plus = 9,
PSP2 = 10,
PS4 = 11,
XboxOne = 12,
PSM = 13,
Metal = 14,
OpenGLCore = 15,
N3DS = 16,
WiiU = 17,
Vulkan = 18,
Switch = 19,
XboxOneD3D12 = 20,
GameCoreXboxOne = 21,
GameCoreScarlett = 22,
PS5 = 23,
PS5NGGC = 24
};
public class Shader : NamedObject
@@ -959,9 +970,9 @@ namespace AssetStudio
//5.5 and up
public SerializedShader m_ParsedForm;
public ShaderCompilerPlatform[] platforms;
public uint[] offsets;
public uint[] compressedLengths;
public uint[] decompressedLengths;
public uint[][] offsets;
public uint[][] compressedLengths;
public uint[][] decompressedLengths;
public byte[] compressedBlob;
public Shader(ObjectReader reader) : base(reader)
@@ -972,15 +983,15 @@ namespace AssetStudio
platforms = reader.ReadUInt32Array().Select(x => (ShaderCompilerPlatform)x).ToArray();
if (version[0] > 2019 || (version[0] == 2019 && version[1] >= 3)) //2019.3 and up
{
offsets = reader.ReadUInt32ArrayArray().Select(x => x[0]).ToArray();
compressedLengths = reader.ReadUInt32ArrayArray().Select(x => x[0]).ToArray();
decompressedLengths = reader.ReadUInt32ArrayArray().Select(x => x[0]).ToArray();
offsets = reader.ReadUInt32ArrayArray();
compressedLengths = reader.ReadUInt32ArrayArray();
decompressedLengths = reader.ReadUInt32ArrayArray();
}
else
{
offsets = reader.ReadUInt32Array();
compressedLengths = reader.ReadUInt32Array();
decompressedLengths = reader.ReadUInt32Array();
offsets = reader.ReadUInt32Array().Select(x => new[] { x }).ToArray();
compressedLengths = reader.ReadUInt32Array().Select(x => new[] { x }).ToArray();
decompressedLengths = reader.ReadUInt32Array().Select(x => new[] { x }).ToArray();
}
compressedBlob = reader.ReadUInt8Array();
reader.AlignStream();

View File

@@ -18,23 +18,23 @@ namespace AssetStudio
public enum SpritePackingRotation
{
kSPRNone = 0,
kSPRFlipHorizontal = 1,
kSPRFlipVertical = 2,
kSPRRotate180 = 3,
kSPRRotate90 = 4
None = 0,
FlipHorizontal = 1,
FlipVertical = 2,
Rotate180 = 3,
Rotate90 = 4
};
public enum SpritePackingMode
{
kSPMTight = 0,
kSPMRectangle
Tight = 0,
Rectangle
};
public enum SpriteMeshType
{
kSpriteMeshTypeFullRect,
kSpriteMeshTypeTight
FullRect,
Tight
};
public class SpriteSettings
@@ -197,7 +197,7 @@ namespace AssetStudio
public Vector2 m_Offset;
public Vector4 m_Border;
public float m_PixelsToUnits;
public Vector2 m_Pivot;
public Vector2 m_Pivot = new Vector2(0.5f, 0.5f);
public uint m_Extrude;
public bool m_IsPolygon;
public KeyValuePair<Guid, long> m_RenderDataKey;

View File

@@ -46,6 +46,7 @@ namespace AssetStudio
{
public PPtr<Sprite>[] m_PackedSprites;
public Dictionary<KeyValuePair<Guid, long>, SpriteAtlasData> m_RenderDataMap;
public bool m_IsVariant;
public SpriteAtlas(ObjectReader reader) : base(reader)
{
@@ -67,8 +68,9 @@ namespace AssetStudio
var value = new SpriteAtlasData(reader);
m_RenderDataMap.Add(new KeyValuePair<Guid, long>(first, second), value);
}
//string m_Tag
//bool m_IsVariant
var m_Tag = reader.ReadAlignedString();
m_IsVariant = reader.ReadBoolean();
reader.AlignStream();
}
}
}

View File

@@ -151,10 +151,13 @@ namespace AssetStudio
RGB24,
RGBA32,
ARGB32,
RGB565 = 7,
R16 = 9,
ARGBFloat,
RGB565,
BGR24,
R16,
DXT1,
DXT5 = 12,
DXT3,
DXT5,
RGBA4444,
BGRA32,
RHalf,
@@ -165,11 +168,12 @@ namespace AssetStudio
RGBAFloat,
YUY2,
RGB9e5Float,
BC4 = 26,
BC5,
BC6H = 24,
RGBFloat,
BC6H,
BC7,
DXT1Crunched = 28,
BC4,
BC5,
DXT1Crunched,
DXT5Crunched,
PVRTC_RGB2,
PVRTC_RGBA2,

View File

@@ -21,22 +21,27 @@ namespace AssetStudio
public ResourceReader m_VideoData;
public string m_OriginalPath;
public StreamedResource m_ExternalResources;
public uint Width;
public uint Height;
public double m_FrameRate;
public int m_Format;
public bool m_HasSplitAlpha;
public VideoClip(ObjectReader reader) : base(reader)
{
m_OriginalPath = reader.ReadAlignedString();
var m_ProxyWidth = reader.ReadUInt32();
var m_ProxyHeight = reader.ReadUInt32();
var Width = reader.ReadUInt32();
var Height = reader.ReadUInt32();
Width = reader.ReadUInt32();
Height = reader.ReadUInt32();
if (version[0] > 2017 || (version[0] == 2017 && version[1] >= 2)) //2017.2 and up
{
var m_PixelAspecRatioNum = reader.ReadUInt32();
var m_PixelAspecRatioDen = reader.ReadUInt32();
}
var m_FrameRate = reader.ReadDouble();
m_FrameRate = reader.ReadDouble();
var m_FrameCount = reader.ReadUInt64();
var m_Format = reader.ReadInt32();
m_Format = reader.ReadInt32();
var m_AudioChannelCount = reader.ReadUInt16Array();
reader.AlignStream();
var m_AudioSampleRate = reader.ReadUInt32Array();
@@ -51,7 +56,7 @@ namespace AssetStudio
}
}
m_ExternalResources = new StreamedResource(reader);
var m_HasSplitAlpha = reader.ReadBoolean();
m_HasSplitAlpha = reader.ReadBoolean();
if (version[0] >= 2020) //2020.1 and up
{
var m_sRGB = reader.ReadBoolean();

View File

@@ -1,23 +1,19 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Buffers.Binary;
using System.IO;
namespace AssetStudio
{
public enum EndianType
{
LittleEndian,
BigEndian
}
public class EndianBinaryReader : BinaryReader
{
public EndianType endian;
private readonly byte[] buffer;
public EndianType Endian;
public EndianBinaryReader(Stream stream, EndianType endian = EndianType.BigEndian) : base(stream)
{
this.endian = endian;
Endian = endian;
buffer = new byte[8];
}
public long Position
@@ -28,88 +24,82 @@ namespace AssetStudio
public override short ReadInt16()
{
if (endian == EndianType.BigEndian)
if (Endian == EndianType.BigEndian)
{
var buff = ReadBytes(2);
Array.Reverse(buff);
return BitConverter.ToInt16(buff, 0);
Read(buffer, 0, 2);
return BinaryPrimitives.ReadInt16BigEndian(buffer);
}
return base.ReadInt16();
}
public override int ReadInt32()
{
if (endian == EndianType.BigEndian)
if (Endian == EndianType.BigEndian)
{
var buff = ReadBytes(4);
Array.Reverse(buff);
return BitConverter.ToInt32(buff, 0);
Read(buffer, 0, 4);
return BinaryPrimitives.ReadInt32BigEndian(buffer);
}
return base.ReadInt32();
}
public override long ReadInt64()
{
if (endian == EndianType.BigEndian)
if (Endian == EndianType.BigEndian)
{
var buff = ReadBytes(8);
Array.Reverse(buff);
return BitConverter.ToInt64(buff, 0);
Read(buffer, 0, 8);
return BinaryPrimitives.ReadInt64BigEndian(buffer);
}
return base.ReadInt64();
}
public override ushort ReadUInt16()
{
if (endian == EndianType.BigEndian)
if (Endian == EndianType.BigEndian)
{
var buff = ReadBytes(2);
Array.Reverse(buff);
return BitConverter.ToUInt16(buff, 0);
Read(buffer, 0, 2);
return BinaryPrimitives.ReadUInt16BigEndian(buffer);
}
return base.ReadUInt16();
}
public override uint ReadUInt32()
{
if (endian == EndianType.BigEndian)
if (Endian == EndianType.BigEndian)
{
var buff = ReadBytes(4);
Array.Reverse(buff);
return BitConverter.ToUInt32(buff, 0);
Read(buffer, 0, 4);
return BinaryPrimitives.ReadUInt32BigEndian(buffer);
}
return base.ReadUInt32();
}
public override ulong ReadUInt64()
{
if (endian == EndianType.BigEndian)
if (Endian == EndianType.BigEndian)
{
var buff = ReadBytes(8);
Array.Reverse(buff);
return BitConverter.ToUInt64(buff, 0);
Read(buffer, 0, 8);
return BinaryPrimitives.ReadUInt64BigEndian(buffer);
}
return base.ReadUInt64();
}
public override float ReadSingle()
{
if (endian == EndianType.BigEndian)
if (Endian == EndianType.BigEndian)
{
var buff = ReadBytes(4);
Array.Reverse(buff);
return BitConverter.ToSingle(buff, 0);
Read(buffer, 0, 4);
Array.Reverse(buffer, 0, 4);
return BitConverter.ToSingle(buffer, 0);
}
return base.ReadSingle();
}
public override double ReadDouble()
{
if (endian == EndianType.BigEndian)
if (Endian == EndianType.BigEndian)
{
var buff = ReadBytes(8);
Array.Reverse(buff);
return BitConverter.ToUInt64(buff, 0);
Read(buffer, 0, 8);
Array.Reverse(buffer);
return BitConverter.ToDouble(buffer, 0);
}
return base.ReadDouble();
}

14
AssetStudio/EndianType.cs Normal file
View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AssetStudio
{
public enum EndianType
{
LittleEndian,
BigEndian
}
}

View File

@@ -11,6 +11,8 @@ namespace AssetStudio
private static readonly byte[] gzipMagic = { 0x1f, 0x8b };
private static readonly byte[] brotliMagic = { 0x62, 0x72, 0x6F, 0x74, 0x6C, 0x69 };
private static readonly byte[] zipMagic = { 0x50, 0x4B, 0x03, 0x04 };
private static readonly byte[] zipSpannedMagic = { 0x50, 0x4B, 0x07, 0x08 };
public FileReader(string path) : this(path, File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { }
@@ -36,7 +38,7 @@ namespace AssetStudio
return FileType.WebFile;
default:
{
var magic = ReadBytes(2);
byte[] magic = ReadBytes(2);
Position = 0;
if (gzipMagic.SequenceEqual(magic))
{
@@ -53,10 +55,11 @@ namespace AssetStudio
{
return FileType.AssetsFile;
}
else
{
return FileType.ResourceFile;
}
magic = ReadBytes(4);
Position = 0;
if (zipMagic.SequenceEqual(magic) || zipSpannedMagic.SequenceEqual(magic))
return FileType.ZipFile;
return FileType.ResourceFile;
}
}
}

View File

@@ -13,6 +13,7 @@ namespace AssetStudio
WebFile,
ResourceFile,
GZipFile,
BrotliFile
BrotliFile,
ZipFile
}
}

View File

@@ -73,6 +73,28 @@ namespace AssetStudio
return null;
}
public ImportedFrame FindRelativeFrameWithPath(string path)
{
var subs = path.Split(new[] { '/' }, 2);
foreach (var child in children)
{
if (child.Name == subs[0])
{
if (subs.Length == 1)
{
return child;
}
else
{
var result = child.FindRelativeFrameWithPath(subs[1]);
if (result != null)
return result;
}
}
}
return null;
}
public ImportedFrame FindFrame(string name)
{
if (Name == name)

View File

@@ -16,11 +16,11 @@ namespace AssetStudio
public interface ILogger
{
void Log(LoggerEvent loggerEvent, string message);
void Log(LoggerEvent loggerEvent, string message, bool ignoreLevel = false);
}
public sealed class DummyLogger : ILogger
{
public void Log(LoggerEvent loggerEvent, string message) { }
public void Log(LoggerEvent loggerEvent, string message, bool ignoreLevel) { }
}
}

View File

@@ -1,17 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AssetStudio
{
public interface IProgress
{
void Report(int value);
}
public sealed class DummyProgress : IProgress
{
public void Report(int value) { }
}
}

View File

@@ -19,6 +19,7 @@ namespace AssetStudio
{
var sb = new StringBuilder();
sb.AppendLine(message);
sb.AppendLine();
sb.AppendLine(e.ToString());
Default.Log(LoggerEvent.Error, sb.ToString());
}

View File

@@ -1,540 +0,0 @@
#define CHECK_ARGS
#define CHECK_EOF
//#define LOCAL_SHADOW
using System;
using System.IO;
namespace Lz4
{
public class Lz4DecoderStream : Stream
{
public Lz4DecoderStream(Stream input, long inputLength = long.MaxValue)
{
Reset(input, inputLength);
}
private void Reset(Stream input, long inputLength = long.MaxValue)
{
this.inputLength = inputLength;
this.input = input;
phase = DecodePhase.ReadToken;
decodeBufferPos = 0;
litLen = 0;
matLen = 0;
matDst = 0;
inBufPos = DecBufLen;
inBufEnd = DecBufLen;
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing && input != null)
{
input.Close();
}
input = null;
decodeBuffer = null;
}
finally
{
base.Dispose(disposing);
}
}
private long inputLength;
private Stream input;
//because we might not be able to match back across invocations,
//we have to keep the last window's worth of bytes around for reuse
//we use a circular buffer for this - every time we write into this
//buffer, we also write the same into our output buffer
private const int DecBufLen = 0x10000;
private const int DecBufMask = 0xFFFF;
private const int InBufLen = 128;
private byte[] decodeBuffer = new byte[DecBufLen + InBufLen];
private int decodeBufferPos, inBufPos, inBufEnd;
//we keep track of which phase we're in so that we can jump right back
//into the correct part of decoding
private DecodePhase phase;
private enum DecodePhase
{
ReadToken,
ReadExLiteralLength,
CopyLiteral,
ReadOffset,
ReadExMatchLength,
CopyMatch,
}
//state within interruptable phases and across phase boundaries is
//kept here - again, so that we can punt out and restart freely
private int litLen, matLen, matDst;
public override int Read(byte[] buffer, int offset, int count)
{
#if CHECK_ARGS
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0 || count < 0 || buffer.Length - count < offset)
throw new ArgumentOutOfRangeException();
if (input == null)
throw new InvalidOperationException();
#endif
int nRead, nToRead = count;
var decBuf = decodeBuffer;
//the stringy gotos are obnoxious, but their purpose is to
//make it *blindingly* obvious how the state machine transitions
//back and forth as it reads - remember, we can yield out of
//this routine in several places, and we must be able to re-enter
//and pick up where we left off!
#if LOCAL_SHADOW
var phase = this.phase;
var inBufPos = this.inBufPos;
var inBufEnd = this.inBufEnd;
#endif
switch (phase)
{
case DecodePhase.ReadToken:
goto readToken;
case DecodePhase.ReadExLiteralLength:
goto readExLiteralLength;
case DecodePhase.CopyLiteral:
goto copyLiteral;
case DecodePhase.ReadOffset:
goto readOffset;
case DecodePhase.ReadExMatchLength:
goto readExMatchLength;
case DecodePhase.CopyMatch:
goto copyMatch;
}
readToken:
int tok;
if (inBufPos < inBufEnd)
{
tok = decBuf[inBufPos++];
}
else
{
#if LOCAL_SHADOW
this.inBufPos = inBufPos;
#endif
tok = ReadByteCore();
#if LOCAL_SHADOW
inBufPos = this.inBufPos;
inBufEnd = this.inBufEnd;
#endif
#if CHECK_EOF
if (tok == -1)
goto finish;
#endif
}
litLen = tok >> 4;
matLen = (tok & 0xF) + 4;
switch (litLen)
{
case 0:
phase = DecodePhase.ReadOffset;
goto readOffset;
case 0xF:
phase = DecodePhase.ReadExLiteralLength;
goto readExLiteralLength;
default:
phase = DecodePhase.CopyLiteral;
goto copyLiteral;
}
readExLiteralLength:
int exLitLen;
if (inBufPos < inBufEnd)
{
exLitLen = decBuf[inBufPos++];
}
else
{
#if LOCAL_SHADOW
this.inBufPos = inBufPos;
#endif
exLitLen = ReadByteCore();
#if LOCAL_SHADOW
inBufPos = this.inBufPos;
inBufEnd = this.inBufEnd;
#endif
#if CHECK_EOF
if (exLitLen == -1)
goto finish;
#endif
}
litLen += exLitLen;
if (exLitLen == 255)
goto readExLiteralLength;
phase = DecodePhase.CopyLiteral;
goto copyLiteral;
copyLiteral:
int nReadLit = litLen < nToRead ? litLen : nToRead;
if (nReadLit != 0)
{
if (inBufPos + nReadLit <= inBufEnd)
{
int ofs = offset;
for (int c = nReadLit; c-- != 0;)
buffer[ofs++] = decBuf[inBufPos++];
nRead = nReadLit;
}
else
{
#if LOCAL_SHADOW
this.inBufPos = inBufPos;
#endif
nRead = ReadCore(buffer, offset, nReadLit);
#if LOCAL_SHADOW
inBufPos = this.inBufPos;
inBufEnd = this.inBufEnd;
#endif
#if CHECK_EOF
if (nRead == 0)
goto finish;
#endif
}
offset += nRead;
nToRead -= nRead;
litLen -= nRead;
if (litLen != 0)
goto copyLiteral;
}
if (nToRead == 0)
goto finish;
phase = DecodePhase.ReadOffset;
goto readOffset;
readOffset:
if (inBufPos + 1 < inBufEnd)
{
matDst = (decBuf[inBufPos + 1] << 8) | decBuf[inBufPos];
inBufPos += 2;
}
else
{
#if LOCAL_SHADOW
this.inBufPos = inBufPos;
#endif
matDst = ReadOffsetCore();
#if LOCAL_SHADOW
inBufPos = this.inBufPos;
inBufEnd = this.inBufEnd;
#endif
#if CHECK_EOF
if (matDst == -1)
goto finish;
#endif
}
if (matLen == 15 + 4)
{
phase = DecodePhase.ReadExMatchLength;
goto readExMatchLength;
}
else
{
phase = DecodePhase.CopyMatch;
goto copyMatch;
}
readExMatchLength:
int exMatLen;
if (inBufPos < inBufEnd)
{
exMatLen = decBuf[inBufPos++];
}
else
{
#if LOCAL_SHADOW
this.inBufPos = inBufPos;
#endif
exMatLen = ReadByteCore();
#if LOCAL_SHADOW
inBufPos = this.inBufPos;
inBufEnd = this.inBufEnd;
#endif
#if CHECK_EOF
if (exMatLen == -1)
goto finish;
#endif
}
matLen += exMatLen;
if (exMatLen == 255)
goto readExMatchLength;
phase = DecodePhase.CopyMatch;
goto copyMatch;
copyMatch:
int nCpyMat = matLen < nToRead ? matLen : nToRead;
if (nCpyMat != 0)
{
nRead = count - nToRead;
int bufDst = matDst - nRead;
if (bufDst > 0)
{
//offset is fairly far back, we need to pull from the buffer
int bufSrc = decodeBufferPos - bufDst;
if (bufSrc < 0)
bufSrc += DecBufLen;
int bufCnt = bufDst < nCpyMat ? bufDst : nCpyMat;
for (int c = bufCnt; c-- != 0;)
buffer[offset++] = decBuf[bufSrc++ & DecBufMask];
}
else
{
bufDst = 0;
}
int sOfs = offset - matDst;
for (int i = bufDst; i < nCpyMat; i++)
buffer[offset++] = buffer[sOfs++];
nToRead -= nCpyMat;
matLen -= nCpyMat;
}
if (nToRead == 0)
goto finish;
phase = DecodePhase.ReadToken;
goto readToken;
finish:
nRead = count - nToRead;
int nToBuf = nRead < DecBufLen ? nRead : DecBufLen;
int repPos = offset - nToBuf;
if (nToBuf == DecBufLen)
{
Buffer.BlockCopy(buffer, repPos, decBuf, 0, DecBufLen);
decodeBufferPos = 0;
}
else
{
int decPos = decodeBufferPos;
while (nToBuf-- != 0)
decBuf[decPos++ & DecBufMask] = buffer[repPos++];
decodeBufferPos = decPos & DecBufMask;
}
#if LOCAL_SHADOW
this.phase = phase;
this.inBufPos = inBufPos;
#endif
return nRead;
}
private int ReadByteCore()
{
var buf = decodeBuffer;
if (inBufPos == inBufEnd)
{
int nRead = input.Read(buf, DecBufLen,
InBufLen < inputLength ? InBufLen : (int)inputLength);
#if CHECK_EOF
if (nRead == 0)
return -1;
#endif
inputLength -= nRead;
inBufPos = DecBufLen;
inBufEnd = DecBufLen + nRead;
}
return buf[inBufPos++];
}
private int ReadOffsetCore()
{
var buf = decodeBuffer;
if (inBufPos == inBufEnd)
{
int nRead = input.Read(buf, DecBufLen,
InBufLen < inputLength ? InBufLen : (int)inputLength);
#if CHECK_EOF
if (nRead == 0)
return -1;
#endif
inputLength -= nRead;
inBufPos = DecBufLen;
inBufEnd = DecBufLen + nRead;
}
if (inBufEnd - inBufPos == 1)
{
buf[DecBufLen] = buf[inBufPos];
int nRead = input.Read(buf, DecBufLen + 1,
InBufLen - 1 < inputLength ? InBufLen - 1 : (int)inputLength);
#if CHECK_EOF
if (nRead == 0)
{
inBufPos = DecBufLen;
inBufEnd = DecBufLen + 1;
return -1;
}
#endif
inputLength -= nRead;
inBufPos = DecBufLen;
inBufEnd = DecBufLen + nRead + 1;
}
int ret = (buf[inBufPos + 1] << 8) | buf[inBufPos];
inBufPos += 2;
return ret;
}
private int ReadCore(byte[] buffer, int offset, int count)
{
int nToRead = count;
var buf = decodeBuffer;
int inBufLen = inBufEnd - inBufPos;
int fromBuf = nToRead < inBufLen ? nToRead : inBufLen;
if (fromBuf != 0)
{
var bufPos = inBufPos;
for (int c = fromBuf; c-- != 0;)
buffer[offset++] = buf[bufPos++];
inBufPos = bufPos;
nToRead -= fromBuf;
}
if (nToRead != 0)
{
int nRead;
if (nToRead >= InBufLen)
{
nRead = input.Read(buffer, offset,
nToRead < inputLength ? nToRead : (int)inputLength);
nToRead -= nRead;
}
else
{
nRead = input.Read(buf, DecBufLen,
InBufLen < inputLength ? InBufLen : (int)inputLength);
inBufPos = DecBufLen;
inBufEnd = DecBufLen + nRead;
fromBuf = nToRead < nRead ? nToRead : nRead;
var bufPos = inBufPos;
for (int c = fromBuf; c-- != 0;)
buffer[offset++] = buf[bufPos++];
inBufPos = bufPos;
nToRead -= fromBuf;
}
inputLength -= nRead;
}
return count - nToRead;
}
#region Stream internals
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override void Flush()
{
}
public override long Length => throw new NotSupportedException();
public override long Position
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
#endregion
}
}

View File

@@ -20,7 +20,7 @@ namespace AssetStudio
public int[] version => assetsFile.version;
public BuildType buildType => assetsFile.buildType;
public ObjectReader(EndianBinaryReader reader, SerializedFile assetsFile, ObjectInfo objectInfo) : base(reader.BaseStream, reader.endian)
public ObjectReader(EndianBinaryReader reader, SerializedFile assetsFile, ObjectInfo objectInfo) : base(reader.BaseStream, reader.Endian)
{
this.assetsFile = assetsFile;
m_PathID = objectInfo.m_PathID;

View File

@@ -1,8 +1,10 @@
namespace AssetStudio
using System;
namespace AssetStudio
{
public static class Progress
{
public static IProgress Default = new DummyProgress();
public static IProgress<int> Default = new Progress<int>();
private static int preValue;
public static void Reset()

View File

@@ -11,6 +11,8 @@ namespace AssetStudio
private long size;
private BinaryReader reader;
public int Size { get => (int)size; }
public ResourceReader(string path, SerializedFile assetsFile, long offset, long size)
{
needSearch = true;
@@ -69,6 +71,13 @@ namespace AssetStudio
return binaryReader.ReadBytes((int)size);
}
public void GetData(byte[] buff)
{
var binaryReader = GetReader();
binaryReader.BaseStream.Position = offset;
binaryReader.Read(buff, 0, (int)size);
}
public void WriteData(string path)
{
var binaryReader = GetReader();

View File

@@ -45,7 +45,7 @@ namespace AssetStudio
header.m_Version = (SerializedFileFormatVersion)reader.ReadUInt32();
header.m_DataOffset = reader.ReadUInt32();
if (header.m_Version >= SerializedFileFormatVersion.kUnknown_9)
if (header.m_Version >= SerializedFileFormatVersion.Unknown_9)
{
header.m_Endianess = reader.ReadByte();
header.m_Reserved = reader.ReadBytes(3);
@@ -57,7 +57,7 @@ namespace AssetStudio
m_FileEndianess = reader.ReadByte();
}
if (header.m_Version >= SerializedFileFormatVersion.kLargeFilesSupport)
if (header.m_Version >= SerializedFileFormatVersion.LargeFilesSupport)
{
header.m_MetadataSize = reader.ReadUInt32();
header.m_FileSize = reader.ReadInt64();
@@ -68,14 +68,14 @@ namespace AssetStudio
// ReadMetadata
if (m_FileEndianess == 0)
{
reader.endian = EndianType.LittleEndian;
reader.Endian = EndianType.LittleEndian;
}
if (header.m_Version >= SerializedFileFormatVersion.kUnknown_7)
if (header.m_Version >= SerializedFileFormatVersion.Unknown_7)
{
unityVersion = reader.ReadStringToNull();
SetVersion(unityVersion);
}
if (header.m_Version >= SerializedFileFormatVersion.kUnknown_8)
if (header.m_Version >= SerializedFileFormatVersion.Unknown_8)
{
m_TargetPlatform = (BuildTarget)reader.ReadInt32();
if (!Enum.IsDefined(typeof(BuildTarget), m_TargetPlatform))
@@ -83,7 +83,7 @@ namespace AssetStudio
m_TargetPlatform = BuildTarget.UnknownPlatform;
}
}
if (header.m_Version >= SerializedFileFormatVersion.kHasTypeTreeHashes)
if (header.m_Version >= SerializedFileFormatVersion.HasTypeTreeHashes)
{
m_EnableTypeTree = reader.ReadBoolean();
}
@@ -96,7 +96,7 @@ namespace AssetStudio
m_Types.Add(ReadSerializedType(false));
}
if (header.m_Version >= SerializedFileFormatVersion.kUnknown_7 && header.m_Version < SerializedFileFormatVersion.kUnknown_14)
if (header.m_Version >= SerializedFileFormatVersion.Unknown_7 && header.m_Version < SerializedFileFormatVersion.Unknown_14)
{
bigIDEnabled = reader.ReadInt32();
}
@@ -113,7 +113,7 @@ namespace AssetStudio
{
objectInfo.m_PathID = reader.ReadInt64();
}
else if (header.m_Version < SerializedFileFormatVersion.kUnknown_14)
else if (header.m_Version < SerializedFileFormatVersion.Unknown_14)
{
objectInfo.m_PathID = reader.ReadInt32();
}
@@ -123,7 +123,7 @@ namespace AssetStudio
objectInfo.m_PathID = reader.ReadInt64();
}
if (header.m_Version >= SerializedFileFormatVersion.kLargeFilesSupport)
if (header.m_Version >= SerializedFileFormatVersion.LargeFilesSupport)
objectInfo.byteStart = reader.ReadInt64();
else
objectInfo.byteStart = reader.ReadUInt32();
@@ -131,7 +131,7 @@ namespace AssetStudio
objectInfo.byteStart += header.m_DataOffset;
objectInfo.byteSize = reader.ReadUInt32();
objectInfo.typeID = reader.ReadInt32();
if (header.m_Version < SerializedFileFormatVersion.kRefactoredClassId)
if (header.m_Version < SerializedFileFormatVersion.RefactoredClassId)
{
objectInfo.classID = reader.ReadUInt16();
objectInfo.serializedType = m_Types.Find(x => x.classID == objectInfo.typeID);
@@ -142,24 +142,24 @@ namespace AssetStudio
objectInfo.serializedType = type;
objectInfo.classID = type.classID;
}
if (header.m_Version < SerializedFileFormatVersion.kHasScriptTypeIndex)
if (header.m_Version < SerializedFileFormatVersion.HasScriptTypeIndex)
{
objectInfo.isDestroyed = reader.ReadUInt16();
}
if (header.m_Version >= SerializedFileFormatVersion.kHasScriptTypeIndex && header.m_Version < SerializedFileFormatVersion.kRefactorTypeData)
if (header.m_Version >= SerializedFileFormatVersion.HasScriptTypeIndex && header.m_Version < SerializedFileFormatVersion.RefactorTypeData)
{
var m_ScriptTypeIndex = reader.ReadInt16();
if (objectInfo.serializedType != null)
objectInfo.serializedType.m_ScriptTypeIndex = m_ScriptTypeIndex;
}
if (header.m_Version == SerializedFileFormatVersion.kSupportsStrippedObject || header.m_Version == SerializedFileFormatVersion.kRefactoredClassId)
if (header.m_Version == SerializedFileFormatVersion.SupportsStrippedObject || header.m_Version == SerializedFileFormatVersion.RefactoredClassId)
{
objectInfo.stripped = reader.ReadByte();
}
m_Objects.Add(objectInfo);
}
if (header.m_Version >= SerializedFileFormatVersion.kHasScriptTypeIndex)
if (header.m_Version >= SerializedFileFormatVersion.HasScriptTypeIndex)
{
int scriptCount = reader.ReadInt32();
m_ScriptTypes = new List<LocalSerializedObjectIdentifier>(scriptCount);
@@ -167,7 +167,7 @@ namespace AssetStudio
{
var m_ScriptType = new LocalSerializedObjectIdentifier();
m_ScriptType.localSerializedFileIndex = reader.ReadInt32();
if (header.m_Version < SerializedFileFormatVersion.kUnknown_14)
if (header.m_Version < SerializedFileFormatVersion.Unknown_14)
{
m_ScriptType.localIdentifierInFile = reader.ReadInt32();
}
@@ -185,11 +185,11 @@ namespace AssetStudio
for (int i = 0; i < externalsCount; i++)
{
var m_External = new FileIdentifier();
if (header.m_Version >= SerializedFileFormatVersion.kUnknown_6)
if (header.m_Version >= SerializedFileFormatVersion.Unknown_6)
{
var tempEmpty = reader.ReadStringToNull();
}
if (header.m_Version >= SerializedFileFormatVersion.kUnknown_5)
if (header.m_Version >= SerializedFileFormatVersion.Unknown_5)
{
m_External.guid = new Guid(reader.ReadBytes(16));
m_External.type = reader.ReadInt32();
@@ -199,7 +199,7 @@ namespace AssetStudio
m_Externals.Add(m_External);
}
if (header.m_Version >= SerializedFileFormatVersion.kSupportsRefObject)
if (header.m_Version >= SerializedFileFormatVersion.SupportsRefObject)
{
int refTypesCount = reader.ReadInt32();
m_RefTypes = new List<SerializedType>(refTypesCount);
@@ -209,7 +209,7 @@ namespace AssetStudio
}
}
if (header.m_Version >= SerializedFileFormatVersion.kUnknown_5)
if (header.m_Version >= SerializedFileFormatVersion.Unknown_5)
{
userInformation = reader.ReadStringToNull();
}
@@ -223,6 +223,10 @@ namespace AssetStudio
{
unityVersion = stringVersion;
var buildSplit = Regex.Replace(stringVersion, @"\d", "").Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries);
if (buildSplit.Length == 0)
throw new NotSupportedException("Specified Unity version is not in a correct format.\n" +
"Specify full Unity version, including letters at the end.\n" +
"Example: 2017.4.39f1");
buildType = new BuildType(buildSplit[0]);
var versionSplit = Regex.Replace(stringVersion, @"\D", ".").Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries);
version = versionSplit.Select(int.Parse).ToArray();
@@ -235,23 +239,23 @@ namespace AssetStudio
type.classID = reader.ReadInt32();
if (header.m_Version >= SerializedFileFormatVersion.kRefactoredClassId)
if (header.m_Version >= SerializedFileFormatVersion.RefactoredClassId)
{
type.m_IsStrippedType = reader.ReadBoolean();
}
if (header.m_Version >= SerializedFileFormatVersion.kRefactorTypeData)
if (header.m_Version >= SerializedFileFormatVersion.RefactorTypeData)
{
type.m_ScriptTypeIndex = reader.ReadInt16();
}
if (header.m_Version >= SerializedFileFormatVersion.kHasTypeTreeHashes)
if (header.m_Version >= SerializedFileFormatVersion.HasTypeTreeHashes)
{
if (isRefType && type.m_ScriptTypeIndex >= 0)
{
type.m_ScriptID = reader.ReadBytes(16);
}
else if ((header.m_Version < SerializedFileFormatVersion.kRefactoredClassId && type.classID < 0) || (header.m_Version >= SerializedFileFormatVersion.kRefactoredClassId && type.classID == 114))
else if ((header.m_Version < SerializedFileFormatVersion.RefactoredClassId && type.classID < 0) || (header.m_Version >= SerializedFileFormatVersion.RefactoredClassId && type.classID == 114))
{
type.m_ScriptID = reader.ReadBytes(16);
}
@@ -262,7 +266,7 @@ namespace AssetStudio
{
type.m_Type = new TypeTree();
type.m_Type.m_Nodes = new List<TypeTreeNode>();
if (header.m_Version >= SerializedFileFormatVersion.kUnknown_12 || header.m_Version == SerializedFileFormatVersion.kUnknown_10)
if (header.m_Version >= SerializedFileFormatVersion.Unknown_12 || header.m_Version == SerializedFileFormatVersion.Unknown_10)
{
TypeTreeBlobRead(type.m_Type);
}
@@ -270,7 +274,7 @@ namespace AssetStudio
{
ReadTypeTree(type.m_Type);
}
if (header.m_Version >= SerializedFileFormatVersion.kStoresTypeDependencies)
if (header.m_Version >= SerializedFileFormatVersion.StoresTypeDependencies)
{
if (isRefType)
{
@@ -296,17 +300,17 @@ namespace AssetStudio
typeTreeNode.m_Type = reader.ReadStringToNull();
typeTreeNode.m_Name = reader.ReadStringToNull();
typeTreeNode.m_ByteSize = reader.ReadInt32();
if (header.m_Version == SerializedFileFormatVersion.kUnknown_2)
if (header.m_Version == SerializedFileFormatVersion.Unknown_2)
{
var variableCount = reader.ReadInt32();
}
if (header.m_Version != SerializedFileFormatVersion.kUnknown_3)
if (header.m_Version != SerializedFileFormatVersion.Unknown_3)
{
typeTreeNode.m_Index = reader.ReadInt32();
}
typeTreeNode.m_TypeFlags = reader.ReadInt32();
typeTreeNode.m_Version = reader.ReadInt32();
if (header.m_Version != SerializedFileFormatVersion.kUnknown_3)
if (header.m_Version != SerializedFileFormatVersion.Unknown_3)
{
typeTreeNode.m_MetaFlag = reader.ReadInt32();
}
@@ -334,7 +338,7 @@ namespace AssetStudio
typeTreeNode.m_ByteSize = reader.ReadInt32();
typeTreeNode.m_Index = reader.ReadInt32();
typeTreeNode.m_MetaFlag = reader.ReadInt32();
if (header.m_Version >= SerializedFileFormatVersion.kTypeTreeNodeWithTypeFlags)
if (header.m_Version >= SerializedFileFormatVersion.TypeTreeNodeWithTypeFlags)
{
typeTreeNode.m_RefTypeHash = reader.ReadUInt64();
}

View File

@@ -8,80 +8,80 @@ namespace AssetStudio
{
public enum SerializedFileFormatVersion
{
kUnsupported = 1,
kUnknown_2 = 2,
kUnknown_3 = 3,
Unsupported = 1,
Unknown_2 = 2,
Unknown_3 = 3,
/// <summary>
/// 1.2.0 to 2.0.0
/// </summary>
kUnknown_5 = 5,
Unknown_5 = 5,
/// <summary>
/// 2.1.0 to 2.6.1
/// </summary>
kUnknown_6 = 6,
Unknown_6 = 6,
/// <summary>
/// 3.0.0b
/// </summary>
kUnknown_7 = 7,
Unknown_7 = 7,
/// <summary>
/// 3.0.0 to 3.4.2
/// </summary>
kUnknown_8 = 8,
Unknown_8 = 8,
/// <summary>
/// 3.5.0 to 4.7.2
/// </summary>
kUnknown_9 = 9,
Unknown_9 = 9,
/// <summary>
/// 5.0.0aunk1
/// </summary>
kUnknown_10 = 10,
Unknown_10 = 10,
/// <summary>
/// 5.0.0aunk2
/// </summary>
kHasScriptTypeIndex = 11,
HasScriptTypeIndex = 11,
/// <summary>
/// 5.0.0aunk3
/// </summary>
kUnknown_12 = 12,
Unknown_12 = 12,
/// <summary>
/// 5.0.0aunk4
/// </summary>
kHasTypeTreeHashes = 13,
HasTypeTreeHashes = 13,
/// <summary>
/// 5.0.0unk
/// </summary>
kUnknown_14 = 14,
Unknown_14 = 14,
/// <summary>
/// 5.0.1 to 5.4.0
/// </summary>
kSupportsStrippedObject = 15,
SupportsStrippedObject = 15,
/// <summary>
/// 5.5.0a
/// </summary>
kRefactoredClassId = 16,
RefactoredClassId = 16,
/// <summary>
/// 5.5.0unk to 2018.4
/// </summary>
kRefactorTypeData = 17,
RefactorTypeData = 17,
/// <summary>
/// 2019.1a
/// </summary>
kRefactorShareableTypeTreeData = 18,
RefactorShareableTypeTreeData = 18,
/// <summary>
/// 2019.1unk
/// </summary>
kTypeTreeNodeWithTypeFlags = 19,
TypeTreeNodeWithTypeFlags = 19,
/// <summary>
/// 2019.2
/// </summary>
kSupportsRefObject = 20,
SupportsRefObject = 20,
/// <summary>
/// 2019.3 to 2019.4
/// </summary>
kStoresTypeDependencies = 21,
StoresTypeDependencies = 21,
/// <summary>
/// 2020.1 to x
/// </summary>
kLargeFilesSupport = 22
LargeFilesSupport = 22
}
}

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Text;
@@ -39,9 +40,11 @@ namespace AssetStudio
value = reader.ReadSByte();
break;
case "UInt8":
case "char":
value = reader.ReadByte();
break;
case "char":
value = BitConverter.ToChar(reader.ReadBytes(2), 0);
break;
case "short":
case "SInt16":
value = reader.ReadInt16();
@@ -81,7 +84,8 @@ namespace AssetStudio
append = false;
var str = reader.ReadAlignedString();
sb.AppendFormat("{0}{1} {2} = \"{3}\"\r\n", (new string('\t', level)), varTypeStr, varNameStr, str);
i += 3;
var toSkip = GetNodes(m_Nodes, i);
i += toSkip.Count - 1;
break;
case "map":
{
@@ -190,9 +194,11 @@ namespace AssetStudio
value = reader.ReadSByte();
break;
case "UInt8":
case "char":
value = reader.ReadByte();
break;
case "char":
value = BitConverter.ToChar(reader.ReadBytes(2), 0);
break;
case "short":
case "SInt16":
value = reader.ReadInt16();
@@ -230,7 +236,8 @@ namespace AssetStudio
break;
case "string":
value = reader.ReadAlignedString();
i += 3;
var toSkip = GetNodes(m_Nodes, i);
i += toSkip.Count - 1;
break;
case "map":
{

View File

@@ -17,7 +17,7 @@ namespace AssetStudio
public WebFile(EndianBinaryReader reader)
{
reader.endian = EndianType.LittleEndian;
reader.Endian = EndianType.LittleEndian;
var signature = reader.ReadStringToNull();
var headLength = reader.ReadInt32();
var dataList = new List<WebData>();

View File

@@ -0,0 +1,96 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net472;net6.0;net7.0</TargetFrameworks>
<AssemblyTitle>AssetStudio Mod by VaDiM</AssemblyTitle>
<Version>0.16.48.1</Version>
<Copyright>Copyright © Perfare; Copyright © aelurum 2023</Copyright>
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>embedded</DebugType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AssetStudioUtility\AssetStudioUtility.csproj" />
<ProjectReference Include="..\AssetStudio\AssetStudio.csproj" />
</ItemGroup>
<!-- Use local compiled win-x86 and win-x64 Texture2DDecoder libs, because libs from Kyaru.Texture2DDecoder.Windows were compiled with /MD flag -->
<Target Name="CopyExtraFilesPortable" AfterTargets="AfterBuild" Condition=" '$(RuntimeIdentifier)' == '' ">
<Message Text="Copying windows extra files for $(TargetFramework)... " Importance="high" />
<Copy SourceFiles="$(SolutionDir)Texture2DDecoderNative\bin\Win32\$(Configuration)\Texture2DDecoderNative.dll" DestinationFolder="$(TargetDir)runtimes\win-x86\native" ContinueOnError="false" />
<Copy SourceFiles="$(SolutionDir)Texture2DDecoderNative\bin\x64\$(Configuration)\Texture2DDecoderNative.dll" DestinationFolder="$(TargetDir)runtimes\win-x64\native" ContinueOnError="false" />
<Copy SourceFiles="$(ProjectDir)Libraries\win-x86\fmod.dll" DestinationFolder="$(TargetDir)runtimes\win-x86\native" ContinueOnError="false" />
<Copy SourceFiles="$(ProjectDir)Libraries\win-x64\fmod.dll" DestinationFolder="$(TargetDir)runtimes\win-x64\native" ContinueOnError="false" />
</Target>
<Target Name="CopyExtraFilesPortableNet" AfterTargets="AfterBuild" Condition=" '$(RuntimeIdentifier)' == '' AND '$(TargetFramework)' != 'net472' ">
<Message Text="Copying other platforms extra files for $(TargetFramework)... " Importance="high" />
<Copy SourceFiles="$(ProjectDir)Libraries\linux-x86\libfmod.so" DestinationFolder="$(TargetDir)runtimes\linux-x86\native" ContinueOnError="false" />
<Copy SourceFiles="$(ProjectDir)Libraries\linux-x64\libfmod.so" DestinationFolder="$(TargetDir)runtimes\linux-x64\native" ContinueOnError="false" />
<Copy SourceFiles="$(ProjectDir)Libraries\osx-x64\libfmod.dylib" DestinationFolder="$(TargetDir)runtimes\osx-x64\native" ContinueOnError="false" />
<Copy SourceFiles="$(ProjectDir)Libraries\osx-arm64\libfmod.dylib" DestinationFolder="$(TargetDir)runtimes\osx-arm64\native" ContinueOnError="false" />
</Target>
<!-- Publishing an app as framework-dependent produces a cross-platform binary as a dll file, and a platform-specific executable that targets your current platform.
The dll is cross-platform while the executable isn't -->
<Target Name="PublishExtraFilesPortable" AfterTargets="Publish" Condition=" '$(RuntimeIdentifier)' == '' ">
<Message Text="Publishing windows extra files for Portable build ($(TargetFramework))... " Importance="high" />
<Copy SourceFiles="$(TargetDir)runtimes\win-x86\native\Texture2DDecoderNative.dll" DestinationFolder="$(PublishDir)runtimes\win-x86\native" ContinueOnError="false" />
<Copy SourceFiles="$(TargetDir)runtimes\win-x64\native\Texture2DDecoderNative.dll" DestinationFolder="$(PublishDir)runtimes\win-x64\native" ContinueOnError="false" />
<Copy SourceFiles="$(TargetDir)runtimes\win-x86\native\fmod.dll" DestinationFolder="$(PublishDir)runtimes\win-x86\native" ContinueOnError="false" />
<Copy SourceFiles="$(TargetDir)runtimes\win-x64\native\fmod.dll" DestinationFolder="$(PublishDir)runtimes\win-x64\native" ContinueOnError="false" />
</Target>
<Target Name="PublishExtraFilesPortableNet" AfterTargets="Publish" Condition=" '$(RuntimeIdentifier)' == '' AND '$(TargetFramework)' != 'net472' ">
<Message Text="Publishing other platforms extra files for Portable build ($(TargetFramework))... " Importance="high" />
<Copy SourceFiles="$(TargetDir)runtimes\linux-x86\native\libfmod.so" DestinationFolder="$(PublishDir)runtimes\linux-x86\native" ContinueOnError="false" />
<Copy SourceFiles="$(TargetDir)runtimes\linux-x64\native\libfmod.so" DestinationFolder="$(PublishDir)runtimes\linux-x64\native" ContinueOnError="false" />
<Copy SourceFiles="$(TargetDir)runtimes\osx-x64\native\libfmod.dylib" DestinationFolder="$(PublishDir)runtimes\osx-x64\native" ContinueOnError="false" />
<Copy SourceFiles="$(TargetDir)runtimes\osx-arm64\native\libfmod.dylib" DestinationFolder="$(PublishDir)runtimes\osx-arm64\native" ContinueOnError="false" />
</Target>
<Target Name="CopyExtraFilesWin86" AfterTargets="AfterBuild" Condition=" '$(RuntimeIdentifier)' == 'win-x86' ">
<Message Text="Copying extra files for $(RuntimeIdentifier)($(TargetFramework))... " Importance="high" />
<Copy SourceFiles="$(SolutionDir)Texture2DDecoderNative\bin\Win32\$(Configuration)\Texture2DDecoderNative.dll" DestinationFolder="$(TargetDir)" ContinueOnError="false" />
<Copy SourceFiles="$(ProjectDir)Libraries\win-x86\fmod.dll" DestinationFolder="$(TargetDir)" ContinueOnError="false" />
</Target>
<Target Name="CopyExtraFilesWin64" AfterTargets="AfterBuild" Condition=" '$(RuntimeIdentifier)' == 'win-x64' ">
<Message Text="Copying extra files for $(RuntimeIdentifier)($(TargetFramework))... " Importance="high" />
<Copy SourceFiles="$(SolutionDir)Texture2DDecoderNative\bin\x64\$(Configuration)\Texture2DDecoderNative.dll" DestinationFolder="$(TargetDir)" ContinueOnError="false" />
<Copy SourceFiles="$(ProjectDir)Libraries\win-x64\fmod.dll" DestinationFolder="$(TargetDir)" ContinueOnError="false" />
</Target>
<Target Name="PublishExtraFilesWin" AfterTargets="Publish" Condition=" $(RuntimeIdentifier.Contains('win-x')) ">
<Message Text="Publishing extra files for $(RuntimeIdentifier)($(TargetFramework))... " Importance="high" />
<Copy SourceFiles="$(TargetDir)\Texture2DDecoderNative.dll" DestinationFolder="$(PublishDir)" ContinueOnError="false" />
<Copy SourceFiles="$(TargetDir)\fmod.dll" DestinationFolder="$(PublishDir)" ContinueOnError="false" />
</Target>
<Target Name="CopyExtraFilesLinux64" AfterTargets="AfterBuild" Condition=" '$(RuntimeIdentifier)' == 'linux-x64' ">
<Message Text="Copying extra files for $(RuntimeIdentifier)($(TargetFramework))... " Importance="high" />
<Copy SourceFiles="$(ProjectDir)Libraries\linux-x64\libfmod.so" DestinationFolder="$(TargetDir)" ContinueOnError="false" />
</Target>
<Target Name="PublishExtraFilesLinux64" AfterTargets="Publish" Condition=" '$(RuntimeIdentifier)' == 'linux-x64' ">
<Message Text="Publishing extra files for $(RuntimeIdentifier)($(TargetFramework))... " Importance="high" />
<Copy SourceFiles="$(TargetDir)\libfmod.so" DestinationFolder="$(PublishDir)" ContinueOnError="false" />
</Target>
<Target Name="CopyExtraFilesMac" AfterTargets="AfterBuild" Condition=" $(RuntimeIdentifier.Contains('osx-')) ">
<Message Text="Copying extra files for $(RuntimeIdentifier)($(TargetFramework))... " Importance="high" />
<Copy SourceFiles="$(ProjectDir)Libraries\$(RuntimeIdentifier)\libfmod.dylib" DestinationFolder="$(TargetDir)" ContinueOnError="false" />
</Target>
<Target Name="PublishExtraFilesMac" AfterTargets="Publish" Condition=" $(RuntimeIdentifier.Contains('osx-')) ">
<Message Text="Publishing extra files for $(RuntimeIdentifier)($(TargetFramework))... " Importance="high" />
<Copy SourceFiles="$(TargetDir)\libfmod.dylib" DestinationFolder="$(PublishDir)" ContinueOnError="false" />
</Target>
</Project>

117
AssetStudioCLI/CLILogger.cs Normal file
View File

@@ -0,0 +1,117 @@
using AssetStudio;
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using AssetStudioCLI.Options;
namespace AssetStudioCLI
{
internal enum LogOutputMode
{
Console,
File,
Both,
}
internal class CLILogger : ILogger
{
private readonly LogOutputMode logOutput;
private readonly LoggerEvent logMinLevel;
public string LogName;
public string LogPath;
public CLILogger(CLIOptions options)
{
logOutput = options.o_logOutput.Value;
logMinLevel = options.o_logLevel.Value;
LogName = $"AssetStudioCLI_{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.log";
LogPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, LogName);
var ver = typeof(Program).Assembly.GetName().Version;
LogToFile(LoggerEvent.Verbose, $"---AssetStudioCLI v{ver} | Logger launched---\n" +
$"CMD Args: {string.Join(" ", options.cliArgs)}");
}
private static string ColorLogLevel(LoggerEvent logLevel)
{
string formattedLevel = $"[{logLevel}]";
switch (logLevel)
{
case LoggerEvent.Info:
return $"{formattedLevel.Color(CLIAnsiColors.BrightCyan)}";
case LoggerEvent.Warning:
return $"{formattedLevel.Color(CLIAnsiColors.BrightYellow)}";
case LoggerEvent.Error:
return $"{formattedLevel.Color(CLIAnsiColors.BrightRed)}";
default:
return formattedLevel;
}
}
private static string FormatMessage(LoggerEvent logMsgLevel, string message, bool consoleMode = false)
{
var curTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
message = message.TrimEnd();
var multiLine = message.Contains('\n');
string formattedMessage;
if (consoleMode)
{
string colorLogLevel = ColorLogLevel(logMsgLevel);
formattedMessage = $"{colorLogLevel} {message}";
if (multiLine)
{
formattedMessage = formattedMessage.Replace("\n", $"\n{colorLogLevel} ");
}
}
else
{
message = Regex.Replace(message, @"\e\[[0-9;]*m(?:\e\[K)?", ""); //Delete ANSI colors
var logLevel = $"{logMsgLevel.ToString().ToUpper(),-7}";
formattedMessage = $"{curTime} | {logLevel} | {message}";
if (multiLine)
{
formattedMessage = formattedMessage.Replace("\n", $"\n{curTime} | {logLevel} | ");
}
}
return formattedMessage;
}
public void LogToConsole(LoggerEvent logMsgLevel, string message)
{
if (logOutput != LogOutputMode.File)
{
Console.WriteLine(FormatMessage(logMsgLevel, message, consoleMode: true));
}
}
public async void LogToFile(LoggerEvent logMsgLevel, string message)
{
if (logOutput != LogOutputMode.Console)
{
using (var sw = new StreamWriter(LogPath, append: true, System.Text.Encoding.UTF8))
{
await sw.WriteLineAsync(FormatMessage(logMsgLevel, message));
}
}
}
public void Log(LoggerEvent logMsgLevel, string message, bool ignoreLevel)
{
if ((logMsgLevel < logMinLevel && !ignoreLevel) || string.IsNullOrEmpty(message))
{
return;
}
if (logOutput != LogOutputMode.File)
{
LogToConsole(logMsgLevel, message);
}
if (logOutput != LogOutputMode.Console)
{
LogToFile(logMsgLevel, message);
}
}
}
}

View File

@@ -0,0 +1,27 @@
using AssetStudio;
namespace AssetStudioCLI
{
internal class AssetItem
{
public Object Asset;
public SerializedFile SourceFile;
public string Container = string.Empty;
public string TypeString;
public long m_PathID;
public long FullSize;
public ClassIDType Type;
public string Text;
public string UniqueID;
public AssetItem(Object asset)
{
Asset = asset;
SourceFile = asset.assetsFile;
Type = asset.type;
TypeString = Type.ToString();
m_PathID = asset.m_PathID;
FullSize = asset.byteSize;
}
}
}

View File

@@ -0,0 +1,49 @@
using System;
namespace AssetStudioCLI
{
// Represents set with 16 base colors using ANSI escape codes, which should be supported in most terminals
// (well, except for windows editions before windows 10)
public static class CLIAnsiColors
{
public static readonly string
Black = "\u001b[30m",
Red = "\u001b[31m",
Green = "\u001b[32m",
Yellow = "\u001b[33m", //remapped to ~BrightWhite in Windows PowerShell 6
Blue = "\u001b[34m",
Magenta = "\u001b[35m", //remapped to ~Blue in Windows PowerShell 6
Cyan = "\u001b[36m",
White = "\u001b[37m",
BrightBlack = "\u001b[30;1m",
BrightRed = "\u001b[31;1m",
BrightGreen = "\u001b[32;1m",
BrightYellow = "\u001b[33;1m",
BrightBlue = "\u001b[34;1m",
BrightMagenta = "\u001b[35;1m",
BrightCyan = "\u001b[36;1m",
BrightWhite = "\u001b[37;1m";
private static readonly string Reset = "\u001b[0m";
public static string Color(this string str, string ansiColor)
{
if (!CLIWinAnsiFix.isAnsiSupported)
{
return str;
}
return $"{ansiColor}{str}{Reset}";
}
public static void ANSICodesTest()
{
Console.WriteLine("ANSI escape codes test");
Console.WriteLine($"Supported: {CLIWinAnsiFix.isAnsiSupported}");
Console.WriteLine("\u001b[30m A \u001b[31m B \u001b[32m C \u001b[33m D \u001b[0m");
Console.WriteLine("\u001b[34m E \u001b[35m F \u001b[36m G \u001b[37m H \u001b[0m");
Console.WriteLine("\u001b[30;1m A \u001b[31;1m B \u001b[32;1m C \u001b[33;1m D \u001b[0m");
Console.WriteLine("\u001b[34;1m E \u001b[35;1m F \u001b[36;1m G \u001b[37;1m H \u001b[0m");
}
}
}

View File

@@ -0,0 +1,62 @@
// Based on code by tomzorz (https://gist.github.com/tomzorz/6142d69852f831fb5393654c90a1f22e)
using System;
using System.Runtime.InteropServices;
namespace AssetStudioCLI
{
static class CLIWinAnsiFix
{
public static readonly bool isAnsiSupported;
private const int STD_OUTPUT_HANDLE = -11;
private const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
[DllImport("kernel32.dll")]
private static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
[DllImport("kernel32.dll")]
private static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
[DllImport("kernel32.dll")]
private static extern IntPtr GetStdHandle(int nStdHandle);
static CLIWinAnsiFix()
{
bool isWin = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
if (isWin)
{
isAnsiSupported = TryEnableVTMode();
if (!isAnsiSupported)
{
//Check for bash terminal emulator. E.g., Git Bash, Cmder
isAnsiSupported = Environment.GetEnvironmentVariable("TERM") != null;
}
}
else
{
isAnsiSupported = true;
}
}
// Enable support for ANSI escape codes
// (but probably only suitable for windows 10+)
// https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
private static bool TryEnableVTMode()
{
var iStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (!GetConsoleMode(iStdOut, out uint outConsoleMode))
{
return false;
}
outConsoleMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if (!SetConsoleMode(iStdOut, outConsoleMode))
{
return false;
}
return true;
}
}
}

314
AssetStudioCLI/Exporter.cs Normal file
View File

@@ -0,0 +1,314 @@
using AssetStudio;
using AssetStudioCLI.Options;
using Newtonsoft.Json;
using System.IO;
using System.Linq;
using System.Text;
namespace AssetStudioCLI
{
internal static class Exporter
{
public static AssemblyLoader assemblyLoader = new AssemblyLoader();
public static bool ExportTexture2D(AssetItem item, string exportPath, CLIOptions options)
{
var m_Texture2D = (Texture2D)item.Asset;
if (options.convertTexture)
{
var type = options.o_imageFormat.Value;
if (!TryExportFile(exportPath, item, "." + type.ToString().ToLower(), out var exportFullPath))
return false;
var image = m_Texture2D.ConvertToImage(flip: true);
if (image == null)
{
Logger.Error($"Export error. Failed to convert texture \"{m_Texture2D.m_Name}\" into image");
return false;
}
using (image)
{
using (var file = File.OpenWrite(exportFullPath))
{
image.WriteToStream(file, type);
}
Logger.Debug($"{item.TypeString}: \"{item.Text}\" exported to \"{exportFullPath}\"");
return true;
}
}
else
{
if (!TryExportFile(exportPath, item, ".tex", out var exportFullPath))
return false;
File.WriteAllBytes(exportFullPath, m_Texture2D.image_data.GetData());
Logger.Debug($"{item.TypeString}: \"{item.Text}\" exported to \"{exportFullPath}\"");
return true;
}
}
public static bool ExportAudioClip(AssetItem item, string exportPath, CLIOptions options)
{
string exportFullPath;
var m_AudioClip = (AudioClip)item.Asset;
var m_AudioData = m_AudioClip.m_AudioData.GetData();
if (m_AudioData == null || m_AudioData.Length == 0)
{
Logger.Error($"Export error. \"{item.Text}\": AudioData was not found");
return false;
}
var converter = new AudioClipConverter(m_AudioClip);
if (options.o_audioFormat.Value != AudioFormat.None && converter.IsSupport)
{
if (!TryExportFile(exportPath, item, ".wav", out exportFullPath))
return false;
var sb = new StringBuilder();
sb.AppendLine($"Converting \"{m_AudioClip.m_Name}\" to wav..");
sb.AppendLine(m_AudioClip.version[0] < 5 ? $"AudioClip type: {m_AudioClip.m_Type}" : $"AudioClip compression format: {m_AudioClip.m_CompressionFormat}");
sb.AppendLine($"AudioClip channel count: {m_AudioClip.m_Channels}");
sb.AppendLine($"AudioClip sample rate: {m_AudioClip.m_Frequency}");
sb.AppendLine($"AudioClip bit depth: {m_AudioClip.m_BitsPerSample}");
Logger.Debug(sb.ToString());
var buffer = converter.ConvertToWav(m_AudioData);
if (buffer == null)
{
Logger.Error($"Export error. \"{item.Text}\": Failed to convert to Wav");
return false;
}
File.WriteAllBytes(exportFullPath, buffer);
}
else
{
if (!TryExportFile(exportPath, item, converter.GetExtensionName(), out exportFullPath))
return false;
File.WriteAllBytes(exportFullPath, m_AudioData);
}
Logger.Debug($"{item.TypeString}: \"{item.Text}\" exported to \"{exportFullPath}\"");
return true;
}
public static bool ExportVideoClip(AssetItem item, string exportPath)
{
var m_VideoClip = (VideoClip)item.Asset;
if (m_VideoClip.m_ExternalResources.m_Size > 0)
{
if (!TryExportFile(exportPath, item, Path.GetExtension(m_VideoClip.m_OriginalPath), out var exportFullPath))
return false;
var sb = new StringBuilder();
sb.AppendLine($"VideoClip format: {m_VideoClip.m_Format}");
sb.AppendLine($"VideoClip width: {m_VideoClip.Width}");
sb.AppendLine($"VideoClip height: {m_VideoClip.Height}");
sb.AppendLine($"VideoClip frame rate: {m_VideoClip.m_FrameRate}");
sb.AppendLine($"VideoClip split alpha: {m_VideoClip.m_HasSplitAlpha}");
Logger.Debug(sb.ToString());
m_VideoClip.m_VideoData.WriteData(exportFullPath);
Logger.Debug($"{item.TypeString}: \"{item.Text}\" exported to \"{exportFullPath}\"");
return true;
}
return false;
}
public static bool ExportMovieTexture(AssetItem item, string exportPath)
{
var m_MovieTexture = (MovieTexture)item.Asset;
if (!TryExportFile(exportPath, item, ".ogv", out var exportFullPath))
return false;
File.WriteAllBytes(exportFullPath, m_MovieTexture.m_MovieData);
Logger.Debug($"{item.TypeString}: \"{item.Text}\" exported to \"{exportFullPath}\"");
return true;
}
public static bool ExportShader(AssetItem item, string exportPath)
{
if (!TryExportFile(exportPath, item, ".shader", out var exportFullPath))
return false;
var m_Shader = (Shader)item.Asset;
var str = m_Shader.Convert();
File.WriteAllText(exportFullPath, str);
Logger.Debug($"{item.TypeString}: \"{item.Text}\" exported to \"{exportFullPath}\"");
return true;
}
public static bool ExportTextAsset(AssetItem item, string exportPath, CLIOptions options)
{
var m_TextAsset = (TextAsset)item.Asset;
var extension = ".txt";
if (!options.f_notRestoreExtensionName.Value)
{
if (!string.IsNullOrEmpty(item.Container))
{
extension = Path.GetExtension(item.Container);
}
}
if (!TryExportFile(exportPath, item, extension, out var exportFullPath))
return false;
File.WriteAllBytes(exportFullPath, m_TextAsset.m_Script);
Logger.Debug($"{item.TypeString}: \"{item.Text}\" exported to \"{exportFullPath}\"");
return true;
}
public static bool ExportMonoBehaviour(AssetItem item, string exportPath, CLIOptions options)
{
if (!TryExportFile(exportPath, item, ".json", out var exportFullPath))
return false;
var m_MonoBehaviour = (MonoBehaviour)item.Asset;
var type = m_MonoBehaviour.ToType();
if (type == null)
{
var m_Type = MonoBehaviourToTypeTree(m_MonoBehaviour, options);
type = m_MonoBehaviour.ToType(m_Type);
}
var str = JsonConvert.SerializeObject(type, Formatting.Indented);
File.WriteAllText(exportFullPath, str);
Logger.Debug($"{item.TypeString}: \"{item.Text}\" exported to \"{exportFullPath}\"");
return true;
}
public static bool ExportFont(AssetItem item, string exportPath)
{
var m_Font = (Font)item.Asset;
if (m_Font.m_FontData != null)
{
var extension = ".ttf";
if (m_Font.m_FontData[0] == 79 && m_Font.m_FontData[1] == 84 && m_Font.m_FontData[2] == 84 && m_Font.m_FontData[3] == 79)
{
extension = ".otf";
}
if (!TryExportFile(exportPath, item, extension, out var exportFullPath))
return false;
File.WriteAllBytes(exportFullPath, m_Font.m_FontData);
Logger.Debug($"{item.TypeString}: \"{item.Text}\" exported to \"{exportFullPath}\"");
return true;
}
return false;
}
public static bool ExportSprite(AssetItem item, string exportPath, CLIOptions options)
{
var type = options.o_imageFormat.Value;
var alphaMask = SpriteMaskMode.On;
if (!TryExportFile(exportPath, item, "." + type.ToString().ToLower(), out var exportFullPath))
return false;
var image = ((Sprite)item.Asset).GetImage(alphaMask);
if (image != null)
{
using (image)
{
using (var file = File.OpenWrite(exportFullPath))
{
image.WriteToStream(file, type);
}
Logger.Debug($"{item.TypeString}: \"{item.Text}\" exported to \"{exportFullPath}\"");
return true;
}
}
return false;
}
public static bool ExportRawFile(AssetItem item, string exportPath)
{
if (!TryExportFile(exportPath, item, ".dat", out var exportFullPath))
return false;
File.WriteAllBytes(exportFullPath, item.Asset.GetRawData());
Logger.Debug($"{item.TypeString}: \"{item.Text}\" exported to \"{exportFullPath}\"");
return true;
}
public static bool ExportDumpFile(AssetItem item, string exportPath, CLIOptions options)
{
if (!TryExportFile(exportPath, item, ".txt", out var exportFullPath))
return false;
var str = item.Asset.Dump();
if (str == null && item.Asset is MonoBehaviour m_MonoBehaviour)
{
var m_Type = MonoBehaviourToTypeTree(m_MonoBehaviour, options);
str = m_MonoBehaviour.Dump(m_Type);
}
if (str != null)
{
File.WriteAllText(exportFullPath, str);
Logger.Debug($"{item.TypeString}: \"{item.Text}\" saved to \"{exportFullPath}\"");
return true;
}
return false;
}
private static bool TryExportFile(string dir, AssetItem item, string extension, out string fullPath)
{
var fileName = FixFileName(item.Text);
fullPath = Path.Combine(dir, fileName + extension);
if (!File.Exists(fullPath))
{
Directory.CreateDirectory(dir);
return true;
}
fullPath = Path.Combine(dir, fileName + item.UniqueID + extension);
if (!File.Exists(fullPath))
{
Directory.CreateDirectory(dir);
return true;
}
Logger.Error($"Export error. File \"{fullPath.Color(CLIAnsiColors.BrightRed)}\" already exist");
return false;
}
public static bool ExportConvertFile(AssetItem item, string exportPath, CLIOptions options)
{
switch (item.Type)
{
case ClassIDType.Texture2D:
return ExportTexture2D(item, exportPath, options);
case ClassIDType.AudioClip:
return ExportAudioClip(item, exportPath, options);
case ClassIDType.VideoClip:
return ExportVideoClip(item, exportPath);
case ClassIDType.MovieTexture:
return ExportMovieTexture(item, exportPath);
case ClassIDType.Shader:
return ExportShader(item, exportPath);
case ClassIDType.TextAsset:
return ExportTextAsset(item, exportPath, options);
case ClassIDType.MonoBehaviour:
return ExportMonoBehaviour(item, exportPath, options);
case ClassIDType.Font:
return ExportFont(item, exportPath);
case ClassIDType.Sprite:
return ExportSprite(item, exportPath, options);
default:
return ExportRawFile(item, exportPath);
}
}
public static TypeTree MonoBehaviourToTypeTree(MonoBehaviour m_MonoBehaviour, CLIOptions options)
{
if (!assemblyLoader.Loaded)
{
var assemblyFolder = options.o_assemblyPath.Value;
if (assemblyFolder != "")
{
assemblyLoader.Load(assemblyFolder);
}
else
{
assemblyLoader.Loaded = true;
}
}
return m_MonoBehaviour.ConvertToTypeTree(assemblyLoader);
}
public static string FixFileName(string str)
{
if (str.Length >= 260) return Path.GetRandomFileName();
return Path.GetInvalidFileNameChars().Aggregate(str, (current, c) => current.Replace(c, '_'));
}
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,795 @@
using AssetStudio;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace AssetStudioCLI.Options
{
internal enum HelpGroups
{
General,
Convert,
Logger,
Advanced,
}
internal enum WorkMode
{
Export,
ExportRaw,
Dump,
Info,
}
internal enum AssetGroupOption
{
None,
TypeName,
ContainerPath,
SourceFileName,
}
internal enum ExportListType
{
None,
XML,
}
internal enum AudioFormat
{
None,
Wav,
}
internal enum FilterBy
{
None,
Name,
Container,
PathID,
NameOrContainer,
NameAndContainer,
}
internal class GroupedOption<T> : Option<T>
{
public GroupedOption(T optionDefaultValue, string optionName, string optionDescription, HelpGroups optionHelpGroup, bool isFlag = false) : base(optionDefaultValue, optionName, optionDescription, optionHelpGroup, isFlag)
{
CLIOptions.OptionGrouping(optionName, optionDescription, optionHelpGroup, isFlag);
}
}
internal class CLIOptions
{
public bool isParsed;
public bool showHelp;
public string[] cliArgs;
public string inputPath;
public FilterBy filterBy;
private static Dictionary<string, string> optionsDict;
private static Dictionary<string, string> flagsDict;
private static Dictionary<HelpGroups, Dictionary<string, string>> optionGroups;
private List<ClassIDType> supportedAssetTypes;
//general
public Option<WorkMode> o_workMode;
public Option<List<ClassIDType>> o_exportAssetTypes;
public Option<AssetGroupOption> o_groupAssetsBy;
public Option<string> o_outputFolder;
public Option<bool> o_displayHelp;
//logger
public Option<LoggerEvent> o_logLevel;
public Option<LogOutputMode> o_logOutput;
//convert
public bool convertTexture;
public Option<ImageFormat> o_imageFormat;
public Option<AudioFormat> o_audioFormat;
//advanced
public Option<ExportListType> o_exportAssetList;
public Option<List<string>> o_filterByName;
public Option<List<string>> o_filterByContainer;
public Option<List<string>> o_filterByPathID;
public Option<List<string>> o_filterByText;
public Option<string> o_assemblyPath;
public Option<string> o_unityVersion;
public Option<bool> f_notRestoreExtensionName;
public CLIOptions(string[] args)
{
cliArgs = args;
InitOptions();
ParseArgs(args);
}
private void InitOptions()
{
isParsed = false;
showHelp = false;
inputPath = "";
filterBy = FilterBy.None;
optionsDict = new Dictionary<string, string>();
flagsDict = new Dictionary<string, string>();
optionGroups = new Dictionary<HelpGroups, Dictionary<string, string>>();
supportedAssetTypes = new List<ClassIDType>
{
ClassIDType.Texture2D,
ClassIDType.Sprite,
ClassIDType.TextAsset,
ClassIDType.MonoBehaviour,
ClassIDType.Font,
ClassIDType.Shader,
ClassIDType.AudioClip,
ClassIDType.VideoClip,
ClassIDType.MovieTexture,
};
#region Init General Options
o_workMode = new GroupedOption<WorkMode>
(
optionDefaultValue: WorkMode.Export,
optionName: "-m, --mode <value>",
optionDescription: "Specify working mode\n" +
"<Value: export(default) | exportRaw | dump | info>\n" +
"Export - Exports converted assets\n" +
"ExportRaw - Exports raw data\n" +
"Dump - Makes asset dumps\n" +
"Info - Loads file(s), shows the number of supported for export assets and exits\n" +
"Example: \"-m info\"\n",
optionHelpGroup: HelpGroups.General
);
o_exportAssetTypes = new GroupedOption<List<ClassIDType>>
(
optionDefaultValue: supportedAssetTypes,
optionName: "-t, --asset-type <value(s)>",
optionDescription: "Specify asset type(s) to export\n" +
"<Value(s): tex2d, sprite, textAsset, monoBehaviour, font, shader, movieTexture,\n" +
"audio, video | all(default)>\n" +
"All - export all asset types, which are listed in the values\n" +
"*To specify multiple asset types, write them separated by ',' or ';' without spaces\n" +
"Examples: \"-t sprite\" or \"-t all\" or \"-t tex2d,sprite,audio\" or \"-t tex2d;sprite;font\"\n",
optionHelpGroup: HelpGroups.General
);
o_groupAssetsBy = new GroupedOption<AssetGroupOption>
(
optionDefaultValue: AssetGroupOption.ContainerPath,
optionName: "-g, --group-option <value>",
optionDescription: "Specify the way in which exported assets should be grouped\n" +
"<Value: none | type | container(default) | filename>\n" +
"None - Do not group exported assets\n" +
"Type - Group exported assets by type name\n" +
"Container - Group exported assets by container path\n" +
"Filename - Group exported assets by source file name\n" +
"Example: \"-g container\"\n",
optionHelpGroup: HelpGroups.General
);
o_outputFolder = new GroupedOption<string>
(
optionDefaultValue: "",
optionName: "-o, --output <path>",
optionDescription: "Specify path to the output folder\n" +
"If path isn't specifyed, 'ASExport' folder will be created in the program's work folder\n",
optionHelpGroup: HelpGroups.General
);
o_displayHelp = new GroupedOption<bool>
(
optionDefaultValue: false,
optionName: "-h, --help",
optionDescription: "Display help and exit",
optionHelpGroup: HelpGroups.General
);
#endregion
#region Init Logger Options
o_logLevel = new GroupedOption<LoggerEvent>
(
optionDefaultValue: LoggerEvent.Info,
optionName: "--log-level <value>",
optionDescription: "Specify the log level\n" +
"<Value: verbose | debug | info(default) | warning | error>\n" +
"Example: \"--log-level warning\"\n",
optionHelpGroup: HelpGroups.Logger
);
o_logOutput = new GroupedOption<LogOutputMode>
(
optionDefaultValue: LogOutputMode.Console,
optionName: "--log-output <value>",
optionDescription: "Specify the log output\n" +
"<Value: console(default) | file | both>\n" +
"Example: \"--log-output both\"",
optionHelpGroup: HelpGroups.Logger
);
#endregion
#region Init Convert Options
convertTexture = true;
o_imageFormat = new GroupedOption<ImageFormat>
(
optionDefaultValue: ImageFormat.Png,
optionName: "--image-format <value>",
optionDescription: "Specify the format for converting image assets\n" +
"<Value: none | jpg | png(default) | bmp | tga | webp>\n" +
"None - Do not convert images and export them as texture data (.tex)\n" +
"Example: \"--image-format jpg\"\n",
optionHelpGroup: HelpGroups.Convert
);
o_audioFormat = new GroupedOption<AudioFormat>
(
optionDefaultValue: AudioFormat.Wav,
optionName: "--audio-format <value>",
optionDescription: "Specify the format for converting audio assets\n" +
"<Value: none | wav(default)>\n" +
"None - Do not convert audios and export them in their own format\n" +
"Example: \"--audio-format wav\"",
optionHelpGroup: HelpGroups.Convert
);
#endregion
#region Init Advanced Options
o_exportAssetList = new GroupedOption<ExportListType>
(
optionDefaultValue: ExportListType.None,
optionName: "--export-asset-list <value>",
optionDescription: "Specify the format in which you want to export asset list\n" +
"<Value: none(default) | xml>\n" +
"None - Do not export asset list\n" +
"Example: \"--export-asset-list xml\"\n",
optionHelpGroup: HelpGroups.Advanced
);
o_filterByName = new GroupedOption<List<string>>
(
optionDefaultValue: new List<string>(),
optionName: "--filter-by-name <text>",
optionDescription: "Specify the name by which assets should be filtered\n" +
"*To specify multiple names write them separated by ',' or ';' without spaces\n" +
"Example: \"--filter-by-name char\" or \"--filter-by-name char,bg\"\n",
optionHelpGroup: HelpGroups.Advanced
);
o_filterByContainer = new GroupedOption<List<string>>
(
optionDefaultValue: new List<string>(),
optionName: "--filter-by-container <text>",
optionDescription: "Specify the container by which assets should be filtered\n" +
"*To specify multiple containers write them separated by ',' or ';' without spaces\n" +
"Example: \"--filter-by-container arts\" or \"--filter-by-container arts,icons\"\n",
optionHelpGroup: HelpGroups.Advanced
);
o_filterByPathID = new GroupedOption<List<string>>
(
optionDefaultValue: new List<string>(),
optionName: "--filter-by-pathid <text>",
optionDescription: "Specify the PathID by which assets should be filtered\n" +
"*To specify multiple PathIDs write them separated by ',' or ';' without spaces\n" +
"Example: \"--filter-by-pathid 7238605633795851352,-2430306240205277265\"\n",
optionHelpGroup: HelpGroups.Advanced
);
o_filterByText = new GroupedOption<List<string>>
(
optionDefaultValue: new List<string>(),
optionName: "--filter-by-text <text>",
optionDescription: "Specify the text by which assets should be filtered\n" +
"Looks for assets that contain the specified text in their names or containers\n" +
"*To specify multiple values write them separated by ',' or ';' without spaces\n" +
"Example: \"--filter-by-text portrait\" or \"--filter-by-text portrait,art\"\n",
optionHelpGroup: HelpGroups.Advanced
);
o_assemblyPath = new GroupedOption<string>
(
optionDefaultValue: "",
optionName: "--assembly-folder <path>",
optionDescription: "Specify the path to the assembly folder",
optionHelpGroup: HelpGroups.Advanced
);
o_unityVersion = new GroupedOption<string>
(
optionDefaultValue: "",
optionName: "--unity-version <text>",
optionDescription: "Specify Unity version. Example: \"--unity-version 2017.4.39f1\"",
optionHelpGroup: HelpGroups.Advanced
);
f_notRestoreExtensionName = new GroupedOption<bool>
(
optionDefaultValue: false,
optionName: "--not-restore-extension",
optionDescription: "(Flag) If specified, AssetStudio will not try to restore TextAssets extension name, \nand will just export all TextAssets with the \".txt\" extension",
optionHelpGroup: HelpGroups.Advanced,
isFlag: true
);
#endregion
}
internal static void OptionGrouping(string name, string desc, HelpGroups group, bool isFlag)
{
if (string.IsNullOrEmpty(name))
{
return;
}
var optionDict = new Dictionary<string, string>() { { name, desc } };
if (!optionGroups.ContainsKey(group))
{
optionGroups.Add(group, optionDict);
}
else
{
optionGroups[group].Add(name, desc);
}
if (isFlag)
{
flagsDict.Add(name, desc);
}
else
{
optionsDict.Add(name, desc);
}
}
private void ParseArgs(string[] args)
{
var brightYellow = CLIAnsiColors.BrightYellow;
var brightRed = CLIAnsiColors.BrightRed;
if (args.Length == 0 || args.Any(x => x == "-h" || x == "--help"))
{
showHelp = true;
return;
}
if (!args[0].StartsWith("-"))
{
inputPath = Path.GetFullPath(args[0]).Replace("\"", "");
if (!Directory.Exists(inputPath) && !File.Exists(inputPath))
{
Console.WriteLine($"{"Error:".Color(brightRed)} Invalid input path \"{args[0].Color(brightRed)}\".\n" +
$"Specified file or folder was not found. The input path must be specified as the first argument.");
return;
}
o_outputFolder.Value = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ASExport");
}
else
{
Console.WriteLine($"{"Error:".Color(brightRed)} Input path was empty. Specify the input path as the first argument.");
return;
}
var resplittedArgs = new List<string>();
for (int i = 1; i < args.Length; i++)
{
string arg = args[i];
if (arg.Contains('='))
{
var splittedArgs = arg.Split('=');
resplittedArgs.Add(splittedArgs[0]);
resplittedArgs.Add(splittedArgs[1]);
}
else
{
resplittedArgs.Add(arg);
}
};
#region Parse Flags
for (int i = 0; i < resplittedArgs.Count; i++)
{
string flag = resplittedArgs[i].ToLower();
switch(flag)
{
case "--not-restore-extension":
f_notRestoreExtensionName.Value = true;
resplittedArgs.RemoveAt(i);
break;
}
}
#endregion
#region Parse Options
for (int i = 0; i < resplittedArgs.Count; i++)
{
var option = resplittedArgs[i].ToLower();
try
{
var value = resplittedArgs[i + 1].Replace("\"", "");
switch (option)
{
case "-m":
case "--mode":
switch (value.ToLower())
{
case "export":
o_workMode.Value = WorkMode.Export;
break;
case "raw":
case "exportraw":
o_workMode.Value = WorkMode.ExportRaw;
break;
case "dump":
o_workMode.Value = WorkMode.Dump;
break;
case "info":
o_workMode.Value = WorkMode.Info;
break;
default:
Console.WriteLine($"{"Error".Color(brightRed)} during parsing [{option}] option. Unsupported working mode: [{value.Color(brightRed)}].\n");
Console.WriteLine(o_workMode.Description);
return;
}
break;
case "-t":
case "--asset-type":
var splittedTypes = ValueSplitter(value);
o_exportAssetTypes.Value = new List<ClassIDType>();
foreach (var type in splittedTypes)
{
switch (type.ToLower())
{
case "tex2d":
case "texture2d":
o_exportAssetTypes.Value.Add(ClassIDType.Texture2D);
break;
case "sprite":
o_exportAssetTypes.Value.Add(ClassIDType.Sprite);
break;
case "textasset":
o_exportAssetTypes.Value.Add(ClassIDType.TextAsset);
break;
case "monobehaviour":
o_exportAssetTypes.Value.Add(ClassIDType.MonoBehaviour);
break;
case "font":
o_exportAssetTypes.Value.Add(ClassIDType.Font);
break;
case "shader":
o_exportAssetTypes.Value.Add(ClassIDType.Shader);
break;
case "audio":
case "audioclip":
o_exportAssetTypes.Value.Add(ClassIDType.AudioClip);
break;
case "video":
case "videoclip":
o_exportAssetTypes.Value.Add(ClassIDType.VideoClip);
break;
case "movietexture":
o_exportAssetTypes.Value.Add(ClassIDType.MovieTexture);
break;
case "all":
o_exportAssetTypes.Value = supportedAssetTypes;
break;
default:
Console.WriteLine($"{"Error".Color(brightRed)} during parsing [{option}] option. Unsupported asset type: [{value.Color(brightRed)}].\n");
Console.WriteLine(o_exportAssetTypes.Description);
return;
}
}
break;
case "-g":
case "--group-option":
switch (value.ToLower())
{
case "type":
o_groupAssetsBy.Value = AssetGroupOption.TypeName;
break;
case "container":
o_groupAssetsBy.Value = AssetGroupOption.ContainerPath;
break;
case "filename":
o_groupAssetsBy.Value = AssetGroupOption.SourceFileName;
break;
case "none":
o_groupAssetsBy.Value = AssetGroupOption.None;
break;
default:
Console.WriteLine($"{"Error".Color(brightRed)} during parsing [{option}] option. Unsupported grouping option: [{value.Color(brightRed)}].\n");
Console.WriteLine(o_groupAssetsBy.Description);
return;
}
break;
case "-o":
case "--output":
try
{
value = Path.GetFullPath(value);
if (!Directory.Exists(value))
{
Directory.CreateDirectory(value);
}
o_outputFolder.Value = value;
}
catch (Exception ex)
{
Console.WriteLine($"{"Warning:".Color(brightYellow)} Invalid output folder \"{value.Color(brightYellow)}\".\n{ex.Message}");
Console.WriteLine($"Working folder \"{o_outputFolder.Value.Color(brightYellow)}\" will be used as the output folder.\n");
Console.WriteLine("Press ESC to exit or any other key to continue...\n");
switch (Console.ReadKey(intercept: true).Key)
{
case ConsoleKey.Escape:
return;
}
}
break;
case "--log-level":
switch (value.ToLower())
{
case "verbose":
o_logLevel.Value = LoggerEvent.Verbose;
break;
case "debug":
o_logLevel.Value = LoggerEvent.Debug;
break;
case "info":
o_logLevel.Value = LoggerEvent.Info;
break;
case "warning":
o_logLevel.Value = LoggerEvent.Warning;
break;
case "error":
o_logLevel.Value = LoggerEvent.Error;
break;
default:
Console.WriteLine($"{"Error".Color(brightRed)} during parsing [{option}] option. Unsupported log level value: [{value.Color(brightRed)}].\n");
Console.WriteLine(o_logLevel.Description);
return;
}
break;
case "--log-output":
switch (value.ToLower())
{
case "console":
o_logOutput.Value = LogOutputMode.Console;
break;
case "file":
o_logOutput.Value = LogOutputMode.File;
break;
case "both":
o_logOutput.Value = LogOutputMode.Both;
break;
default:
Console.WriteLine($"{"Error".Color(brightRed)} during parsing [{option}] option. Unsupported log output mode: [{value.Color(brightRed)}].\n");
Console.WriteLine(o_logOutput.Description);
return;
}
break;
case "--image-format":
switch (value.ToLower())
{
case "jpg":
case "jpeg":
o_imageFormat.Value = ImageFormat.Jpeg;
break;
case "png":
o_imageFormat.Value = ImageFormat.Png;
break;
case "bmp":
o_imageFormat.Value = ImageFormat.Bmp;
break;
case "tga":
o_imageFormat.Value = ImageFormat.Tga;
break;
case "webp":
o_imageFormat.Value = ImageFormat.Webp;
break;
case "none":
convertTexture = false;
break;
default:
Console.WriteLine($"{"Error".Color(brightRed)} during parsing [{option}] option. Unsupported image format: [{value.Color(brightRed)}].\n");
Console.WriteLine(o_imageFormat.Description);
return;
}
break;
case "--audio-format":
switch (value.ToLower())
{
case "wav":
case "wave":
o_audioFormat.Value = AudioFormat.Wav;
break;
case "none":
o_audioFormat.Value = AudioFormat.None;
break;
default:
Console.WriteLine($"{"Error".Color(brightRed)} during parsing [{option}] option. Unsupported audio format: [{value.Color(brightRed)}].\n");
Console.WriteLine(o_audioFormat.Description);
return;
}
break;
case "--export-asset-list":
switch (value.ToLower())
{
case "xml":
o_exportAssetList.Value = ExportListType.XML;
break;
case "none":
o_exportAssetList.Value = ExportListType.None;
break;
default:
Console.WriteLine($"{"Error".Color(brightRed)} during parsing [{option}] option. Unsupported asset list export option: [{value.Color(brightRed)}].\n");
Console.WriteLine(o_exportAssetList.Description);
return;
}
break;
case "--filter-by-name":
o_filterByName.Value.AddRange(ValueSplitter(value));
filterBy = filterBy == FilterBy.None ? FilterBy.Name : filterBy == FilterBy.Container ? FilterBy.NameAndContainer : filterBy;
break;
case "--filter-by-container":
o_filterByContainer.Value.AddRange(ValueSplitter(value));
filterBy = filterBy == FilterBy.None ? FilterBy.Container : filterBy == FilterBy.Name ? FilterBy.NameAndContainer : filterBy;
break;
case "--filter-by-pathid":
o_filterByPathID.Value.AddRange(ValueSplitter(value));
filterBy = FilterBy.PathID;
break;
case "--filter-by-text":
o_filterByText.Value.AddRange(ValueSplitter(value));
filterBy = FilterBy.NameOrContainer;
break;
case "--assembly-folder":
if (Directory.Exists(value))
{
o_assemblyPath.Value = value;
}
else
{
Console.WriteLine($"{"Error".Color(brightRed)} during parsing [{option}] option. Assembly folder [{value.Color(brightRed)}] was not found.");
return;
}
break;
case "--unity-version":
o_unityVersion.Value = value;
break;
default:
Console.WriteLine($"{"Error:".Color(brightRed)} Unknown option [{option.Color(brightRed)}].\n");
if (!TryShowOptionDescription(option, optionsDict))
{
TryShowOptionDescription(option, flagsDict);
}
return;
}
i++;
}
catch (IndexOutOfRangeException)
{
if (optionsDict.Any(x => x.Key.Contains(option)))
{
Console.WriteLine($"{"Error during parsing options:".Color(brightRed)} Value for [{option.Color(brightRed)}] option was not found.\n");
TryShowOptionDescription(option, optionsDict);
}
else if (flagsDict.Any(x => x.Key.Contains(option)))
{
Console.WriteLine($"{"Error:".Color(brightRed)} Unknown flag [{option.Color(brightRed)}].\n");
TryShowOptionDescription(option, flagsDict);
}
else
{
Console.WriteLine($"{"Error:".Color(brightRed)} Unknown option [{option.Color(brightRed)}].");
}
return;
}
catch (Exception ex)
{
Console.WriteLine("Unknown Error.".Color(CLIAnsiColors.Red));
Console.WriteLine(ex);
return;
}
}
isParsed = true;
#endregion
}
private static string[] ValueSplitter(string value)
{
var separator = value.Contains(';') ? ';' : ',';
return value.Split(separator);
}
private bool TryShowOptionDescription(string option, Dictionary<string, string> descDict)
{
var optionDesc = descDict.Where(x => x.Key.Contains(option));
if (optionDesc.Any())
{
var rand = new Random();
var rndOption = optionDesc.ElementAt(rand.Next(0, optionDesc.Count()));
Console.WriteLine($"Did you mean [{ $"{rndOption.Key}".Color(CLIAnsiColors.BrightYellow) }] option?");
Console.WriteLine($"Here's a description of it: \n\n{rndOption.Value}");
return true;
}
return false;
}
public void ShowHelp(bool showUsageOnly = false)
{
const int indent = 22;
var helpMessage = new StringBuilder();
var usage = new StringBuilder();
var appAssembly = typeof(Program).Assembly.GetName();
usage.Append($"Usage: {appAssembly.Name} <input path to asset file/folder> ");
var i = 0;
foreach (var optionsGroup in optionGroups.Keys)
{
helpMessage.AppendLine($"{optionsGroup} Options:");
foreach (var optionDict in optionGroups[optionsGroup])
{
var optionName = $"{optionDict.Key,-indent - 8}";
var optionDesc = optionDict.Value.Replace("\n", $"{"\n",-indent - 11}");
helpMessage.AppendLine($" {optionName}{optionDesc}");
usage.Append($"[{optionDict.Key}] ");
if (i++ % 2 == 0)
{
usage.Append($"\n{"",indent}");
}
}
helpMessage.AppendLine();
}
if (showUsageOnly)
{
Console.WriteLine(usage);
}
else
{
Console.WriteLine($"# {appAssembly.Name}\n# Based on AssetStudio Mod v{appAssembly.Version}\n");
Console.WriteLine($"{usage}\n\n{helpMessage}");
}
}
private string ShowCurrentFilter()
{
switch (filterBy)
{
case FilterBy.Name:
return $"# Filter by {filterBy}(s): \"{string.Join("\", \"", o_filterByName.Value)}\"";
case FilterBy.Container:
return $"# Filter by {filterBy}(s): \"{string.Join("\", \"", o_filterByContainer.Value)}\"";
case FilterBy.PathID:
return $"# Filter by {filterBy}(s): \"{string.Join("\", \"", o_filterByPathID.Value)}\"";
case FilterBy.NameOrContainer:
return $"# Filter by Text: \"{string.Join("\", \"", o_filterByText.Value)}\"";
case FilterBy.NameAndContainer:
return $"# Filter by Name(s): \"{string.Join("\", \"", o_filterByName.Value)}\"\n# Filter by Container(s): \"{string.Join("\", \"", o_filterByContainer.Value)}\"";
default:
return $"# Filter by: {filterBy}";
}
}
public void ShowCurrentOptions()
{
var sb = new StringBuilder();
sb.AppendLine("[Current Options]");
sb.AppendLine($"# Working Mode: {o_workMode}");
sb.AppendLine($"# Input Path: \"{inputPath}\"");
if (o_workMode.Value != WorkMode.Info)
{
sb.AppendLine($"# Output Path: \"{o_outputFolder}\"");
sb.AppendLine($"# Export Asset Type(s): {string.Join(", ", o_exportAssetTypes.Value)}");
sb.AppendLine($"# Asset Group Option: {o_groupAssetsBy}");
sb.AppendLine($"# Export Image Format: {o_imageFormat}");
sb.AppendLine($"# Export Audio Format: {o_audioFormat}");
sb.AppendLine($"# Log Level: {o_logLevel}");
sb.AppendLine($"# Log Output: {o_logOutput}");
sb.AppendLine($"# Export Asset List: {o_exportAssetList}");
sb.AppendLine(ShowCurrentFilter());
sb.AppendLine($"# Assebmly Path: \"{o_assemblyPath}\"");
sb.AppendLine($"# Unity Version: \"{o_unityVersion}\"");
sb.AppendLine($"# Restore TextAsset extension: {!f_notRestoreExtensionName.Value}");
}
else
{
sb.AppendLine($"# Export Asset Type(s): {string.Join(", ", o_exportAssetTypes.Value)}");
sb.AppendLine($"# Log Level: {o_logLevel}");
sb.AppendLine($"# Log Output: {o_logOutput}");
sb.AppendLine($"# Export Asset List: {o_exportAssetList}");
sb.AppendLine(ShowCurrentFilter());
sb.AppendLine($"# Unity Version: \"{o_unityVersion}\"");
}
sb.AppendLine("======");
Logger.Info(sb.ToString());
}
}
}

View File

@@ -0,0 +1,27 @@
namespace AssetStudioCLI.Options
{
internal class Option<T>
{
public string Name { get; }
public string Description { get; }
public T Value { get; set; }
public T DefaultValue { get; }
public HelpGroups HelpGroup { get; }
public bool IsFlag { get; }
public Option(T optionDefaultValue, string optionName, string optionDescription, HelpGroups optionHelpGroup, bool isFlag)
{
Name = optionName;
Description = optionDescription;
DefaultValue = optionDefaultValue;
Value = DefaultValue;
HelpGroup = optionHelpGroup;
IsFlag = isFlag;
}
public override string ToString()
{
return Value != null ? Value.ToString() : string.Empty;
}
}
}

65
AssetStudioCLI/Program.cs Normal file
View File

@@ -0,0 +1,65 @@
using AssetStudio;
using AssetStudioCLI.Options;
using System;
namespace AssetStudioCLI
{
class Program
{
public static void Main(string[] args)
{
var options = new CLIOptions(args);
if (options.isParsed)
{
CLIRun(options);
}
else if (options.showHelp)
{
options.ShowHelp();
}
else
{
Console.WriteLine();
options.ShowHelp(showUsageOnly: true);
}
}
private static void CLIRun(CLIOptions options)
{
var cliLogger = new CLILogger(options);
Logger.Default = cliLogger;
var studio = new Studio(options);
options.ShowCurrentOptions();
try
{
if (studio.LoadAssets())
{
studio.ParseAssets();
if (options.filterBy != FilterBy.None)
{
studio.FilterAssets();
}
if (options.o_exportAssetList.Value != ExportListType.None)
{
studio.ExportAssetList();
}
if (options.o_workMode.Value == WorkMode.Info)
{
studio.ShowExportableAssetsInfo();
return;
}
studio.ExportAssets();
}
}
catch (Exception ex)
{
Logger.Error(ex.ToString());
}
finally
{
cliLogger.LogToFile(LoggerEvent.Verbose, "---Program ended---");
}
}
}
}

96
AssetStudioCLI/ReadMe.md Normal file
View File

@@ -0,0 +1,96 @@
## AssetStudioCLI
CLI version of AssetStudio Mod.
- Supported asset types: `Texture2D`, `Sprite`, `TextAsset`, `MonoBehaviour`, `Font`, `Shader`, `MovieTexture`, `AudioClip`, `VideoClip`
- *There are no plans to add support for `Mesh`/`AnimationClip`/`Animator` for now*
### Usage
```
AssetStudioCLI <input path to asset file/folder> [-m, --mode <value>]
[-t, --asset-type <value(s)>] [-g, --group-option <value>]
[-o, --output <path>] [-h, --help]
[--log-level <value>] [--log-output <value>]
[--image-format <value>] [--audio-format <value>]
[--export-asset-list <value>] [--filter-by-name <text>]
[--filter-by-container <text>] [--filter-by-pathid <text>]
[--filter-by-text <text>] [--assembly-folder <path>]
[--unity-version <text>] [--not-restore-extension]
General Options:
-m, --mode <value> Specify working mode
<Value: export(default) | exportRaw | dump | info>
Export - Exports converted assets
ExportRaw - Exports raw data
Dump - Makes asset dumps
Info - Loads file(s), shows the number of supported for export assets and exits
Example: "-m info"
-t, --asset-type <value(s)> Specify asset type(s) to export
<Value(s): tex2d, sprite, textAsset, monoBehaviour, font, shader, movieTexture,
audio, video | all(default)>
All - export all asset types, which are listed in the values
*To specify multiple asset types, write them separated by ',' or ';' without spaces
Examples: "-t sprite" or "-t all" or "-t tex2d,sprite,audio" or "-t tex2d;sprite;font"
-g, --group-option <value> Specify the way in which exported assets should be grouped
<Value: none | type | container(default) | filename>
None - Do not group exported assets
Type - Group exported assets by type name
Container - Group exported assets by container path
Filename - Group exported assets by source file name
Example: "-g container"
-o, --output <path> Specify path to the output folder
If path isn't specifyed, 'ASExport' folder will be created in the program's work folder
-h, --help Display help and exit
Logger Options:
--log-level <value> Specify the log level
<Value: verbose | debug | info(default) | warning | error>
Example: "--log-level warning"
--log-output <value> Specify the log output
<Value: console(default) | file | both>
Example: "--log-output both"
Convert Options:
--image-format <value> Specify the format for converting image assets
<Value: none | jpg | png(default) | bmp | tga | webp>
None - Do not convert images and export them as texture data (.tex)
Example: "--image-format jpg"
--audio-format <value> Specify the format for converting audio assets
<Value: none | wav(default)>
None - Do not convert audios and export them in their own format
Example: "--audio-format wav"
Advanced Options:
--export-asset-list <value> Specify the format in which you want to export asset list
<Value: none(default) | xml>
None - Do not export asset list
Example: "--export-asset-list xml"
--filter-by-name <text> Specify the name by which assets should be filtered
*To specify multiple names write them separated by ',' or ';' without spaces
Example: "--filter-by-name char" or "--filter-by-name char,bg"
--filter-by-container <text> Specify the container by which assets should be filtered
*To specify multiple containers write them separated by ',' or ';' without spaces
Example: "--filter-by-container arts" or "--filter-by-container arts,icons"
--filter-by-pathid <text> Specify the PathID by which assets should be filtered
*To specify multiple PathIDs write them separated by ',' or ';' without spaces
Example: "--filter-by-pathid 7238605633795851352,-2430306240205277265"
--filter-by-text <text> Specify the text by which assets should be filtered
Looks for assets that contain the specified text in their names or containers
*To specify multiple values write them separated by ',' or ';' without spaces
Example: "--filter-by-text portrait" or "--filter-by-text portrait,art"
--assembly-folder <path> Specify the path to the assembly folder
--unity-version <text> Specify Unity version. Example: "--unity-version 2017.4.39f1"
--not-restore-extension (Flag) If specified, AssetStudio will not try to restore TextAssets extension name,
and will just export all TextAssets with the ".txt" extension
```

383
AssetStudioCLI/Studio.cs Normal file
View File

@@ -0,0 +1,383 @@
using AssetStudio;
using AssetStudioCLI.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using static AssetStudioCLI.Exporter;
using Ansi = AssetStudioCLI.CLIAnsiColors;
namespace AssetStudioCLI
{
internal class Studio
{
public AssetsManager assetsManager = new AssetsManager();
public List<AssetItem> parsedAssetsList = new List<AssetItem>();
private readonly CLIOptions options;
public Studio(CLIOptions cliOptions)
{
Progress.Default = new Progress<int>(ShowCurProgressValue);
options = cliOptions;
}
private void ShowCurProgressValue(int value)
{
Console.Write($"[{value:000}%]\r");
}
public bool LoadAssets()
{
var isLoaded = false;
assetsManager.SpecifyUnityVersion = options.o_unityVersion.Value;
assetsManager.SetAssetFilter(options.o_exportAssetTypes.Value);
if (Directory.Exists(options.inputPath))
{
assetsManager.LoadFolder(options.inputPath);
}
else
{
assetsManager.LoadFiles(options.inputPath);
}
if (assetsManager.assetsFileList.Count == 0)
{
Logger.Warning("No Unity file can be loaded.");
}
else
{
isLoaded = true;
}
return isLoaded;
}
public void ParseAssets()
{
Logger.Info("Parse assets...");
var fileAssetsList = new List<AssetItem>();
var containers = new Dictionary<AssetStudio.Object, string>();
var objectCount = assetsManager.assetsFileList.Sum(x => x.Objects.Count);
Progress.Reset();
var i = 0;
foreach (var assetsFile in assetsManager.assetsFileList)
{
foreach (var asset in assetsFile.Objects)
{
var assetItem = new AssetItem(asset);
assetItem.UniqueID = "_#" + i;
var isExportable = false;
switch (asset)
{
case AssetBundle m_AssetBundle:
foreach (var m_Container in m_AssetBundle.m_Container)
{
var preloadIndex = m_Container.Value.preloadIndex;
var preloadSize = m_Container.Value.preloadSize;
var preloadEnd = preloadIndex + preloadSize;
for (int k = preloadIndex; k < preloadEnd; k++)
{
var pptr = m_AssetBundle.m_PreloadTable[k];
if (pptr.TryGet(out var obj))
{
containers[obj] = m_Container.Key;
}
}
}
break;
case ResourceManager m_ResourceManager:
foreach (var m_Container in m_ResourceManager.m_Container)
{
if (m_Container.Value.TryGet(out var obj))
{
containers[obj] = m_Container.Key;
}
}
break;
case Texture2D m_Texture2D:
if (!string.IsNullOrEmpty(m_Texture2D.m_StreamData?.path))
assetItem.FullSize = asset.byteSize + m_Texture2D.m_StreamData.size;
assetItem.Text = m_Texture2D.m_Name;
break;
case AudioClip m_AudioClip:
if (!string.IsNullOrEmpty(m_AudioClip.m_Source))
assetItem.FullSize = asset.byteSize + m_AudioClip.m_Size;
assetItem.Text = m_AudioClip.m_Name;
break;
case VideoClip m_VideoClip:
if (!string.IsNullOrEmpty(m_VideoClip.m_OriginalPath))
assetItem.FullSize = asset.byteSize + m_VideoClip.m_ExternalResources.m_Size;
assetItem.Text = m_VideoClip.m_Name;
break;
case MovieTexture _:
case TextAsset _:
case Font _:
case Sprite _:
assetItem.Text = ((NamedObject)asset).m_Name;
break;
case Shader m_Shader:
assetItem.Text = m_Shader.m_ParsedForm?.m_Name ?? m_Shader.m_Name;
break;
case MonoBehaviour m_MonoBehaviour:
if (m_MonoBehaviour.m_Name == "" && m_MonoBehaviour.m_Script.TryGet(out var m_Script))
{
assetItem.Text = m_Script.m_ClassName;
}
else
{
assetItem.Text = m_MonoBehaviour.m_Name;
}
break;
}
if (assetItem.Text == "")
{
assetItem.Text = assetItem.TypeString + assetItem.UniqueID;
}
isExportable = options.o_exportAssetTypes.Value.Contains(asset.type);
if (isExportable)
{
fileAssetsList.Add(assetItem);
}
Progress.Report(++i, objectCount);
}
foreach (var asset in fileAssetsList)
{
if (containers.ContainsKey(asset.Asset))
{
asset.Container = containers[asset.Asset];
}
}
parsedAssetsList.AddRange(fileAssetsList);
containers.Clear();
fileAssetsList.Clear();
}
}
public void ShowExportableAssetsInfo()
{
var exportableAssetsCountDict = new Dictionary<ClassIDType, int>();
string info = "";
if (parsedAssetsList.Count > 0)
{
foreach (var asset in parsedAssetsList)
{
if (exportableAssetsCountDict.ContainsKey(asset.Type))
{
exportableAssetsCountDict[asset.Type] += 1;
}
else
{
exportableAssetsCountDict.Add(asset.Type, 1);
}
}
info += "\n[Exportable Assets Count]\n";
foreach (var assetType in exportableAssetsCountDict.Keys)
{
info += $"# {assetType}: {exportableAssetsCountDict[assetType]}\n";
}
if (exportableAssetsCountDict.Count > 1)
{
info += $"#\n# Total: {parsedAssetsList.Count} assets";
}
}
else
{
info += "No exportable assets found.";
}
if (options.o_logLevel.Value > LoggerEvent.Info)
{
Console.WriteLine(info);
}
else
{
Logger.Info(info);
}
}
public void FilterAssets()
{
var assetsCount = parsedAssetsList.Count;
var filteredAssets = new List<AssetItem>();
switch(options.filterBy)
{
case FilterBy.Name:
filteredAssets = parsedAssetsList.FindAll(x => options.o_filterByName.Value.Any(y => x.Text.ToString().IndexOf(y, StringComparison.OrdinalIgnoreCase) >= 0));
Logger.Info(
$"Found [{filteredAssets.Count}/{assetsCount}] asset(s) " +
$"that contain {$"\"{string.Join("\", \"", options.o_filterByName.Value)}\"".Color(Ansi.BrightYellow)} in their Names."
);
break;
case FilterBy.Container:
filteredAssets = parsedAssetsList.FindAll(x => options.o_filterByContainer.Value.Any(y => x.Container.ToString().IndexOf(y, StringComparison.OrdinalIgnoreCase) >= 0));
Logger.Info(
$"Found [{filteredAssets.Count}/{assetsCount}] asset(s) " +
$"that contain {$"\"{string.Join("\", \"", options.o_filterByContainer.Value)}\"".Color(Ansi.BrightYellow)} in their Containers."
);
break;
case FilterBy.PathID:
filteredAssets = parsedAssetsList.FindAll(x => options.o_filterByPathID.Value.Any(y => x.m_PathID.ToString().IndexOf(y, StringComparison.OrdinalIgnoreCase) >= 0));
Logger.Info(
$"Found [{filteredAssets.Count}/{assetsCount}] asset(s) " +
$"that contain {$"\"{string.Join("\", \"", options.o_filterByPathID.Value)}\"".Color(Ansi.BrightYellow)} in their PathIDs."
);
break;
case FilterBy.NameOrContainer:
filteredAssets = parsedAssetsList.FindAll(x =>
options.o_filterByText.Value.Any(y => x.Text.ToString().IndexOf(y, StringComparison.OrdinalIgnoreCase) >= 0) ||
options.o_filterByText.Value.Any(y => x.Container.ToString().IndexOf(y, StringComparison.OrdinalIgnoreCase) >= 0)
);
Logger.Info(
$"Found [{filteredAssets.Count}/{assetsCount}] asset(s) " +
$"that contain {$"\"{string.Join("\", \"", options.o_filterByText.Value)}\"".Color(Ansi.BrightYellow)} in their Names or Contaniers."
);
break;
case FilterBy.NameAndContainer:
filteredAssets = parsedAssetsList.FindAll(x =>
options.o_filterByName.Value.Any(y => x.Text.ToString().IndexOf(y, StringComparison.OrdinalIgnoreCase) >= 0) &&
options.o_filterByContainer.Value.Any(y => x.Container.ToString().IndexOf(y, StringComparison.OrdinalIgnoreCase) >= 0)
);
Logger.Info(
$"Found [{filteredAssets.Count}/{assetsCount}] asset(s) " +
$"that contain {$"\"{string.Join("\", \"", options.o_filterByContainer.Value)}\"".Color(Ansi.BrightYellow)} in their Containers " +
$"and {$"\"{string.Join("\", \"", options.o_filterByName.Value)}\"".Color(Ansi.BrightYellow)} in their Names."
);
break;
}
parsedAssetsList.Clear();
parsedAssetsList = filteredAssets;
}
public void ExportAssets()
{
var savePath = options.o_outputFolder.Value;
var toExportCount = parsedAssetsList.Count;
var exportedCount = 0;
foreach (var asset in parsedAssetsList)
{
string exportPath;
switch (options.o_groupAssetsBy.Value)
{
case AssetGroupOption.TypeName:
exportPath = Path.Combine(savePath, asset.TypeString);
break;
case AssetGroupOption.ContainerPath:
if (!string.IsNullOrEmpty(asset.Container))
{
exportPath = Path.Combine(savePath, Path.GetDirectoryName(asset.Container));
}
else
{
exportPath = savePath;
}
break;
case AssetGroupOption.SourceFileName:
if (string.IsNullOrEmpty(asset.SourceFile.originalPath))
{
exportPath = Path.Combine(savePath, asset.SourceFile.fileName + "_export");
}
else
{
exportPath = Path.Combine(savePath, Path.GetFileName(asset.SourceFile.originalPath) + "_export", asset.SourceFile.fileName);
}
break;
default:
exportPath = savePath;
break;
}
exportPath += Path.DirectorySeparatorChar;
try
{
switch (options.o_workMode.Value)
{
case WorkMode.ExportRaw:
Logger.Debug($"{options.o_workMode}: {asset.Type} : {asset.Container} : {asset.Text}");
if (ExportRawFile(asset, exportPath))
{
exportedCount++;
}
break;
case WorkMode.Dump:
Logger.Debug($"{options.o_workMode}: {asset.Type} : {asset.Container} : {asset.Text}");
if (ExportDumpFile(asset, exportPath, options))
{
exportedCount++;
}
break;
case WorkMode.Export:
Logger.Debug($"{options.o_workMode}: {asset.Type} : {asset.Container} : {asset.Text}");
if (ExportConvertFile(asset, exportPath, options))
{
exportedCount++;
}
break;
}
}
catch (Exception ex)
{
Logger.Error($"{asset.SourceFile.originalPath}: [{$"{asset.Type}: {asset.Text}".Color(Ansi.BrightRed)}] : Export error\n{ex}");
}
Console.Write($"Exported [{exportedCount}/{toExportCount}]\r");
}
Console.WriteLine("");
if (exportedCount == 0)
{
Logger.Default.Log(LoggerEvent.Info, "Nothing exported.", ignoreLevel: true);
}
else if (toExportCount > exportedCount)
{
Logger.Default.Log(LoggerEvent.Info, $"Finished exporting {exportedCount} asset(s) to \"{options.o_outputFolder.Value.Color(Ansi.BrightYellow)}\".", ignoreLevel: true);
}
else
{
Logger.Default.Log(LoggerEvent.Info, $"Finished exporting {exportedCount} asset(s) to \"{options.o_outputFolder.Value.Color(Ansi.BrightGreen)}\".", ignoreLevel: true);
}
if (toExportCount > exportedCount)
{
Logger.Default.Log(LoggerEvent.Info, $"{toExportCount - exportedCount} asset(s) skipped (not extractable or file(s) already exist).", ignoreLevel: true);
}
}
public void ExportAssetList()
{
var savePath = options.o_outputFolder.Value;
switch (options.o_exportAssetList.Value)
{
case ExportListType.XML:
var filename = Path.Combine(savePath, "assets.xml");
var doc = new XDocument(
new XElement("Assets",
new XAttribute("filename", filename),
new XAttribute("createdAt", DateTime.UtcNow.ToString("s")),
parsedAssetsList.Select(
asset => new XElement("Asset",
new XElement("Name", asset.Text),
new XElement("Container", asset.Container),
new XElement("Type", new XAttribute("id", (int)asset.Type), asset.TypeString),
new XElement("PathID", asset.m_PathID),
new XElement("Source", asset.SourceFile.fullName),
new XElement("Size", asset.FullSize)
)
)
)
);
doc.Save(filename);
break;
}
Logger.Info($"Finished exporting asset list with {parsedAssetsList.Count} items.");
}
}
}

View File

@@ -29,26 +29,26 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
@@ -100,14 +100,14 @@
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_AS_DLL;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>C:\Program Files\Autodesk\FBX\FBX SDK\2020.0.1\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>C:\Program Files\Autodesk\FBX\FBX SDK\2020.2.1\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>libfbxsdk-mt.lib;libxml2-mt.lib;zlib-mt.lib;wininet.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>C:\Program Files\Autodesk\FBX\FBX SDK\2020.0.1\lib\vs2017\x86\debug;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalLibraryDirectories>C:\Program Files\Autodesk\FBX\FBX SDK\2020.2.1\lib\vs2019\x86\debug;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<IgnoreSpecificDefaultLibraries>LIBCMT;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
</Link>
</ItemDefinitionGroup>
@@ -119,7 +119,7 @@
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_AS_DLL;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>C:\Program Files\Autodesk\FBX\FBX SDK\2020.0.1\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>C:\Program Files\Autodesk\FBX\FBX SDK\2020.2.1\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
</ClCompile>
@@ -129,7 +129,7 @@
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>libfbxsdk-mt.lib;libxml2-mt.lib;zlib-mt.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>C:\Program Files\Autodesk\FBX\FBX SDK\2020.0.1\lib\vs2017\x86\release;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalLibraryDirectories>C:\Program Files\Autodesk\FBX\FBX SDK\2020.2.1\lib\vs2019\x86\release;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
@@ -138,14 +138,14 @@
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_AS_DLL;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>C:\Program Files\Autodesk\FBX\FBX SDK\2020.0.1\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>C:\Program Files\Autodesk\FBX\FBX SDK\2020.2.1\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>libfbxsdk-mt.lib;libxml2-mt.lib;zlib-mt.lib;wininet.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>C:\Program Files\Autodesk\FBX\FBX SDK\2020.0.1\lib\vs2017\x64\debug;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalLibraryDirectories>C:\Program Files\Autodesk\FBX\FBX SDK\2020.2.1\lib\vs2019\x64\debug;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<IgnoreSpecificDefaultLibraries>LIBCMT;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
</Link>
</ItemDefinitionGroup>
@@ -157,7 +157,7 @@
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_AS_DLL;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>C:\Program Files\Autodesk\FBX\FBX SDK\2020.0.1\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>C:\Program Files\Autodesk\FBX\FBX SDK\2020.2.1\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
</ClCompile>
@@ -167,7 +167,7 @@
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>libfbxsdk-mt.lib;libxml2-mt.lib;zlib-mt.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>C:\Program Files\Autodesk\FBX\FBX SDK\2020.0.1\lib\vs2017\x64\release;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalLibraryDirectories>C:\Program Files\Autodesk\FBX\FBX SDK\2020.2.1\lib\vs2019\x64\release;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemGroup>

View File

@@ -1,17 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net472;netstandard2.0</TargetFrameworks>
<TargetFrameworks>net472;net6.0;net6.0-windows;net7.0;net7.0-windows</TargetFrameworks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Version>0.16.8.1</Version>
<AssemblyVersion>0.16.8.1</AssemblyVersion>
<FileVersion>0.16.8.1</FileVersion>
<Copyright>Copyright © Perfare 2018-2021; Copyright © hozuki 2020</Copyright>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net472|AnyCPU'">
<DebugType>none</DebugType>
<DebugSymbols>false</DebugSymbols>
<Version>0.16.48.1</Version>
<Copyright>Copyright © Perfare 2018-2022; Copyright © hozuki 2020</Copyright>
<DebugType>embedded</DebugType>
</PropertyGroup>
<ItemGroup>

View File

@@ -1,16 +1,20 @@
using AssetStudio.FbxInterop;
using AssetStudio.PInvoke;
using System.IO;
#if NETFRAMEWORK
using AssetStudio.PInvoke;
#endif
namespace AssetStudio
{
public static partial class Fbx
{
#if NETFRAMEWORK
static Fbx()
{
DllLoader.PreloadDll(FbxDll.DllName);
}
#endif
public static Vector3 QuaternionToEuler(Quaternion q)
{

View File

@@ -1,72 +1,114 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net472</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
<ApplicationIcon>Resources\as.ico</ApplicationIcon>
<AssemblyTitle>AssetStudio Mod by VaDiM</AssemblyTitle>
<Version>0.16.8.1</Version>
<AssemblyVersion>0.16.8.1</AssemblyVersion>
<FileVersion>0.16.8.1</FileVersion>
<Copyright>Copyright © Perfare 2018-2021</Copyright>
</PropertyGroup>
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFrameworks>net472;net6.0-windows;net7.0-windows</TargetFrameworks>
<UseWindowsForms>true</UseWindowsForms>
<ApplicationIcon>Resources\as.ico</ApplicationIcon>
<AssemblyTitle>AssetStudio Mod by VaDiM</AssemblyTitle>
<Version>0.16.48.1</Version>
<Copyright>Copyright © Perfare 2018-2022</Copyright>
<DebugType>embedded</DebugType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DebugType>none</DebugType>
<DebugSymbols>false</DebugSymbols>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'net472' ">
<IsPublishable>false</IsPublishable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AssetStudioUtility\AssetStudioUtility.csproj" />
<ProjectReference Include="..\AssetStudio\AssetStudio.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AssetStudioUtility\AssetStudioUtility.csproj" />
<ProjectReference Include="..\AssetStudio\AssetStudio.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Update="Properties\Settings.Designer.cs">
<DesignTimeSharedInput>True</DesignTimeSharedInput>
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Update="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<Compile Update="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<Compile Update="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' != 'net472' ">
<PackageReference Include="OpenTK" Version="4.7.7" />
<Reference Include="OpenTK.WinForms">
<HintPath>Libraries\OpenTK.WinForms.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<ContentWithTargetPath Include="Libraries\x86\fmod.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<TargetPath>x86\fmod.dll</TargetPath>
</ContentWithTargetPath>
<ContentWithTargetPath Include="Libraries\x64\fmod.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<TargetPath>x64\fmod.dll</TargetPath>
</ContentWithTargetPath>
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net472' ">
<PackageReference Include="OpenTK" Version="3.3.3" />
<PackageReference Include="OpenTK.GLControl" Version="3.3.3" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="OpenTK" Version="3.1.0" />
<PackageReference Include="OpenTK.GLControl" Version="3.1.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
</ItemGroup>
<Target Name="CustomAfterBuild" AfterTargets="AfterBuild">
<Copy SourceFiles="$(SolutionDir)AssetStudioFBXNative\bin\Win32\$(Configuration)\AssetStudioFBXNative.dll" DestinationFolder="$(TargetDir)x86" ContinueOnError="true" />
<Copy SourceFiles="$(SolutionDir)AssetStudioFBXNative\bin\x64\$(Configuration)\AssetStudioFBXNative.dll" DestinationFolder="$(TargetDir)x64" ContinueOnError="true" />
<Copy SourceFiles="$(SolutionDir)Texture2DDecoderNative\bin\Win32\$(Configuration)\Texture2DDecoderNative.dll" DestinationFolder="$(TargetDir)x86" ContinueOnError="true" />
<Copy SourceFiles="$(SolutionDir)Texture2DDecoderNative\bin\x64\$(Configuration)\Texture2DDecoderNative.dll" DestinationFolder="$(TargetDir)x64" ContinueOnError="true" />
</Target>
</Project>
<!-- Use local compiled win-x86 and win-x64 Texture2DDecoder libs, because libs from Kyaru.Texture2DDecoder.Windows were compiled with /MD flag -->
<Target Name="CopyExtraFilesPortable" AfterTargets="AfterBuild" Condition=" '$(RuntimeIdentifier)' == '' OR '$(TargetFramework)' == 'net472' ">
<Message Text="Copying extra files for $(TargetFramework)... " Importance="high" />
<Copy SourceFiles="$(SolutionDir)Texture2DDecoderNative\bin\Win32\$(Configuration)\Texture2DDecoderNative.dll" DestinationFolder="$(TargetDir)runtimes\win-x86\native" ContinueOnError="false" />
<Copy SourceFiles="$(SolutionDir)Texture2DDecoderNative\bin\x64\$(Configuration)\Texture2DDecoderNative.dll" DestinationFolder="$(TargetDir)runtimes\win-x64\native" ContinueOnError="false" />
<Copy SourceFiles="$(SolutionDir)AssetStudioFBXNative\bin\Win32\$(Configuration)\AssetStudioFBXNative.dll" DestinationFolder="$(TargetDir)runtimes\win-x86\native" ContinueOnError="false" />
<Copy SourceFiles="$(SolutionDir)AssetStudioFBXNative\bin\x64\$(Configuration)\AssetStudioFBXNative.dll" DestinationFolder="$(TargetDir)runtimes\win-x64\native" ContinueOnError="false" />
<Copy SourceFiles="$(ProjectDir)Libraries\x86\fmod.dll" DestinationFolder="$(TargetDir)runtimes\win-x86\native" ContinueOnError="false" />
<Copy SourceFiles="$(ProjectDir)Libraries\x64\fmod.dll" DestinationFolder="$(TargetDir)runtimes\win-x64\native" ContinueOnError="false" />
</Target>
<!-- Publishing an app as framework-dependent produces a cross-platform binary as a dll file, and a platform-specific executable that targets your current platform.
The dll is cross-platform while the executable isn't -->
<Target Name="PublishExtraFilesPortable" AfterTargets="Publish" Condition=" '$(RuntimeIdentifier)' == '' ">
<Message Text="Publishing extra files for Portable build ($(TargetFramework))... " Importance="high" />
<Copy SourceFiles="$(TargetDir)runtimes\win-x86\native\AssetStudioFBXNative.dll" DestinationFolder="$(PublishDir)runtimes\win-x86\native" ContinueOnError="false" />
<Copy SourceFiles="$(TargetDir)runtimes\win-x64\native\AssetStudioFBXNative.dll" DestinationFolder="$(PublishDir)runtimes\win-x64\native" ContinueOnError="false" />
<Copy SourceFiles="$(TargetDir)runtimes\win-x86\native\Texture2DDecoderNative.dll" DestinationFolder="$(PublishDir)runtimes\win-x86\native" ContinueOnError="false" />
<Copy SourceFiles="$(TargetDir)runtimes\win-x64\native\Texture2DDecoderNative.dll" DestinationFolder="$(PublishDir)runtimes\win-x64\native" ContinueOnError="false" />
<Copy SourceFiles="$(TargetDir)runtimes\win-x86\native\fmod.dll" DestinationFolder="$(PublishDir)runtimes\win-x86\native" ContinueOnError="false" />
<Copy SourceFiles="$(TargetDir)runtimes\win-x64\native\fmod.dll" DestinationFolder="$(PublishDir)runtimes\win-x64\native" ContinueOnError="false" />
</Target>
<!-- No need to publish net472 build of AssetStudioGUI -->
<Target Name="PublishNet472" AfterTargets="Publish" Condition=" '$(TargetFramework)' == 'net472' ">
<Message Text="%0a NOTE: Publishing net472 build of AssetStudioGUI was disabled." Importance="high" />
<Message Text=" Instead, use the binaries created after the build.%0a" Importance="high" />
</Target>
<Target Name="CopyExtraFilesWin86" AfterTargets="AfterBuild" Condition=" $(RuntimeIdentifier.Contains('-x86')) AND '$(TargetFramework)' != 'net472' ">
<Message Text="Copying extra files for $(RuntimeIdentifier)($(TargetFramework))... " Importance="high" />
<Copy SourceFiles="$(SolutionDir)Texture2DDecoderNative\bin\Win32\$(Configuration)\Texture2DDecoderNative.dll" DestinationFolder="$(TargetDir)" ContinueOnError="false" />
<Copy SourceFiles="$(SolutionDir)AssetStudioFBXNative\bin\Win32\$(Configuration)\AssetStudioFBXNative.dll" DestinationFolder="$(TargetDir)" ContinueOnError="false" />
<Copy SourceFiles="$(ProjectDir)Libraries\x86\fmod.dll" DestinationFolder="$(TargetDir)" ContinueOnError="false" />
</Target>
<Target Name="CopyExtraFilesWin64" AfterTargets="AfterBuild" Condition=" '$(RuntimeIdentifier)' == 'win-x64' AND '$(TargetFramework)' != 'net472' ">
<Message Text="Copying extra files for $(RuntimeIdentifier)($(TargetFramework))... " Importance="high" />
<Copy SourceFiles="$(SolutionDir)Texture2DDecoderNative\bin\x64\$(Configuration)\Texture2DDecoderNative.dll" DestinationFolder="$(TargetDir)" ContinueOnError="false" />
<Copy SourceFiles="$(SolutionDir)AssetStudioFBXNative\bin\x64\$(Configuration)\AssetStudioFBXNative.dll" DestinationFolder="$(TargetDir)" ContinueOnError="false" />
<Copy SourceFiles="$(ProjectDir)Libraries\x64\fmod.dll" DestinationFolder="$(TargetDir)" ContinueOnError="false" />
</Target>
<Target Name="PublishExtraFilesWin" AfterTargets="Publish" Condition=" $(RuntimeIdentifier.Contains('win')) AND '$(TargetFramework)' != 'net472' ">
<Message Text="Publishing extra files for $(RuntimeIdentifier)($(TargetFramework))... " Importance="high" />
<Copy SourceFiles="$(TargetDir)\AssetStudioFBXNative.dll" DestinationFolder="$(PublishDir)" ContinueOnError="false" />
<Copy SourceFiles="$(TargetDir)\Texture2DDecoderNative.dll" DestinationFolder="$(PublishDir)" ContinueOnError="false" />
<Copy SourceFiles="$(TargetDir)\fmod.dll" DestinationFolder="$(PublishDir)" ContinueOnError="false" />
</Target>
</Project>

View File

@@ -82,6 +82,7 @@
this.sceneTreeView = new AssetStudioGUI.GOHierarchy();
this.treeSearch = new System.Windows.Forms.TextBox();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.filterExcludeMode = new System.Windows.Forms.CheckBox();
this.assetListView = new System.Windows.Forms.ListView();
this.columnHeaderName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeaderContainer = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
@@ -118,6 +119,12 @@
this.dumpTextBox = new System.Windows.Forms.TextBox();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.contextMenuStrip2 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.selectNoneToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.collapseAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.expandAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.timer = new System.Windows.Forms.Timer(this.components);
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
@@ -145,6 +152,7 @@
((System.ComponentModel.ISupportInitialize)(this.FMODvolumeBar)).BeginInit();
this.tabPage5.SuspendLayout();
this.statusStrip1.SuspendLayout();
this.contextMenuStrip2.SuspendLayout();
this.contextMenuStrip1.SuspendLayout();
this.SuspendLayout();
//
@@ -582,6 +590,7 @@
this.sceneTreeView.Size = new System.Drawing.Size(472, 587);
this.sceneTreeView.TabIndex = 1;
this.sceneTreeView.AfterCheck += new System.Windows.Forms.TreeViewEventHandler(this.sceneTreeView_AfterCheck);
this.sceneTreeView.MouseClick += new System.Windows.Forms.MouseEventHandler(this.sceneTreeView_MouseClick);
//
// treeSearch
//
@@ -599,6 +608,7 @@
//
// tabPage2
//
this.tabPage2.Controls.Add(this.filterExcludeMode);
this.tabPage2.Controls.Add(this.assetListView);
this.tabPage2.Controls.Add(this.listSearch);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
@@ -608,6 +618,24 @@
this.tabPage2.Text = "Asset List";
this.tabPage2.UseVisualStyleBackColor = true;
//
// filterExcludeMode
//
this.filterExcludeMode.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.filterExcludeMode.AutoSize = true;
this.filterExcludeMode.BackColor = System.Drawing.Color.WhiteSmoke;
this.filterExcludeMode.Enabled = false;
this.filterExcludeMode.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.filterExcludeMode.ForeColor = System.Drawing.SystemColors.ControlText;
this.filterExcludeMode.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.filterExcludeMode.Location = new System.Drawing.Point(409, 2);
this.filterExcludeMode.Name = "filterExcludeMode";
this.filterExcludeMode.Size = new System.Drawing.Size(61, 17);
this.filterExcludeMode.TabIndex = 2;
this.filterExcludeMode.Text = "Exclude";
this.filterExcludeMode.TextAlign = System.Drawing.ContentAlignment.BottomRight;
this.filterExcludeMode.UseVisualStyleBackColor = false;
this.filterExcludeMode.CheckedChanged += new System.EventHandler(this.filterExcludeMode_CheckedChanged);
//
// assetListView
//
this.assetListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
@@ -723,6 +751,7 @@
// progressBar1
//
this.progressBar1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.progressBar1.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.progressBar1.Location = new System.Drawing.Point(1, 3);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(478, 18);
@@ -774,6 +803,7 @@
this.assetInfoLabel.AutoSize = true;
this.assetInfoLabel.BackColor = System.Drawing.Color.Transparent;
this.assetInfoLabel.ForeColor = System.Drawing.SystemColors.ControlLightLight;
this.assetInfoLabel.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.assetInfoLabel.Location = new System.Drawing.Point(4, 8);
this.assetInfoLabel.Name = "assetInfoLabel";
this.assetInfoLabel.Size = new System.Drawing.Size(0, 13);
@@ -803,6 +833,7 @@
//
this.FMODcopyright.AutoSize = true;
this.FMODcopyright.ForeColor = System.Drawing.SystemColors.ControlLight;
this.FMODcopyright.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.FMODcopyright.Location = new System.Drawing.Point(214, 365);
this.FMODcopyright.Name = "FMODcopyright";
this.FMODcopyright.Size = new System.Drawing.Size(283, 13);
@@ -813,33 +844,38 @@
//
this.FMODinfoLabel.AutoSize = true;
this.FMODinfoLabel.ForeColor = System.Drawing.SystemColors.ControlLightLight;
this.FMODinfoLabel.Location = new System.Drawing.Point(269, 255);
this.FMODinfoLabel.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.FMODinfoLabel.Location = new System.Drawing.Point(275, 255);
this.FMODinfoLabel.Name = "FMODinfoLabel";
this.FMODinfoLabel.Size = new System.Drawing.Size(0, 13);
this.FMODinfoLabel.TabIndex = 8;
//
// FMODtimerLabel
//
this.FMODtimerLabel.AutoSize = true;
this.FMODtimerLabel.ForeColor = System.Drawing.SystemColors.ControlLightLight;
this.FMODtimerLabel.Location = new System.Drawing.Point(404, 255);
this.FMODtimerLabel.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.FMODtimerLabel.Location = new System.Drawing.Point(457, 253);
this.FMODtimerLabel.Name = "FMODtimerLabel";
this.FMODtimerLabel.Size = new System.Drawing.Size(155, 13);
this.FMODtimerLabel.Size = new System.Drawing.Size(102, 13);
this.FMODtimerLabel.TabIndex = 7;
this.FMODtimerLabel.Text = "0:00.0 / 0:00.0";
this.FMODtimerLabel.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.FMODtimerLabel.Text = "00:00.00 / 00:00.00";
//
// FMODstatusLabel
//
this.FMODstatusLabel.AutoSize = true;
this.FMODstatusLabel.ForeColor = System.Drawing.SystemColors.ControlLightLight;
this.FMODstatusLabel.Location = new System.Drawing.Point(213, 255);
this.FMODstatusLabel.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.FMODstatusLabel.Location = new System.Drawing.Point(214, 255);
this.FMODstatusLabel.Name = "FMODstatusLabel";
this.FMODstatusLabel.Size = new System.Drawing.Size(50, 13);
this.FMODstatusLabel.Size = new System.Drawing.Size(47, 13);
this.FMODstatusLabel.TabIndex = 6;
this.FMODstatusLabel.Text = "Stopped";
//
// FMODprogressBar
//
this.FMODprogressBar.AutoSize = false;
this.FMODprogressBar.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.FMODprogressBar.Location = new System.Drawing.Point(213, 274);
this.FMODprogressBar.Maximum = 1000;
this.FMODprogressBar.Name = "FMODprogressBar";
@@ -852,6 +888,7 @@
//
// FMODvolumeBar
//
this.FMODvolumeBar.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.FMODvolumeBar.LargeChange = 2;
this.FMODvolumeBar.Location = new System.Drawing.Point(460, 303);
this.FMODvolumeBar.Name = "FMODvolumeBar";
@@ -864,6 +901,7 @@
// FMODloopButton
//
this.FMODloopButton.Appearance = System.Windows.Forms.Appearance.Button;
this.FMODloopButton.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.FMODloopButton.Location = new System.Drawing.Point(399, 303);
this.FMODloopButton.Name = "FMODloopButton";
this.FMODloopButton.Size = new System.Drawing.Size(55, 46);
@@ -875,6 +913,7 @@
//
// FMODstopButton
//
this.FMODstopButton.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.FMODstopButton.Location = new System.Drawing.Point(338, 303);
this.FMODstopButton.Name = "FMODstopButton";
this.FMODstopButton.Size = new System.Drawing.Size(55, 46);
@@ -885,6 +924,7 @@
//
// FMODpauseButton
//
this.FMODpauseButton.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.FMODpauseButton.Location = new System.Drawing.Point(277, 303);
this.FMODpauseButton.Name = "FMODpauseButton";
this.FMODpauseButton.Size = new System.Drawing.Size(55, 46);
@@ -895,6 +935,7 @@
//
// FMODplayButton
//
this.FMODplayButton.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.FMODplayButton.Location = new System.Drawing.Point(216, 303);
this.FMODplayButton.Name = "FMODplayButton";
this.FMODplayButton.Size = new System.Drawing.Size(55, 46);
@@ -936,7 +977,7 @@
// textPreviewBox
//
this.textPreviewBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.textPreviewBox.Font = new System.Drawing.Font("Consolas", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.textPreviewBox.Font = new System.Drawing.Font("Consolas", 9.75F);
this.textPreviewBox.Location = new System.Drawing.Point(0, 0);
this.textPreviewBox.Multiline = true;
this.textPreviewBox.Name = "textPreviewBox";
@@ -1001,6 +1042,50 @@
this.toolStripStatusLabel1.Text = "Ready to go";
this.toolStripStatusLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// contextMenuStrip2
//
this.contextMenuStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.selectAllToolStripMenuItem,
this.selectNoneToolStripMenuItem,
this.toolStripSeparator5,
this.expandAllToolStripMenuItem,
this.collapseAllToolStripMenuItem});
this.contextMenuStrip2.Name = "contextMenuStrip2";
this.contextMenuStrip2.Size = new System.Drawing.Size(181, 120);
//
// selectAllToolStripMenuItem
//
this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem";
this.selectAllToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.selectAllToolStripMenuItem.Text = "Select all";
this.selectAllToolStripMenuItem.Click += new System.EventHandler(this.selectAllToolStripMenuItem_Click);
//
// selectNoneToolStripMenuItem
//
this.selectNoneToolStripMenuItem.Name = "selectNoneToolStripMenuItem";
this.selectNoneToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.selectNoneToolStripMenuItem.Text = "Select none";
this.selectNoneToolStripMenuItem.Click += new System.EventHandler(this.selectNoneToolStripMenuItem_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(177, 6);
//
// collapseAllToolStripMenuItem
//
this.collapseAllToolStripMenuItem.Name = "collapseAllToolStripMenuItem";
this.collapseAllToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.collapseAllToolStripMenuItem.Text = "Collapse all";
this.collapseAllToolStripMenuItem.Click += new System.EventHandler(this.collapseAllToolStripMenuItem_Click);
//
// expandAllToolStripMenuItem
//
this.expandAllToolStripMenuItem.Name = "expandAllToolStripMenuItem";
this.expandAllToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.expandAllToolStripMenuItem.Text = "Expand all";
this.expandAllToolStripMenuItem.Click += new System.EventHandler(this.expandAllToolStripMenuItem_Click);
//
// timer
//
this.timer.Interval = 10;
@@ -1024,7 +1109,7 @@
this.goToSceneHierarchyToolStripMenuItem,
this.showOriginalFileToolStripMenuItem});
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(304, 158);
this.contextMenuStrip1.Size = new System.Drawing.Size(304, 136);
//
// copyToolStripMenuItem
//
@@ -1074,8 +1159,6 @@
// AssetStudioGUIForm
//
this.AllowDrop = true;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1264, 681);
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.menuStrip1);
@@ -1115,6 +1198,7 @@
this.tabPage5.PerformLayout();
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.contextMenuStrip2.ResumeLayout(false);
this.contextMenuStrip1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
@@ -1220,6 +1304,13 @@
private System.Windows.Forms.ToolStripTextBox specifyUnityVersion;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem15;
private System.Windows.Forms.ToolStripMenuItem dumpSelectedAssetsToolStripMenuItem;
private System.Windows.Forms.CheckBox filterExcludeMode;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip2;
private System.Windows.Forms.ToolStripMenuItem selectAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem selectNoneToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripMenuItem collapseAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem expandAllToolStripMenuItem;
}
}

View File

@@ -6,7 +6,6 @@ using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Globalization;
using System.IO;
@@ -19,17 +18,21 @@ using System.Timers;
using System.Windows.Forms;
using static AssetStudioGUI.Studio;
using Font = AssetStudio.Font;
using ImageFormat = AssetStudio.ImageFormat;
using PixelFormat = System.Drawing.Imaging.PixelFormat;
#if NET472
using Vector3 = OpenTK.Vector3;
using Vector4 = OpenTK.Vector4;
#else
using Vector3 = OpenTK.Mathematics.Vector3;
using Vector4 = OpenTK.Mathematics.Vector4;
using Matrix4 = OpenTK.Mathematics.Matrix4;
#endif
namespace AssetStudioGUI
{
partial class AssetStudioGUIForm : Form
{
private AssetItem lastSelectedItem;
private Bitmap imageTexture;
private DirectBitmap imageTexture;
private string tempClipboard;
private FMOD.System system;
@@ -40,6 +43,10 @@ namespace AssetStudioGUI
private uint FMODlenms;
private float FMODVolume = 0.8f;
#region SpriteControl
private SpriteMaskMode spriteMaskVisibleMode = SpriteMaskMode.On;
#endregion
#region TexControl
private static char[] textureChannelNames = new[] { 'B', 'G', 'R', 'A' };
private bool[] textureChannels = new[] { true, true, true, true };
@@ -73,7 +80,12 @@ namespace AssetStudioGUI
//asset list sorting
private int sortColumn = -1;
private bool reverseSort;
#if NET6_0_OR_GREATER
private AlphanumComparatorFastNet alphanumComparator = new AlphanumComparatorFastNet();
#else
private AlphanumComparatorFast alphanumComparator = new AlphanumComparatorFast();
#endif
//asset list filter
private System.Timers.Timer delayTimer;
@@ -105,7 +117,7 @@ namespace AssetStudioGUI
logger = new GUILogger(StatusStripUpdate);
Logger.Default = logger;
Progress.Default = new GUIProgress(SetProgressBarValue);
Progress.Default = new Progress<int>(SetProgressBarValue);
Studio.StatusStripUpdate = StatusStripUpdate;
}
@@ -139,7 +151,7 @@ namespace AssetStudioGUI
private async void loadFile_Click(object sender, EventArgs e)
{
openFileDialog1.InitialDirectory = openDirectoryBackup;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
ResetForm();
openDirectoryBackup = Path.GetDirectoryName(openFileDialog1.FileNames[0]);
@@ -165,7 +177,7 @@ namespace AssetStudioGUI
private async void extractFileToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
var saveFolderDialog = new OpenFolderDialog();
saveFolderDialog.Title = "Select the save folder";
@@ -174,7 +186,7 @@ namespace AssetStudioGUI
var fileNames = openFileDialog1.FileNames;
var savePath = saveFolderDialog.Folder;
var extractedCount = await Task.Run(() => ExtractFile(fileNames, savePath));
StatusStripUpdate($"Finished extracting {extractedCount} files.");
Logger.Info($"Finished extracting {extractedCount} files.");
}
}
}
@@ -191,7 +203,7 @@ namespace AssetStudioGUI
var path = openFolderDialog.Folder;
var savePath = saveFolderDialog.Folder;
var extractedCount = await Task.Run(() => ExtractFolder(path, savePath));
StatusStripUpdate($"Finished extracting {extractedCount} files.");
Logger.Info($"Finished extracting {extractedCount} files.");
}
}
}
@@ -200,7 +212,8 @@ namespace AssetStudioGUI
{
if (assetsManager.assetsFileList.Count == 0)
{
StatusStripUpdate("No Unity file can be loaded.");
filterExcludeModeCheck(assetsManager.assetsFileList.Count);
Logger.Info("No Unity file can be loaded.");
return;
}
@@ -220,10 +233,6 @@ namespace AssetStudioGUI
sceneTreeView.BeginUpdate();
sceneTreeView.Nodes.AddRange(treeNodeCollection.ToArray());
foreach (var node in treeNodeCollection)
{
node.HideCheckBox();
}
sceneTreeView.EndUpdate();
treeNodeCollection.Clear();
@@ -242,6 +251,8 @@ namespace AssetStudioGUI
typeMap.Clear();
classesListView.EndUpdate();
filterExcludeModeCheck(exportableAssets.Count);
var types = exportableAssets.Select(x => x.Type).Distinct().OrderBy(x => x.ToString()).ToArray();
foreach (var type in types)
{
@@ -263,7 +274,7 @@ namespace AssetStudioGUI
{
log += $" and {m_ObjectsCount - objectsCount} assets failed to read";
}
StatusStripUpdate(log);
Logger.Info(log);
}
private void typeToolStripMenuItem_Click(object sender, EventArgs e)
@@ -316,24 +327,41 @@ namespace AssetStudioGUI
if (e.Control)
{
var need = false;
switch (e.KeyCode)
if (lastSelectedItem?.Type == ClassIDType.Texture2D)
{
case Keys.B:
textureChannels[0] = !textureChannels[0];
need = true;
break;
case Keys.G:
textureChannels[1] = !textureChannels[1];
need = true;
break;
case Keys.R:
textureChannels[2] = !textureChannels[2];
need = true;
break;
case Keys.A:
textureChannels[3] = !textureChannels[3];
need = true;
break;
switch (e.KeyCode)
{
case Keys.B:
textureChannels[0] = !textureChannels[0];
need = true;
break;
case Keys.G:
textureChannels[1] = !textureChannels[1];
need = true;
break;
case Keys.R:
textureChannels[2] = !textureChannels[2];
need = true;
break;
case Keys.A:
textureChannels[3] = !textureChannels[3];
need = true;
break;
}
}
else if (lastSelectedItem?.Type == ClassIDType.Sprite && !((Sprite)lastSelectedItem.Asset).m_RD.alphaTexture.IsNull)
{
switch (e.KeyCode)
{
case Keys.A:
spriteMaskVisibleMode = spriteMaskVisibleMode == SpriteMaskMode.On ? SpriteMaskMode.Off : SpriteMaskMode.On;
need = true;
break;
case Keys.M:
spriteMaskVisibleMode = spriteMaskVisibleMode == SpriteMaskMode.MaskOnly ? SpriteMaskMode.On : SpriteMaskMode.MaskOnly;
need = true;
break;
}
}
if (need)
{
@@ -369,7 +397,7 @@ namespace AssetStudioGUI
Progress.Report(++i, count);
}
StatusStripUpdate("Finished exporting class structures");
Logger.Info("Finished exporting class structures");
}
}
}
@@ -391,7 +419,7 @@ namespace AssetStudioGUI
{
if (enablePreview.Checked && imageTexture != null)
{
previewPanel.BackgroundImage = imageTexture;
previewPanel.BackgroundImage = imageTexture.Bitmap;
}
else
{
@@ -412,7 +440,7 @@ namespace AssetStudioGUI
{
FMODpanel.Visible = !FMODpanel.Visible;
if (sound != null && channel != null)
if (sound.hasHandle() && channel.hasHandle())
{
var result = channel.isPlaying(out var playing);
if (result == FMOD.RESULT.OK && playing)
@@ -459,7 +487,7 @@ namespace AssetStudioGUI
private void showExpOpt_Click(object sender, EventArgs e)
{
var exportOpt = new ExportOptions();
exportOpt.ShowDialog();
exportOpt.ShowDialog(this);
}
private void assetListView_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
@@ -635,9 +663,10 @@ namespace AssetStudioGUI
{
visibleAssets.Sort((a, b) =>
{
var at = a.SubItems[sortColumn].Text;
var bt = b.SubItems[sortColumn].Text;
return reverseSort ? bt.CompareTo(at) : at.CompareTo(bt);
var at = a.SubItems[sortColumn].Text.AsSpan();
var bt = b.SubItems[sortColumn].Text.AsSpan();
return reverseSort ? MemoryExtensions.CompareTo(bt, at, StringComparison.OrdinalIgnoreCase) : MemoryExtensions.CompareTo(at, bt, StringComparison.OrdinalIgnoreCase);
});
}
assetListView.EndUpdate();
@@ -732,7 +761,9 @@ namespace AssetStudioGUI
case Mesh m_Mesh:
PreviewMesh(m_Mesh);
break;
case VideoClip _:
case VideoClip m_VideoClip:
PreviewVideoClip(assetItem, m_VideoClip);
break;
case MovieTexture _:
StatusStripUpdate("Only supported export.");
break;
@@ -763,9 +794,11 @@ namespace AssetStudioGUI
private void PreviewTexture2D(AssetItem assetItem, Texture2D m_Texture2D)
{
var bitmap = m_Texture2D.ConvertToBitmap(true);
if (bitmap != null)
var image = m_Texture2D.ConvertToImage(true);
if (image != null)
{
var bitmap = new DirectBitmap(image);
image.Dispose();
assetItem.InfoText = $"Width: {m_Texture2D.m_Width}\nHeight: {m_Texture2D.m_Height}\nFormat: {m_Texture2D.m_TextureFormat}";
switch (m_Texture2D.m_TextureSettings.m_FilterMode)
{
@@ -793,13 +826,11 @@ namespace AssetStudioGUI
assetItem.InfoText += "None";
if (validChannel != 4)
{
var bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
var bytes = new byte[bitmap.Width * bitmap.Height * 4];
Marshal.Copy(bmpData.Scan0, bytes, 0, bytes.Length);
for (int i = 0; i < bmpData.Height; i++)
var bytes = bitmap.Bits;
for (int i = 0; i < bitmap.Height; i++)
{
int offset = Math.Abs(bmpData.Stride) * i;
for (int j = 0; j < bmpData.Width; j++)
int offset = Math.Abs(bitmap.Stride) * i;
for (int j = 0; j < bitmap.Width; j++)
{
bytes[offset] = textureChannels[0] ? bytes[offset] : validChannel == 1 && textureChannels[3] ? byte.MaxValue : byte.MinValue;
bytes[offset + 1] = textureChannels[1] ? bytes[offset + 1] : validChannel == 1 && textureChannels[3] ? byte.MaxValue : byte.MinValue;
@@ -808,8 +839,6 @@ namespace AssetStudioGUI
offset += 4;
}
}
Marshal.Copy(bytes, 0, bmpData.Scan0, bytes.Length);
bitmap.UnlockBits(bmpData);
}
PreviewTexture(bitmap);
@@ -829,44 +858,44 @@ namespace AssetStudioGUI
{
switch (m_AudioClip.m_Type)
{
case AudioType.ACC:
case FMODSoundType.ACC:
assetItem.InfoText += "Acc";
break;
case AudioType.AIFF:
case FMODSoundType.AIFF:
assetItem.InfoText += "AIFF";
break;
case AudioType.IT:
case FMODSoundType.IT:
assetItem.InfoText += "Impulse tracker";
break;
case AudioType.MOD:
case FMODSoundType.MOD:
assetItem.InfoText += "Protracker / Fasttracker MOD";
break;
case AudioType.MPEG:
case FMODSoundType.MPEG:
assetItem.InfoText += "MP2/MP3 MPEG";
break;
case AudioType.OGGVORBIS:
case FMODSoundType.OGGVORBIS:
assetItem.InfoText += "Ogg vorbis";
break;
case AudioType.S3M:
case FMODSoundType.S3M:
assetItem.InfoText += "ScreamTracker 3";
break;
case AudioType.WAV:
case FMODSoundType.WAV:
assetItem.InfoText += "Microsoft WAV";
break;
case AudioType.XM:
case FMODSoundType.XM:
assetItem.InfoText += "FastTracker 2 XM";
break;
case AudioType.XMA:
case FMODSoundType.XMA:
assetItem.InfoText += "Xbox360 XMA";
break;
case AudioType.VAG:
case FMODSoundType.VAG:
assetItem.InfoText += "PlayStation Portable ADPCM";
break;
case AudioType.AUDIOQUEUE:
case FMODSoundType.AUDIOQUEUE:
assetItem.InfoText += "iPhone";
break;
default:
assetItem.InfoText += "Unknown";
assetItem.InfoText += $"Unknown ({m_AudioClip.m_Type})";
break;
}
}
@@ -886,7 +915,7 @@ namespace AssetStudioGUI
case AudioCompressionFormat.MP3:
assetItem.InfoText += "MP3";
break;
case AudioCompressionFormat.VAG:
case AudioCompressionFormat.PSMVAG:
assetItem.InfoText += "PlayStation Portable ADPCM";
break;
case AudioCompressionFormat.HEVAG:
@@ -935,7 +964,8 @@ namespace AssetStudioGUI
result = sound.getLength(out FMODlenms, FMOD.TIMEUNIT.MS);
if (ERRCHECK(result)) return;
result = system.playSound(sound, null, true, out channel);
_ = system.getMasterChannelGroup(out var channelGroup);
result = system.playSound(sound, channelGroup, true, out channel);
if (ERRCHECK(result)) return;
FMODpanel.Visible = true;
@@ -944,7 +974,19 @@ namespace AssetStudioGUI
if (ERRCHECK(result)) return;
FMODinfoLabel.Text = frequency + " Hz";
FMODtimerLabel.Text = $"0:0.0 / {FMODlenms / 1000 / 60}:{FMODlenms / 1000 % 60}.{FMODlenms / 10 % 100}";
FMODtimerLabel.Text = $"00:00.00 / {(FMODlenms / 1000 / 60):00}:{(FMODlenms / 1000 % 60):00}.{(FMODlenms / 10 % 100):00}";
}
private void PreviewVideoClip(AssetItem assetItem, VideoClip m_VideoClip)
{
var sb = new StringBuilder();
sb.AppendLine($"Width: {m_VideoClip.Width}");
sb.AppendLine($"Height: {m_VideoClip.Height}");
sb.AppendLine($"Frame rate: {m_VideoClip.m_FrameRate}");
sb.AppendLine($"Split alpha: {m_VideoClip.m_HasSplitAlpha}");
assetItem.InfoText = sb.ToString();
StatusStripUpdate("Only supported export.");
}
private void PreviewShader(Shader m_Shader)
@@ -1173,11 +1215,19 @@ namespace AssetStudioGUI
private void PreviewSprite(AssetItem assetItem, Sprite m_Sprite)
{
var bitmap = m_Sprite.GetImage();
if (bitmap != null)
var image = m_Sprite.GetImage(spriteMaskMode: spriteMaskVisibleMode);
if (image != null)
{
var bitmap = new DirectBitmap(image);
image.Dispose();
assetItem.InfoText = $"Width: {bitmap.Width}\nHeight: {bitmap.Height}\n";
PreviewTexture(bitmap);
if (!m_Sprite.m_RD.alphaTexture.IsNull)
{
assetItem.InfoText += $"Alpha Mask: {spriteMaskVisibleMode}\n";
StatusStripUpdate("'Ctrl'+'A' - Enable/Disable alpha mask usage. 'Ctrl'+'M' - Show alpha mask only.");
}
}
else
{
@@ -1185,11 +1235,11 @@ namespace AssetStudioGUI
}
}
private void PreviewTexture(Bitmap bitmap)
private void PreviewTexture(DirectBitmap bitmap)
{
imageTexture?.Dispose();
imageTexture = bitmap;
previewPanel.BackgroundImage = imageTexture;
previewPanel.BackgroundImage = imageTexture.Bitmap;
if (imageTexture.Width > previewPanel.Width || imageTexture.Height > previewPanel.Height)
previewPanel.BackgroundImageLayout = ImageLayout.Zoom;
else
@@ -1218,7 +1268,7 @@ namespace AssetStudioGUI
{
if (InvokeRequired)
{
BeginInvoke(new Action(() => { toolStripStatusLabel1.Text = statusText; }));
Invoke(new Action(() => { toolStripStatusLabel1.Text = statusText; }));
}
else
{
@@ -1240,6 +1290,7 @@ namespace AssetStudioGUI
classesListView.Groups.Clear();
previewPanel.BackgroundImage = Properties.Resources.preview;
imageTexture?.Dispose();
imageTexture = null;
previewPanel.BackgroundImageLayout = ImageLayout.Center;
assetInfoLabel.Visible = false;
assetInfoLabel.Text = null;
@@ -1263,6 +1314,14 @@ namespace AssetStudioGUI
FMODreset();
}
private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl2.SelectedIndex == 1 && lastSelectedItem != null)
{
dumpTextBox.Text = DumpAsset(lastSelectedItem.Asset);
}
}
private void assetListView_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right && assetListView.SelectedIndices.Count > 0)
@@ -1400,25 +1459,32 @@ namespace AssetStudioGUI
{
var gameObjects = new List<GameObject>();
GetSelectedParentNode(sceneTreeView.Nodes, gameObjects);
var saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = gameObjects[0].m_Name + " (merge).fbx";
saveFileDialog.AddExtension = false;
saveFileDialog.Filter = "Fbx file (*.fbx)|*.fbx";
saveFileDialog.InitialDirectory = saveDirectoryBackup;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
if (gameObjects.Count > 0)
{
saveDirectoryBackup = Path.GetDirectoryName(saveFileDialog.FileName);
var exportPath = saveFileDialog.FileName;
List<AssetItem> animationList = null;
if (animation)
var saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = gameObjects[0].m_Name + " (merge).fbx";
saveFileDialog.AddExtension = false;
saveFileDialog.Filter = "Fbx file (*.fbx)|*.fbx";
saveFileDialog.InitialDirectory = saveDirectoryBackup;
if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
{
animationList = GetSelectedAssets().Where(x => x.Type == ClassIDType.AnimationClip).ToList();
if (animationList.Count == 0)
saveDirectoryBackup = Path.GetDirectoryName(saveFileDialog.FileName);
var exportPath = saveFileDialog.FileName;
List<AssetItem> animationList = null;
if (animation)
{
animationList = null;
animationList = GetSelectedAssets().Where(x => x.Type == ClassIDType.AnimationClip).ToList();
if (animationList.Count == 0)
{
animationList = null;
}
}
ExportObjectsMergeWithAnimationClip(exportPath, gameObjects, animationList);
}
ExportObjectsMergeWithAnimationClip(exportPath, gameObjects, animationList);
}
else
{
StatusStripUpdate("No Object selected for export.");
}
}
}
@@ -1535,6 +1601,20 @@ namespace AssetStudioGUI
return selectedAssets;
}
private void filterExcludeMode_CheckedChanged(object sender, EventArgs e)
{
FilterAssetList();
}
private void filterExcludeModeCheck(int itemCount)
{
filterExcludeMode.Enabled = itemCount > 0;
if (!filterExcludeMode.Enabled)
{
filterExcludeMode.Checked = false;
}
}
private void FilterAssetList()
{
assetListView.BeginUpdate();
@@ -1558,10 +1638,20 @@ namespace AssetStudioGUI
}
if (listSearch.Text != " Filter ")
{
visibleAssets = visibleAssets.FindAll(
x => x.Text.IndexOf(listSearch.Text, StringComparison.OrdinalIgnoreCase) >= 0 ||
x.SubItems[1].Text.IndexOf(listSearch.Text, StringComparison.OrdinalIgnoreCase) >= 0 ||
x.SubItems[3].Text.IndexOf(listSearch.Text, StringComparison.OrdinalIgnoreCase) >= 0);
if (filterExcludeMode.Checked)
{
visibleAssets = visibleAssets.FindAll(
x => x.Text.IndexOf(listSearch.Text, StringComparison.OrdinalIgnoreCase) <= 0 &&
x.SubItems[1].Text.IndexOf(listSearch.Text, StringComparison.OrdinalIgnoreCase) <= 0 &&
x.SubItems[3].Text.IndexOf(listSearch.Text, StringComparison.OrdinalIgnoreCase) <= 0);
}
else
{
visibleAssets = visibleAssets.FindAll(
x => x.Text.IndexOf(listSearch.Text, StringComparison.OrdinalIgnoreCase) >= 0 ||
x.SubItems[1].Text.IndexOf(listSearch.Text, StringComparison.OrdinalIgnoreCase) >= 0 ||
x.SubItems[3].Text.IndexOf(listSearch.Text, StringComparison.OrdinalIgnoreCase) >= 0);
}
}
assetListView.VirtualListSize = visibleAssets.Count;
assetListView.EndUpdate();
@@ -1633,6 +1723,65 @@ namespace AssetStudioGUI
}
}
private void toolStripMenuItem15_Click(object sender, EventArgs e)
{
logger.ShowErrorMessage = toolStripMenuItem15.Checked;
}
private void sceneTreeView_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right && sceneTreeView.Nodes.Count > 0)
{
contextMenuStrip2.Show(sceneTreeView, e.Location.X, e.Location.Y);
}
}
private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
{
sceneTreeView.BeginUpdate();
foreach (TreeNode node in sceneTreeView.Nodes)
{
node.Checked = true;
}
sceneTreeView.EndUpdate();
}
private void selectNoneToolStripMenuItem_Click(object sender, EventArgs e)
{
sceneTreeView.BeginUpdate();
foreach (TreeNode node in sceneTreeView.Nodes)
{
node.Checked = false;
}
sceneTreeView.EndUpdate();
}
private void expandAllToolStripMenuItem_Click(object sender, EventArgs e)
{
if (sceneTreeView.Nodes.Count > 500)
{
MessageBox.Show("Too many elements.");
return;
}
sceneTreeView.BeginUpdate();
foreach (TreeNode node in sceneTreeView.Nodes)
{
node.ExpandAll();
}
sceneTreeView.EndUpdate();
}
private void collapseAllToolStripMenuItem_Click(object sender, EventArgs e)
{
sceneTreeView.BeginUpdate();
foreach (TreeNode node in sceneTreeView.Nodes)
{
node.Collapse(ignoreChildren: false);
}
sceneTreeView.EndUpdate();
}
#region FMOD
private void FMODinit()
{
@@ -1645,7 +1794,7 @@ namespace AssetStudioGUI
ERRCHECK(result);
if (version < FMOD.VERSION.number)
{
MessageBox.Show($"Error! You are using an old version of FMOD {version:X}. This program requires {FMOD.VERSION.number:X}.");
Logger.Error($"Error! You are using an old version of FMOD {version:X}. This program requires {FMOD.VERSION.number:X}.");
Application.Exit();
}
@@ -1663,22 +1812,23 @@ namespace AssetStudioGUI
{
timer.Stop();
FMODprogressBar.Value = 0;
FMODtimerLabel.Text = "0:00.0 / 0:00.0";
FMODtimerLabel.Text = "00:00.00 / 00:00.00";
FMODstatusLabel.Text = "Stopped";
FMODinfoLabel.Text = "";
if (sound != null && sound.isValid())
if (sound.hasHandle())
{
var result = sound.release();
ERRCHECK(result);
sound = null;
sound.clearHandle();
}
}
private void FMODplayButton_Click(object sender, EventArgs e)
{
if (sound != null && channel != null)
if (sound.hasHandle() && channel.hasHandle())
{
_ = system.getMasterChannelGroup(out var channelGroup);
timer.Start();
var result = channel.isPlaying(out var playing);
if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE))
@@ -1691,14 +1841,14 @@ namespace AssetStudioGUI
result = channel.stop();
if (ERRCHECK(result)) { return; }
result = system.playSound(sound, null, false, out channel);
result = system.playSound(sound, channelGroup, false, out channel);
if (ERRCHECK(result)) { return; }
FMODpauseButton.Text = "Pause";
}
else
{
result = system.playSound(sound, null, false, out channel);
result = system.playSound(sound, channelGroup, false, out channel);
if (ERRCHECK(result)) { return; }
FMODstatusLabel.Text = "Playing";
@@ -1719,7 +1869,7 @@ namespace AssetStudioGUI
private void FMODpauseButton_Click(object sender, EventArgs e)
{
if (sound != null && channel != null)
if (sound.hasHandle() && channel.hasHandle())
{
var result = channel.isPlaying(out var playing);
if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE))
@@ -1752,7 +1902,7 @@ namespace AssetStudioGUI
private void FMODstopButton_Click(object sender, EventArgs e)
{
if (channel != null)
if (channel.hasHandle())
{
var result = channel.isPlaying(out var playing);
if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE))
@@ -1768,7 +1918,7 @@ namespace AssetStudioGUI
//don't FMODreset, it will nullify the sound
timer.Stop();
FMODprogressBar.Value = 0;
FMODtimerLabel.Text = "0:00.0 / 0:00.0";
FMODtimerLabel.Text = "00:00.00 / 00:00.00";
FMODstatusLabel.Text = "Stopped";
FMODpauseButton.Text = "Pause";
}
@@ -1781,13 +1931,13 @@ namespace AssetStudioGUI
loopMode = FMODloopButton.Checked ? FMOD.MODE.LOOP_NORMAL : FMOD.MODE.LOOP_OFF;
if (sound != null)
if (sound.hasHandle())
{
result = sound.setMode(loopMode);
if (ERRCHECK(result)) { return; }
}
if (channel != null)
if (channel.hasHandle())
{
result = channel.isPlaying(out var playing);
if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE))
@@ -1819,10 +1969,10 @@ namespace AssetStudioGUI
private void FMODprogressBar_Scroll(object sender, EventArgs e)
{
if (channel != null)
if (channel.hasHandle())
{
uint newms = FMODlenms / 1000 * (uint)FMODprogressBar.Value;
FMODtimerLabel.Text = $"{newms / 1000 / 60}:{newms / 1000 % 60}.{newms / 10 % 100}/{FMODlenms / 1000 / 60}:{FMODlenms / 1000 % 60}.{FMODlenms / 10 % 100}";
FMODtimerLabel.Text = $"{newms / 1000 / 60:00}:{newms / 1000 % 60:00}.{newms / 10 % 100:00} / {FMODlenms / 1000 / 60:00}:{FMODlenms / 1000 % 60:00}.{FMODlenms / 10 % 100:00}";
}
}
@@ -1833,7 +1983,7 @@ namespace AssetStudioGUI
private void FMODprogressBar_MouseUp(object sender, MouseEventArgs e)
{
if (channel != null)
if (channel.hasHandle())
{
uint newms = FMODlenms / 1000 * (uint)FMODprogressBar.Value;
@@ -1860,7 +2010,7 @@ namespace AssetStudioGUI
bool playing = false;
bool paused = false;
if (channel != null)
if (channel.hasHandle())
{
var result = channel.getPosition(out ms, FMOD.TIMEUNIT.MS);
if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE))
@@ -1881,11 +2031,15 @@ namespace AssetStudioGUI
}
}
FMODtimerLabel.Text = $"{ms / 1000 / 60}:{ms / 1000 % 60}.{ms / 10 % 100} / {FMODlenms / 1000 / 60}:{FMODlenms / 1000 % 60}.{FMODlenms / 10 % 100}";
FMODprogressBar.Value = (int)(ms * 1000 / FMODlenms);
FMODtimerLabel.Text = $"{ms / 1000 / 60:00}:{ms / 1000 % 60:00}.{ms / 10 % 100:00} / {FMODlenms / 1000 / 60:00}:{FMODlenms / 1000 % 60:00}.{FMODlenms / 10 % 100:00}";
#if NETFRAMEWORK
FMODprogressBar.Value = (int)Math.Max(0, Math.Min(ms * 1000f / FMODlenms, 1000));
#else
FMODprogressBar.Value = (int)Math.Clamp(ms * 1000f / FMODlenms, 0, 1000);
#endif
FMODstatusLabel.Text = paused ? "Paused " : playing ? "Playing" : "Stopped";
if (system != null && channel != null)
if (system.hasHandle() && channel.hasHandle())
{
system.update();
}
@@ -1896,7 +2050,7 @@ namespace AssetStudioGUI
if (result != FMOD.RESULT.OK)
{
FMODreset();
StatusStripUpdate($"FMOD error! {result} - {FMOD.Error.String(result)}");
Logger.Warning($"FMOD error! {result} - {FMOD.Error.String(result)}");
return true;
}
return false;
@@ -2061,19 +2215,6 @@ namespace AssetStudioGUI
glControl1.SwapBuffers();
}
private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl2.SelectedIndex == 1 && lastSelectedItem != null)
{
dumpTextBox.Text = DumpAsset(lastSelectedItem.Asset);
}
}
private void toolStripMenuItem15_Click(object sender, EventArgs e)
{
logger.ShowErrorMessage = toolStripMenuItem15.Checked;
}
private void glControl1_MouseWheel(object sender, MouseEventArgs e)
{
if (glControl1.Visible)

View File

@@ -141,6 +141,9 @@ The quick brown fox jumps over the lazy dog. 1234567890</value>
<metadata name="statusStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>432, 17</value>
</metadata>
<metadata name="contextMenuStrip2.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>775, 21</value>
</metadata>
<metadata name="timer.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>553, 17</value>
</metadata>

View File

@@ -1,22 +1,16 @@
// This code developed by Dot Net Perls
using System.Collections;
// AlphanumComparatorFast mod by VaDiM
// Original code was developed by Dot Net Perls
// For more detail visit: https://www.dotnetperls.com/alphanumeric-sorting
using System;
using System.Collections.Generic;
namespace AssetStudioGUI
{
internal class AlphanumComparatorFast : IComparer
internal class AlphanumComparatorFast : IComparer<string>
{
public int Compare(object x, object y)
public int Compare(string s1, string s2)
{
if (!(x is string s1))
{
return 0;
}
if (!(y is string s2))
{
return 0;
}
int len1 = s1.Length;
int len2 = s2.Length;
int marker1 = 0;
@@ -69,20 +63,23 @@ namespace AssetStudioGUI
// If we have collected numbers, compare them numerically.
// Otherwise, if we have strings, compare them alphabetically.
string str1 = new string(space1);
string str2 = new string(space2);
int result;
if (char.IsDigit(space1[0]) && char.IsDigit(space2[0]))
{
int thisNumericChunk = int.Parse(str1);
int thatNumericChunk = int.Parse(str2);
result = thisNumericChunk.CompareTo(thatNumericChunk);
if (long.TryParse(new string(space1), out long thisNumericChunk) &&
long.TryParse(new string(space2), out long thatNumericChunk))
{
result = thisNumericChunk.CompareTo(thatNumericChunk);
}
else
{
result = MemoryExtensions.CompareTo(space1, space2, StringComparison.Ordinal);
}
}
else
{
result = str1.CompareTo(str2);
result = MemoryExtensions.CompareTo(space1, space2, StringComparison.InvariantCultureIgnoreCase);
}
if (result != 0)

View File

@@ -0,0 +1,99 @@
// AlphanumComparatorFast mod by VaDiM
// Original code was developed by Dot Net Perls
// For more detail visit: https://www.dotnetperls.com/alphanumeric-sorting
using System;
using System.Collections.Generic;
#if NET6_0_OR_GREATER
namespace AssetStudioGUI
{
internal class AlphanumComparatorFastNet : IComparer<string>
{
public int Compare(string s1, string s2)
{
const int maxStackSize = 256;
int len1 = s1.Length;
int len2 = s2.Length;
int marker1 = 0;
int marker2 = 0;
// Some buffers we can build up characters in for each chunk.
Span<char> space1 = len1 > maxStackSize ? new char[len1] : stackalloc char[len1];
Span<char> space2 = len2 > maxStackSize ? new char[len2] : stackalloc char[len2];
// Walk through two the strings with two markers.
while (marker1 < len1 && marker2 < len2)
{
char ch1 = s1[marker1];
char ch2 = s2[marker2];
int loc1 = 0;
int loc2 = 0;
space1.Clear();
space2.Clear();
// Walk through all following characters that are digits or
// characters in BOTH strings starting at the appropriate marker.
// Collect char arrays.
do
{
space1[loc1++] = ch1;
marker1++;
if (marker1 < len1)
{
ch1 = s1[marker1];
}
else
{
break;
}
} while (char.IsDigit(ch1) == char.IsDigit(space1[0]));
do
{
space2[loc2++] = ch2;
marker2++;
if (marker2 < len2)
{
ch2 = s2[marker2];
}
else
{
break;
}
} while (char.IsDigit(ch2) == char.IsDigit(space2[0]));
// If we have collected numbers, compare them numerically.
// Otherwise, if we have strings, compare them alphabetically.
int result;
if (char.IsDigit(space1[0]) && char.IsDigit(space2[0]))
{
if (long.TryParse(space1, out long thisNumericChunk) &&
long.TryParse(space2, out long thatNumericChunk))
{
result = thisNumericChunk.CompareTo(thatNumericChunk);
}
else
{
result = MemoryExtensions.CompareTo(space1, space2, StringComparison.Ordinal);
}
}
else
{
result = MemoryExtensions.CompareTo(space1, space2, StringComparison.InvariantCultureIgnoreCase);
}
if (result != 0)
{
return result;
}
}
return len1 - len2;
}
}
}
#endif

View File

@@ -7,11 +7,6 @@ namespace AssetStudioGUI
{
public GameObject gameObject;
public GameObjectTreeNode(string name)
{
Text = name;
}
public GameObjectTreeNode(GameObject gameObject)
{
this.gameObject = gameObject;

View File

@@ -1,5 +1,4 @@
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Forms;
@@ -15,12 +14,13 @@ namespace AssetStudioGUI
internal DialogResult ShowDialog(IWin32Window owner = null)
{
//#if NETFRAMEWORK
if (Environment.OSVersion.Version.Major >= 6)
{
return ShowVistaDialog(owner);
}
return ShowLegacyDialog(owner);
//#endif
return ShowFolderBrowserDialog(owner);
}
private DialogResult ShowVistaDialog(IWin32Window owner)
@@ -74,7 +74,7 @@ namespace AssetStudioGUI
return DialogResult.Cancel;
}
private DialogResult ShowLegacyDialog(IWin32Window owner)
private DialogResult ShowFolderBrowserDialog(IWin32Window owner)
{
using (var frm = new FolderBrowserDialog())
{
@@ -82,13 +82,20 @@ namespace AssetStudioGUI
{
frm.SelectedPath = InitialFolder;
}
if ((owner == null ? frm.ShowDialog() : frm.ShowDialog(owner)) == DialogResult.OK)
#if !NETFRAMEWORK
if (Title != null)
{
Folder = Path.GetDirectoryName(frm.SelectedPath);
return DialogResult.OK;
frm.Description = Title;
frm.UseDescriptionForTitle = true;
}
return DialogResult.Cancel;
#endif
var result = owner == null ? frm.ShowDialog() : frm.ShowDialog(owner);
if (result == DialogResult.OK)
{
Folder = frm.SelectedPath;
return result;
}
return result;
}
}
}

View File

@@ -1,48 +0,0 @@
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace AssetStudioGUI
{
internal static class TreeViewExtensions
{
private const int TVIF_STATE = 0x8;
private const int TVIS_STATEIMAGEMASK = 0xF000;
private const int TV_FIRST = 0x1100;
private const int TVM_SETITEM = TV_FIRST + 63;
[StructLayout(LayoutKind.Sequential, Pack = 8, CharSet = CharSet.Auto)]
private struct TVITEM
{
public int mask;
public IntPtr hItem;
public int state;
public int stateMask;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpszText;
public int cchTextMax;
public int iImage;
public int iSelectedImage;
public int cChildren;
public IntPtr lParam;
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, ref TVITEM lParam);
/// <summary>
/// Hides the checkbox for the specified node on a TreeView control.
/// </summary>
public static void HideCheckBox(this TreeNode node)
{
var tvi = new TVITEM
{
hItem = node.Handle,
mask = TVIF_STATE,
stateMask = TVIS_STATEIMAGEMASK,
state = TVIS_STATEIMAGEMASK //temp bugfix for an issue with getting stuck during the "Building tree structure" step
};
SendMessage(node.TreeView.Handle, TVM_SETITEM, IntPtr.Zero, ref tvi);
}
}
}

View File

@@ -0,0 +1,48 @@
using AssetStudio;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace AssetStudioGUI
{
public sealed class DirectBitmap : IDisposable
{
public DirectBitmap(Image<Bgra32> image)
{
Width = image.Width;
Height = image.Height;
Bits = BigArrayPool<byte>.Shared.Rent(Width * Height * 4);
image.CopyPixelDataTo(Bits);
m_handle = GCHandle.Alloc(Bits, GCHandleType.Pinned);
m_bitmap = new Bitmap(Width, Height, Stride, PixelFormat.Format32bppArgb, m_handle.AddrOfPinnedObject());
}
private void Dispose(bool disposing)
{
if (disposing)
{
m_bitmap.Dispose();
m_handle.Free();
BigArrayPool<byte>.Shared.Return(Bits);
}
m_bitmap = null;
}
public void Dispose()
{
Dispose(true);
}
public int Height { get; }
public int Width { get; }
public int Stride => Width * 4;
public byte[] Bits { get; }
public Bitmap Bitmap => m_bitmap;
private Bitmap m_bitmap;
private readonly GCHandle m_handle;
}
}

View File

@@ -32,12 +32,14 @@
this.OKbutton = new System.Windows.Forms.Button();
this.Cancel = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.exportSpriteWithAlphaMask = new System.Windows.Forms.CheckBox();
this.openAfterExport = new System.Windows.Forms.CheckBox();
this.restoreExtensionName = new System.Windows.Forms.CheckBox();
this.assetGroupOptions = new System.Windows.Forms.ComboBox();
this.label6 = new System.Windows.Forms.Label();
this.convertAudio = new System.Windows.Forms.CheckBox();
this.panel1 = new System.Windows.Forms.Panel();
this.towebp = new System.Windows.Forms.RadioButton();
this.totga = new System.Windows.Forms.RadioButton();
this.tojpg = new System.Windows.Forms.RadioButton();
this.topng = new System.Windows.Forms.RadioButton();
@@ -72,7 +74,7 @@
//
// OKbutton
//
this.OKbutton.Location = new System.Drawing.Point(318, 380);
this.OKbutton.Location = new System.Drawing.Point(381, 380);
this.OKbutton.Name = "OKbutton";
this.OKbutton.Size = new System.Drawing.Size(75, 23);
this.OKbutton.TabIndex = 6;
@@ -83,7 +85,7 @@
// Cancel
//
this.Cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Cancel.Location = new System.Drawing.Point(399, 380);
this.Cancel.Location = new System.Drawing.Point(462, 380);
this.Cancel.Name = "Cancel";
this.Cancel.Size = new System.Drawing.Size(75, 23);
this.Cancel.TabIndex = 7;
@@ -94,6 +96,7 @@
// groupBox1
//
this.groupBox1.AutoSize = true;
this.groupBox1.Controls.Add(this.exportSpriteWithAlphaMask);
this.groupBox1.Controls.Add(this.openAfterExport);
this.groupBox1.Controls.Add(this.restoreExtensionName);
this.groupBox1.Controls.Add(this.assetGroupOptions);
@@ -103,17 +106,29 @@
this.groupBox1.Controls.Add(this.converttexture);
this.groupBox1.Location = new System.Drawing.Point(12, 13);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(232, 362);
this.groupBox1.Size = new System.Drawing.Size(301, 362);
this.groupBox1.TabIndex = 9;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Export";
//
// exportSpriteWithAlphaMask
//
this.exportSpriteWithAlphaMask.AutoSize = true;
this.exportSpriteWithAlphaMask.Checked = true;
this.exportSpriteWithAlphaMask.CheckState = System.Windows.Forms.CheckState.Checked;
this.exportSpriteWithAlphaMask.Location = new System.Drawing.Point(6, 150);
this.exportSpriteWithAlphaMask.Name = "exportSpriteWithAlphaMask";
this.exportSpriteWithAlphaMask.Size = new System.Drawing.Size(205, 17);
this.exportSpriteWithAlphaMask.TabIndex = 11;
this.exportSpriteWithAlphaMask.Text = "Export sprites with alpha mask applied";
this.exportSpriteWithAlphaMask.UseVisualStyleBackColor = true;
//
// openAfterExport
//
this.openAfterExport.AutoSize = true;
this.openAfterExport.Checked = true;
this.openAfterExport.CheckState = System.Windows.Forms.CheckState.Checked;
this.openAfterExport.Location = new System.Drawing.Point(6, 173);
this.openAfterExport.Location = new System.Drawing.Point(6, 196);
this.openAfterExport.Name = "openAfterExport";
this.openAfterExport.Size = new System.Drawing.Size(137, 17);
this.openAfterExport.TabIndex = 10;
@@ -160,7 +175,7 @@
this.convertAudio.AutoSize = true;
this.convertAudio.Checked = true;
this.convertAudio.CheckState = System.Windows.Forms.CheckState.Checked;
this.convertAudio.Location = new System.Drawing.Point(6, 150);
this.convertAudio.Location = new System.Drawing.Point(6, 173);
this.convertAudio.Name = "convertAudio";
this.convertAudio.Size = new System.Drawing.Size(179, 17);
this.convertAudio.TabIndex = 6;
@@ -169,15 +184,27 @@
//
// panel1
//
this.panel1.Controls.Add(this.towebp);
this.panel1.Controls.Add(this.totga);
this.panel1.Controls.Add(this.tojpg);
this.panel1.Controls.Add(this.topng);
this.panel1.Controls.Add(this.tobmp);
this.panel1.Location = new System.Drawing.Point(20, 111);
this.panel1.Location = new System.Drawing.Point(18, 111);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(202, 33);
this.panel1.Size = new System.Drawing.Size(260, 33);
this.panel1.TabIndex = 5;
//
// towebp
//
this.towebp.AutoSize = true;
this.towebp.Location = new System.Drawing.Point(201, 7);
this.towebp.Name = "towebp";
this.towebp.Size = new System.Drawing.Size(54, 17);
this.towebp.TabIndex = 5;
this.towebp.TabStop = true;
this.towebp.Text = "Webp";
this.towebp.UseVisualStyleBackColor = true;
//
// totga
//
this.totga.AutoSize = true;
@@ -252,7 +279,7 @@
this.groupBox2.Controls.Add(this.castToBone);
this.groupBox2.Controls.Add(this.exportAllNodes);
this.groupBox2.Controls.Add(this.eulerFilter);
this.groupBox2.Location = new System.Drawing.Point(250, 13);
this.groupBox2.Location = new System.Drawing.Point(313, 13);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(224, 362);
this.groupBox2.TabIndex = 11;
@@ -470,7 +497,7 @@
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.Cancel;
this.ClientSize = new System.Drawing.Size(486, 416);
this.ClientSize = new System.Drawing.Size(549, 416);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.Cancel);
@@ -531,5 +558,7 @@
private System.Windows.Forms.CheckBox openAfterExport;
private System.Windows.Forms.CheckBox exportAllUvsAsDiffuseMaps;
private System.Windows.Forms.ToolTip exportUvsTooltip;
private System.Windows.Forms.CheckBox exportSpriteWithAlphaMask;
private System.Windows.Forms.RadioButton towebp;
}
}

View File

@@ -12,6 +12,7 @@ namespace AssetStudioGUI
assetGroupOptions.SelectedIndex = Properties.Settings.Default.assetGroupOption;
restoreExtensionName.Checked = Properties.Settings.Default.restoreExtensionName;
converttexture.Checked = Properties.Settings.Default.convertTexture;
exportSpriteWithAlphaMask.Checked = Properties.Settings.Default.exportSpriteWithMask;
convertAudio.Checked = Properties.Settings.Default.convertAudio;
var str = Properties.Settings.Default.convertType.ToString();
foreach (Control c in panel1.Controls)
@@ -43,6 +44,7 @@ namespace AssetStudioGUI
Properties.Settings.Default.assetGroupOption = assetGroupOptions.SelectedIndex;
Properties.Settings.Default.restoreExtensionName = restoreExtensionName.Checked;
Properties.Settings.Default.convertTexture = converttexture.Checked;
Properties.Settings.Default.exportSpriteWithMask = exportSpriteWithAlphaMask.Checked;
Properties.Settings.Default.convertAudio = convertAudio.Checked;
foreach (Control c in panel1.Controls)
{
@@ -75,6 +77,5 @@ namespace AssetStudioGUI
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@@ -120,7 +120,4 @@
<metadata name="exportUvsTooltip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="exportUvsTooltip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

View File

@@ -17,12 +17,15 @@ namespace AssetStudioGUI
var type = Properties.Settings.Default.convertType;
if (!TryExportFile(exportPath, item, "." + type.ToString().ToLower(), out var exportFullPath))
return false;
var stream = m_Texture2D.ConvertToStream(type, true);
if (stream == null)
var image = m_Texture2D.ConvertToImage(true);
if (image == null)
return false;
using (stream)
using (image)
{
File.WriteAllBytes(exportFullPath, stream.ToArray());
using (var file = File.OpenWrite(exportFullPath))
{
image.WriteToStream(file, type);
}
return true;
}
}
@@ -46,7 +49,7 @@ namespace AssetStudioGUI
{
if (!TryExportFile(exportPath, item, ".wav", out var exportFullPath))
return false;
var buffer = converter.ConvertToWav();
var buffer = converter.ConvertToWav(m_AudioData);
if (buffer == null)
return false;
File.WriteAllBytes(exportFullPath, buffer);
@@ -149,6 +152,7 @@ namespace AssetStudioGUI
#region UV
if (m_Mesh.m_UV0?.Length > 0)
{
c = 4;
if (m_Mesh.m_UV0.Length == m_Mesh.m_VertexCount * 2)
{
c = 2;
@@ -227,14 +231,18 @@ namespace AssetStudioGUI
public static bool ExportSprite(AssetItem item, string exportPath)
{
var type = Properties.Settings.Default.convertType;
var spriteMaskMode = Properties.Settings.Default.exportSpriteWithMask ? SpriteMaskMode.Export : SpriteMaskMode.Off;
if (!TryExportFile(exportPath, item, "." + type.ToString().ToLower(), out var exportFullPath))
return false;
var stream = ((Sprite)item.Asset).GetImage(type);
if (stream != null)
var image = ((Sprite)item.Asset).GetImage(spriteMaskMode: spriteMaskMode);
if (image != null)
{
using (stream)
using (image)
{
File.WriteAllBytes(exportFullPath, stream.ToArray());
using (var file = File.OpenWrite(exportFullPath))
{
image.WriteToStream(file, type);
}
return true;
}
}

View File

@@ -14,21 +14,29 @@ namespace AssetStudioGUI
this.action = action;
}
public void Log(LoggerEvent loggerEvent, string message)
public void Log(LoggerEvent loggerEvent, string message, bool ignoreLevel)
{
switch (loggerEvent)
{
case LoggerEvent.Error:
MessageBox.Show(message, "Error");
break;
case LoggerEvent.Warning:
if (ShowErrorMessage)
{
MessageBox.Show(message);
MessageBox.Show(message, "Warning");
}
else
{
action("An error has occurred. Turn on \"Show all error messages\" to see details next time.");
}
break;
case LoggerEvent.Debug:
break;
default:
action(message);
break;
}
}
}
}

View File

@@ -1,23 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AssetStudio;
namespace AssetStudioGUI
{
class GUIProgress : IProgress
{
private Action<int> action;
public GUIProgress(Action<int> action)
{
this.action = action;
}
public void Report(int value)
{
action(value);
}
}
}

Binary file not shown.

View File

@@ -1,10 +1,10 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
@@ -12,7 +12,7 @@ namespace AssetStudioGUI.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.10.0.0")]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.1.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
@@ -274,5 +274,17 @@ namespace AssetStudioGUI.Properties {
this["exportAllUvsAsDiffuseMaps"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool exportSpriteWithMask {
get {
return ((bool)(this["exportSpriteWithMask"]));
}
set {
this["exportSpriteWithMask"] = value;
}
}
}
}

View File

@@ -65,5 +65,8 @@
<Setting Name="exportAllUvsAsDiffuseMaps" Type="System.Boolean" Scope="User">
<Value Profile="(Default)">False</Value>
</Setting>
<Setting Name="exportSpriteWithMask" Type="System.Boolean" Scope="User">
<Value Profile="(Default)">True</Value>
</Setting>
</Settings>
</SettingsFile>

View File

@@ -84,8 +84,8 @@ namespace AssetStudioGUI
private static int ExtractBundleFile(FileReader reader, string savePath)
{
StatusStripUpdate($"Decompressing {reader.FileName} ...");
var bundleFile = new BundleFile(reader);
Logger.Info($"Decompressing {reader.FileName} ...");
var bundleFile = new BundleFile(reader, assetsManager.SpecifyUnityVersion);
reader.Dispose();
if (bundleFile.fileList.Length > 0)
{
@@ -97,7 +97,7 @@ namespace AssetStudioGUI
private static int ExtractWebDataFile(FileReader reader, string savePath)
{
StatusStripUpdate($"Decompressing {reader.FileName} ...");
Logger.Info($"Decompressing {reader.FileName} ...");
var webFile = new WebFile(reader);
reader.Dispose();
if (webFile.fileList.Length > 0)
@@ -134,7 +134,7 @@ namespace AssetStudioGUI
public static (string, List<TreeNode>) BuildAssetData()
{
StatusStripUpdate("Building asset list...");
Logger.Info("Building asset list...");
string productName = null;
var objectCount = assetsManager.assetsFileList.Sum(x => x.Objects.Count);
@@ -256,7 +256,7 @@ namespace AssetStudioGUI
visibleAssets = exportableAssets;
StatusStripUpdate("Building tree structure...");
Logger.Info("Building tree structure...");
var treeNodeCollection = new List<TreeNode>();
var treeNodeDictionary = new Dictionary<GameObject, GameObjectTreeNode>();
@@ -265,7 +265,7 @@ namespace AssetStudioGUI
Progress.Reset();
foreach (var assetsFile in assetsManager.assetsFileList)
{
var fileNode = new GameObjectTreeNode(assetsFile.fileName); //RootNode
var fileNode = new TreeNode(assetsFile.fileName); //RootNode
foreach (var obj in assetsFile.Objects)
{
@@ -307,11 +307,12 @@ namespace AssetStudioGUI
{
if (m_Father.m_GameObject.TryGet(out var parentGameObject))
{
if (!treeNodeDictionary.TryGetValue(parentGameObject, out parentNode))
if (!treeNodeDictionary.TryGetValue(parentGameObject, out var parentGameObjectNode))
{
parentNode = new GameObjectTreeNode(parentGameObject);
treeNodeDictionary.Add(parentGameObject, parentNode);
parentGameObjectNode = new GameObjectTreeNode(parentGameObject);
treeNodeDictionary.Add(parentGameObject, parentGameObjectNode);
}
parentNode = parentGameObjectNode;
}
}
}
@@ -413,7 +414,7 @@ namespace AssetStudioGUI
break;
}
exportPath += Path.DirectorySeparatorChar;
StatusStripUpdate($"[{exportedCount}/{toExportCount}] Exporting {asset.TypeString}: {asset.Text}");
Logger.Info($"[{exportedCount}/{toExportCount}] Exporting {asset.TypeString}: {asset.Text}");
try
{
switch (exportType)
@@ -440,7 +441,7 @@ namespace AssetStudioGUI
}
catch (Exception ex)
{
MessageBox.Show($"Export {asset.Type}:{asset.Text} error\r\n{ex.Message}\r\n{ex.StackTrace}");
Logger.Error($"Export {asset.Type}:{asset.Text} error", ex);
}
Progress.Report(++i, toExportCount);
@@ -453,11 +454,11 @@ namespace AssetStudioGUI
statusText += $" {toExportCount - exportedCount} assets skipped (not extractable or files already exist)";
}
StatusStripUpdate(statusText);
Logger.Info(statusText);
if (Properties.Settings.Default.openAfterExport && exportedCount > 0)
{
Process.Start(savePath);
OpenFolderInExplorer(savePath);
}
});
}
@@ -498,11 +499,11 @@ namespace AssetStudioGUI
var statusText = $"Finished exporting asset list with {toExportAssets.Count()} items.";
StatusStripUpdate(statusText);
Logger.Info(statusText);
if (Properties.Settings.Default.openAfterExport && toExportAssets.Count() > 0)
{
Process.Start(savePath);
OpenFolderInExplorer(savePath);
}
});
}
@@ -514,7 +515,7 @@ namespace AssetStudioGUI
var count = nodes.Cast<TreeNode>().Sum(x => x.Nodes.Count);
int k = 0;
Progress.Reset();
foreach (GameObjectTreeNode node in nodes)
foreach (TreeNode node in nodes)
{
//遍历一级子节点
foreach (GameObjectTreeNode j in node.Nodes)
@@ -546,25 +547,25 @@ namespace AssetStudioGUI
}
Directory.CreateDirectory(targetPath);
//导出FBX
StatusStripUpdate($"Exporting {filename}.fbx");
Logger.Info($"Exporting {filename}.fbx");
try
{
ExportGameObject(j.gameObject, targetPath);
}
catch (Exception ex)
{
MessageBox.Show($"Export GameObject:{j.Text} error\r\n{ex.Message}\r\n{ex.StackTrace}");
Logger.Error($"Export GameObject:{j.Text} error", ex);
}
Progress.Report(++k, count);
StatusStripUpdate($"Finished exporting {filename}.fbx");
Logger.Info($"Finished exporting {filename}.fbx");
}
}
if (Properties.Settings.Default.openAfterExport)
{
Process.Start(savePath);
OpenFolderInExplorer(savePath);
}
StatusStripUpdate("Finished");
Logger.Info("Finished");
});
}
@@ -582,21 +583,21 @@ namespace AssetStudioGUI
ThreadPool.QueueUserWorkItem(state =>
{
Progress.Reset();
StatusStripUpdate($"Exporting {animator.Text}");
Logger.Info($"Exporting {animator.Text}");
try
{
ExportAnimator(animator, exportPath, animationList);
if (Properties.Settings.Default.openAfterExport)
{
Process.Start(exportPath);
OpenFolderInExplorer(exportPath);
}
Progress.Report(1, 1);
StatusStripUpdate($"Finished exporting {animator.Text}");
Logger.Info($"Finished exporting {animator.Text}");
}
catch (Exception ex)
{
MessageBox.Show($"Export Animator:{animator.Text} error\r\n{ex.Message}\r\n{ex.StackTrace}");
StatusStripUpdate("Error in export");
Logger.Error($"Export Animator:{animator.Text} error", ex);
Logger.Info("Error in export");
}
});
}
@@ -614,28 +615,28 @@ namespace AssetStudioGUI
Progress.Reset();
foreach (var gameObject in gameObjects)
{
StatusStripUpdate($"Exporting {gameObject.m_Name}");
Logger.Info($"Exporting {gameObject.m_Name}");
try
{
ExportGameObject(gameObject, exportPath, animationList);
StatusStripUpdate($"Finished exporting {gameObject.m_Name}");
Logger.Info($"Finished exporting {gameObject.m_Name}");
}
catch (Exception ex)
{
MessageBox.Show($"Export GameObject:{gameObject.m_Name} error\r\n{ex.Message}\r\n{ex.StackTrace}");
StatusStripUpdate("Error in export");
Logger.Error($"Export GameObject:{gameObject.m_Name} error", ex);
Logger.Info("Error in export");
}
Progress.Report(++i, count);
}
if (Properties.Settings.Default.openAfterExport)
{
Process.Start(exportPath);
OpenFolderInExplorer(exportPath);
}
}
else
{
StatusStripUpdate("No Object can be exported.");
Logger.Info("No Object selected for export.");
}
});
}
@@ -646,32 +647,32 @@ namespace AssetStudioGUI
{
var name = Path.GetFileName(exportPath);
Progress.Reset();
StatusStripUpdate($"Exporting {name}");
Logger.Info($"Exporting {name}");
try
{
ExportGameObjectMerge(gameObjects, exportPath, animationList);
Progress.Report(1, 1);
StatusStripUpdate($"Finished exporting {name}");
Logger.Info($"Finished exporting {name}");
}
catch (Exception ex)
{
MessageBox.Show($"Export Model:{name} error\r\n{ex.Message}\r\n{ex.StackTrace}");
StatusStripUpdate("Error in export");
Logger.Error($"Export Model:{name} error", ex);
Logger.Info("Error in export");
}
if (Properties.Settings.Default.openAfterExport)
{
Process.Start(Path.GetDirectoryName(exportPath));
OpenFolderInExplorer(Path.GetDirectoryName(exportPath));
}
});
}
public static void GetSelectedParentNode(TreeNodeCollection nodes, List<GameObject> gameObjects)
{
foreach (GameObjectTreeNode i in nodes)
foreach (TreeNode i in nodes)
{
if (i.Checked)
if (i is GameObjectTreeNode gameObjectTreeNode && i.Checked)
{
gameObjects.Add(i.gameObject);
gameObjects.Add(gameObjectTreeNode.gameObject);
}
else
{
@@ -708,5 +709,12 @@ namespace AssetStudioGUI
}
return str;
}
public static void OpenFolderInExplorer(string path)
{
var info = new ProcessStartInfo(path);
info.UseShellExecute = true;
Process.Start(info);
}
}
}

View File

@@ -1,28 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net472;netstandard2.0</TargetFrameworks>
<Version>0.16.8.1</Version>
<AssemblyVersion>0.16.8.1</AssemblyVersion>
<FileVersion>0.16.8.1</FileVersion>
<Copyright>Copyright © Perfare 2018-2021</Copyright>
</PropertyGroup>
<PropertyGroup>
<TargetFrameworks>net472;net6.0;net6.0-windows;net7.0;net7.0-windows</TargetFrameworks>
<Version>0.16.48.1</Version>
<Copyright>Copyright © Perfare 2018-2022</Copyright>
<DebugType>embedded</DebugType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net472|AnyCPU'">
<DebugType>none</DebugType>
<DebugSymbols>false</DebugSymbols>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Mono.Cecil" Version="0.11.3" />
<PackageReference Include="SixLabors.ImageSharp.Drawing" Version="1.0.0-beta15" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Mono.Cecil" Version="0.11.3" />
<PackageReference Include="System.Drawing.Common" Version="6.0.0" />
</ItemGroup>
<ItemGroup Condition=" !$(TargetFramework.Contains('windows')) ">
<PackageReference Include="Kyaru.Texture2DDecoder.Linux" Version="0.1.0" />
<PackageReference Include="Kyaru.Texture2DDecoder.macOS" Version="0.1.0" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' != 'net472' ">
<PackageReference Include="Kyaru.Texture2DDecoder.Windows" Version="0.1.0" />
<PackageReference Include="Kyaru.Texture2DDecoder">
<Version>0.17.0</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AssetStudio.PInvoke\AssetStudio.PInvoke.csproj" />
<ProjectReference Include="..\AssetStudioFBXWrapper\AssetStudioFBXWrapper.csproj" />
<ProjectReference Include="..\AssetStudio\AssetStudio.csproj" />
<ProjectReference Include="..\Texture2DDecoderWrapper\Texture2DDecoderWrapper.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AssetStudio.PInvoke\AssetStudio.PInvoke.csproj" />
<ProjectReference Include="..\AssetStudioFBXWrapper\AssetStudioFBXWrapper.csproj" />
<ProjectReference Include="..\AssetStudio\AssetStudio.csproj" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net472' ">
<ProjectReference Include="..\Texture2DDecoderWrapper\Texture2DDecoderWrapper.csproj" />
</ItemGroup>
</Project>

View File

@@ -14,11 +14,8 @@ namespace AssetStudio
m_AudioClip = audioClip;
}
public byte[] ConvertToWav()
public byte[] ConvertToWav(byte[] m_AudioData)
{
var m_AudioData = m_AudioClip.m_AudioData.GetData();
if (m_AudioData == null || m_AudioData.Length == 0)
return null;
var exinfo = new CREATESOUNDEXINFO();
var result = Factory.System_Create(out var system);
if (result != RESULT.OK)
@@ -54,9 +51,14 @@ namespace AssetStudio
public byte[] SoundToWav(Sound sound)
{
var result = sound.getFormat(out _, out _, out int channels, out int bits);
Logger.Debug($"[Fmod] Detecting sound format..\n");
var result = sound.getFormat(out SOUND_TYPE soundType, out SOUND_FORMAT soundFormat, out int channels, out int bits);
if (result != RESULT.OK)
return null;
Logger.Debug($"Detected sound type: {soundType}\n" +
$"Detected sound format: {soundFormat}\n" +
$"Detected channels: {channels}\n" +
$"Detected bit depth: {bits}");
result = sound.getDefaults(out var frequency, out _);
if (result != RESULT.OK)
return null;
@@ -94,29 +96,29 @@ namespace AssetStudio
{
switch (m_AudioClip.m_Type)
{
case AudioType.ACC:
case FMODSoundType.ACC:
return ".m4a";
case AudioType.AIFF:
case FMODSoundType.AIFF:
return ".aif";
case AudioType.IT:
case FMODSoundType.IT:
return ".it";
case AudioType.MOD:
case FMODSoundType.MOD:
return ".mod";
case AudioType.MPEG:
case FMODSoundType.MPEG:
return ".mp3";
case AudioType.OGGVORBIS:
case FMODSoundType.OGGVORBIS:
return ".ogg";
case AudioType.S3M:
case FMODSoundType.S3M:
return ".s3m";
case AudioType.WAV:
case FMODSoundType.WAV:
return ".wav";
case AudioType.XM:
case FMODSoundType.XM:
return ".xm";
case AudioType.XMA:
case FMODSoundType.XMA:
return ".wav";
case AudioType.VAG:
case FMODSoundType.VAG:
return ".vag";
case AudioType.AUDIOQUEUE:
case FMODSoundType.AUDIOQUEUE:
return ".fsb";
}
@@ -133,7 +135,7 @@ namespace AssetStudio
return ".fsb";
case AudioCompressionFormat.MP3:
return ".fsb";
case AudioCompressionFormat.VAG:
case AudioCompressionFormat.PSMVAG:
return ".fsb";
case AudioCompressionFormat.HEVAG:
return ".fsb";
@@ -159,13 +161,13 @@ namespace AssetStudio
{
switch (m_AudioClip.m_Type)
{
case AudioType.AIFF:
case AudioType.IT:
case AudioType.MOD:
case AudioType.S3M:
case AudioType.XM:
case AudioType.XMA:
case AudioType.AUDIOQUEUE:
case FMODSoundType.AIFF:
case FMODSoundType.IT:
case FMODSoundType.MOD:
case FMODSoundType.S3M:
case FMODSoundType.XM:
case FMODSoundType.XMA:
case FMODSoundType.AUDIOQUEUE:
return true;
default:
return false;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,13 @@
/* =================================================================================================== */
/* FMOD Studio - Error string header file. Copyright (c), Firelight Technologies Pty, Ltd. 2004-2016. */
/* */
/* Use this header if you want to store or display a string version / english explanation of */
/* the FMOD error codes. */
/* */
/* =================================================================================================== */
/* ============================================================================================== */
/* FMOD Core / Studio API - Error string header file. */
/* Copyright (c), Firelight Technologies Pty, Ltd. 2004-2020. */
/* */
/* Use this header if you want to store or display a string version / english explanation */
/* of the FMOD error codes. */
/* */
/* For more detail visit: */
/* https://fmod.com/resources/documentation-api?version=2.0&page=core-api-common.html#fmod_result */
/* =============================================================================================== */
namespace FMOD
{

View File

@@ -1,32 +1,52 @@
using System.Drawing;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Bmp;
using SixLabors.ImageSharp.Formats.Tga;
using SixLabors.ImageSharp.Formats.Webp;
using System.IO;
using TGASharpLib;
namespace AssetStudio
{
public static class ImageExtensions
{
public static MemoryStream ConvertToStream(this Bitmap image, ImageFormat imageFormat)
public static void WriteToStream(this Image image, Stream stream, ImageFormat imageFormat)
{
var outputStream = new MemoryStream();
switch (imageFormat)
{
case ImageFormat.Jpeg:
image.Save(outputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
image.SaveAsJpeg(stream);
break;
case ImageFormat.Png:
image.Save(outputStream, System.Drawing.Imaging.ImageFormat.Png);
image.SaveAsPng(stream);
break;
case ImageFormat.Bmp:
image.Save(outputStream, System.Drawing.Imaging.ImageFormat.Bmp);
image.Save(stream, new BmpEncoder
{
BitsPerPixel = BmpBitsPerPixel.Pixel32,
SupportTransparency = true
});
break;
case ImageFormat.Tga:
var tga = new TGA(image);
tga.Save(outputStream);
image.Save(stream, new TgaEncoder
{
BitsPerPixel = TgaBitsPerPixel.Pixel32,
Compression = TgaCompression.None
});
break;
case ImageFormat.Webp:
image.Save(stream, new WebpEncoder
{
FileFormat = WebpFileFormatType.Lossless,
Quality = 50
});
break;
}
image.Dispose();
return outputStream;
}
public static MemoryStream ConvertToStream(this Image image, ImageFormat imageFormat)
{
var stream = new MemoryStream();
image.WriteToStream(stream, imageFormat);
return stream;
}
}
}

View File

@@ -5,6 +5,7 @@
Jpeg,
Png,
Bmp,
Tga
Tga,
Webp,
}
}

View File

@@ -1063,26 +1063,21 @@ namespace AssetStudio
else
{
transformName = strs.Last();
var parentFrameName = strs[strs.Length - 2];
parentFrame = RootFrame.FindChild(parentFrameName);
//var parentFramePath = path.Substring(0, path.LastIndexOf('/'));
//parentFrame = RootFrame.FindFrameByPath(parentFramePath);
var parentFramePath = path.Substring(0, path.LastIndexOf('/'));
parentFrame = RootFrame.FindRelativeFrameWithPath(parentFramePath);
}
var skeletonPose = avatar.m_Avatar.m_DefaultPose;
var xform = skeletonPose.m_X[i];
var frame = RootFrame.FindChild(transformName);
if (frame != null)
{
SetFrame(frame, xform.t, xform.q, xform.s);
parentFrame.AddChild(frame);
}
else
{
frame = CreateFrame(transformName, xform.t, xform.q, xform.s);
parentFrame.AddChild(frame);
}
parentFrame.AddChild(frame);
}
}

View File

@@ -1,10 +1,10 @@
using System;
using K4os.Compression.LZ4;
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Lz4;
namespace AssetStudio
{
@@ -15,13 +15,11 @@ namespace AssetStudio
if (shader.m_SubProgramBlob != null) //5.3 - 5.4
{
var decompressedBytes = new byte[shader.decompressedSize];
using (var decoder = new Lz4DecoderStream(new MemoryStream(shader.m_SubProgramBlob)))
{
decoder.Read(decompressedBytes, 0, (int)shader.decompressedSize);
}
LZ4Codec.Decode(shader.m_SubProgramBlob, decompressedBytes);
using (var blobReader = new BinaryReader(new MemoryStream(decompressedBytes)))
{
var program = new ShaderProgram(blobReader, shader.version);
program.Read(blobReader, 0);
return header + program.Export(Encoding.UTF8.GetString(shader.m_Script));
}
}
@@ -36,19 +34,25 @@ namespace AssetStudio
private static string ConvertSerializedShader(Shader shader)
{
var shaderPrograms = new ShaderProgram[shader.platforms.Length];
for (var i = 0; i < shader.platforms.Length; i++)
var length = shader.platforms.Length;
var shaderPrograms = new ShaderProgram[length];
for (var i = 0; i < length; i++)
{
var compressedBytes = new byte[shader.compressedLengths[i]];
Buffer.BlockCopy(shader.compressedBlob, (int)shader.offsets[i], compressedBytes, 0, (int)shader.compressedLengths[i]);
var decompressedBytes = new byte[shader.decompressedLengths[i]];
using (var decoder = new Lz4DecoderStream(new MemoryStream(compressedBytes)))
for (var j = 0; j < shader.offsets[i].Length; j++)
{
decoder.Read(decompressedBytes, 0, (int)shader.decompressedLengths[i]);
}
using (var blobReader = new BinaryReader(new MemoryStream(decompressedBytes)))
{
shaderPrograms[i] = new ShaderProgram(blobReader, shader.version);
var offset = shader.offsets[i][j];
var compressedLength = shader.compressedLengths[i][j];
var decompressedLength = shader.decompressedLengths[i][j];
var decompressedBytes = new byte[decompressedLength];
LZ4Codec.Decode(shader.compressedBlob, (int)offset, (int)compressedLength, decompressedBytes, 0, (int)decompressedLength);
using (var blobReader = new BinaryReader(new MemoryStream(decompressedBytes)))
{
if (j == 0)
{
shaderPrograms[i] = new ShaderProgram(blobReader, shader.version);
}
shaderPrograms[i].Read(blobReader, j);
}
}
}
@@ -105,17 +109,17 @@ namespace AssetStudio
var sb = new StringBuilder();
switch (m_Passe.m_Type)
{
case PassType.kPassTypeNormal:
case PassType.Normal:
sb.Append(" Pass ");
break;
case PassType.kPassTypeUse:
case PassType.Use:
sb.Append(" UsePass ");
break;
case PassType.kPassTypeGrab:
case PassType.Grab:
sb.Append(" GrabPass ");
break;
}
if (m_Passe.m_Type == PassType.kPassTypeUse)
if (m_Passe.m_Type == PassType.Use)
{
sb.Append($"\"{m_Passe.m_UseName}\"\n");
}
@@ -123,7 +127,7 @@ namespace AssetStudio
{
sb.Append("{\n");
if (m_Passe.m_Type == PassType.kPassTypeGrab)
if (m_Passe.m_Type == PassType.Grab)
{
if (!string.IsNullOrEmpty(m_Passe.m_TextureName))
{
@@ -354,7 +358,7 @@ namespace AssetStudio
sb.Append(" }\n");
}
if (m_State.fogMode != FogMode.kFogUnknown ||
if (m_State.fogMode != FogMode.Unknown ||
m_State.fogColor.x.val != 0f ||
m_State.fogColor.y.val != 0f ||
m_State.fogColor.z.val != 0f ||
@@ -364,21 +368,21 @@ namespace AssetStudio
m_State.fogEnd.val != 0f)
{
sb.Append(" Fog {\n");
if (m_State.fogMode != FogMode.kFogUnknown)
if (m_State.fogMode != FogMode.Unknown)
{
sb.Append(" Mode ");
switch (m_State.fogMode)
{
case FogMode.kFogDisabled:
case FogMode.Disabled:
sb.Append("Off");
break;
case FogMode.kFogLinear:
case FogMode.Linear:
sb.Append("Linear");
break;
case FogMode.kFogExp:
case FogMode.Exp:
sb.Append("Exp");
break;
case FogMode.kFogExp2:
case FogMode.Exp2:
sb.Append("Exp2");
break;
}
@@ -670,37 +674,37 @@ namespace AssetStudio
sb.Append($"{m_Prop.m_Name} (\"{m_Prop.m_Description}\", ");
switch (m_Prop.m_Type)
{
case SerializedPropertyType.kColor:
case SerializedPropertyType.Color:
sb.Append("Color");
break;
case SerializedPropertyType.kVector:
case SerializedPropertyType.Vector:
sb.Append("Vector");
break;
case SerializedPropertyType.kFloat:
case SerializedPropertyType.Float:
sb.Append("Float");
break;
case SerializedPropertyType.kRange:
case SerializedPropertyType.Range:
sb.Append($"Range({m_Prop.m_DefValue[1]}, {m_Prop.m_DefValue[2]})");
break;
case SerializedPropertyType.kTexture:
case SerializedPropertyType.Texture:
switch (m_Prop.m_DefTexture.m_TexDim)
{
case TextureDimension.kTexDimAny:
case TextureDimension.Any:
sb.Append("any");
break;
case TextureDimension.kTexDim2D:
case TextureDimension.Tex2D:
sb.Append("2D");
break;
case TextureDimension.kTexDim3D:
case TextureDimension.Tex3D:
sb.Append("3D");
break;
case TextureDimension.kTexDimCUBE:
case TextureDimension.Cube:
sb.Append("Cube");
break;
case TextureDimension.kTexDim2DArray:
case TextureDimension.Tex2DArray:
sb.Append("2DArray");
break;
case TextureDimension.kTexDimCubeArray:
case TextureDimension.CubeArray:
sb.Append("CubeArray");
break;
}
@@ -709,15 +713,15 @@ namespace AssetStudio
sb.Append(") = ");
switch (m_Prop.m_Type)
{
case SerializedPropertyType.kColor:
case SerializedPropertyType.kVector:
case SerializedPropertyType.Color:
case SerializedPropertyType.Vector:
sb.Append($"({m_Prop.m_DefValue[0]},{m_Prop.m_DefValue[1]},{m_Prop.m_DefValue[2]},{m_Prop.m_DefValue[3]})");
break;
case SerializedPropertyType.kFloat:
case SerializedPropertyType.kRange:
case SerializedPropertyType.Float:
case SerializedPropertyType.Range:
sb.Append(m_Prop.m_DefValue[0]);
break;
case SerializedPropertyType.kTexture:
case SerializedPropertyType.Texture:
sb.Append($"\"{m_Prop.m_DefTexture.m_DefaultName}\" {{ }}");
break;
default:
@@ -731,64 +735,65 @@ namespace AssetStudio
{
switch (platform)
{
case ShaderCompilerPlatform.kShaderCompPlatformGL:
return programType == ShaderGpuProgramType.kShaderGpuProgramGLLegacy;
case ShaderCompilerPlatform.kShaderCompPlatformD3D9:
return programType == ShaderGpuProgramType.kShaderGpuProgramDX9VertexSM20
|| programType == ShaderGpuProgramType.kShaderGpuProgramDX9VertexSM30
|| programType == ShaderGpuProgramType.kShaderGpuProgramDX9PixelSM20
|| programType == ShaderGpuProgramType.kShaderGpuProgramDX9PixelSM30;
case ShaderCompilerPlatform.kShaderCompPlatformXbox360:
case ShaderCompilerPlatform.kShaderCompPlatformPS3:
case ShaderCompilerPlatform.kShaderCompPlatformPSP2:
case ShaderCompilerPlatform.kShaderCompPlatformPS4:
case ShaderCompilerPlatform.kShaderCompPlatformXboxOne:
case ShaderCompilerPlatform.kShaderCompPlatformN3DS:
case ShaderCompilerPlatform.kShaderCompPlatformWiiU:
case ShaderCompilerPlatform.kShaderCompPlatformSwitch:
case ShaderCompilerPlatform.kShaderCompPlatformXboxOneD3D12:
case ShaderCompilerPlatform.kShaderCompPlatformGameCoreXboxOne:
case ShaderCompilerPlatform.kShaderCompPlatformGameCoreScarlett:
case ShaderCompilerPlatform.kShaderCompPlatformPS5:
case ShaderCompilerPlatform.kShaderCompPlatformPS5NGGC:
return programType == ShaderGpuProgramType.kShaderGpuProgramConsoleVS
|| programType == ShaderGpuProgramType.kShaderGpuProgramConsoleFS
|| programType == ShaderGpuProgramType.kShaderGpuProgramConsoleHS
|| programType == ShaderGpuProgramType.kShaderGpuProgramConsoleDS
|| programType == ShaderGpuProgramType.kShaderGpuProgramConsoleGS;
case ShaderCompilerPlatform.kShaderCompPlatformD3D11:
return programType == ShaderGpuProgramType.kShaderGpuProgramDX11VertexSM40
|| programType == ShaderGpuProgramType.kShaderGpuProgramDX11VertexSM50
|| programType == ShaderGpuProgramType.kShaderGpuProgramDX11PixelSM40
|| programType == ShaderGpuProgramType.kShaderGpuProgramDX11PixelSM50
|| programType == ShaderGpuProgramType.kShaderGpuProgramDX11GeometrySM40
|| programType == ShaderGpuProgramType.kShaderGpuProgramDX11GeometrySM50
|| programType == ShaderGpuProgramType.kShaderGpuProgramDX11HullSM50
|| programType == ShaderGpuProgramType.kShaderGpuProgramDX11DomainSM50;
case ShaderCompilerPlatform.kShaderCompPlatformGLES20:
return programType == ShaderGpuProgramType.kShaderGpuProgramGLES;
case ShaderCompilerPlatform.kShaderCompPlatformNaCl: //Obsolete
case ShaderCompilerPlatform.GL:
return programType == ShaderGpuProgramType.GLLegacy;
case ShaderCompilerPlatform.D3D9:
return programType == ShaderGpuProgramType.DX9VertexSM20
|| programType == ShaderGpuProgramType.DX9VertexSM30
|| programType == ShaderGpuProgramType.DX9PixelSM20
|| programType == ShaderGpuProgramType.DX9PixelSM30;
case ShaderCompilerPlatform.Xbox360:
case ShaderCompilerPlatform.PS3:
case ShaderCompilerPlatform.PSP2:
case ShaderCompilerPlatform.PS4:
case ShaderCompilerPlatform.XboxOne:
case ShaderCompilerPlatform.N3DS:
case ShaderCompilerPlatform.WiiU:
case ShaderCompilerPlatform.Switch:
case ShaderCompilerPlatform.XboxOneD3D12:
case ShaderCompilerPlatform.GameCoreXboxOne:
case ShaderCompilerPlatform.GameCoreScarlett:
case ShaderCompilerPlatform.PS5:
return programType == ShaderGpuProgramType.ConsoleVS
|| programType == ShaderGpuProgramType.ConsoleFS
|| programType == ShaderGpuProgramType.ConsoleHS
|| programType == ShaderGpuProgramType.ConsoleDS
|| programType == ShaderGpuProgramType.ConsoleGS;
case ShaderCompilerPlatform.PS5NGGC:
return programType == ShaderGpuProgramType.PS5NGGC;
case ShaderCompilerPlatform.D3D11:
return programType == ShaderGpuProgramType.DX11VertexSM40
|| programType == ShaderGpuProgramType.DX11VertexSM50
|| programType == ShaderGpuProgramType.DX11PixelSM40
|| programType == ShaderGpuProgramType.DX11PixelSM50
|| programType == ShaderGpuProgramType.DX11GeometrySM40
|| programType == ShaderGpuProgramType.DX11GeometrySM50
|| programType == ShaderGpuProgramType.DX11HullSM50
|| programType == ShaderGpuProgramType.DX11DomainSM50;
case ShaderCompilerPlatform.GLES20:
return programType == ShaderGpuProgramType.GLES;
case ShaderCompilerPlatform.NaCl: //Obsolete
throw new NotSupportedException();
case ShaderCompilerPlatform.kShaderCompPlatformFlash: //Obsolete
case ShaderCompilerPlatform.Flash: //Obsolete
throw new NotSupportedException();
case ShaderCompilerPlatform.kShaderCompPlatformD3D11_9x:
return programType == ShaderGpuProgramType.kShaderGpuProgramDX10Level9Vertex
|| programType == ShaderGpuProgramType.kShaderGpuProgramDX10Level9Pixel;
case ShaderCompilerPlatform.kShaderCompPlatformGLES3Plus:
return programType == ShaderGpuProgramType.kShaderGpuProgramGLES31AEP
|| programType == ShaderGpuProgramType.kShaderGpuProgramGLES31
|| programType == ShaderGpuProgramType.kShaderGpuProgramGLES3;
case ShaderCompilerPlatform.kShaderCompPlatformPSM: //Unknown
case ShaderCompilerPlatform.D3D11_9x:
return programType == ShaderGpuProgramType.DX10Level9Vertex
|| programType == ShaderGpuProgramType.DX10Level9Pixel;
case ShaderCompilerPlatform.GLES3Plus:
return programType == ShaderGpuProgramType.GLES31AEP
|| programType == ShaderGpuProgramType.GLES31
|| programType == ShaderGpuProgramType.GLES3;
case ShaderCompilerPlatform.PSM: //Unknown
throw new NotSupportedException();
case ShaderCompilerPlatform.kShaderCompPlatformMetal:
return programType == ShaderGpuProgramType.kShaderGpuProgramMetalVS
|| programType == ShaderGpuProgramType.kShaderGpuProgramMetalFS;
case ShaderCompilerPlatform.kShaderCompPlatformOpenGLCore:
return programType == ShaderGpuProgramType.kShaderGpuProgramGLCore32
|| programType == ShaderGpuProgramType.kShaderGpuProgramGLCore41
|| programType == ShaderGpuProgramType.kShaderGpuProgramGLCore43;
case ShaderCompilerPlatform.kShaderCompPlatformVulkan:
return programType == ShaderGpuProgramType.kShaderGpuProgramSPIRV;
case ShaderCompilerPlatform.Metal:
return programType == ShaderGpuProgramType.MetalVS
|| programType == ShaderGpuProgramType.MetalFS;
case ShaderCompilerPlatform.OpenGLCore:
return programType == ShaderGpuProgramType.GLCore32
|| programType == ShaderGpuProgramType.GLCore41
|| programType == ShaderGpuProgramType.GLCore43;
case ShaderCompilerPlatform.Vulkan:
return programType == ShaderGpuProgramType.SPIRV;
default:
throw new NotSupportedException();
}
@@ -798,55 +803,55 @@ namespace AssetStudio
{
switch (platform)
{
case ShaderCompilerPlatform.kShaderCompPlatformGL:
case ShaderCompilerPlatform.GL:
return "openGL";
case ShaderCompilerPlatform.kShaderCompPlatformD3D9:
case ShaderCompilerPlatform.D3D9:
return "d3d9";
case ShaderCompilerPlatform.kShaderCompPlatformXbox360:
case ShaderCompilerPlatform.Xbox360:
return "xbox360";
case ShaderCompilerPlatform.kShaderCompPlatformPS3:
case ShaderCompilerPlatform.PS3:
return "ps3";
case ShaderCompilerPlatform.kShaderCompPlatformD3D11:
case ShaderCompilerPlatform.D3D11:
return "d3d11";
case ShaderCompilerPlatform.kShaderCompPlatformGLES20:
case ShaderCompilerPlatform.GLES20:
return "gles";
case ShaderCompilerPlatform.kShaderCompPlatformNaCl:
case ShaderCompilerPlatform.NaCl:
return "glesdesktop";
case ShaderCompilerPlatform.kShaderCompPlatformFlash:
case ShaderCompilerPlatform.Flash:
return "flash";
case ShaderCompilerPlatform.kShaderCompPlatformD3D11_9x:
case ShaderCompilerPlatform.D3D11_9x:
return "d3d11_9x";
case ShaderCompilerPlatform.kShaderCompPlatformGLES3Plus:
case ShaderCompilerPlatform.GLES3Plus:
return "gles3";
case ShaderCompilerPlatform.kShaderCompPlatformPSP2:
case ShaderCompilerPlatform.PSP2:
return "psp2";
case ShaderCompilerPlatform.kShaderCompPlatformPS4:
case ShaderCompilerPlatform.PS4:
return "ps4";
case ShaderCompilerPlatform.kShaderCompPlatformXboxOne:
case ShaderCompilerPlatform.XboxOne:
return "xboxone";
case ShaderCompilerPlatform.kShaderCompPlatformPSM:
case ShaderCompilerPlatform.PSM:
return "psm";
case ShaderCompilerPlatform.kShaderCompPlatformMetal:
case ShaderCompilerPlatform.Metal:
return "metal";
case ShaderCompilerPlatform.kShaderCompPlatformOpenGLCore:
case ShaderCompilerPlatform.OpenGLCore:
return "glcore";
case ShaderCompilerPlatform.kShaderCompPlatformN3DS:
case ShaderCompilerPlatform.N3DS:
return "n3ds";
case ShaderCompilerPlatform.kShaderCompPlatformWiiU:
case ShaderCompilerPlatform.WiiU:
return "wiiu";
case ShaderCompilerPlatform.kShaderCompPlatformVulkan:
case ShaderCompilerPlatform.Vulkan:
return "vulkan";
case ShaderCompilerPlatform.kShaderCompPlatformSwitch:
case ShaderCompilerPlatform.Switch:
return "switch";
case ShaderCompilerPlatform.kShaderCompPlatformXboxOneD3D12:
case ShaderCompilerPlatform.XboxOneD3D12:
return "xboxone_d3d12";
case ShaderCompilerPlatform.kShaderCompPlatformGameCoreXboxOne:
case ShaderCompilerPlatform.GameCoreXboxOne:
return "xboxone";
case ShaderCompilerPlatform.kShaderCompPlatformGameCoreScarlett:
case ShaderCompilerPlatform.GameCoreScarlett:
return "xbox_scarlett";
case ShaderCompilerPlatform.kShaderCompPlatformPS5:
case ShaderCompilerPlatform.PS5:
return "ps5";
case ShaderCompilerPlatform.kShaderCompPlatformPS5NGGC:
case ShaderCompilerPlatform.PS5NGGC:
return "ps5_nggc";
default:
return "unknown";
@@ -860,29 +865,49 @@ namespace AssetStudio
"///////////////////////////////////////////\n";
}
public class ShaderSubProgramEntry
{
public int Offset;
public int Length;
public int Segment;
public ShaderSubProgramEntry(BinaryReader reader, int[] version)
{
Offset = reader.ReadInt32();
Length = reader.ReadInt32();
if (version[0] > 2019 || (version[0] == 2019 && version[1] >= 3)) //2019.3 and up
{
Segment = reader.ReadInt32();
}
}
}
public class ShaderProgram
{
public ShaderSubProgramEntry[] entries;
public ShaderSubProgram[] m_SubPrograms;
public ShaderProgram(BinaryReader reader, int[] version)
{
var subProgramsCapacity = reader.ReadInt32();
m_SubPrograms = new ShaderSubProgram[subProgramsCapacity];
int entrySize;
if (version[0] > 2019 || (version[0] == 2019 && version[1] >= 3)) //2019.3 and up
{
entrySize = 12;
}
else
{
entrySize = 8;
}
entries = new ShaderSubProgramEntry[subProgramsCapacity];
for (int i = 0; i < subProgramsCapacity; i++)
{
reader.BaseStream.Position = 4 + i * entrySize;
var offset = reader.ReadInt32();
reader.BaseStream.Position = offset;
m_SubPrograms[i] = new ShaderSubProgram(reader);
entries[i] = new ShaderSubProgramEntry(reader, version);
}
m_SubPrograms = new ShaderSubProgram[subProgramsCapacity];
}
public void Read(BinaryReader reader, int segment)
{
for (int i = 0; i < entries.Length; i++)
{
var entry = entries[i];
if (entry.Segment == segment)
{
reader.BaseStream.Position = entry.Offset;
m_SubPrograms[i] = new ShaderSubProgram(reader);
}
}
}
@@ -972,36 +997,36 @@ namespace AssetStudio
{
switch (m_ProgramType)
{
case ShaderGpuProgramType.kShaderGpuProgramGLLegacy:
case ShaderGpuProgramType.kShaderGpuProgramGLES31AEP:
case ShaderGpuProgramType.kShaderGpuProgramGLES31:
case ShaderGpuProgramType.kShaderGpuProgramGLES3:
case ShaderGpuProgramType.kShaderGpuProgramGLES:
case ShaderGpuProgramType.kShaderGpuProgramGLCore32:
case ShaderGpuProgramType.kShaderGpuProgramGLCore41:
case ShaderGpuProgramType.kShaderGpuProgramGLCore43:
case ShaderGpuProgramType.GLLegacy:
case ShaderGpuProgramType.GLES31AEP:
case ShaderGpuProgramType.GLES31:
case ShaderGpuProgramType.GLES3:
case ShaderGpuProgramType.GLES:
case ShaderGpuProgramType.GLCore32:
case ShaderGpuProgramType.GLCore41:
case ShaderGpuProgramType.GLCore43:
sb.Append(Encoding.UTF8.GetString(m_ProgramCode));
break;
case ShaderGpuProgramType.kShaderGpuProgramDX9VertexSM20:
case ShaderGpuProgramType.kShaderGpuProgramDX9VertexSM30:
case ShaderGpuProgramType.kShaderGpuProgramDX9PixelSM20:
case ShaderGpuProgramType.kShaderGpuProgramDX9PixelSM30:
case ShaderGpuProgramType.DX9VertexSM20:
case ShaderGpuProgramType.DX9VertexSM30:
case ShaderGpuProgramType.DX9PixelSM20:
case ShaderGpuProgramType.DX9PixelSM30:
{
/*var shaderBytecode = new ShaderBytecode(m_ProgramCode);
sb.Append(shaderBytecode.Disassemble());*/
sb.Append("// shader disassembly not supported on DXBC");
break;
}
case ShaderGpuProgramType.kShaderGpuProgramDX10Level9Vertex:
case ShaderGpuProgramType.kShaderGpuProgramDX10Level9Pixel:
case ShaderGpuProgramType.kShaderGpuProgramDX11VertexSM40:
case ShaderGpuProgramType.kShaderGpuProgramDX11VertexSM50:
case ShaderGpuProgramType.kShaderGpuProgramDX11PixelSM40:
case ShaderGpuProgramType.kShaderGpuProgramDX11PixelSM50:
case ShaderGpuProgramType.kShaderGpuProgramDX11GeometrySM40:
case ShaderGpuProgramType.kShaderGpuProgramDX11GeometrySM50:
case ShaderGpuProgramType.kShaderGpuProgramDX11HullSM50:
case ShaderGpuProgramType.kShaderGpuProgramDX11DomainSM50:
case ShaderGpuProgramType.DX10Level9Vertex:
case ShaderGpuProgramType.DX10Level9Pixel:
case ShaderGpuProgramType.DX11VertexSM40:
case ShaderGpuProgramType.DX11VertexSM50:
case ShaderGpuProgramType.DX11PixelSM40:
case ShaderGpuProgramType.DX11PixelSM50:
case ShaderGpuProgramType.DX11GeometrySM40:
case ShaderGpuProgramType.DX11GeometrySM50:
case ShaderGpuProgramType.DX11HullSM50:
case ShaderGpuProgramType.DX11DomainSM50:
{
/*int start = 6;
if (m_Version == 201509030) // 5.3
@@ -1015,8 +1040,8 @@ namespace AssetStudio
sb.Append("// shader disassembly not supported on DXBC");
break;
}
case ShaderGpuProgramType.kShaderGpuProgramMetalVS:
case ShaderGpuProgramType.kShaderGpuProgramMetalFS:
case ShaderGpuProgramType.MetalVS:
case ShaderGpuProgramType.MetalFS:
using (var reader = new BinaryReader(new MemoryStream(m_ProgramCode)))
{
var fourCC = reader.ReadUInt32();
@@ -1030,7 +1055,7 @@ namespace AssetStudio
sb.Append(Encoding.UTF8.GetString(buff));
}
break;
case ShaderGpuProgramType.kShaderGpuProgramSPIRV:
case ShaderGpuProgramType.SPIRV:
try
{
sb.Append(SpirVShaderConverter.Convert(m_ProgramCode));
@@ -1040,11 +1065,11 @@ namespace AssetStudio
sb.Append($"// disassembly error {e.Message}\n");
}
break;
case ShaderGpuProgramType.kShaderGpuProgramConsoleVS:
case ShaderGpuProgramType.kShaderGpuProgramConsoleFS:
case ShaderGpuProgramType.kShaderGpuProgramConsoleHS:
case ShaderGpuProgramType.kShaderGpuProgramConsoleDS:
case ShaderGpuProgramType.kShaderGpuProgramConsoleGS:
case ShaderGpuProgramType.ConsoleVS:
case ShaderGpuProgramType.ConsoleFS:
case ShaderGpuProgramType.ConsoleHS:
case ShaderGpuProgramType.ConsoleDS:
case ShaderGpuProgramType.ConsoleGS:
sb.Append(Encoding.UTF8.GetString(m_ProgramCode));
break;
default:

View File

@@ -1,128 +1,157 @@
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
namespace AssetStudio
{
public enum SpriteMaskMode
{
Off,
On,
MaskOnly,
Export
}
public static class SpriteHelper
{
public static MemoryStream GetImage(this Sprite m_Sprite, ImageFormat imageFormat)
{
var image = GetImage(m_Sprite);
if (image != null)
{
using (image)
{
return image.ConvertToStream(imageFormat);
}
}
return null;
}
public static Bitmap GetImage(this Sprite m_Sprite)
public static Image<Bgra32> GetImage(this Sprite m_Sprite, SpriteMaskMode spriteMaskMode = SpriteMaskMode.On)
{
if (m_Sprite.m_SpriteAtlas != null && m_Sprite.m_SpriteAtlas.TryGet(out var m_SpriteAtlas))
{
if (m_SpriteAtlas.m_RenderDataMap.TryGetValue(m_Sprite.m_RenderDataKey, out var spriteAtlasData) && spriteAtlasData.texture.TryGet(out var m_Texture2D))
{
return CutImage(m_Texture2D, m_Sprite, spriteAtlasData.textureRect, spriteAtlasData.textureRectOffset, spriteAtlasData.settingsRaw);
return CutImage(m_Sprite, m_Texture2D, spriteAtlasData.textureRect, spriteAtlasData.textureRectOffset, spriteAtlasData.downscaleMultiplier, spriteAtlasData.settingsRaw);
}
}
else
{
if (m_Sprite.m_RD.texture.TryGet(out var m_Texture2D))
if (m_Sprite.m_RD.texture.TryGet(out var m_Texture2D) && m_Sprite.m_RD.alphaTexture.TryGet(out var m_AlphaTexture2D) && spriteMaskMode != SpriteMaskMode.Off)
{
return CutImage(m_Texture2D, m_Sprite, m_Sprite.m_RD.textureRect, m_Sprite.m_RD.textureRectOffset, m_Sprite.m_RD.settingsRaw);
var tex = CutImage(m_Sprite, m_Texture2D, m_Sprite.m_RD.textureRect, m_Sprite.m_RD.textureRectOffset, m_Sprite.m_RD.downscaleMultiplier, m_Sprite.m_RD.settingsRaw);
var alphaTex = CutImage(m_Sprite, m_AlphaTexture2D, m_Sprite.m_RD.textureRect, m_Sprite.m_RD.textureRectOffset, m_Sprite.m_RD.downscaleMultiplier, m_Sprite.m_RD.settingsRaw);
switch (spriteMaskMode)
{
case SpriteMaskMode.On:
tex.ApplyRGBMask(alphaTex, isPreview: true);
return tex;
case SpriteMaskMode.Export:
tex.ApplyRGBMask(alphaTex);
return tex;
case SpriteMaskMode.MaskOnly:
tex.Dispose();
return alphaTex;
}
}
else if (m_Sprite.m_RD.texture.TryGet(out m_Texture2D))
{
return CutImage(m_Sprite, m_Texture2D, m_Sprite.m_RD.textureRect, m_Sprite.m_RD.textureRectOffset, m_Sprite.m_RD.downscaleMultiplier, m_Sprite.m_RD.settingsRaw);
}
}
return null;
}
private static Bitmap CutImage(Texture2D m_Texture2D, Sprite m_Sprite, Rectf textureRect, Vector2 textureRectOffset, SpriteSettings settingsRaw)
private static void ApplyRGBMask(this Image<Bgra32> tex, Image<Bgra32> texMask, bool isPreview = false)
{
var originalImage = m_Texture2D.ConvertToBitmap(false);
using (texMask)
{
if (tex.Width != texMask.Width || tex.Height != texMask.Height)
{
var resampler = isPreview ? KnownResamplers.NearestNeighbor : KnownResamplers.Bicubic;
texMask.Mutate(x => x.Resize(tex.Width, tex.Height, resampler));
}
tex.ProcessPixelRows(texMask, (sourceTex, targetTexMask) =>
{
for (int y = 0; y < texMask.Height; y++)
{
var texRow = sourceTex.GetRowSpan(y);
var maskRow = targetTexMask.GetRowSpan(y);
for (int x = 0; x < maskRow.Length; x++)
{
var grayscale = (byte)((maskRow[x].R + maskRow[x].G + maskRow[x].B) / 3);
texRow[x].A = grayscale;
}
}
});
}
}
private static Image<Bgra32> CutImage(Sprite m_Sprite, Texture2D m_Texture2D, Rectf textureRect, Vector2 textureRectOffset, float downscaleMultiplier, SpriteSettings settingsRaw)
{
var originalImage = m_Texture2D.ConvertToImage(false);
if (originalImage != null)
{
using (originalImage)
{
if (downscaleMultiplier > 0f && downscaleMultiplier != 1f)
{
var width = (int)(m_Texture2D.m_Width / downscaleMultiplier);
var height = (int)(m_Texture2D.m_Height / downscaleMultiplier);
originalImage.Mutate(x => x.Resize(width, height));
}
var rectX = (int)Math.Floor(textureRect.x);
var rectY = (int)Math.Floor(textureRect.y);
var rectRight = (int)Math.Ceiling(textureRect.x + textureRect.width);
var rectBottom = (int)Math.Ceiling(textureRect.y + textureRect.height);
rectRight = Math.Min(rectRight, m_Texture2D.m_Width);
rectBottom = Math.Min(rectBottom, m_Texture2D.m_Height);
rectRight = Math.Min(rectRight, originalImage.Width);
rectBottom = Math.Min(rectBottom, originalImage.Height);
var rect = new Rectangle(rectX, rectY, rectRight - rectX, rectBottom - rectY);
var spriteImage = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);
var destRect = new Rectangle(0, 0, rect.Width, rect.Height);
using (var graphic = Graphics.FromImage(spriteImage))
{
graphic.DrawImage(originalImage, destRect, rect, GraphicsUnit.Pixel);
}
var spriteImage = originalImage.Clone(x => x.Crop(rect));
if (settingsRaw.packed == 1)
{
//RotateAndFlip
switch (settingsRaw.packingRotation)
{
case SpritePackingRotation.kSPRFlipHorizontal:
spriteImage.RotateFlip(RotateFlipType.RotateNoneFlipX);
case SpritePackingRotation.FlipHorizontal:
spriteImage.Mutate(x => x.Flip(FlipMode.Horizontal));
break;
case SpritePackingRotation.kSPRFlipVertical:
spriteImage.RotateFlip(RotateFlipType.RotateNoneFlipY);
case SpritePackingRotation.FlipVertical:
spriteImage.Mutate(x => x.Flip(FlipMode.Vertical));
break;
case SpritePackingRotation.kSPRRotate180:
spriteImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
case SpritePackingRotation.Rotate180:
spriteImage.Mutate(x => x.Rotate(180));
break;
case SpritePackingRotation.kSPRRotate90:
spriteImage.RotateFlip(RotateFlipType.Rotate270FlipNone);
case SpritePackingRotation.Rotate90:
spriteImage.Mutate(x => x.Rotate(270));
break;
}
}
//Tight
if (settingsRaw.packingMode == SpritePackingMode.kSPMTight)
if (settingsRaw.packingMode == SpritePackingMode.Tight)
{
try
{
var triangles = GetTriangles(m_Sprite.m_RD);
var points = triangles.Select(x => x.Select(y => new PointF(y.X, y.Y)).ToArray());
using (var path = new GraphicsPath())
var polygons = triangles.Select(x => new Polygon(new LinearLineSegment(x.Select(y => new PointF(y.X, y.Y)).ToArray()))).ToArray();
IPathCollection path = new PathCollection(polygons);
var matrix = Matrix3x2.CreateScale(m_Sprite.m_PixelsToUnits);
matrix *= Matrix3x2.CreateTranslation(m_Sprite.m_Rect.width * m_Sprite.m_Pivot.X - textureRectOffset.X, m_Sprite.m_Rect.height * m_Sprite.m_Pivot.Y - textureRectOffset.Y);
path = path.Transform(matrix);
var graphicsOptions = new GraphicsOptions
{
foreach (var p in points)
{
path.AddPolygon(p);
}
using (var matr = new Matrix())
{
var version = m_Sprite.version;
if (version[0] < 5
|| (version[0] == 5 && version[1] < 4)
|| (version[0] == 5 && version[1] == 4 && version[2] <= 1)) //5.4.1p3 down
{
matr.Translate(m_Sprite.m_Rect.width * 0.5f - textureRectOffset.X, m_Sprite.m_Rect.height * 0.5f - textureRectOffset.Y);
}
else
{
matr.Translate(m_Sprite.m_Rect.width * m_Sprite.m_Pivot.X - textureRectOffset.X, m_Sprite.m_Rect.height * m_Sprite.m_Pivot.Y - textureRectOffset.Y);
}
matr.Scale(m_Sprite.m_PixelsToUnits, m_Sprite.m_PixelsToUnits);
path.Transform(matr);
var bitmap = new Bitmap(rect.Width, rect.Height);
using (var graphic = Graphics.FromImage(bitmap))
{
using (var brush = new TextureBrush(spriteImage))
{
graphic.FillPath(brush, path);
bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
spriteImage.Dispose();
return bitmap;
}
}
}
Antialias = false,
AlphaCompositionMode = PixelAlphaCompositionMode.DestOut
};
var options = new DrawingOptions
{
GraphicsOptions = graphicsOptions
};
using (var mask = new Image<Bgra32>(rect.Width, rect.Height, SixLabors.ImageSharp.Color.Black))
{
mask.Mutate(x => x.Fill(options, SixLabors.ImageSharp.Color.Red, path));
var brush = new ImageBrush(mask);
spriteImage.Mutate(x => x.Fill(options, brush));
spriteImage.Mutate(x => x.Flip(FlipMode.Vertical));
return spriteImage;
}
}
catch
@@ -132,7 +161,7 @@ namespace AssetStudio
}
//Rectangle
spriteImage.RotateFlip(RotateFlipType.RotateNoneFlipY);
spriteImage.Mutate(x => x.Flip(FlipMode.Vertical));
return spriteImage;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,241 +1,247 @@
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using Texture2DDecoder;
namespace AssetStudio
{
public class Texture2DConverter
{
private ResourceReader reader;
private int m_Width;
private int m_Height;
private TextureFormat m_TextureFormat;
private int image_data_size;
private byte[] image_data;
private int[] version;
private BuildTarget platform;
private int outPutSize;
public Texture2DConverter(Texture2D m_Texture2D)
{
image_data = m_Texture2D.image_data.GetData();
image_data_size = image_data.Length;
reader = m_Texture2D.image_data;
m_Width = m_Texture2D.m_Width;
m_Height = m_Texture2D.m_Height;
m_TextureFormat = m_Texture2D.m_TextureFormat;
version = m_Texture2D.version;
platform = m_Texture2D.platform;
outPutSize = m_Width * m_Height * 4;
}
public byte[] DecodeTexture2D()
public bool DecodeTexture2D(byte[] bytes)
{
byte[] bytes = null;
if (reader.Size == 0 || m_Width == 0 || m_Height == 0)
{
return false;
}
var flag = false;
var buff = BigArrayPool<byte>.Shared.Rent(reader.Size);
reader.GetData(buff);
switch (m_TextureFormat)
{
case TextureFormat.Alpha8: //test pass
bytes = DecodeAlpha8();
flag = DecodeAlpha8(buff, bytes);
break;
case TextureFormat.ARGB4444: //test pass
SwapBytesForXbox();
bytes = DecodeARGB4444();
SwapBytesForXbox(buff);
flag = DecodeARGB4444(buff, bytes);
break;
case TextureFormat.RGB24: //test pass
bytes = DecodeRGB24();
flag = DecodeRGB24(buff, bytes);
break;
case TextureFormat.RGBA32: //test pass
bytes = DecodeRGBA32();
flag = DecodeRGBA32(buff, bytes);
break;
case TextureFormat.ARGB32: //test pass
bytes = DecodeARGB32();
flag = DecodeARGB32(buff, bytes);
break;
case TextureFormat.RGB565: //test pass
SwapBytesForXbox();
bytes = DecodeRGB565();
SwapBytesForXbox(buff);
flag = DecodeRGB565(buff, bytes);
break;
case TextureFormat.R16: //test pass
bytes = DecodeR16();
flag = DecodeR16(buff, bytes);
break;
case TextureFormat.DXT1: //test pass
SwapBytesForXbox();
bytes = DecodeDXT1();
SwapBytesForXbox(buff);
flag = DecodeDXT1(buff, bytes);
break;
case TextureFormat.DXT3:
break;
case TextureFormat.DXT5: //test pass
SwapBytesForXbox();
bytes = DecodeDXT5();
SwapBytesForXbox(buff);
flag = DecodeDXT5(buff, bytes);
break;
case TextureFormat.RGBA4444: //test pass
bytes = DecodeRGBA4444();
flag = DecodeRGBA4444(buff, bytes);
break;
case TextureFormat.BGRA32: //test pass
bytes = DecodeBGRA32();
flag = DecodeBGRA32(buff, bytes);
break;
case TextureFormat.RHalf:
bytes = DecodeRHalf();
flag = DecodeRHalf(buff, bytes);
break;
case TextureFormat.RGHalf:
bytes = DecodeRGHalf();
flag = DecodeRGHalf(buff, bytes);
break;
case TextureFormat.RGBAHalf: //test pass
bytes = DecodeRGBAHalf();
flag = DecodeRGBAHalf(buff, bytes);
break;
case TextureFormat.RFloat:
bytes = DecodeRFloat();
flag = DecodeRFloat(buff, bytes);
break;
case TextureFormat.RGFloat:
bytes = DecodeRGFloat();
flag = DecodeRGFloat(buff, bytes);
break;
case TextureFormat.RGBAFloat:
bytes = DecodeRGBAFloat();
flag = DecodeRGBAFloat(buff, bytes);
break;
case TextureFormat.YUY2: //test pass
bytes = DecodeYUY2();
flag = DecodeYUY2(buff, bytes);
break;
case TextureFormat.RGB9e5Float: //test pass
bytes = DecodeRGB9e5Float();
break;
case TextureFormat.BC4: //test pass
bytes = DecodeBC4();
break;
case TextureFormat.BC5: //test pass
bytes = DecodeBC5();
flag = DecodeRGB9e5Float(buff, bytes);
break;
case TextureFormat.BC6H: //test pass
bytes = DecodeBC6H();
flag = DecodeBC6H(buff, bytes);
break;
case TextureFormat.BC7: //test pass
bytes = DecodeBC7();
flag = DecodeBC7(buff, bytes);
break;
case TextureFormat.BC4: //test pass
flag = DecodeBC4(buff, bytes);
break;
case TextureFormat.BC5: //test pass
flag = DecodeBC5(buff, bytes);
break;
case TextureFormat.DXT1Crunched: //test pass
if (UnpackCrunch())
{
bytes = DecodeDXT1();
}
flag = DecodeDXT1Crunched(buff, bytes);
break;
case TextureFormat.DXT5Crunched: //test pass
if (UnpackCrunch())
{
bytes = DecodeDXT5();
}
flag = DecodeDXT5Crunched(buff, bytes);
break;
case TextureFormat.PVRTC_RGB2: //test pass
case TextureFormat.PVRTC_RGBA2: //test pass
bytes = DecodePVRTC(true);
flag = DecodePVRTC(buff, bytes, true);
break;
case TextureFormat.PVRTC_RGB4: //test pass
case TextureFormat.PVRTC_RGBA4: //test pass
bytes = DecodePVRTC(false);
flag = DecodePVRTC(buff, bytes, false);
break;
case TextureFormat.ETC_RGB4: //test pass
case TextureFormat.ETC_RGB4_3DS:
bytes = DecodeETC1();
flag = DecodeETC1(buff, bytes);
break;
case TextureFormat.ATC_RGB4: //test pass
bytes = DecodeATCRGB4();
flag = DecodeATCRGB4(buff, bytes);
break;
case TextureFormat.ATC_RGBA8: //test pass
bytes = DecodeATCRGBA8();
flag = DecodeATCRGBA8(buff, bytes);
break;
case TextureFormat.EAC_R: //test pass
bytes = DecodeEACR();
flag = DecodeEACR(buff, bytes);
break;
case TextureFormat.EAC_R_SIGNED:
bytes = DecodeEACRSigned();
flag = DecodeEACRSigned(buff, bytes);
break;
case TextureFormat.EAC_RG: //test pass
bytes = DecodeEACRG();
flag = DecodeEACRG(buff, bytes);
break;
case TextureFormat.EAC_RG_SIGNED:
bytes = DecodeEACRGSigned();
flag = DecodeEACRGSigned(buff, bytes);
break;
case TextureFormat.ETC2_RGB: //test pass
bytes = DecodeETC2();
flag = DecodeETC2(buff, bytes);
break;
case TextureFormat.ETC2_RGBA1: //test pass
bytes = DecodeETC2A1();
flag = DecodeETC2A1(buff, bytes);
break;
case TextureFormat.ETC2_RGBA8: //test pass
case TextureFormat.ETC_RGBA8_3DS:
bytes = DecodeETC2A8();
flag = DecodeETC2A8(buff, bytes);
break;
case TextureFormat.ASTC_RGB_4x4: //test pass
case TextureFormat.ASTC_RGBA_4x4: //test pass
case TextureFormat.ASTC_HDR_4x4: //test pass
bytes = DecodeASTC(4);
flag = DecodeASTC(buff, bytes, 4);
break;
case TextureFormat.ASTC_RGB_5x5: //test pass
case TextureFormat.ASTC_RGBA_5x5: //test pass
case TextureFormat.ASTC_HDR_5x5: //test pass
bytes = DecodeASTC(5);
flag = DecodeASTC(buff, bytes, 5);
break;
case TextureFormat.ASTC_RGB_6x6: //test pass
case TextureFormat.ASTC_RGBA_6x6: //test pass
case TextureFormat.ASTC_HDR_6x6: //test pass
bytes = DecodeASTC(6);
flag = DecodeASTC(buff, bytes, 6);
break;
case TextureFormat.ASTC_RGB_8x8: //test pass
case TextureFormat.ASTC_RGBA_8x8: //test pass
case TextureFormat.ASTC_HDR_8x8: //test pass
bytes = DecodeASTC(8);
flag = DecodeASTC(buff, bytes, 8);
break;
case TextureFormat.ASTC_RGB_10x10: //test pass
case TextureFormat.ASTC_RGBA_10x10: //test pass
case TextureFormat.ASTC_HDR_10x10: //test pass
bytes = DecodeASTC(10);
flag = DecodeASTC(buff, bytes, 10);
break;
case TextureFormat.ASTC_RGB_12x12: //test pass
case TextureFormat.ASTC_RGBA_12x12: //test pass
case TextureFormat.ASTC_HDR_12x12: //test pass
bytes = DecodeASTC(12);
flag = DecodeASTC(buff, bytes, 12);
break;
case TextureFormat.RG16: //test pass
bytes = DecodeRG16();
flag = DecodeRG16(buff, bytes);
break;
case TextureFormat.R8: //test pass
bytes = DecodeR8();
flag = DecodeR8(buff, bytes);
break;
case TextureFormat.ETC_RGB4Crunched: //test pass
if (UnpackCrunch())
{
bytes = DecodeETC1();
}
flag = DecodeETC1Crunched(buff, bytes);
break;
case TextureFormat.ETC2_RGBA8Crunched: //test pass
if (UnpackCrunch())
{
bytes = DecodeETC2A8();
}
flag = DecodeETC2A8Crunched(buff, bytes);
break;
case TextureFormat.RG32: //test pass
flag = DecodeRG32(buff, bytes);
break;
case TextureFormat.RGB48: //test pass
flag = DecodeRGB48(buff, bytes);
break;
case TextureFormat.RGBA64: //test pass
flag = DecodeRGBA64(buff, bytes);
break;
}
return bytes;
BigArrayPool<byte>.Shared.Return(buff);
return flag;
}
private void SwapBytesForXbox()
private void SwapBytesForXbox(byte[] image_data)
{
if (platform == BuildTarget.XBOX360)
{
for (var i = 0; i < image_data_size / 2; i++)
for (var i = 0; i < reader.Size / 2; i++)
{
var b = image_data[i * 2];
image_data[i * 2] = image_data[i * 2 + 1];
image_data[i * 2 + 1] = b;
(image_data[i * 2 + 1], image_data[i * 2]) = (image_data[i * 2], image_data[i * 2 + 1]);
}
}
}
private byte[] DecodeAlpha8()
private bool DecodeAlpha8(byte[] image_data, byte[] buff)
{
var buff = Enumerable.Repeat<byte>(0xFF, m_Width * m_Height * 4).ToArray();
for (var i = 0; i < m_Width * m_Height; i++)
var size = m_Width * m_Height;
var span = new Span<byte>(buff);
span.Fill(0xFF);
for (var i = 0; i < size; i++)
{
buff[i * 4 + 3] = image_data[i];
}
return buff;
return true;
}
private byte[] DecodeARGB4444()
private bool DecodeARGB4444(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
for (var i = 0; i < m_Width * m_Height; i++)
var size = m_Width * m_Height;
var pixelNew = new byte[4];
for (var i = 0; i < size; i++)
{
var pixelNew = new byte[4];
var pixelOldShort = BitConverter.ToUInt16(image_data, i * 2);
pixelNew[0] = (byte)(pixelOldShort & 0x000f);
pixelNew[1] = (byte)((pixelOldShort & 0x00f0) >> 4);
@@ -245,52 +251,50 @@ namespace AssetStudio
pixelNew[j] = (byte)((pixelNew[j] << 4) | pixelNew[j]);
pixelNew.CopyTo(buff, i * 4);
}
return buff;
return true;
}
private byte[] DecodeRGB24()
private bool DecodeRGB24(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
for (var i = 0; i < m_Width * m_Height; i++)
var size = m_Width * m_Height;
for (var i = 0; i < size; i++)
{
buff[i * 4] = image_data[i * 3 + 2];
buff[i * 4 + 1] = image_data[i * 3 + 1];
buff[i * 4 + 2] = image_data[i * 3 + 0];
buff[i * 4 + 3] = 255;
}
return buff;
return true;
}
private byte[] DecodeRGBA32()
private bool DecodeRGBA32(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
for (var i = 0; i < buff.Length; i += 4)
for (var i = 0; i < outPutSize; i += 4)
{
buff[i] = image_data[i + 2];
buff[i + 1] = image_data[i + 1];
buff[i + 2] = image_data[i + 0];
buff[i + 3] = image_data[i + 3];
}
return buff;
return true;
}
private byte[] DecodeARGB32()
private bool DecodeARGB32(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
for (var i = 0; i < buff.Length; i += 4)
for (var i = 0; i < outPutSize; i += 4)
{
buff[i] = image_data[i + 3];
buff[i + 1] = image_data[i + 2];
buff[i + 2] = image_data[i + 1];
buff[i + 3] = image_data[i + 0];
}
return buff;
return true;
}
private byte[] DecodeRGB565()
private bool DecodeRGB565(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
for (var i = 0; i < m_Width * m_Height; i++)
var size = m_Width * m_Height;
for (var i = 0; i < size; i++)
{
var p = BitConverter.ToUInt16(image_data, i * 2);
buff[i * 4] = (byte)((p << 3) | (p >> 2 & 7));
@@ -298,46 +302,38 @@ namespace AssetStudio
buff[i * 4 + 2] = (byte)((p >> 8 & 0xf8) | (p >> 13));
buff[i * 4 + 3] = 255;
}
return buff;
return true;
}
private byte[] DecodeR16()
private bool DecodeR16(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
for (var i = 0; i < m_Width * m_Height; i++)
var size = m_Width * m_Height;
for (var i = 0; i < size; i++)
{
buff[i * 4 + 2] = image_data[i * 2 + 1]; //r
buff[i * 4] = 0; //b
buff[i * 4 + 1] = 0; //g
buff[i * 4 + 2] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i * 2)); //r
buff[i * 4 + 3] = 255; //a
}
return buff;
return true;
}
private byte[] DecodeDXT1()
private bool DecodeDXT1(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodeDXT1(image_data, m_Width, m_Height, buff))
{
return null;
}
return buff;
return TextureDecoder.DecodeDXT1(image_data, m_Width, m_Height, buff);
}
private byte[] DecodeDXT5()
private bool DecodeDXT5(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodeDXT5(image_data, m_Width, m_Height, buff))
{
return null;
}
return buff;
return TextureDecoder.DecodeDXT5(image_data, m_Width, m_Height, buff);
}
private byte[] DecodeRGBA4444()
private bool DecodeRGBA4444(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
for (var i = 0; i < m_Width * m_Height; i++)
var size = m_Width * m_Height;
var pixelNew = new byte[4];
for (var i = 0; i < size; i++)
{
var pixelNew = new byte[4];
var pixelOldShort = BitConverter.ToUInt16(image_data, i * 2);
pixelNew[0] = (byte)((pixelOldShort & 0x00f0) >> 4);
pixelNew[1] = (byte)((pixelOldShort & 0x0f00) >> 8);
@@ -347,108 +343,101 @@ namespace AssetStudio
pixelNew[j] = (byte)((pixelNew[j] << 4) | pixelNew[j]);
pixelNew.CopyTo(buff, i * 4);
}
return buff;
return true;
}
private byte[] DecodeBGRA32()
private bool DecodeBGRA32(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
for (var i = 0; i < buff.Length; i += 4)
for (var i = 0; i < outPutSize; i += 4)
{
buff[i] = image_data[i];
buff[i + 1] = image_data[i + 1];
buff[i + 2] = image_data[i + 2];
buff[i + 3] = image_data[i + 3];
}
return buff;
return true;
}
private byte[] DecodeRHalf()
private bool DecodeRHalf(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
for (var i = 0; i < buff.Length; i += 4)
for (var i = 0; i < outPutSize; i += 4)
{
buff[i] = 0;
buff[i + 1] = 0;
buff[i + 2] = (byte)Math.Round(Half.ToHalf(image_data, i / 2) * 255f);
buff[i + 3] = 255;
}
return buff;
return true;
}
private byte[] DecodeRGHalf()
private bool DecodeRGHalf(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
for (var i = 0; i < buff.Length; i += 4)
for (var i = 0; i < outPutSize; i += 4)
{
buff[i] = 0;
buff[i + 1] = (byte)Math.Round(Half.ToHalf(image_data, i + 2) * 255f);
buff[i + 2] = (byte)Math.Round(Half.ToHalf(image_data, i) * 255f);
buff[i + 3] = 255;
}
return buff;
return true;
}
private byte[] DecodeRGBAHalf()
private bool DecodeRGBAHalf(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
for (var i = 0; i < buff.Length; i += 4)
for (var i = 0; i < outPutSize; i += 4)
{
buff[i] = (byte)Math.Round(Half.ToHalf(image_data, i * 2 + 4) * 255f);
buff[i + 1] = (byte)Math.Round(Half.ToHalf(image_data, i * 2 + 2) * 255f);
buff[i + 2] = (byte)Math.Round(Half.ToHalf(image_data, i * 2) * 255f);
buff[i + 3] = (byte)Math.Round(Half.ToHalf(image_data, i * 2 + 6) * 255f);
}
return buff;
return true;
}
private byte[] DecodeRFloat()
private bool DecodeRFloat(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
for (var i = 0; i < buff.Length; i += 4)
for (var i = 0; i < outPutSize; i += 4)
{
buff[i] = 0;
buff[i + 1] = 0;
buff[i + 2] = (byte)Math.Round(BitConverter.ToSingle(image_data, i) * 255f);
buff[i + 3] = 255;
}
return buff;
return true;
}
private byte[] DecodeRGFloat()
private bool DecodeRGFloat(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
for (var i = 0; i < buff.Length; i += 4)
for (var i = 0; i < outPutSize; i += 4)
{
buff[i] = 0;
buff[i + 1] = (byte)Math.Round(BitConverter.ToSingle(image_data, i * 2 + 4) * 255f);
buff[i + 2] = (byte)Math.Round(BitConverter.ToSingle(image_data, i * 2) * 255f);
buff[i + 3] = 255;
}
return buff;
return true;
}
private byte[] DecodeRGBAFloat()
private bool DecodeRGBAFloat(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
for (var i = 0; i < buff.Length; i += 4)
for (var i = 0; i < outPutSize; i += 4)
{
buff[i] = (byte)Math.Round(BitConverter.ToSingle(image_data, i * 4 + 8) * 255f);
buff[i + 1] = (byte)Math.Round(BitConverter.ToSingle(image_data, i * 4 + 4) * 255f);
buff[i + 2] = (byte)Math.Round(BitConverter.ToSingle(image_data, i * 4) * 255f);
buff[i + 3] = (byte)Math.Round(BitConverter.ToSingle(image_data, i * 4 + 12) * 255f);
}
return buff;
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static byte ClampByte(int x)
{
return (byte)(byte.MaxValue < x ? byte.MaxValue : (x > byte.MinValue ? x : byte.MinValue));
}
private byte[] DecodeYUY2()
private bool DecodeYUY2(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
int p = 0;
int o = 0;
int halfWidth = m_Width / 2;
@@ -474,13 +463,12 @@ namespace AssetStudio
buff[o++] = 255;
}
}
return buff;
return true;
}
private byte[] DecodeRGB9e5Float()
private bool DecodeRGB9e5Float(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
for (var i = 0; i < buff.Length; i += 4)
for (var i = 0; i < outPutSize; i += 4)
{
var n = BitConverter.ToInt32(image_data, i);
var scale = n >> 27 & 0x1f;
@@ -493,195 +481,208 @@ namespace AssetStudio
buff[i + 2] = (byte)Math.Round(r * scalef * 255f);
buff[i + 3] = 255;
}
return buff;
return true;
}
private byte[] DecodeBC4()
private bool DecodeBC4(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodeBC4(image_data, m_Width, m_Height, buff))
return TextureDecoder.DecodeBC4(image_data, m_Width, m_Height, buff);
}
private bool DecodeBC5(byte[] image_data, byte[] buff)
{
return TextureDecoder.DecodeBC5(image_data, m_Width, m_Height, buff);
}
private bool DecodeBC6H(byte[] image_data, byte[] buff)
{
return TextureDecoder.DecodeBC6(image_data, m_Width, m_Height, buff);
}
private bool DecodeBC7(byte[] image_data, byte[] buff)
{
return TextureDecoder.DecodeBC7(image_data, m_Width, m_Height, buff);
}
private bool DecodeDXT1Crunched(byte[] image_data, byte[] buff)
{
if (UnpackCrunch(image_data, out var result))
{
return null;
if (DecodeDXT1(result, buff))
{
return true;
}
}
return buff;
return false;
}
private byte[] DecodeBC5()
private bool DecodeDXT5Crunched(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodeBC5(image_data, m_Width, m_Height, buff))
if (UnpackCrunch(image_data, out var result))
{
return null;
if (DecodeDXT5(result, buff))
{
return true;
}
}
return buff;
return false;
}
private byte[] DecodeBC6H()
private bool DecodePVRTC(byte[] image_data, byte[] buff, bool is2bpp)
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodeBC6(image_data, m_Width, m_Height, buff))
return TextureDecoder.DecodePVRTC(image_data, m_Width, m_Height, buff, is2bpp);
}
private bool DecodeETC1(byte[] image_data, byte[] buff)
{
return TextureDecoder.DecodeETC1(image_data, m_Width, m_Height, buff);
}
private bool DecodeATCRGB4(byte[] image_data, byte[] buff)
{
return TextureDecoder.DecodeATCRGB4(image_data, m_Width, m_Height, buff);
}
private bool DecodeATCRGBA8(byte[] image_data, byte[] buff)
{
return TextureDecoder.DecodeATCRGBA8(image_data, m_Width, m_Height, buff);
}
private bool DecodeEACR(byte[] image_data, byte[] buff)
{
return TextureDecoder.DecodeEACR(image_data, m_Width, m_Height, buff);
}
private bool DecodeEACRSigned(byte[] image_data, byte[] buff)
{
return TextureDecoder.DecodeEACRSigned(image_data, m_Width, m_Height, buff);
}
private bool DecodeEACRG(byte[] image_data, byte[] buff)
{
return TextureDecoder.DecodeEACRG(image_data, m_Width, m_Height, buff);
}
private bool DecodeEACRGSigned(byte[] image_data, byte[] buff)
{
return TextureDecoder.DecodeEACRGSigned(image_data, m_Width, m_Height, buff);
}
private bool DecodeETC2(byte[] image_data, byte[] buff)
{
return TextureDecoder.DecodeETC2(image_data, m_Width, m_Height, buff);
}
private bool DecodeETC2A1(byte[] image_data, byte[] buff)
{
return TextureDecoder.DecodeETC2A1(image_data, m_Width, m_Height, buff);
}
private bool DecodeETC2A8(byte[] image_data, byte[] buff)
{
return TextureDecoder.DecodeETC2A8(image_data, m_Width, m_Height, buff);
}
private bool DecodeASTC(byte[] image_data, byte[] buff, int blocksize)
{
return TextureDecoder.DecodeASTC(image_data, m_Width, m_Height, blocksize, blocksize, buff);
}
private bool DecodeRG16(byte[] image_data, byte[] buff)
{
var size = m_Width * m_Height;
for (var i = 0; i < size; i++)
{
return null;
buff[i * 4] = 0; //B
buff[i * 4 + 1] = image_data[i * 2 + 1];//G
buff[i * 4 + 2] = image_data[i * 2];//R
buff[i * 4 + 3] = 255;//A
}
return buff;
return true;
}
private byte[] DecodeBC7()
private bool DecodeR8(byte[] image_data, byte[] buff)
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodeBC7(image_data, m_Width, m_Height, buff))
{
return null;
}
return buff;
}
private byte[] DecodePVRTC(bool is2bpp)
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodePVRTC(image_data, m_Width, m_Height, buff, is2bpp))
{
return null;
}
return buff;
}
private byte[] DecodeETC1()
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodeETC1(image_data, m_Width, m_Height, buff))
{
return null;
}
return buff;
}
private byte[] DecodeATCRGB4()
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodeATCRGB4(image_data, m_Width, m_Height, buff))
{
return null;
}
return buff;
}
private byte[] DecodeATCRGBA8()
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodeATCRGBA8(image_data, m_Width, m_Height, buff))
{
return null;
}
return buff;
}
private byte[] DecodeEACR()
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodeEACR(image_data, m_Width, m_Height, buff))
{
return null;
}
return buff;
}
private byte[] DecodeEACRSigned()
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodeEACRSigned(image_data, m_Width, m_Height, buff))
{
return null;
}
return buff;
}
private byte[] DecodeEACRG()
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodeEACRG(image_data, m_Width, m_Height, buff))
{
return null;
}
return buff;
}
private byte[] DecodeEACRGSigned()
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodeEACRGSigned(image_data, m_Width, m_Height, buff))
{
return null;
}
return buff;
}
private byte[] DecodeETC2()
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodeETC2(image_data, m_Width, m_Height, buff))
{
return null;
}
return buff;
}
private byte[] DecodeETC2A1()
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodeETC2A1(image_data, m_Width, m_Height, buff))
{
return null;
}
return buff;
}
private byte[] DecodeETC2A8()
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodeETC2A8(image_data, m_Width, m_Height, buff))
{
return null;
}
return buff;
}
private byte[] DecodeASTC(int blocksize)
{
var buff = new byte[m_Width * m_Height * 4];
if (!TextureDecoder.DecodeASTC(image_data, m_Width, m_Height, blocksize, blocksize, buff))
{
return null;
}
return buff;
}
private byte[] DecodeRG16()
{
var buff = new byte[m_Width * m_Height * 4];
for (var i = 0; i < m_Width * m_Height; i += 2)
{
buff[i * 2 + 1] = image_data[i + 1];//G
buff[i * 2 + 2] = image_data[i];//R
buff[i * 2 + 3] = 255;//A
}
return buff;
}
private byte[] DecodeR8()
{
var buff = new byte[m_Width * m_Height * 4];
for (var i = 0; i < m_Width * m_Height; i++)
var size = m_Width * m_Height;
for (var i = 0; i < size; i++)
{
buff[i * 4] = 0; //B
buff[i * 4 + 1] = 0; //G
buff[i * 4 + 2] = image_data[i];//R
buff[i * 4 + 3] = 255;//A
}
return buff;
return true;
}
private bool UnpackCrunch()
private bool DecodeETC1Crunched(byte[] image_data, byte[] buff)
{
if (UnpackCrunch(image_data, out var result))
{
if (DecodeETC1(result, buff))
{
return true;
}
}
return false;
}
private bool DecodeETC2A8Crunched(byte[] image_data, byte[] buff)
{
if (UnpackCrunch(image_data, out var result))
{
if (DecodeETC2A8(result, buff))
{
return true;
}
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte DownScaleFrom16BitTo8Bit(ushort component)
{
return (byte)(((component * 255) + 32895) >> 16);
}
private bool DecodeRG32(byte[] image_data, byte[] buff)
{
for (var i = 0; i < outPutSize; i += 4)
{
buff[i] = 0; //b
buff[i + 1] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i + 2)); //g
buff[i + 2] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i)); //r
buff[i + 3] = byte.MaxValue; //a
}
return true;
}
private bool DecodeRGB48(byte[] image_data, byte[] buff)
{
var size = m_Width * m_Height;
for (var i = 0; i < size; i++)
{
buff[i * 4] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i * 6 + 4)); //b
buff[i * 4 + 1] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i * 6 + 2)); //g
buff[i * 4 + 2] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i * 6)); //r
buff[i * 4 + 3] = byte.MaxValue; //a
}
return true;
}
private bool DecodeRGBA64(byte[] image_data, byte[] buff)
{
for (var i = 0; i < outPutSize; i += 4)
{
buff[i] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i * 2 + 4)); //b
buff[i + 1] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i * 2 + 2)); //g
buff[i + 2] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i * 2)); //r
buff[i + 3] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i * 2 + 6)); //a
}
return true;
}
private bool UnpackCrunch(byte[] image_data, out byte[] result)
{
byte[] result;
if (version[0] > 2017 || (version[0] == 2017 && version[1] >= 3) //2017.3 and up
|| m_TextureFormat == TextureFormat.ETC_RGB4Crunched
|| m_TextureFormat == TextureFormat.ETC2_RGBA8Crunched)
@@ -694,8 +695,6 @@ namespace AssetStudio
}
if (result != null)
{
image_data = result;
image_data_size = result.Length;
return true;
}
return false;

View File

@@ -1,34 +1,38 @@
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using System.IO;
namespace AssetStudio
{
public static class Texture2DExtensions
{
public static Bitmap ConvertToBitmap(this Texture2D m_Texture2D, bool flip)
public static Image<Bgra32> ConvertToImage(this Texture2D m_Texture2D, bool flip)
{
var converter = new Texture2DConverter(m_Texture2D);
var bytes = converter.DecodeTexture2D();
if (bytes != null && bytes.Length > 0)
var buff = BigArrayPool<byte>.Shared.Rent(m_Texture2D.m_Width * m_Texture2D.m_Height * 4);
try
{
var bitmap = new Bitmap(m_Texture2D.m_Width, m_Texture2D.m_Height, PixelFormat.Format32bppArgb);
var bmpData = bitmap.LockBits(new Rectangle(0, 0, m_Texture2D.m_Width, m_Texture2D.m_Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
Marshal.Copy(bytes, 0, bmpData.Scan0, bytes.Length);
bitmap.UnlockBits(bmpData);
if (flip)
if (converter.DecodeTexture2D(buff))
{
bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
var image = Image.LoadPixelData<Bgra32>(buff, m_Texture2D.m_Width, m_Texture2D.m_Height);
if (flip)
{
image.Mutate(x => x.Flip(FlipMode.Vertical));
}
return image;
}
return bitmap;
return null;
}
finally
{
BigArrayPool<byte>.Shared.Return(buff);
}
return null;
}
public static MemoryStream ConvertToStream(this Texture2D m_Texture2D, ImageFormat imageFormat, bool flip)
{
var image = ConvertToBitmap(m_Texture2D, flip);
var image = ConvertToImage(m_Texture2D, flip);
if (image != null)
{
using (image)

View File

@@ -253,28 +253,28 @@ namespace AssetStudio
switch (typeRef.FullName)
{
case "UnityEngine.AnimationCurve":
Helper.AddAnimationCurve(nodes, name, indent + 1);
Helper.AddAnimationCurve(nodes, name, indent);
break;
case "UnityEngine.Gradient":
Helper.AddGradient(nodes, name, indent + 1);
Helper.AddGradient(nodes, name, indent);
break;
case "UnityEngine.GUIStyle":
Helper.AddGUIStyle(nodes, name, indent + 1);
Helper.AddGUIStyle(nodes, name, indent);
break;
case "UnityEngine.RectOffset":
Helper.AddRectOffset(nodes, name, indent + 1);
Helper.AddRectOffset(nodes, name, indent);
break;
case "UnityEngine.Color32":
Helper.AddColor32(nodes, name, indent + 1);
Helper.AddColor32(nodes, name, indent);
break;
case "UnityEngine.Matrix4x4":
Helper.AddMatrix4x4(nodes, name, indent + 1);
Helper.AddMatrix4x4(nodes, name, indent);
break;
case "UnityEngine.Rendering.SphericalHarmonicsL2":
Helper.AddSphericalHarmonicsL2(nodes, name, indent + 1);
Helper.AddSphericalHarmonicsL2(nodes, name, indent);
break;
case "UnityEngine.PropertyName":
Helper.AddPropertyName(nodes, name, indent + 1);
Helper.AddPropertyName(nodes, name, indent);
break;
}
}

View File

@@ -7,7 +7,7 @@ AssetStudio is a tool for exploring, extracting and exporting assets and assetbu
## Features
* Support version:
* 3.4 - 2021.2
* 3.4 - 2022.1
* Support asset types:
* **Texture2D** : convert to png, tga, jpeg, bmp
* **Sprite** : crop Texture2D to png, tga, jpeg, bmp
@@ -23,7 +23,13 @@ AssetStudio is a tool for exploring, extracting and exporting assets and assetbu
## Requirements
- [.NET Framework 4.7.2](https://dotnet.microsoft.com/download/dotnet-framework/net472)
- AssetStudio.net472
- [.NET Framework 4.7.2](https://dotnet.microsoft.com/download/dotnet-framework/net472)
- AssetStudio.net5
- [.NET Desktop Runtime 5.0](https://dotnet.microsoft.com/download/dotnet/5.0)
- AssetStudio.net6
- [.NET Desktop Runtime 6.0](https://dotnet.microsoft.com/download/dotnet/6.0)
## Usage
@@ -63,8 +69,8 @@ First, use my another program [Il2CppDumper](https://github.com/Perfare/Il2CppDu
## Build
* Visual Studio 2019 or newer
* **AssetStudioFBXNative** uses FBX SDK 2020.0.1 VS2017, before building, you need to install the FBX SDK and modify the project file, change include directory and library directory to point to the FBX SDK directory
* Visual Studio 2022 or newer
* **AssetStudioFBXNative** uses [FBX SDK 2020.2.1](https://www.autodesk.com/developer-network/platform-technologies/fbx-sdk-2020-2-1), before building, you need to install the FBX SDK and modify the project file, change include directory and library directory to point to the FBX SDK directory
## Open source libraries used

View File

@@ -0,0 +1,52 @@
# Set the minimum version of CMake that can be used
cmake_minimum_required (VERSION 3.8)
# Set the project name
project("Texture2DDecoderNative")
# Set the C++ standard to C++ 14
set(CMAKE_CXX_STANDARD 14)
# Add definitions from the project file
# 'Release|x64'
# <PreprocessorDefinitions>_T2D_DLL;NDEBUG;TEXTURE2DDECODERNATIVE_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
add_compile_definitions(_T2D_DLL)
add_compile_definitions(NDEBUG)
add_compile_definitions(TEXTURE2DDECODERNATIVE_EXPORTS)
# Add the given directories to those the compiler uses to search for include files
include_directories(.)
include_directories(crunch)
include_directories(fp16)
include_directories(unitycrunch)
# Generate the shared library from the library sources
add_library(Texture2DDecoderNative SHARED
crunch/crn_decomp.h
crunch/crnlib.h
fp16/bitcasts.h
fp16/fp16.h
unitycrunch/crn_decomp.h
unitycrunch/crn_defs.h
unitycrunch/crnlib.h
astc.cpp
astc.h
atc.cpp
atc.h
bcn.cpp
bcn.h
bool32_t.h
color.h
crunch.cpp
crunch.h
dllexport.h
dllmain.cpp
endianness.h
etc.cpp
etc.h
fp16.h
pvrtc.cpp
pvrtc.h
resource.h
unitycrunch.cpp
unitycrunch.h)

View File

@@ -67,26 +67,26 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>

View File

@@ -21,14 +21,43 @@ bool crunch_unpack_level(const uint8_t* data, uint32_t data_size, uint32_t level
const crn_uint32 blocks_x = std::max(1U, (width + 3) >> 2);
const crn_uint32 blocks_y = std::max(1U, (height + 3) >> 2);
const crn_uint32 row_pitch = blocks_x * crnd::crnd_get_bytes_per_dxt_block(tex_info.m_format);
const crn_uint32 total_face_size = row_pitch * blocks_y;
*ret = new uint8_t[total_face_size];
*ret_size = total_face_size;
if (!crnd::crnd_unpack_level(pContext, ret, total_face_size, row_pitch, level_index))
const crn_uint32 face_count = tex_info.m_faces;
const crn_uint32 face_size = row_pitch * blocks_y;
const crn_uint32 total_face_size = face_size * face_count;
void* out_ptrs[cCRNMaxFaces]{};
if (face_count == 1)
{
out_ptrs[0] = new uint8_t[face_size]{};
*ret_size = face_size;
}
else if (1 < face_count < 7)
{
for (uint8_t i = 0; i < face_count; i++)
{
out_ptrs[i] = new uint8_t[face_size]{};
}
*ret_size = total_face_size;
}
else
{
return false;
}
if (!crnd::crnd_unpack_level(pContext, out_ptrs, face_size, row_pitch, level_index))
{
crnd::crnd_unpack_end(pContext);
return false;
}
uint8_t* buff = new uint8_t[total_face_size]{};
for (uint8_t i = 0; i < face_count; i++)
{
memcpy(buff + (face_size * i), out_ptrs[i], face_size);
free(out_ptrs[i]);
}
*ret = buff;
crnd::crnd_unpack_end(pContext);
return true;
}

View File

@@ -316,9 +316,16 @@ namespace crnd
#include <stdlib.h>
#include <stdio.h>
#ifdef _WIN32
#include <memory.h>
#else
#include <malloc.h>
#include <memory.h>
#define MALLOC_SIZE _msize
#elif __APPLE__
#include <cstring>
#include <malloc/malloc.h>
#define MALLOC_SIZE malloc_size
#else // Linux
#include <cstring>
#include <malloc.h>
#define MALLOC_SIZE malloc_usable_size
#endif
#include <stdarg.h>
#include <new> // needed for placement new, _msize, _expand
@@ -2424,11 +2431,7 @@ namespace crnd
if (pActual_size)
{
#ifdef _WIN32
*pActual_size = p_new ? ::_msize(p_new) : 0;
#else
*pActual_size = p_new ? malloc_usable_size(p_new) : 0;
#endif
*pActual_size = p_new ? MALLOC_SIZE(p_new) : 0;
}
}
else if (!size)
@@ -2460,11 +2463,7 @@ namespace crnd
if (pActual_size)
{
#ifdef _WIN32
*pActual_size = ::_msize(p_final_block);
#else
*pActual_size = ::malloc_usable_size(p_final_block);
#endif
*pActual_size = ::MALLOC_SIZE(p_final_block);
}
}
@@ -2474,11 +2473,7 @@ namespace crnd
static size_t crnd_default_msize(void* p, void* pUser_data)
{
pUser_data;
#ifdef _WIN32
return p ? _msize(p) : 0;
#else
return p ? malloc_usable_size(p) : 0;
#endif
return p ? MALLOC_SIZE(p) : 0;
}
static crnd_realloc_func g_pRealloc = crnd_default_realloc;

Some files were not shown because too many files have changed in this diff Show More