├── .gitattributes
├── .github
└── workflows
│ └── build.yml
├── .gitignore
├── BmsLoader.cs
├── CustomAlbums.csproj
├── CustomAlbums.sln
├── Data
├── Album.cs
├── AlbumInfo.cs
├── AnimatedCover.cs
├── AssetIdentifiers.cs
├── Bms.cs
├── BmsStates.cs
├── ChartSave.cs
├── CustomAlbumsSave.cs
├── Pack.cs
├── SceneEggs.cs
├── Sheet.cs
└── Talk.cs
├── Directory.Build.props
├── ILRepack.targets
├── LICENSE
├── Main.cs
├── Managers
├── AlbumManager.cs
├── AudioManager.cs
├── CoverManager.cs
├── HotReloadManager.cs
├── MusicDataManager.cs
├── PackManager.cs
└── SaveManager.cs
├── ModExtensions
├── AlbumEventArgs.cs
├── AssetEventArgs.cs
└── Events.cs
├── ModSettings.cs
├── Patches
├── AnalyticsPatch.cs
├── AnimatedCoverPatch.cs
├── AssetPatch.cs
├── ChartDialogPatch.cs
├── DifficultyGradeIconPatch.cs
├── HiddenSupportPatch.cs
├── LongChartPatch.cs
├── MikuSceneSupportPatch.cs
├── MusicTagManagerPatch.cs
├── PackPatch.cs
├── ReportCardPatch.cs
├── SavePatch.cs
├── SceneEggPatch.cs
├── SilenceLogPatch.cs
├── TagPatch.cs
├── TreeItemPatch.cs
└── WebApiPatch.cs
├── Properties
└── AssemblyInfo.cs
├── README.md
├── SetPath.cmd
└── Utilities
├── Backup.cs
├── ConfigDataExtensions.cs
├── Converters.cs
├── DataExtensions.cs
├── Debug.cs
├── Formatting.cs
├── Il2CppExtensions.cs
├── Interop.cs
├── Json.cs
├── Logger.cs
├── SaveExtensions.cs
├── StreamExtensions.cs
└── StringExtensions.cs
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: Build CustomAlbums
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 | pull_request:
8 | branches:
9 | - master
10 |
11 | jobs:
12 | build:
13 | runs-on: ubuntu-latest
14 |
15 | steps:
16 | - name: Checkout
17 | uses: actions/checkout@v4
18 | with:
19 | fetch-depth: 0
20 |
21 | - name: Install .NET Core
22 | uses: actions/setup-dotnet@v4
23 | with:
24 | dotnet-version: 6.0.x
25 |
26 | - name: Download Dependencies
27 | run: |
28 | wget -O dependencies.zip https://cdn.mdmc.moe/static/cadeps.zip
29 | unzip dependencies.zip -d dependencies
30 |
31 | - name: Restore and Build
32 | run: |
33 | dotnet restore CustomAlbums.sln
34 | dotnet build -c Release "/p:MelonNET6=./dependencies;WORKER=GitHub" CustomAlbums.sln
35 |
36 | - name: Upload Artifact
37 | uses: actions/upload-artifact@v4
38 | with:
39 | name: CustomAlbums.dll
40 | path: ./bin/Release/CustomAlbums.dll
41 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET Core
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # ASP.NET Scaffolding
66 | ScaffoldingReadMe.txt
67 |
68 | # StyleCop
69 | StyleCopReport.xml
70 |
71 | # Files built by Visual Studio
72 | *_i.c
73 | *_p.c
74 | *_h.h
75 | *.ilk
76 | *.meta
77 | *.obj
78 | *.iobj
79 | *.pch
80 | *.pdb
81 | *.ipdb
82 | *.pgc
83 | *.pgd
84 | *.rsp
85 | *.sbr
86 | *.tlb
87 | *.tli
88 | *.tlh
89 | *.tmp
90 | *.tmp_proj
91 | *_wpftmp.csproj
92 | *.log
93 | *.tlog
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.)
298 | *.vbp
299 |
300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project)
301 | *.dsw
302 | *.dsp
303 |
304 | # Visual Studio 6 technical files
305 | *.ncb
306 | *.aps
307 |
308 | # Visual Studio LightSwitch build output
309 | **/*.HTMLClient/GeneratedArtifacts
310 | **/*.DesktopClient/GeneratedArtifacts
311 | **/*.DesktopClient/ModelManifest.xml
312 | **/*.Server/GeneratedArtifacts
313 | **/*.Server/ModelManifest.xml
314 | _Pvt_Extensions
315 |
316 | # Paket dependency manager
317 | .paket/paket.exe
318 | paket-files/
319 |
320 | # FAKE - F# Make
321 | .fake/
322 |
323 | # CodeRush personal settings
324 | .cr/personal
325 |
326 | # Python Tools for Visual Studio (PTVS)
327 | __pycache__/
328 | *.pyc
329 |
330 | # Cake - Uncomment if you are using it
331 | # tools/**
332 | # !tools/packages.config
333 |
334 | # Tabs Studio
335 | *.tss
336 |
337 | # Telerik's JustMock configuration file
338 | *.jmconfig
339 |
340 | # BizTalk build output
341 | *.btp.cs
342 | *.btm.cs
343 | *.odx.cs
344 | *.xsd.cs
345 |
346 | # OpenCover UI analysis results
347 | OpenCover/
348 |
349 | # Azure Stream Analytics local run output
350 | ASALocalRun/
351 |
352 | # MSBuild Binary and Structured Log
353 | *.binlog
354 |
355 | # NVidia Nsight GPU debugger configuration file
356 | *.nvuser
357 |
358 | # MFractors (Xamarin productivity tool) working folder
359 | .mfractor/
360 |
361 | # Local History for Visual Studio
362 | .localhistory/
363 |
364 | # Visual Studio History (VSHistory) files
365 | .vshistory/
366 |
367 | # BeatPulse healthcheck temp database
368 | healthchecksdb
369 |
370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
371 | MigrationBackup/
372 |
373 | # Ionide (cross platform F# VS Code tools) working folder
374 | .ionide/
375 |
376 | # Fody - auto-generated XML schema
377 | FodyWeavers.xsd
378 |
379 | # VS Code files for those working on multiple tools
380 | .vscode/*
381 | !.vscode/settings.json
382 | !.vscode/tasks.json
383 | !.vscode/launch.json
384 | !.vscode/extensions.json
385 | *.code-workspace
386 |
387 | # Local History for Visual Studio Code
388 | .history/
389 |
390 | # Windows Installer files from build outputs
391 | *.cab
392 | *.msi
393 | *.msix
394 | *.msm
395 | *.msp
396 |
397 | # JetBrains Rider
398 | *.sln.iml
399 | .idea
400 |
--------------------------------------------------------------------------------
/CustomAlbums.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net6.0
4 | enable
5 | disable
6 | false
7 | true
8 | AnyCPU;x64
9 | true
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | all
25 | runtime; build; native; contentfiles; analyzers; buildtransitive
26 |
27 |
28 | contentFiles
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/CustomAlbums.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.7.34221.43
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CustomAlbums", "CustomAlbums.csproj", "{AE06FA98-27DC-4F0D-8C4D-59D049F2E5FB}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Debug|x64 = Debug|x64
12 | Release|Any CPU = Release|Any CPU
13 | Release|x64 = Release|x64
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {AE06FA98-27DC-4F0D-8C4D-59D049F2E5FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {AE06FA98-27DC-4F0D-8C4D-59D049F2E5FB}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {AE06FA98-27DC-4F0D-8C4D-59D049F2E5FB}.Debug|x64.ActiveCfg = Debug|x64
19 | {AE06FA98-27DC-4F0D-8C4D-59D049F2E5FB}.Debug|x64.Build.0 = Debug|x64
20 | {AE06FA98-27DC-4F0D-8C4D-59D049F2E5FB}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {AE06FA98-27DC-4F0D-8C4D-59D049F2E5FB}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {AE06FA98-27DC-4F0D-8C4D-59D049F2E5FB}.Release|x64.ActiveCfg = Release|x64
23 | {AE06FA98-27DC-4F0D-8C4D-59D049F2E5FB}.Release|x64.Build.0 = Release|x64
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {B77F8FBA-9A6D-485A-B265-FEEE920E41B3}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/Data/Album.cs:
--------------------------------------------------------------------------------
1 | using System.IO.Compression;
2 | using CustomAlbums.Managers;
3 | using CustomAlbums.Utilities;
4 | using UnityEngine;
5 | using Logger = CustomAlbums.Utilities.Logger;
6 |
7 | namespace CustomAlbums.Data
8 | {
9 | public class Album
10 | {
11 | private static readonly Logger Logger = new(nameof(Album));
12 |
13 | public Album(string path, int index, string packName = null)
14 | {
15 | // If packName is not null then it's a file path, not a folder chart
16 | if (Directory.Exists(path) && packName == null)
17 | {
18 | // Load album from directory
19 | if (!File.Exists($"{path}\\info.json"))
20 | {
21 | Logger.Error($"Could not find info.json at: {path}\\info.json");
22 | throw new FileNotFoundException();
23 | }
24 |
25 | using var fileStream = File.OpenRead($"{path}\\info.json");
26 | Info = Json.Deserialize(fileStream);
27 | }
28 | else if (File.Exists(path))
29 | {
30 | // Load album from package
31 | PackName = packName;
32 | using var zip = ZipFile.OpenRead(path);
33 | var info = zip.GetEntry("info.json");
34 | if (info == null)
35 | {
36 | Logger.Error($"Could not find info.json in package: {path}");
37 | throw new FileNotFoundException();
38 | }
39 |
40 | using var stream = info.Open();
41 | Info = Json.Deserialize(stream);
42 | IsPackaged = true;
43 |
44 | // CurrentPack will always be null if album is not in a pack
45 | IsPack = AlbumManager.CurrentPack != null;
46 | }
47 | else
48 | {
49 | Logger.Error($"Could not find album at: {path}");
50 | throw new FileNotFoundException();
51 | }
52 |
53 | Index = index;
54 | Path = path;
55 |
56 | GetSheets();
57 | }
58 |
59 | public int Index { get; }
60 | public string Path { get; }
61 | public bool IsPackaged { get; }
62 | public bool IsPack { get; }
63 | public string PackName { get; }
64 | public AlbumInfo Info { get; }
65 | public Sprite Cover => this.GetCover();
66 | public AnimatedCover AnimatedCover => this.GetAnimatedCover();
67 | public AudioClip Music => this.GetAudio();
68 | public AudioClip Demo => this.GetAudio("demo");
69 | public Dictionary Sheets { get; } = new();
70 | public string AlbumName =>
71 | IsPackaged ?
72 | $"album_{System.IO.Path.GetFileNameWithoutExtension(Path)}{(PackName != null ? $"_{PackName}" : string.Empty)}"
73 | : $"album_{System.IO.Path.GetFileName(Path)}_folder";
74 | public string Uid => $"{AlbumManager.Uid}-{Index}";
75 |
76 | public bool HasFile(string name)
77 | {
78 | if (IsPackaged)
79 | {
80 | if (!File.Exists(Path)) return false;
81 | try
82 | {
83 | using var zip = ZipFile.OpenRead(Path);
84 | return zip.GetEntry(name) != null;
85 | }
86 | catch (IOException)
87 | {
88 | // This is expected in the case of deleting an album
89 | return false;
90 | }
91 | }
92 |
93 | var path = $"{Path}\\{name}";
94 | return File.Exists(path);
95 | }
96 |
97 | public Stream OpenFileStreamIfPossible(string file)
98 | {
99 | if (IsPackaged)
100 | {
101 | using var zip = ZipFile.OpenRead(Path);
102 | var entry = zip.GetEntry(file);
103 |
104 | if (entry != null)
105 | {
106 | return entry.Open().ToMemoryStream();
107 | }
108 |
109 | Logger.Error($"Could not find file in package: {file}");
110 | throw new FileNotFoundException();
111 | }
112 |
113 | var path = $"{Path}\\{file}";
114 | if (File.Exists(path))
115 | return File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
116 |
117 | Logger.Error($"Could not find file: {path}");
118 | throw new FileNotFoundException();
119 | }
120 |
121 | public Stream OpenNullableStream(string file)
122 | {
123 | if (IsPackaged)
124 | {
125 | using var zip = ZipFile.OpenRead(Path);
126 | var entry = zip.GetEntry(file);
127 |
128 | if (entry != null)
129 | {
130 | return entry.Open().ToMemoryStream();
131 | }
132 |
133 | return null;
134 | }
135 |
136 | var path = $"{Path}\\{file}";
137 | if (File.Exists(path))
138 | return File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
139 |
140 | return null;
141 | }
142 |
143 | public MemoryStream OpenMemoryStream(string file)
144 | {
145 | if (IsPackaged)
146 | {
147 | using var zip = ZipFile.OpenRead(Path);
148 | var entry = zip.GetEntry(file);
149 |
150 | if (entry != null)
151 | {
152 | return entry.Open().ToMemoryStream();
153 | }
154 |
155 | Logger.Error($"Could not find file in package: {file}");
156 | throw new FileNotFoundException();
157 | }
158 |
159 | var path = $"{Path}\\{file}";
160 | if (File.Exists(path))
161 | return File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite).ToMemoryStream();
162 |
163 | Logger.Error($"Could not find file: {path}");
164 | throw new FileNotFoundException();
165 | }
166 | private void GetSheets()
167 | {
168 | // Adds to the Sheets dictionary
169 | foreach (var difficulty in Info.Difficulties.Keys.Where(difficulty => HasFile($"map{difficulty}.bms")))
170 | Sheets.Add(difficulty, new Sheet(this, difficulty));
171 | }
172 |
173 | public bool HasDifficulty(int difficulty) => Sheets.ContainsKey(difficulty);
174 | }
175 | }
--------------------------------------------------------------------------------
/Data/AlbumInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Serialization;
2 | using CustomAlbums.Utilities;
3 | using static CustomAlbums.Data.SceneEgg;
4 |
5 | namespace CustomAlbums.Data
6 | {
7 | public class AlbumInfo
8 | {
9 | public enum HiddenMode
10 | {
11 | Click,
12 | Press,
13 | Toggle
14 | }
15 |
16 | public string Name { get; set; } = string.Empty;
17 | [JsonPropertyName("name_romanized")]
18 | public string NameRomanized { get; set; } = string.Empty;
19 | public string Author { get; set; } = string.Empty;
20 | public string LevelDesigner { get; set; } = string.Empty;
21 | public string LevelDesigner1 { get; set; } = string.Empty;
22 | public string LevelDesigner2 { get; set; } = string.Empty;
23 | public string LevelDesigner3 { get; set; } = string.Empty;
24 | public string LevelDesigner4 { get; set; } = string.Empty;
25 | public string LevelDesigner5 { get; set; } = string.Empty;
26 | public string Bpm { get; set; } = "0";
27 | public string Scene { get; set; } = "scene_01";
28 | public SceneEggs SceneEgg { get; set; } = SceneEggs.None;
29 |
30 | public Dictionary Difficulties
31 | {
32 | get
33 | {
34 | var dict = new Dictionary();
35 | if (Difficulty1 != "0") dict.Add(1, Difficulty1);
36 | if (Difficulty2 != "0") dict.Add(2, Difficulty2);
37 | if (Difficulty3 != "0") dict.Add(3, Difficulty3);
38 | if (Difficulty4 != "0") dict.Add(4, Difficulty4);
39 | if (Difficulty5 != "0") dict.Add(5, Difficulty5);
40 | return dict;
41 | }
42 | }
43 |
44 | public string Difficulty1 { get; set; } = "0";
45 | public string Difficulty2 { get; set; } = "0";
46 | public string Difficulty3 { get; set; } = "0";
47 | public string Difficulty4 { get; set; } = "0";
48 | public string Difficulty5 { get; set; } = "0";
49 |
50 | public string HideBmsMode { get; set; } = "CLICK";
51 |
52 | [JsonConverter(typeof(Converters.NumberConverter))]
53 | public string HideBmsDifficulty { get; set; } = "0";
54 |
55 | public string HideBmsMessage { get; set; } = string.Empty;
56 |
57 | public string[] SearchTags { get; set; } = Array.Empty();
58 | }
59 | }
--------------------------------------------------------------------------------
/Data/AnimatedCover.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace CustomAlbums.Data
4 | {
5 | public class AnimatedCover
6 | {
7 | public AnimatedCover(Sprite[] frames, int framesPerSecond)
8 | {
9 | Frames = frames;
10 | FramesPerSecond = framesPerSecond;
11 | }
12 |
13 | public Sprite[] Frames { get; }
14 | public int FrameCount => Frames.Length;
15 | public int Width => Frames[0].texture.width;
16 | public int Height => Frames[0].texture.height;
17 | public int FramesPerSecond { get; }
18 | }
19 | }
--------------------------------------------------------------------------------
/Data/AssetIdentifiers.cs:
--------------------------------------------------------------------------------
1 | namespace CustomAlbums.Data
2 | {
3 | internal class AssetIdentifiers
4 | {
5 | internal static readonly List AssetSuffixes = new()
6 | {
7 | "_demo",
8 | "_music",
9 | "_cover",
10 | "_map1",
11 | "_map2",
12 | "_map3",
13 | "_map4",
14 | "_map5"
15 | };
16 | }
17 | }
--------------------------------------------------------------------------------
/Data/Bms.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Nodes;
2 | using CustomAlbums.Utilities;
3 | using Il2CppAssets.Scripts.GameCore.Managers;
4 | using Il2CppAssets.Scripts.PeroTools.Commons;
5 | using Il2CppGameLogic;
6 | using Il2CppPeroPeroGames.GlobalDefines;
7 |
8 | namespace CustomAlbums.Data
9 | {
10 | public class Bms
11 | {
12 | public enum BmsId
13 | {
14 | None,
15 | Small,
16 | SmallUp,
17 | SmallDown,
18 | Medium1,
19 | Medium1Up,
20 | Medium1Down,
21 | Medium2,
22 | Medium2Up,
23 | Medium2Down,
24 | Large1,
25 | Large2,
26 | Raider,
27 | Hammer,
28 | Gemini,
29 | Hold,
30 | Masher,
31 | Gear,
32 | UpsideDownRaider,
33 | UpsideDownHammer,
34 | Speed1Both,
35 | Speed2Both,
36 | Speed3Both,
37 | Speed1Low,
38 | Speed2Low,
39 | Speed3Low,
40 | Speed1High,
41 | Speed2High,
42 | Speed3High,
43 | Music,
44 | BossMelee1,
45 | BossMelee2,
46 | BossProjectile1,
47 | BossProjectile2,
48 | BossProjectile3,
49 | BossMasher1,
50 | BossMasher2,
51 | BossGear,
52 | BossEntrance,
53 | BossExit,
54 | BossReadyPhase1,
55 | BossEndPhase1,
56 | BossReadyPhase2,
57 | BossEndPhase2,
58 | BossSwapPhase12,
59 | BossSwapPhase21,
60 | HideNotes,
61 | UnhideNotes,
62 | HideBoss,
63 | UnhideBoss,
64 | SceneSwitchSpaceStation,
65 | SceneSwitchRetroCity,
66 | SceneSwitchCastle,
67 | SceneSwitchRainyNight,
68 | SceneSwitchOriental,
69 | SceneSwitchGrooveCoaster,
70 | SceneSwitchTouhou,
71 | SceneSwitchDjmax,
72 | SceneSwitchMiku,
73 | PItem,
74 | Ghost,
75 | Heart,
76 | Note,
77 | HideBackground,
78 | UnhideBackground,
79 | ScreenScrollUp,
80 | ScreenScrollDown,
81 | ScreenScrollOff,
82 | ScanlineRipplesOn,
83 | ScanlineRipplesOff,
84 | ChromaticAberrationOn,
85 | ChromaticAberrationOff,
86 | VignetteOn,
87 | VignetteOff,
88 | TvStaticOn,
89 | TvStaticOff,
90 | FlashbangStart,
91 | FlashbangMid,
92 | FlashbangEnd,
93 | BgStopOn,
94 | BgStopOff,
95 | MosaicOn,
96 | MosaicOff,
97 | SepiaOn,
98 | SepiaOff,
99 | MediumBullet,
100 | MediumBulletUp,
101 | MediumBulletDown,
102 | MediumBulletLaneShift,
103 | SmallBullet,
104 | SmallBulletUp,
105 | SmallBulletDown,
106 | SmallBulletLaneShift,
107 | LargeBullet,
108 | LargeBulletUp,
109 | LargeBulletDown,
110 | LargeBulletLaneShift,
111 | BossBullet1,
112 | BossBullet1LaneShift,
113 | BossBullet2,
114 | BossBullet2LaneShift
115 | }
116 |
117 | [Flags]
118 | public enum ChannelType
119 | {
120 | ///
121 | /// Channel does not support anything.
122 | ///
123 | None = 0,
124 |
125 | ///
126 | /// Channel supports the Ground Lane.
127 | ///
128 | Ground = 1,
129 |
130 | ///
131 | /// Channel supports the Air Lane.
132 | ///
133 | Air = 2,
134 |
135 | ///
136 | /// Channel supports standard events.
137 | ///
138 | Event = 4,
139 |
140 | ///
141 | /// Channel supports scene events.
142 | ///
143 | Scene = 8,
144 |
145 | ///
146 | /// Notes in this channel become Heart Enemies if possible.
147 | ///
148 | SpBlood = 16,
149 |
150 | ///
151 | /// Notes in this channel become Tap Holds if possible.
152 | ///
153 | SpTapHolds = 32,
154 |
155 | ///
156 | /// This channel is used for BPM changes, with the value directly present.
157 | ///
158 | SpBpmDirect = 64,
159 |
160 | ///
161 | /// This channel is used for BPM changes, with the value placed in a lookup table.
162 | ///
163 | SpBpmLookup = 128,
164 |
165 | ///
166 | /// This channel is used for time signature changes.
167 | ///
168 | SpTimesig = 256,
169 |
170 | ///
171 | /// This channel is used for scroll speed changes.
172 | ///
173 | SpScroll = 512
174 | }
175 |
176 | public static readonly Dictionary Channels = new()
177 | {
178 | ["01"] = ChannelType.Scene,
179 | ["02"] = ChannelType.SpTimesig,
180 | ["03"] = ChannelType.SpBpmDirect,
181 | ["08"] = ChannelType.SpBpmLookup,
182 | ["15"] = ChannelType.Event,
183 | ["16"] = ChannelType.Event,
184 | ["18"] = ChannelType.Event,
185 | ["11"] = ChannelType.Air | ChannelType.Event,
186 | ["13"] = ChannelType.Air | ChannelType.Event,
187 | ["31"] = ChannelType.Air | ChannelType.Event | ChannelType.SpBlood,
188 | ["33"] = ChannelType.Air | ChannelType.Event | ChannelType.SpBlood,
189 | ["51"] = ChannelType.Air | ChannelType.Event,
190 | ["53"] = ChannelType.Air | ChannelType.Event,
191 | ["D1"] = ChannelType.Air | ChannelType.Event | ChannelType.SpTapHolds,
192 | ["D3"] = ChannelType.Air | ChannelType.Event | ChannelType.SpTapHolds,
193 | ["12"] = ChannelType.Ground | ChannelType.Event,
194 | ["14"] = ChannelType.Ground | ChannelType.Event,
195 | ["32"] = ChannelType.Ground | ChannelType.Event | ChannelType.SpBlood,
196 | ["34"] = ChannelType.Ground | ChannelType.Event | ChannelType.SpBlood,
197 | ["52"] = ChannelType.Ground | ChannelType.Event,
198 | ["54"] = ChannelType.Ground | ChannelType.Event,
199 | ["D2"] = ChannelType.Ground | ChannelType.Event | ChannelType.SpTapHolds,
200 | ["D4"] = ChannelType.Ground | ChannelType.Event | ChannelType.SpTapHolds,
201 | ["SC"] = ChannelType.SpScroll
202 | };
203 |
204 | public static readonly Dictionary BmsIds = new()
205 | {
206 | ["00"] = BmsId.None,
207 | ["01"] = BmsId.Small,
208 | ["02"] = BmsId.SmallUp,
209 | ["03"] = BmsId.SmallDown,
210 | ["04"] = BmsId.Medium1,
211 | ["05"] = BmsId.Medium1Up,
212 | ["06"] = BmsId.Medium1Down,
213 | ["07"] = BmsId.Medium2,
214 | ["08"] = BmsId.Medium2Up,
215 | ["09"] = BmsId.Medium2Down,
216 | ["0A"] = BmsId.Large1,
217 | ["0B"] = BmsId.Large2,
218 | ["0C"] = BmsId.Raider,
219 | ["0D"] = BmsId.Hammer,
220 | ["0E"] = BmsId.Gemini,
221 | ["0F"] = BmsId.Hold,
222 | ["0G"] = BmsId.Masher,
223 | ["0H"] = BmsId.Gear,
224 | ["0I"] = BmsId.UpsideDownRaider,
225 | ["0J"] = BmsId.UpsideDownHammer,
226 | ["0O"] = BmsId.Speed1Both,
227 | ["0P"] = BmsId.Speed2Both,
228 | ["0Q"] = BmsId.Speed3Both,
229 | ["0R"] = BmsId.Speed1Low,
230 | ["0S"] = BmsId.Speed2Low,
231 | ["0T"] = BmsId.Speed3Low,
232 | ["0U"] = BmsId.Speed1High,
233 | ["0V"] = BmsId.Speed2High,
234 | ["0W"] = BmsId.Speed3High,
235 | ["10"] = BmsId.Music,
236 | ["11"] = BmsId.BossMelee1,
237 | ["12"] = BmsId.BossMelee2,
238 | ["13"] = BmsId.BossProjectile1,
239 | ["14"] = BmsId.BossProjectile2,
240 | ["15"] = BmsId.BossProjectile3,
241 | ["16"] = BmsId.BossMasher1,
242 | ["17"] = BmsId.BossMasher2,
243 | ["18"] = BmsId.BossGear,
244 | ["1A"] = BmsId.BossEntrance,
245 | ["1B"] = BmsId.BossExit,
246 | ["1C"] = BmsId.BossReadyPhase1,
247 | ["1D"] = BmsId.BossEndPhase1,
248 | ["1E"] = BmsId.BossReadyPhase2,
249 | ["1F"] = BmsId.BossEndPhase2,
250 | ["1G"] = BmsId.BossSwapPhase12,
251 | ["1H"] = BmsId.BossSwapPhase21,
252 | ["1J"] = BmsId.HideNotes,
253 | ["1K"] = BmsId.UnhideNotes,
254 | ["1L"] = BmsId.HideBoss,
255 | ["1M"] = BmsId.UnhideBoss,
256 | ["1O"] = BmsId.SceneSwitchSpaceStation,
257 | ["1P"] = BmsId.SceneSwitchRetroCity,
258 | ["1Q"] = BmsId.SceneSwitchCastle,
259 | ["1R"] = BmsId.SceneSwitchRainyNight,
260 | ["1S"] = BmsId.SceneSwitchOriental,
261 | ["1T"] = BmsId.SceneSwitchGrooveCoaster,
262 | ["1U"] = BmsId.SceneSwitchTouhou,
263 | ["1V"] = BmsId.SceneSwitchDjmax,
264 | ["1X"] = BmsId.SceneSwitchMiku,
265 | ["20"] = BmsId.PItem,
266 | ["21"] = BmsId.Ghost,
267 | ["22"] = BmsId.Heart,
268 | ["23"] = BmsId.Note,
269 | ["25"] = BmsId.HideBackground,
270 | ["26"] = BmsId.UnhideBackground,
271 | ["27"] = BmsId.ScreenScrollUp,
272 | ["28"] = BmsId.ScreenScrollDown,
273 | ["29"] = BmsId.ScreenScrollOff,
274 | ["2A"] = BmsId.ScanlineRipplesOn,
275 | ["2B"] = BmsId.ScanlineRipplesOff,
276 | ["2C"] = BmsId.ChromaticAberrationOn,
277 | ["2D"] = BmsId.ChromaticAberrationOff,
278 | ["2E"] = BmsId.VignetteOn,
279 | ["2F"] = BmsId.VignetteOff,
280 | ["2G"] = BmsId.TvStaticOn,
281 | ["2H"] = BmsId.TvStaticOff,
282 | ["2I"] = BmsId.FlashbangStart,
283 | ["2J"] = BmsId.FlashbangMid,
284 | ["2K"] = BmsId.FlashbangEnd,
285 | ["2N"] = BmsId.BgStopOn,
286 | ["2O"] = BmsId.BgStopOff,
287 | ["2P"] = BmsId.MosaicOn,
288 | ["2Q"] = BmsId.MosaicOff,
289 | ["2R"] = BmsId.SepiaOn,
290 | ["2S"] = BmsId.SepiaOff,
291 | ["30"] = BmsId.MediumBullet,
292 | ["31"] = BmsId.MediumBulletUp,
293 | ["32"] = BmsId.MediumBulletDown,
294 | ["33"] = BmsId.MediumBulletLaneShift,
295 | ["34"] = BmsId.SmallBullet,
296 | ["35"] = BmsId.SmallBulletUp,
297 | ["36"] = BmsId.SmallBulletDown,
298 | ["37"] = BmsId.SmallBulletLaneShift,
299 | ["38"] = BmsId.LargeBullet,
300 | ["39"] = BmsId.LargeBulletUp,
301 | ["3A"] = BmsId.LargeBulletDown,
302 | ["3B"] = BmsId.LargeBulletLaneShift,
303 | ["3C"] = BmsId.BossBullet1,
304 | ["3D"] = BmsId.BossBullet1LaneShift,
305 | ["3E"] = BmsId.BossBullet2,
306 | ["3F"] = BmsId.BossBullet2LaneShift
307 | };
308 |
309 | public JsonObject Info { get; set; }
310 | public JsonArray Notes { get; set; }
311 | public JsonArray NotesPercent { get; set; }
312 | public string Md5 { get; set; }
313 | public Dictionary NoteData { get; set; }
314 |
315 | public float Bpm
316 | {
317 | get
318 | {
319 | var bpmString = Info["BPM"]?.GetValue() ?? Info["BPM01"]?.GetValue() ?? string.Empty;
320 | return bpmString.TryParseAsFloat(out var bpm) ? bpm : 0f;
321 | }
322 | }
323 |
324 | public static string GetNoteDataKey(string bmsId, int pathway, int speed, string scene)
325 | {
326 | return $"{bmsId}-{pathway}-{speed}-{scene}";
327 | }
328 |
329 | public void InitNoteData()
330 | {
331 | NoteData = new Dictionary();
332 |
333 | // NOTE: PPG has officially gone mad. The new scene 12 does not appear in the scene list, so we can't really use the scene list anymore.
334 | Span sceneSpan = stackalloc int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
335 |
336 | foreach (var config in NoteDataMananger.instance.noteDatas)
337 | {
338 | // Ignore april fools variants (these are handled elsewhere)
339 | if (config.IsAprilFools()) continue;
340 | // Ignore phase 2 boss gears
341 | if (config.IsPhase2BossGear()) continue;
342 |
343 | // Scene setting of "0" is a wildcard
344 | var anyScene = config.IsAnyScene();
345 | // Notes with these values are extremely likely to be events, and get registered to all pathways
346 | var anyPathway = config.IsAnyPathway();
347 | // Boss type, None type, boss mashers, and events get registered to all speeds
348 | var anySpeed = config.IsAnySpeed();
349 |
350 | var speeds = new List { config.speed };
351 | var scenes = new List { config.scene };
352 | var pathways = new List { config.pathway };
353 |
354 | // Use all speeds if any speed
355 | if (anySpeed) speeds = new List { 1, 2, 3 };
356 | // Use all scenes if any scene
357 | if (anyScene)
358 | {
359 | scenes = new List();
360 |
361 | foreach (var scene in sceneSpan)
362 | {
363 | // Special handling for collectibles in touhou scene
364 | if (config.GetNoteType() is NoteType.Hp or NoteType.Music && scene == 8)
365 | continue;
366 |
367 | var sceneSuffix = scene.ToString().PadLeft(2, '0');
368 | scenes.Add($"scene_{sceneSuffix}");
369 | }
370 | }
371 |
372 | // Use all pathways if any pathway
373 | if (anyPathway) pathways = new List { 0, 1 };
374 |
375 | foreach (var key in pathways.SelectMany(pathway => speeds.SelectMany(speed =>
376 | scenes.Select(scene => GetNoteDataKey(config.ibms_id, pathway, speed, scene)))))
377 | NoteData.TryAdd(key, config);
378 | }
379 | }
380 |
381 | public Il2CppSystem.Collections.Generic.List GetSceneEvents()
382 | {
383 | var sceneEvents = new Il2CppSystem.Collections.Generic.List();
384 |
385 | foreach (var note in Notes)
386 | {
387 | var bmsKey = note["value"]?.GetValue() ?? string.Empty;
388 | if (string.IsNullOrEmpty(bmsKey)) continue;
389 |
390 | var channelTone = note["tone"]?.GetValue() ?? string.Empty;
391 | if (!Channels.TryGetValue(channelTone, out var channel)) continue;
392 |
393 | if (channel.HasFlag(ChannelType.Scene))
394 | sceneEvents.Add(new SceneEvent
395 | {
396 | time = note["time"].GetValueAsIl2CppDecimal(),
397 | uid = $"SceneEvent/{bmsKey}"
398 | });
399 | else if (channel.HasFlag(ChannelType.SpBpmDirect) || channel.HasFlag(ChannelType.SpBpmLookup))
400 | sceneEvents.Add(new SceneEvent
401 | {
402 | time = note["time"].GetValueAsIl2CppDecimal(),
403 | uid = "SceneEvent/OnBPMChanged",
404 | value = note["value"]?.GetValue() ?? string.Empty
405 | });
406 | }
407 |
408 | return sceneEvents;
409 | }
410 |
411 | public JsonArray GetNoteData()
412 | {
413 | if (NoteData is null || NoteData.Count == 0) InitNoteData();
414 | var processed = new JsonArray();
415 |
416 | var speedAir = (Info["PLAYER"]?.GetValue() ?? "1").ParseAsInt();
417 | var speedGround = speedAir;
418 |
419 | var objectId = 1;
420 |
421 | for (var i = 0; i < Notes.Count; i++)
422 | {
423 | var note = Notes[i];
424 | if (note is null) continue;
425 |
426 | var bmsKey = note["value"]?.GetValue() ?? "00";
427 | var bmsId = BmsIds.GetValueOrDefault(bmsKey, BmsId.None);
428 | var channel = note["tone"]?.GetValue() ?? string.Empty;
429 | var channelType = Channels.GetValueOrDefault(channel, ChannelType.None);
430 |
431 | // Handle lane type
432 | var pathway = -1;
433 | if (channelType.HasFlag(ChannelType.Air))
434 | pathway = 1;
435 | else if (channelType.HasFlag(ChannelType.Ground) || channelType.HasFlag(ChannelType.Event))
436 | pathway = 0;
437 |
438 | if (pathway == -1) continue;
439 |
440 | // ReSharper disable once SwitchStatementHandlesSomeKnownEnumValuesWithDefault
441 | // ReSharper disable once SwitchStatementMissingSomeEnumCasesNoDefault
442 | switch (bmsId)
443 | {
444 | // Handle speed changes
445 | case BmsId.Speed1Both:
446 | speedGround = 1;
447 | speedAir = 1;
448 | break;
449 | case BmsId.Speed2Both:
450 | speedGround = 2;
451 | speedAir = 2;
452 | break;
453 | case BmsId.Speed3Both:
454 | speedGround = 3;
455 | speedAir = 3;
456 | break;
457 | case BmsId.Speed1Low:
458 | speedGround = 1;
459 | break;
460 | case BmsId.Speed1High:
461 | speedAir = 1;
462 | break;
463 | case BmsId.Speed2Low:
464 | speedGround = 2;
465 | break;
466 | case BmsId.Speed2High:
467 | speedAir = 2;
468 | break;
469 | case BmsId.Speed3Low:
470 | speedGround = 3;
471 | break;
472 | case BmsId.Speed3High:
473 | speedAir = 3;
474 | break;
475 | }
476 |
477 | var speed = pathway == 1 ? speedAir : speedGround;
478 | var scene = Info["GENRE"]?.GetValue();
479 |
480 | if (!NoteData!.TryGetValue(GetNoteDataKey(bmsKey, pathway, speed, scene), out var configData))
481 | continue;
482 |
483 | var time = note["time"]?.GetValueAsDecimal() ?? 0M;
484 |
485 | // Hold note & masher
486 | var holdLength = 0M;
487 | var isHold = configData.GetNoteType() is NoteType.Press or NoteType.Mul;
488 | if (isHold)
489 | {
490 | if (channelType.HasFlag(ChannelType.SpTapHolds))
491 | holdLength = 0.001M;
492 | else
493 | for (var j = i + 1; j < Notes.Count; j++)
494 | {
495 | var holdEndNote = Notes[j];
496 | var holdEndTime = holdEndNote?["time"]?.GetValueAsDecimal() ?? 0M;
497 | var holdEndBmsKey = holdEndNote?["value"]?.GetValue() ?? string.Empty;
498 | var holdEndChannel = holdEndNote?["tone"]?.GetValue() ?? string.Empty;
499 |
500 | if (holdEndBmsKey != bmsKey || holdEndChannel != channel) continue;
501 | holdLength = holdEndTime - time;
502 | Notes[j]!["value"] = "";
503 | break;
504 | }
505 | }
506 |
507 | processed.Add(new JsonObject
508 | {
509 | ["id"] = objectId++,
510 | ["time"] = time,
511 | ["note_uid"] = configData.uid,
512 | ["length"] = holdLength,
513 | ["pathway"] = pathway,
514 | ["blood"] = !isHold && channelType.HasFlag(ChannelType.SpBlood)
515 | });
516 | }
517 |
518 | return processed;
519 | }
520 | }
521 | }
--------------------------------------------------------------------------------
/Data/BmsStates.cs:
--------------------------------------------------------------------------------
1 | namespace CustomAlbums.Data
2 | {
3 | internal class BmsStates
4 | {
5 | public enum AnimAlignment
6 | {
7 | Left = -1,
8 | Right = 1
9 | }
10 |
11 | public enum BossState
12 | {
13 | OffScreen,
14 | Idle,
15 | Phase1,
16 | Phase2
17 | }
18 |
19 | public static readonly Dictionary AnimStatesLeft = new()
20 | {
21 | { "in", BossState.OffScreen },
22 | { "out", BossState.Idle },
23 | { "boss_close_atk_1", BossState.Idle },
24 | { "boss_close_atk_2", BossState.Idle },
25 | { "multi_atk_48", BossState.Idle },
26 | { "multi_atk_48_end", BossState.Idle },
27 | { "boss_far_atk_1_L", BossState.Phase1 },
28 | { "boss_far_atk_1_R", BossState.Phase1 },
29 | { "boss_far_atk_2", BossState.Phase2 },
30 | { "boss_far_atk_1_start", BossState.Idle },
31 | { "boss_far_atk_2_start", BossState.Idle },
32 | { "boss_far_atk_1_end", BossState.Phase1 },
33 | { "boss_far_atk_2_end", BossState.Phase2 },
34 | { "atk_1_to_2", BossState.Phase1 },
35 | { "atk_2_to_1", BossState.Phase2 }
36 | };
37 |
38 | public static readonly Dictionary AnimStatesRight = new()
39 | {
40 | { "in", BossState.Idle },
41 | { "out", BossState.OffScreen },
42 | { "boss_close_atk_1", BossState.Idle },
43 | { "boss_close_atk_2", BossState.Idle },
44 | { "multi_atk_48", BossState.Idle },
45 | { "multi_atk_48_end", BossState.OffScreen },
46 | { "boss_far_atk_1_L", BossState.Phase1 },
47 | { "boss_far_atk_1_R", BossState.Phase1 },
48 | { "boss_far_atk_2", BossState.Phase2 },
49 | { "boss_far_atk_1_start", BossState.Phase1 },
50 | { "boss_far_atk_2_start", BossState.Phase2 },
51 | { "boss_far_atk_1_end", BossState.Idle },
52 | { "boss_far_atk_2_end", BossState.Idle },
53 | { "atk_1_to_2", BossState.Phase2 },
54 | { "atk_2_to_1", BossState.Phase1 }
55 | };
56 |
57 | public static readonly Dictionary> StateTransferAnims = new()
58 | {
59 | {
60 | BossState.OffScreen, new Dictionary
61 | {
62 | { BossState.OffScreen, "0" },
63 | { BossState.Idle, "in" },
64 | { BossState.Phase1, "boss_far_atk_1_start" },
65 | { BossState.Phase2, "boss_far_atk_2_start" }
66 | }
67 | },
68 | {
69 | BossState.Idle, new Dictionary
70 | {
71 | { BossState.OffScreen, "out" },
72 | { BossState.Idle, "0" },
73 | { BossState.Phase1, "boss_far_atk_1_start" },
74 | { BossState.Phase2, "boss_far_atk_2_start" }
75 | }
76 | },
77 | {
78 | BossState.Phase1, new Dictionary
79 | {
80 | { BossState.OffScreen, "out" },
81 | { BossState.Idle, "boss_far_atk_1_end" },
82 | { BossState.Phase1, "0" },
83 | { BossState.Phase2, "atk_1_to_2" }
84 | }
85 | },
86 | {
87 | BossState.Phase2, new Dictionary
88 | {
89 | { BossState.OffScreen, "out" },
90 | { BossState.Idle, "boss_far_atk_2_end" },
91 | { BossState.Phase1, "atk_2_to_1" },
92 | { BossState.Phase2, "0" }
93 | }
94 | }
95 | };
96 |
97 | public static readonly Dictionary TransferAlignment = new()
98 | {
99 | { "in", AnimAlignment.Right },
100 | { "out", AnimAlignment.Left },
101 | { "boss_far_atk_1_start", AnimAlignment.Right },
102 | { "boss_far_atk_2_start", AnimAlignment.Right },
103 | { "boss_far_atk_1_end", AnimAlignment.Left },
104 | { "boss_far_atk_2_end", AnimAlignment.Left },
105 | { "atk_1_to_2", AnimAlignment.Right },
106 | { "atk_2_to_1", AnimAlignment.Right }
107 | };
108 | }
109 | }
--------------------------------------------------------------------------------
/Data/ChartSave.cs:
--------------------------------------------------------------------------------
1 | namespace CustomAlbums.Data
2 | {
3 | public class ChartSave
4 | {
5 | public int Evaluate { get; set; } = 0;
6 | public int Score { get; set; } = 0;
7 | public int Combo { get; set; } = 0;
8 | public float Accuracy { get; set; } = 0f;
9 | public string AccuracyStr { get; set; } = "0";
10 | public float Clear { get; set; } = 0f;
11 | public int FailCount { get; set; } = 0;
12 | public bool Passed { get; set; } = false;
13 | }
14 | }
--------------------------------------------------------------------------------
/Data/CustomAlbumsSave.cs:
--------------------------------------------------------------------------------
1 | namespace CustomAlbums.Data
2 | {
3 | public class CustomAlbumsSave
4 | {
5 | public string SelectedAlbum { get; set; } = string.Empty;
6 | public float Ability { get; set; } = 0;
7 | public HashSet UnlockedMasters { get; set; } = new();
8 | public HashSet Collections { get; set; } = new();
9 | public HashSet Hides { get; set; } = new();
10 | public List History { get; set; } = new();
11 | public Dictionary> Highest { get; set; } = new();
12 | public Dictionary> FullCombo { get; set; } = new();
13 |
14 | internal bool IsEmpty()
15 | {
16 | return SelectedAlbum == string.Empty
17 | && Ability == 0
18 | && UnlockedMasters.Count == 0
19 | && Collections.Count == 0
20 | && Hides.Count == 0
21 | && History.Count == 0
22 | && Highest.Count == 0
23 | && FullCombo.Count == 0;
24 | }
25 | }
26 | }
--------------------------------------------------------------------------------
/Data/Pack.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Managers;
2 |
3 | namespace CustomAlbums.Data
4 | {
5 | public class Pack
6 | {
7 | public string Title { get; set; } = AlbumManager.GetCustomAlbumsTitle();
8 | public string TitleColorHex { get; set; } = "#ffffff";
9 | public bool LongTextScroll { get; set; } = false;
10 |
11 | internal int StartIndex;
12 | internal int Length;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Data/SceneEggs.cs:
--------------------------------------------------------------------------------
1 | namespace CustomAlbums.Data
2 | {
3 | public class SceneEgg
4 | {
5 | public enum SceneEggs
6 | {
7 | None = -1,
8 | Cytus = 0,
9 | Wacca = 1,
10 | Queen = 2,
11 | Touhou = 3,
12 | Arknights = 4,
13 | Miku = 5,
14 | RinLen = 6,
15 | BlueArchive = 7,
16 | BadApple = 129,
17 | Christmas = 999
18 | }
19 | }
20 | }
--------------------------------------------------------------------------------
/Data/Sheet.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Nodes;
2 | using CustomAlbums.Utilities;
3 | using Il2CppAssets.Scripts.Database;
4 | using Il2CppAssets.Scripts.GameCore;
5 | using Il2CppAssets.Scripts.Structs;
6 |
7 | namespace CustomAlbums.Data
8 | {
9 | public class Sheet
10 | {
11 | private static readonly Logger Logger = new(nameof(Sheet));
12 |
13 | public Sheet(Album parentAlbum, int difficulty)
14 | {
15 | ParentAlbum = parentAlbum;
16 | Difficulty = difficulty;
17 | MapName = $"{parentAlbum.AlbumName}_map{difficulty}";
18 | }
19 |
20 | public Album ParentAlbum { get; }
21 | public string MapName { get; }
22 | public int Difficulty { get; }
23 | public bool TalkFileVersion2 { get; set; }
24 | public string Md5
25 | {
26 | get
27 | {
28 | using var stream = ParentAlbum.OpenMemoryStream($"map{Difficulty}.bms");
29 | return stream.GetHash();
30 | }
31 | }
32 |
33 | public StageInfo GetStage()
34 | {
35 | // If opening a FileStream is possible (i.e. reading from a folder) then open it as FileStream
36 | // Otherwise open it as a MemoryStream
37 | // This allows writing to the map BMS file while it is being read
38 | using var stream = ParentAlbum.OpenFileStreamIfPossible($"map{Difficulty}.bms");
39 |
40 | var bms = BmsLoader.Load(stream, MapName);
41 | if (bms is null) return null;
42 |
43 | var stageInfo = BmsLoader.TransmuteData(bms);
44 | stageInfo.mapName = MapName;
45 | stageInfo.scene = bms.Info["GENRE"]?.GetValue() ?? string.Empty;
46 | stageInfo.music = $"{ParentAlbum.Index}";
47 | stageInfo.difficulty = Difficulty;
48 | stageInfo.bpm = bms.Bpm;
49 | stageInfo.md5 = Md5;
50 | stageInfo.sceneEvents = bms.GetSceneEvents();
51 | stageInfo.name = ParentAlbum.Info.Name;
52 |
53 | if (ParentAlbum.HasFile($"map{Difficulty}.talk"))
54 | {
55 | using var talkStream = ParentAlbum.OpenFileStreamIfPossible($"map{Difficulty}.talk");
56 | if (talkStream.Length > 0)
57 | {
58 | var talkFile = Json.Deserialize(talkStream);
59 | if (talkFile.TryGetPropertyValue("version", out var node) && node?.GetValue() == 2)
60 | {
61 | Logger.Msg("Version 2 talk file!");
62 | TalkFileVersion2 = true;
63 | }
64 |
65 | talkFile.Remove("version");
66 | var dict = Json
67 | .Il2CppJsonDeserialize<
68 | Il2CppSystem.Collections.Generic.Dictionary>>(talkFile.ToJsonString());
70 | stageInfo.dialogEvents =
71 | new Il2CppSystem.Collections.Generic.Dictionary>();
73 | foreach (var dialogEvent in dict) stageInfo.dialogEvents.Add(dialogEvent.Key, dialogEvent.Value);
74 | }
75 | }
76 |
77 | GlobalDataBase.dbStageInfo.SetStageInfo(stageInfo);
78 | return stageInfo;
79 | }
80 | }
81 | }
--------------------------------------------------------------------------------
/Data/Talk.cs:
--------------------------------------------------------------------------------
1 | using Il2CppAssets.Scripts.Structs;
2 |
3 | namespace CustomAlbums.Data
4 | {
5 | public class Talk
6 | {
7 | public int Version { get; set; } = 1;
8 | public Il2CppSystem.Collections.Generic.List English { get; set; }
9 | public Il2CppSystem.Collections.Generic.List ChineseS { get; set; }
10 | public Il2CppSystem.Collections.Generic.List ChineseT { get; set; }
11 | public Il2CppSystem.Collections.Generic.List Japanese { get; set; }
12 | public Il2CppSystem.Collections.Generic.List Korean { get; set; }
13 |
14 | public Il2CppSystem.Collections.Generic.Dictionary>.Enumerator GetEnumerator()
16 | {
17 | var dict =
18 | new Il2CppSystem.Collections.Generic.Dictionary>(5);
20 | dict["English"] = English;
21 | dict["ChineseS"] = ChineseS;
22 | dict["ChineseT"] = ChineseT;
23 | dict["Japanese"] = Japanese;
24 | dict["Korean"] = Korean;
25 | return dict.GetEnumerator();
26 | }
27 | }
28 | }
--------------------------------------------------------------------------------
/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 | false
4 | False
5 | $(MD_NET6_DIRECTORY)
6 | $(MD_DIRECTORY)
7 | $(GameFolder)\MelonLoader\
8 | $(MelonLoader)\net6\
9 | $(MelonLoader)\Il2CppAssemblies\
10 |
11 |
12 |
13 | false
14 | false
15 | $(MelonNET6)\0Harmony.dll
16 |
17 |
18 | false
19 | false
20 | $(MelonAssemblies)\Assembly-CSharp.dll
21 |
22 |
24 | false
25 | false
26 | $(MelonAssemblies)\Assembly-CSharp-firstpass.dll
27 |
28 |
30 | false
31 | false
32 | $(MelonAssemblies)\Il2Cppcom.prpr.log.dll
33 |
34 |
35 | false
36 | false
37 | $(MelonAssemblies)\Il2CppDOTween.dll
38 |
39 |
41 | false
42 | false
43 | $(MelonAssemblies)\Il2CppGoogle.Protobuf.dll
44 |
45 |
47 | false
48 | false
49 | $(MelonNET6)\Il2CppInterop.Common.dll
50 |
51 |
53 | false
54 | false
55 | $(MelonNET6)\Il2CppInterop.Generator.dll
56 |
57 |
59 | false
60 | false
61 | $(MelonNET6)\Il2CppInterop.Runtime.dll
62 |
63 |
64 | false
65 | false
66 | $(MelonAssemblies)\Il2Cppmscorlib.dll
67 |
68 |
69 | false
70 | false
71 | $(MelonAssemblies)\Il2CppNAudio.dll
72 |
73 |
75 | false
76 | false
77 | $(MelonAssemblies)\Il2CppNewtonsoft.Json.dll
78 |
79 |
80 | false
81 | false
82 | $(MelonAssemblies)\Il2CppPeroString.dll
83 |
84 |
85 | false
86 | false
87 | $(MelonAssemblies)\Il2CppPeroTools2.dll
88 |
89 |
91 | false
92 | false
93 | $(MelonAssemblies)\Il2CppPeroTools2.Account.dll
94 |
95 |
97 | false
98 | false
99 | $(MelonAssemblies)\Il2CppPeroTools2.Resources.dll
100 |
101 |
103 | false
104 | false
105 | $(MelonAssemblies)\Il2CppSirenix.Serialization.dll
106 |
107 |
109 | false
110 | false
111 | $(MelonAssemblies)\Il2Cppspine-unity.dll
112 |
113 |
114 | false
115 | false
116 | $(MelonAssemblies)\Il2CppSystem.dll
117 |
118 |
120 | false
121 | false
122 | $(MelonAssemblies)\Il2CppSystem.Core.dll
123 |
124 |
126 | false
127 | false
128 | $(MelonAssemblies)\Il2CppSystem.Runtime.InteropServices.dll
129 |
130 |
131 | false
132 | false
133 | $(MelonNET6)\MelonLoader.dll
134 |
135 |
137 | false
138 | false
139 | $(MelonAssemblies)\Unity.Addressables.dll
140 |
141 |
143 | false
144 | false
145 | $(MelonAssemblies)\Unity.ResourceManager.dll
146 |
147 |
149 | false
150 | false
151 | $(MelonAssemblies)\UnityEngine.AnimationModule.dll
152 |
153 |
155 | false
156 | false
157 | $(MelonAssemblies)\UnityEngine.AudioModule.dll
158 |
159 |
161 | false
162 | false
163 | $(MelonAssemblies)\UnityEngine.CoreModule.dll
164 |
165 |
167 | false
168 | false
169 | $(MelonAssemblies)\UnityEngine.ImageConversionModule.dll
170 |
171 |
172 | false
173 | false
174 | $(MelonAssemblies)\UnityEngine.UI.dll
175 |
176 |
178 | false
179 | false
180 | $(MelonAssemblies)\UnityEngine.UnityWebRequestModule.dll
181 |
182 |
183 |
--------------------------------------------------------------------------------
/ILRepack.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | $(OutputPath)
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Muse Dash Modding Community
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Main.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Managers;
2 | using CustomAlbums.Patches;
3 | using CustomAlbums.Utilities;
4 | using MelonLoader;
5 | using static CustomAlbums.Patches.AnimatedCoverPatch;
6 |
7 | namespace CustomAlbums
8 | {
9 | public class Main : MelonMod
10 | {
11 | private static readonly Logger Logger = new("CustomAlbums");
12 |
13 | public const string MelonName = "CustomAlbums";
14 | public const string MelonAuthor = "Two Fellas";
15 | public const string MelonVersion = "4.1.9";
16 |
17 | public override void OnInitializeMelon()
18 | {
19 | base.OnInitializeMelon();
20 |
21 | if (!Directory.Exists(AlbumManager.SearchPath)) Directory.CreateDirectory(AlbumManager.SearchPath);
22 |
23 | ModSettings.Register();
24 | AssetPatch.AttachHook();
25 | SavePatch.AttachHook();
26 | AlbumManager.LoadAlbums();
27 | SaveManager.LoadSaveFile();
28 | Logger.Msg("Initialized CustomAlbums!", false);
29 | }
30 |
31 | public override void OnLateInitializeMelon()
32 | {
33 | base.OnLateInitializeMelon();
34 | // TODO: Actually write HotReload
35 | // HotReloadManager.OnLateInitializeMelon();
36 | }
37 |
38 | ///
39 | /// This override adds support for animated covers.
40 | ///
41 | public override void OnUpdate()
42 | {
43 | base.OnUpdate();
44 | MusicStageCellPatch.AnimateCoversUpdate();
45 | }
46 |
47 | ///
48 | /// This override adds support for hot reloading.
49 | ///
50 | public override void OnFixedUpdate()
51 | {
52 | base.OnFixedUpdate();
53 | // TODO: Actually write HotReload
54 | // HotReloadManager.FixedUpdate();
55 | }
56 |
57 | public override void OnSceneWasLoaded(int buildIndex, string sceneName)
58 | {
59 | base.OnSceneWasLoaded(buildIndex, sceneName);
60 | MusicStageCellPatch.CurrentScene = sceneName;
61 | }
62 | }
63 | }
--------------------------------------------------------------------------------
/Managers/AlbumManager.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Data;
2 | using CustomAlbums.ModExtensions;
3 | using CustomAlbums.Utilities;
4 | using Il2CppAssets.Scripts.PeroTools.Commons;
5 | using Il2CppAssets.Scripts.PeroTools.GeneralLocalization;
6 | using Il2CppPeroTools2.Resources;
7 | using UnityEngine;
8 | using Logger = CustomAlbums.Utilities.Logger;
9 |
10 | namespace CustomAlbums.Managers
11 | {
12 | public static class AlbumManager
13 | {
14 | public const int Uid = 999;
15 | public const string SearchPath = "Custom_Albums";
16 | public const string SearchPattern = "*.mdm";
17 | public static readonly string JsonName = $"ALBUM{Uid + 1}";
18 | public static readonly string MusicPackage = $"music_package_{Uid}";
19 |
20 | public static readonly Dictionary Languages = new()
21 | {
22 | { "English", "Custom Albums" },
23 | { "ChineseS", "自定义" },
24 | { "ChineseT", "自定義" },
25 | { "Japanese", "カスタムアルバム" },
26 | { "Korean", "커스텀앨범" }
27 | };
28 |
29 | private static readonly Logger Logger = new(nameof(AlbumManager));
30 | internal static readonly FileSystemWatcher AlbumWatcher = new();
31 | internal static Events.LoadAlbumEvent OnAlbumLoaded;
32 |
33 | private static int MaxCount { get; set; }
34 | internal static string CurrentPack { get; set; } = null;
35 | public static Dictionary LoadedAlbums { get; } = new();
36 |
37 |
38 | public static void LoadMany(string directory)
39 | {
40 | // Get the files from the directory
41 | var files = Directory.EnumerateFiles(directory);
42 |
43 | // Filter for .mdm files and find the pack.json file
44 | var mdms = files.Where(file => Path.GetExtension(file).EqualsCaseInsensitive(".mdm")).ToList();
45 | var json = files.FirstOrDefault(file => Path.GetFileName(file).EqualsCaseInsensitive("pack.json"));
46 |
47 | // Initialize pack and variables
48 | var pack = PackManager.CreatePack(json);
49 | CurrentPack = pack.Title;
50 | pack.StartIndex = MaxCount;
51 |
52 | // Count successfully loaded .mdm files
53 | pack.Length = mdms.Count(file => LoadOne(file) != null);
54 |
55 | // Set the current pack to null and add the pack to the pack list
56 | CurrentPack = null;
57 | PackManager.AddPack(pack);
58 | }
59 |
60 | public static Album LoadOne(string path)
61 | {
62 | MaxCount = Math.Max(LoadedAlbums.Count, MaxCount);
63 | var isDirectory = File.GetAttributes(path).HasFlag(FileAttributes.Directory);
64 | var fileName = isDirectory ? Path.GetFileName(path) : Path.GetFileNameWithoutExtension(path);
65 |
66 | if (LoadedAlbums.ContainsKey(fileName)) return null;
67 |
68 | try
69 | {
70 | if (isDirectory && Directory.EnumerateFiles(path)
71 | .Any(file => Path.GetFileName(file)
72 | .EqualsCaseInsensitive("pack.json")))
73 | {
74 | LoadMany(path);
75 | return null;
76 | }
77 |
78 | var album = new Album(path, MaxCount, CurrentPack);
79 | if (album.Info is null) return null;
80 |
81 | var albumName = album.AlbumName;
82 |
83 | LoadedAlbums.Add(albumName, album);
84 |
85 | if (album.HasFile("cover.png") || album.HasFile("cover.gif"))
86 | ResourcesManager.instance.LoadFromName($"{albumName}_cover").hideFlags |=
87 | HideFlags.DontUnloadUnusedAsset;
88 |
89 | Logger.Msg($"Loaded {albumName}: {album.Info.Name}");
90 | OnAlbumLoaded?.Invoke(typeof(AlbumManager), new AlbumEventArgs(album));
91 | return album;
92 | }
93 | catch (Exception ex)
94 | {
95 | Logger.Warning($"Failed to load album at {fileName}. Reason: {ex.Message}");
96 | Logger.Warning(ex.StackTrace);
97 | }
98 |
99 | return null;
100 | }
101 |
102 | public static void LoadAlbums()
103 | {
104 | LoadedAlbums.Clear();
105 |
106 | var files = new List();
107 | files.AddRange(Directory.GetFiles(SearchPath, SearchPattern));
108 | files.AddRange(Directory.GetDirectories(SearchPath));
109 |
110 | foreach (var file in files) LoadOne(file);
111 |
112 | Logger.Msg($"Finished loading {LoadedAlbums.Count} albums.", false);
113 | }
114 |
115 | public static IEnumerable GetAllUid()
116 | {
117 | return LoadedAlbums.Select(album => $"{Uid}-{album.Value.Index}");
118 | }
119 |
120 | public static Album GetByUid(string uid)
121 | {
122 | return LoadedAlbums.FirstOrDefault(album => album.Value.Index == uid[4..].ParseAsInt()).Value;
123 | }
124 | public static string GetAlbumNameFromUid(string uid)
125 | {
126 | var album = GetByUid(uid);
127 | return album is null ? string.Empty : album.AlbumName;
128 | }
129 | public static IEnumerable GetAlbumUidsFromNames(this IEnumerable albumNames)
130 | {
131 | return albumNames.Where(name => LoadedAlbums.ContainsKey(name))
132 | .Select(name => $"{Uid}-{LoadedAlbums[name].Index}");
133 | }
134 |
135 | ///
136 | /// Gets the current "Custom Albums" title based on language.
137 | ///
138 | /// The current "Custom Albums" title based on language.
139 | public static string GetCustomAlbumsTitle()
140 | {
141 | return Languages.GetValueOrDefault(
142 | SingletonScriptableObject
143 | .instance?
144 | .GetActiveOption("Language") ?? "English");
145 | }
146 | }
147 | }
--------------------------------------------------------------------------------
/Managers/AudioManager.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Data;
2 | using Il2CppAssets.Scripts.PeroTools.Commons;
3 | using Il2CppAssets.Scripts.PeroTools.Managers;
4 | using NAudio.Vorbis;
5 | using NLayer;
6 | using UnityEngine;
7 | using Action = Il2CppSystem.Action;
8 | using Logger = CustomAlbums.Utilities.Logger;
9 |
10 | // ReSharper disable AccessToModifiedClosure
11 |
12 | namespace CustomAlbums.Managers
13 | {
14 | public static class AudioManager
15 | {
16 | public const int AsyncReadSpeed = 4096;
17 |
18 | private static Coroutine _currentCoroutine;
19 | private static readonly Dictionary Coroutines = new();
20 | private static readonly Logger Logger = new(nameof(AudioManager));
21 |
22 | public static bool SwitchLoad(string name)
23 | {
24 | if (!Coroutines.TryGetValue(name, out var routine)) return false;
25 | _currentCoroutine = routine;
26 |
27 | Logger.Msg($"Switching to async load of {name}");
28 | return true;
29 | }
30 |
31 | public static AudioClip LoadClipFromMp3(MemoryStream stream, string name)
32 | {
33 | var mp3 = new MpegFile(stream);
34 | var sampleCount = mp3.Length / sizeof(float);
35 | var audioClip =
36 | AudioClip.Create(name, (int)sampleCount / mp3.Channels, mp3.Channels, mp3.SampleRate, false);
37 |
38 | var remainingSamples = sampleCount;
39 | var index = 0;
40 |
41 | if (name.EndsWith("_music") && mp3.SampleRate != 44100)
42 | Logger.Warning(
43 | $"{name}.mp3 is not 44.1khz, desyncs may occur! Consider switching to .ogg format or using 44.1khz");
44 |
45 | Coroutine coroutine = null;
46 | coroutine = CreateCoroutine((Il2CppSystem.Func)delegate
47 | {
48 | // Stop coroutine if the asset is unloaded
49 | if (audioClip == null)
50 | {
51 | Coroutines.Remove(name);
52 | if (_currentCoroutine == coroutine) _currentCoroutine = null;
53 |
54 | Logger.Msg($"Aborting async load of {name}.mp3");
55 | return true;
56 | }
57 |
58 | // Pause coroutine if it is not active
59 | if (coroutine != _currentCoroutine) return false;
60 |
61 | var sampleArray = new float[Math.Min(AsyncReadSpeed, remainingSamples)];
62 | var readCount = mp3.ReadSamples(sampleArray, 0, sampleArray.Length);
63 |
64 | audioClip.SetData(sampleArray, index / mp3.Channels);
65 |
66 | index += readCount;
67 | remainingSamples -= readCount;
68 |
69 | if (remainingSamples > 0 && readCount != 0) return false;
70 |
71 | mp3.Dispose();
72 | stream.Dispose();
73 |
74 | Coroutines.Remove(name);
75 | _currentCoroutine = null;
76 |
77 | Logger.Msg($"Finished async load of {name}.mp3");
78 | return true;
79 | });
80 |
81 | Coroutines[name] = coroutine;
82 | _currentCoroutine = coroutine;
83 |
84 | return audioClip;
85 | }
86 |
87 | public static AudioClip LoadClipFromOgg(MemoryStream stream, string name)
88 | {
89 | var ogg = new VorbisWaveReader(stream);
90 | var sampleCount = (int)(ogg.Length / (ogg.WaveFormat.BitsPerSample / 8));
91 | var audioClip = AudioClip.Create(name, sampleCount / ogg.WaveFormat.Channels, ogg.WaveFormat.Channels,
92 | ogg.WaveFormat.SampleRate, false);
93 |
94 | var remainingSamples = sampleCount;
95 | var index = 0;
96 |
97 | Coroutine coroutine = null;
98 | coroutine = CreateCoroutine((Il2CppSystem.Func)delegate
99 | {
100 | // Stop coroutine if the asset is unloaded
101 | if (audioClip == null)
102 | {
103 | Coroutines.Remove(name);
104 | if (_currentCoroutine == coroutine) _currentCoroutine = null;
105 |
106 | Logger.Msg($"Aborting async load of {name}.ogg");
107 | return true;
108 | }
109 |
110 | // Pause coroutine if it is not active
111 | if (coroutine != _currentCoroutine) return false;
112 |
113 | var sampleArray = new float[Math.Min(AsyncReadSpeed, remainingSamples)];
114 | var readCount = ogg.Read(sampleArray, 0, sampleArray.Length);
115 |
116 | try
117 | {
118 | audioClip.SetData(sampleArray, index / ogg.WaveFormat.Channels);
119 | }
120 | catch (Exception e)
121 | {
122 | if ((double)ogg.Position / 1000 > ogg.Length)
123 | Logger.Warning(
124 | "Possible over-read of audio file. This is a file-dependent anomaly. Consider making a minimal edit and re-saving.");
125 | Logger.Error(
126 | $"Exception while reading at offset {index} of {(double)ogg.Position / 1000 / ogg.Length} in {name}, aborting: {e.Message}");
127 |
128 | ogg.Dispose();
129 | stream.Dispose();
130 |
131 | Coroutines.Remove(name);
132 | _currentCoroutine = null;
133 | return true;
134 | }
135 |
136 | index += readCount;
137 | remainingSamples -= readCount;
138 |
139 | if (remainingSamples > 0 && readCount != 0) return false;
140 |
141 | ogg.Dispose();
142 | stream.Dispose();
143 |
144 | Coroutines.Remove(name);
145 | _currentCoroutine = null;
146 |
147 | Logger.Msg($"Finished async load of {name}.ogg");
148 | return true;
149 | });
150 |
151 | Coroutines[name] = coroutine;
152 | _currentCoroutine = coroutine;
153 |
154 | return audioClip;
155 | }
156 |
157 | private static Coroutine CreateCoroutine(Il2CppSystem.Func update)
158 | {
159 | return SingletonMonoBehaviour.instance.StartCoroutine(
160 | (Action)delegate { }, update);
161 | }
162 |
163 | ///
164 | /// Gets the audio clip for the specified album.
165 | ///
166 | /// The specified album.
167 | /// This is "music" or "demo". Defaults to "music".
168 | ///
169 | public static AudioClip GetAudio(this Album album, string name = "music")
170 | {
171 | var key = $"{album.AlbumName}_{name}";
172 | if (album.HasFile($"{name}.ogg"))
173 | {
174 | // Load music.ogg
175 | var stream = album.OpenMemoryStream($"{name}.ogg");
176 | return LoadClipFromOgg(stream, key);
177 | }
178 |
179 | if (album.HasFile($"{name}.mp3"))
180 | {
181 | // Load music.mp3
182 | var stream = album.OpenMemoryStream($"{name}.mp3");
183 | return LoadClipFromMp3(stream, key);
184 | }
185 |
186 | // No music file found
187 | Logger.Error($"Could not find audio file for {name} in {album.Info.Name}");
188 | return null;
189 | }
190 | }
191 | }
--------------------------------------------------------------------------------
/Managers/CoverManager.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.CompilerServices;
2 | using CustomAlbums.Data;
3 | using CustomAlbums.Utilities;
4 | using SixLabors.ImageSharp;
5 | using SixLabors.ImageSharp.Formats;
6 | using SixLabors.ImageSharp.PixelFormats;
7 | using SixLabors.ImageSharp.Processing;
8 | using UnityEngine;
9 | using Logger = CustomAlbums.Utilities.Logger;
10 |
11 | namespace CustomAlbums.Managers
12 | {
13 | public static class CoverManager
14 | {
15 | internal static readonly Dictionary CachedCovers = new();
16 | internal static readonly Dictionary CachedAnimatedCovers = new();
17 | private static readonly Logger Logger = new(nameof(CoverManager));
18 |
19 | private static readonly Configuration Config = Configuration.Default;
20 |
21 | public static Sprite GetCover(this Album album)
22 | {
23 | if (!album.HasFile("cover.png")) return null;
24 | if (CachedCovers.TryGetValue(album.Index, out var cached)) return cached;
25 |
26 | using var stream = album.OpenMemoryStream("cover.png");
27 |
28 | var bytes = stream.ReadFully();
29 |
30 | // Create the textures
31 | var texture = new Texture2D(2, 2, TextureFormat.ARGB32, false)
32 | {
33 | wrapMode = TextureWrapMode.MirrorOnce
34 | };
35 | texture.LoadImage(bytes);
36 |
37 | var cover = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
38 | CachedCovers.Add(album.Index, cover);
39 |
40 | return cover;
41 | }
42 |
43 | public static unsafe AnimatedCover GetAnimatedCover(this Album album)
44 | {
45 | // Early return statements
46 | if (!album.HasFile("cover.gif")) return null;
47 | if (CachedAnimatedCovers.TryGetValue(album.Index, out var cached)) return cached;
48 |
49 | Config.PreferContiguousImageBuffers = true;
50 |
51 | // Open and load the gif
52 | using var stream = album.OpenMemoryStream("cover.gif");
53 | using var gif = Image.Load(new DecoderOptions { Configuration = Config }, stream);
54 |
55 | // For some reason Unity loads textures upside down?
56 | // Flip the frames
57 | gif.Mutate(c => c.Flip(FlipMode.Vertical));
58 |
59 | var sprites = new Sprite[gif.Frames.Count];
60 |
61 | for (var i = 0; i < gif.Frames.Count; i++)
62 | {
63 | // Get frame data
64 | var frame = gif.Frames[i];
65 | var width = frame.Width;
66 | var height = frame.Height;
67 |
68 | // Get frame pixel data
69 | //
70 | // This should really be done with CopyPixelData and a byte array
71 | // but that causes a 6MB+ copy of an array that slows things down by a bit
72 | // The more efficient way is to retrieve an IntPtr that stores the data and pass that with a size instead
73 | var getPixelDataResult = frame.DangerousTryGetSinglePixelMemory(out var memory);
74 | if (!getPixelDataResult)
75 | {
76 | Logger.Error("Failed to get pixel data.");
77 | return null;
78 | }
79 |
80 | using var handle = memory.Pin();
81 |
82 | // Create the textures
83 | var texture = new Texture2D(width, height, TextureFormat.RGBA32, false)
84 | {
85 | wrapMode = TextureWrapMode.MirrorOnce
86 | };
87 | texture.LoadRawTextureData((IntPtr)handle.Pointer, memory.Length * Unsafe.SizeOf());
88 | texture.Apply(false);
89 |
90 | // Create the sprite with the given texture and add it to the sprites array
91 | var sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height),
92 | new Vector2(0.5f, 0.5f));
93 | sprite.hideFlags |= HideFlags.DontUnloadUnusedAsset;
94 | sprites[i] = sprite;
95 | }
96 |
97 | // Create and add cover to cache
98 | var cover = new AnimatedCover(sprites, gif.Frames.RootFrame.Metadata.GetGifMetadata().FrameDelay * 10);
99 | CachedAnimatedCovers.Add(album.Index, cover);
100 |
101 | return cover;
102 | }
103 | }
104 | }
--------------------------------------------------------------------------------
/Managers/HotReloadManager.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Patches;
2 | using CustomAlbums.Utilities;
3 | using HarmonyLib;
4 | using Il2CppAssets.Scripts.Database;
5 | using Il2CppAssets.Scripts.UI.Panels;
6 |
7 | namespace CustomAlbums.Managers
8 | {
9 | // TODO: Fix all of this with album.AlbumName
10 | internal static class HotReloadManager
11 | {
12 | private static readonly Logger Logger = new(nameof(HotReloadManager));
13 | private static Queue AlbumsAdded { get; } = new();
14 | private static Queue AlbumsDeleted { get; } = new();
15 | private static List AlbumUidsAdded { get; } = new();
16 | private static PnlStage PnlStageInstance { get; set; }
17 |
18 | private static bool IsFileUnlocked(string path)
19 | {
20 | try
21 | {
22 | using var fileStream = File.Open(path, FileMode.Open);
23 | if (fileStream.Length <= 0) return false;
24 |
25 | Logger.Msg("The added album is ready to be read!");
26 | return true;
27 | }
28 | catch (Exception ex) when (ex is FileNotFoundException or IOException)
29 | {
30 | return false;
31 | }
32 | }
33 |
34 | private static void RemoveAllCachedAssets(string albumName)
35 | {
36 | Logger.Msg("Removing " + albumName + "!");
37 |
38 | if (!AlbumManager.LoadedAlbums.TryGetValue($"album_{albumName}", out var album)) return;
39 |
40 | // Remove cached album information, not needed anymore since the album has been deleted
41 | AlbumManager.LoadedAlbums.Remove($"album_{albumName}");
42 | CoverManager.CachedAnimatedCovers.Remove(album.Index);
43 | CoverManager.CachedCovers.Remove(album.Index);
44 | AssetPatch.RemoveFromCache($"album_{albumName}_demo");
45 | AssetPatch.RemoveFromCache($"album_{albumName}_music");
46 | AssetPatch.RemoveFromCache($"album_{albumName}_cover");
47 |
48 | // Get the music info from the UID, remove it from the ShowMusic list, and refresh the UI
49 | var musicInfo = GlobalDataBase.s_DbMusicTag.GetMusicInfoFromAll($"{AlbumManager.Uid}-{album.Index}");
50 | GlobalDataBase.s_DbMusicTag.RemoveShowMusicUid(musicInfo);
51 | PnlStageInstance.m_MusicRootAnimator?.Play(PnlStageInstance.animNameAlbumIn);
52 | PnlStageInstance.RefreshMusicFSV();
53 |
54 | // TODO: Remove the album information from the Custom Albums tag menu
55 |
56 | // TODO: Only change the selected album if the selected album was the album that was deleted
57 | Logger.Msg("Successfully removed from cache!");
58 | }
59 |
60 | private static void RenameAllCachedAssets(string oldAlbumName, string newAlbumName)
61 | {
62 | Logger.Msg($"Renaming {oldAlbumName} to {newAlbumName}!");
63 | var success = AlbumManager.LoadedAlbums.Remove(oldAlbumName, out var album);
64 | if (!success) return;
65 |
66 | // rename the assets to the new name
67 | AlbumManager.LoadedAlbums.TryAdd(newAlbumName, album);
68 | AssetPatch.ModifyCacheKey($"{oldAlbumName}_demo", $"{newAlbumName}_demo");
69 | AssetPatch.ModifyCacheKey($"{oldAlbumName}_music", $"{newAlbumName}_music");
70 | AssetPatch.ModifyCacheKey($"{oldAlbumName}_cover", $"{newAlbumName}_cover");
71 |
72 | Logger.Msg("Successfully modified cache!");
73 | }
74 |
75 | private static void AddNewAlbums(int previousSize)
76 | {
77 | var index = previousSize;
78 | for (var i = previousSize; i < AlbumManager.LoadedAlbums.Count; i++)
79 | {
80 | // TODO: Write added album hot reloading logic here
81 | }
82 |
83 | PnlStageInstance.m_MusicRootAnimator?.Play(PnlStageInstance.animNameAlbumIn);
84 | PnlStageInstance.RefreshMusicFSV();
85 | }
86 |
87 | ///
88 | /// Runs the logic for hot reloading on Unity's FixedUpdate
89 | ///
90 | internal static void FixedUpdate()
91 | {
92 | var previousSize = AlbumManager.LoadedAlbums.Count;
93 | while (AlbumsAdded.Count > 0) AlbumManager.LoadOne(AlbumsAdded.Dequeue());
94 | while (AlbumsDeleted.Count > 0) RemoveAllCachedAssets(AlbumsDeleted.Dequeue());
95 | }
96 |
97 | ///
98 | /// Initializes the AlbumWatcher for adding/deleting/renaming new custom charts.
99 | ///
100 | internal static void OnLateInitializeMelon()
101 | {
102 | AlbumManager.AlbumWatcher.Path = AlbumManager.SearchPath;
103 | AlbumManager.AlbumWatcher.Filter = AlbumManager.SearchPattern;
104 |
105 | AlbumManager.AlbumWatcher.Created += (_, e) =>
106 | {
107 | Logger.Msg("Added file " + e.Name);
108 | while (!IsFileUnlocked(e.FullPath))
109 | // Thread sleep added to not poll the drive a ton
110 | Thread.Sleep(200);
111 | AlbumsAdded.Enqueue(e.FullPath);
112 | };
113 | AlbumManager.AlbumWatcher.Deleted += (s, e) =>
114 | {
115 | Logger.Msg("Deleted file " + e.Name);
116 | AlbumsDeleted.Enqueue(Path.GetFileNameWithoutExtension(e.Name));
117 | };
118 | AlbumManager.AlbumWatcher.Renamed += (s, e) =>
119 | {
120 | Logger.Msg("Renamed file " + e.OldName + " -> " + e.Name);
121 | RenameAllCachedAssets($"album_{Path.GetFileNameWithoutExtension(e.OldName)}",
122 | $"album_{Path.GetFileNameWithoutExtension(e.Name)}");
123 | };
124 |
125 | // Start the AlbumWatcher
126 | AlbumManager.AlbumWatcher.EnableRaisingEvents = true;
127 | }
128 |
129 | [HarmonyPatch(typeof(PnlStage), nameof(PnlStage.PreWarm))]
130 | internal static class StagePreWarmPatch
131 | {
132 | private static void Postfix(PnlStage __instance)
133 | {
134 | Logger.Msg($"PnlStage instance retrieved. Null = {__instance == null}");
135 | PnlStageInstance = __instance;
136 | }
137 | }
138 | }
139 | }
--------------------------------------------------------------------------------
/Managers/MusicDataManager.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.ObjectModel;
2 | using CustomAlbums.Utilities;
3 | using Il2CppGameLogic;
4 | using Decimal = Il2CppSystem.Decimal;
5 |
6 | namespace CustomAlbums.Managers
7 | {
8 | internal static class MusicDataManager
9 | {
10 | private static readonly List MusicDataList = new();
11 | private static readonly Logger Logger = new(nameof(MusicDataManager));
12 |
13 | static MusicDataManager()
14 | {
15 | // Add an empty music data to the list as a placeholder
16 | MusicDataList.Add(Interop.CreateTypeValue());
17 | }
18 |
19 | public static ReadOnlyCollection Data => MusicDataList.AsReadOnly();
20 |
21 | public static void Add(MusicData data)
22 | {
23 | if (MusicDataList.Count >= short.MaxValue - 1)
24 | {
25 | Logger.Warning($"BMS is too large to load. Max MusicData allowed is {short.MaxValue}!");
26 | return;
27 | }
28 |
29 | MusicDataList.Add(data);
30 | }
31 |
32 | public static void Sort()
33 | {
34 | // Remove placeholder music data
35 | MusicDataList.RemoveAt(0);
36 |
37 | // Sort the list
38 | MusicDataList.Sort((l, r) => !(r.tick - r.dt - (l.tick - l.dt) > 0) ? 1 : -1);
39 |
40 | // Add the placeholder music data back
41 | MusicDataList.Insert(0, Interop.CreateTypeValue());
42 |
43 | // Reapply object IDs and round tick to nearest 3 decimal places
44 | for (var i = 1; i < MusicDataList.Count; i++)
45 | {
46 | var musicData = MusicDataList[i];
47 | musicData.tick = Decimal.Round(musicData.tick, 3);
48 | musicData.objId = (short)i;
49 |
50 | MusicDataList[i] = musicData;
51 | }
52 |
53 | Logger.Msg("Sorted MusicData");
54 | }
55 |
56 | public static void Set(int index, MusicData data)
57 | {
58 | MusicDataList[index] = data;
59 | }
60 |
61 | public static void Clear()
62 | {
63 | // Clear the list
64 | MusicDataList.Clear();
65 |
66 | // Add an empty music data to the list as a placeholder
67 | MusicDataList.Add(Interop.CreateTypeValue());
68 | }
69 | }
70 | }
--------------------------------------------------------------------------------
/Managers/PackManager.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Data;
2 | using CustomAlbums.Utilities;
3 |
4 | namespace CustomAlbums.Managers
5 | {
6 | internal class PackManager
7 | {
8 | private static readonly List Packs = new();
9 | internal static Pack GetPackFromUid(string uid)
10 | {
11 | // If the uid is not custom or parsing the index fails
12 | if (!uid.StartsWith($"{AlbumManager.Uid}-") ||
13 | !uid[4..].TryParseAsInt(out var uidIndex)) return null;
14 |
15 | // Retrieve the pack that the uid belongs to
16 | var pack = Packs.FirstOrDefault(pack =>
17 | uidIndex >= pack.StartIndex && uidIndex < pack.StartIndex + pack.Length);
18 |
19 | // If the pack has no albums in it return null, otherwise return pack (will be null if it doesn't exist)
20 | return pack?.Length == 0 ? null : pack;
21 | }
22 |
23 | internal static Pack CreatePack(string file)
24 | {
25 | return Json.Deserialize(File.OpenRead(file));
26 | }
27 |
28 | internal static void AddPack(Pack pack)
29 | {
30 | Packs.Add(pack);
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Managers/SaveManager.cs:
--------------------------------------------------------------------------------
1 | using System.Text;
2 | using System.Text.Json;
3 | using CustomAlbums.Data;
4 | using CustomAlbums.Utilities;
5 | using System.IO.Compression;
6 |
7 | namespace CustomAlbums.Managers
8 | {
9 | internal class SaveManager
10 | {
11 | private const string SaveLocation = "UserData";
12 | internal static CustomAlbumsSave SaveData;
13 | internal static Logger Logger = new(nameof(SaveManager));
14 | internal static string PreviousScore { get; set; } = "-";
15 |
16 | ///
17 | /// Fixes the save file since this version of CAM uses a different naming scheme.
18 | /// This allows cross-compatibility between CAM 3 and CAM 4, but not from CAM 4 to CAM 3.
19 | ///
20 | internal static void FixSaveFile()
21 | {
22 | if (!ModSettings.SavingEnabled) return;
23 | var firstHistory = SaveData.History.FirstOrDefault();
24 | var firstHighest = SaveData.Highest.FirstOrDefault();
25 | var firstFullCombo = SaveData.FullCombo.FirstOrDefault();
26 | var stringBuilder = new StringBuilder();
27 |
28 | // If we need to fix the history
29 | if (firstHistory != null && firstHistory.StartsWith("pkg_"))
30 | {
31 | var fixedList = new List(SaveData.History.Count);
32 | foreach (var history in SaveData.History.Where(history => history.StartsWith("pkg_")))
33 | {
34 | stringBuilder.Clear();
35 | stringBuilder.Append(history);
36 | stringBuilder.Remove(0, 4);
37 | stringBuilder.Insert(0, "album_");
38 | fixedList.Add(stringBuilder.ToString());
39 | }
40 |
41 | SaveData.History = fixedList;
42 | }
43 |
44 | // If we need to fix the highest
45 | if (!firstHighest.Equals(default(KeyValuePair>)) &&
46 | firstHighest.Key.StartsWith("pkg_"))
47 | {
48 | var fixedDictionaryHighest =
49 | new Dictionary>(SaveData.Highest.Count);
50 | foreach (var (key, value) in SaveData.Highest.Where(kv => kv.Key.StartsWith("pkg_")))
51 | {
52 | stringBuilder.Clear();
53 | stringBuilder.Append(key);
54 | stringBuilder.Remove(0, 4);
55 | stringBuilder.Insert(0, "album_");
56 | fixedDictionaryHighest.Add(stringBuilder.ToString(), value);
57 | }
58 |
59 | SaveData.Highest = fixedDictionaryHighest;
60 | }
61 |
62 | if (!SaveData.UnlockedMasters.Any())
63 | {
64 | var unlockedHighest = SaveData.Highest.Where(kv =>
65 | kv.Value.ContainsKey(3) && kv.Value.TryGetValue(2, out var chartSave) && chartSave.Evaluate >= 4).Select(kv => kv.Key);
66 | var folderCharts = AlbumManager.LoadedAlbums.Where(kv => kv.Value.HasDifficulty(2) && kv.Value.HasDifficulty(3) && !kv.Value.IsPackaged).Select(kv => kv.Key);
67 | var concat = unlockedHighest.Concat(folderCharts);
68 | SaveData.UnlockedMasters.UnionWith(concat);
69 | }
70 |
71 | // If we don't need to fix the FullCombo then return
72 | if (!firstFullCombo.Equals(default(KeyValuePair>)) &&
73 | !firstFullCombo.Key.StartsWith("pkg_")) return;
74 |
75 | var fixedDictionaryFc = new Dictionary>(SaveData.FullCombo.Count);
76 | foreach (var (key, value) in SaveData.FullCombo.Where(kv => kv.Key.StartsWith("pkg_")))
77 | {
78 | if (!key.StartsWith("pkg_")) continue;
79 | stringBuilder.Clear();
80 | stringBuilder.Append(key);
81 | stringBuilder.Remove(0, 4);
82 | stringBuilder.Insert(0, "album_");
83 | fixedDictionaryFc.Add(stringBuilder.ToString(), value);
84 | }
85 |
86 | SaveData.FullCombo = fixedDictionaryFc;
87 | }
88 |
89 | private static void RestoreBackup()
90 | {
91 | var backupPath = Path.Join(SaveLocation, "Backups", "Backups.zip");
92 |
93 | // If a backup does not exist at all
94 | if (!File.Exists(backupPath))
95 | {
96 | Logger.Fail("No backups found. Please delete the CustomAlbums.json file in UserData folder to create a new save.");
97 | return;
98 | }
99 |
100 | // Traverse the .zip file, trying every single backup in this archive
101 | using var backupEntries = ZipFile.OpenRead(backupPath);
102 | foreach (var backup in backupEntries.Entries.OrderByDescending(bak => bak.LastWriteTime)
103 | .Where(bak => bak.Name.EndsWith("CustomAlbums.json.bak")))
104 | {
105 | try
106 | {
107 | SaveData = Json.Deserialize(backup.Open());
108 | }
109 | catch (Exception)
110 | {
111 | continue;
112 | }
113 |
114 | // If our backup that we are trying to load is valid but empty, continue to try and find the last save with data in it
115 | if (SaveData.IsEmpty()) continue;
116 | Logger.Success($"Restored backup from {backup.LastWriteTime.DateTime}.");
117 | return;
118 | }
119 | Logger.Fail("Could not restore save file. Please delete the CustomAlbums.json file in UserData folder to create a new save.");
120 | }
121 |
122 | internal static void LoadSaveFile()
123 | {
124 | if (!ModSettings.SavingEnabled) return;
125 | try
126 | {
127 | using var fileStream = File.OpenRead(Path.Join(SaveLocation, "CustomAlbums.json"));
128 | SaveData = Json.Deserialize(fileStream);
129 | FixSaveFile();
130 | }
131 | catch (Exception ex)
132 | {
133 | if (ex is FileNotFoundException)
134 | {
135 | SaveData = new CustomAlbumsSave();
136 | }
137 | else
138 | {
139 | Logger.Warning("Could not load save file. Attempting to restore backup...");
140 | RestoreBackup();
141 | }
142 | }
143 | }
144 |
145 | internal static void SaveSaveFile()
146 | {
147 | if (!ModSettings.SavingEnabled) return;
148 | try
149 | {
150 | if (SaveData is null)
151 | {
152 | Logger.Warning("Trying to save null data, not saving.");
153 | return;
154 | }
155 |
156 | File.WriteAllText(Path.Join(SaveLocation, "CustomAlbums.json"), JsonSerializer.Serialize(SaveData));
157 | }
158 | catch (Exception ex)
159 | {
160 | Logger.Warning("Failed to save save file. " + ex.StackTrace);
161 | }
162 | }
163 |
164 | ///
165 | /// Saves custom score given scoring information.
166 | ///
167 | /// The UID of the chart.
168 | /// The difficulty index of the chart played.
169 | /// The score of the play.
170 | /// The accuracy of the play.
171 | /// The maximum combo of the play.
172 | /// The judgement ranking of the play.
173 | /// The amount of misses in the play.
174 | internal static void SaveScore(string uid, int musicDifficulty, int score, float accuracy, int maxCombo,
175 | string evaluate, int miss)
176 | {
177 | if (!ModSettings.SavingEnabled) return;
178 |
179 | var album = AlbumManager.GetByUid(uid);
180 | if (!album?.IsPackaged ?? true) return;
181 |
182 | var newEvaluate = evaluate switch
183 | {
184 | "sss" => 6,
185 | "ss" => 5,
186 | "s" => 4,
187 | "a" => 3,
188 | "b" => 2,
189 | "c" => 1,
190 | _ => 0
191 | };
192 |
193 | var albumName = album.AlbumName;
194 |
195 | // Create new album save
196 | SaveData.Highest.TryAdd(albumName, new Dictionary());
197 |
198 | var currChartScore = SaveData.Highest[albumName];
199 |
200 | // Create new save data if the difficulty doesn't exist
201 | currChartScore.TryAdd(musicDifficulty, new ChartSave());
202 |
203 | // Set previous score for PnlVictory logic
204 | var newScore = currChartScore[musicDifficulty];
205 | PreviousScore = newScore.Passed ? newScore.Score.ToString() : "-";
206 |
207 | // Set the correct new score, taking the max of everything
208 | newScore.Passed = true;
209 | newScore.Accuracy = Math.Max(accuracy, newScore.Accuracy);
210 | newScore.Score = Math.Max(score, newScore.Score);
211 | newScore.Combo = Math.Max(maxCombo, newScore.Combo);
212 | newScore.Evaluate = Math.Max(newEvaluate, newScore.Evaluate);
213 | newScore.AccuracyStr = (newScore.Accuracy / 100).ToStringInvariant("P2");
214 | newScore.Clear++;
215 |
216 | if (musicDifficulty is 2 && AlbumManager.LoadedAlbums[albumName].HasDifficulty(3) && newScore.Evaluate >= 4)
217 | SaveData.UnlockedMasters.Add(albumName);
218 |
219 | // If there were no misses then add the chart/difficulty to the FullCombo list
220 | if (miss != 0) return;
221 |
222 | SaveData.FullCombo.TryAdd(albumName, new List());
223 |
224 | if (!SaveData.FullCombo[albumName].Contains(musicDifficulty))
225 | SaveData.FullCombo[albumName].Add(musicDifficulty);
226 | }
227 | }
228 | }
--------------------------------------------------------------------------------
/ModExtensions/AlbumEventArgs.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Data;
2 |
3 | namespace CustomAlbums.ModExtensions
4 | {
5 | public class AlbumEventArgs : EventArgs
6 | {
7 | public Album Album;
8 |
9 | public AlbumEventArgs(Album album)
10 | {
11 | Album = album;
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/ModExtensions/AssetEventArgs.cs:
--------------------------------------------------------------------------------
1 | namespace CustomAlbums.ModExtensions
2 | {
3 | public class AssetEventArgs : EventArgs
4 | {
5 | public string AssetName;
6 | public IntPtr AssetPtr;
7 |
8 | public AssetEventArgs(string assetName, IntPtr assetPtr)
9 | {
10 | AssetName = assetName;
11 | AssetPtr = assetPtr;
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/ModExtensions/Events.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Managers;
2 | using CustomAlbums.Patches;
3 |
4 | namespace CustomAlbums.ModExtensions
5 | {
6 | public static class Events
7 | {
8 | public delegate void LoadAssetEvent(object s, AssetEventArgs e);
9 |
10 | public static event LoadAssetEvent OnAssetLoaded
11 | {
12 | add => AssetPatch.OnAssetLoaded += value;
13 | remove => AssetPatch.OnAssetLoaded -= value;
14 | }
15 |
16 | public delegate void LoadAlbumEvent(object s, AlbumEventArgs e);
17 |
18 | public static event LoadAlbumEvent OnAlbumLoaded
19 | {
20 | add => AlbumManager.OnAlbumLoaded += value;
21 | remove => AlbumManager.OnAlbumLoaded -= value;
22 | }
23 |
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/ModSettings.cs:
--------------------------------------------------------------------------------
1 | using MelonLoader;
2 |
3 | namespace CustomAlbums
4 | {
5 | internal static class ModSettings
6 | {
7 | private static MelonPreferences_Entry _verboseLogging;
8 | private static MelonPreferences_Entry _savingEnabled;
9 | private static MelonPreferences_Entry _enableLogWriteToFile;
10 | public static bool VerboseLogging => _verboseLogging.Value;
11 | public static bool SavingEnabled => _savingEnabled.Value;
12 | public static bool LoggingToFileEnabled => _enableLogWriteToFile.Value;
13 |
14 |
15 | internal static void Register()
16 | {
17 | var category = MelonPreferences.CreateCategory("CustomAlbums", "Custom Albums");
18 |
19 | _verboseLogging = category.CreateEntry("VerboseLogging", false, "Verbose Logging");
20 | _savingEnabled = category.CreateEntry("SavingEnabled", true, "Enable Saving");
21 | _enableLogWriteToFile = category.CreateEntry("LogWriteToFile", false, "Enable Log Write to File");
22 | }
23 | }
24 | }
--------------------------------------------------------------------------------
/Patches/AnalyticsPatch.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Managers;
2 | using HarmonyLib;
3 | using Il2CppAssets.Scripts.Database;
4 | using Il2CppPeroPeroGames.DataStatistics;
5 | using System.Reflection;
6 | using UnityEngine;
7 | using Logger = CustomAlbums.Utilities.Logger;
8 |
9 | namespace CustomAlbums.Patches
10 | {
11 | internal class AnalyticsPatch
12 | {
13 | internal static readonly Logger Logger = new(nameof(AnalyticsPatch));
14 |
15 | ///
16 | /// Blocks tag analytics from being sent if tag is CustomAlbums.
17 | ///
18 | [HarmonyPatch(typeof(ThinkingDataPeripheralHelper), nameof(ThinkingDataPeripheralHelper.CommonSendString))]
19 | internal class CommonSendStringPatch
20 | {
21 | private static bool Prefix(string eventName, string propertyName, string info)
22 | {
23 | var runCond = info != AlbumManager.Languages["ChineseS"];
24 | if (!runCond) Logger.Msg("Blocked custom albums tag analytics.");
25 | return runCond;
26 | }
27 | }
28 |
29 | ///
30 | /// Blocks chart analytics from being sent if the chart is custom.
31 | ///
32 | [HarmonyPatch(typeof(ThinkingDataBattleHelper))]
33 | internal class SendMDPatch
34 | {
35 | private static IEnumerable TargetMethods()
36 | {
37 | return typeof(ThinkingDataBattleHelper).GetMethods(BindingFlags.Instance | BindingFlags.Public)
38 | .Where(method => method.Name.StartsWith("Send"));
39 | }
40 |
41 | private static bool Prefix()
42 | {
43 | var runCond = !BattleHelper.MusicInfo().uid.StartsWith($"{AlbumManager.Uid}-");
44 | if (!runCond) Logger.Msg("Blocked sending analytics of custom chart.");
45 | return runCond;
46 | }
47 | }
48 |
49 |
50 | ///
51 | /// Prevents the game from sending any analytics if the musicInfo is custom.
52 | ///
53 | [HarmonyPatch(typeof(ThinkingDataPeripheralHelper), nameof(ThinkingDataPeripheralHelper.PostToThinkingData))]
54 | internal class PostToThinkingDataPatch
55 | {
56 | private static bool Prefix(string dataStatisticsEventDefinesName, MusicInfo musicInfo)
57 | {
58 | var runCond = !musicInfo.uid.StartsWith($"{AlbumManager.Uid}-");
59 | if (!runCond) Logger.Msg("Blocked thinking data post of custom chart.");
60 | return runCond;
61 | }
62 | }
63 |
64 | ///
65 | /// Prevents the game from sending any analytics if the favorited chart is custom.
66 | ///
67 | [HarmonyPatch(typeof(ThinkingDataPeripheralHelper),
68 | nameof(ThinkingDataPeripheralHelper.SendFavoriteMusicBehavior))]
69 | internal class SendFavoriteMusicBehaviorPatch
70 | {
71 | private static bool Prefix(string dataStatisticsEventDefinesNameMusicInfo, MusicInfo musicInfo)
72 | {
73 | var runCond = !musicInfo.uid.StartsWith($"{AlbumManager.Uid}-");
74 | if (!runCond) Logger.Msg("Blocked sending favorite chart analytics of custom chart.");
75 | return runCond;
76 | }
77 | }
78 |
79 |
80 | ///
81 | /// Prevents the game from sending any analytics if the musicInfo is custom.
82 | ///
83 | [HarmonyPatch(typeof(ThinkingDataPeripheralHelper), nameof(ThinkingDataPeripheralHelper.PostMusicChooseInfo))]
84 | internal class PostMusicChooseInfoPatch
85 | {
86 | private static bool Prefix(Vector2Int diffValue, string chooseMusicType, string searchName, MusicInfo musicInfo)
87 | {
88 | var runCond = !musicInfo.uid.StartsWith($"{AlbumManager.Uid}-");
89 | if (!runCond) Logger.Msg("Blocked sending chosen music from search analytics of custom chart.");
90 | return runCond;
91 | }
92 | }
93 |
94 | ///
95 | /// Cleans search result analytics of custom charts.
96 | ///
97 | [HarmonyPatch(typeof(ThinkingDataPeripheralHelper), nameof(ThinkingDataPeripheralHelper.GetSearchResultInfo))]
98 | internal class GetSearchResultInfoPatch
99 | {
100 |
101 | private static bool Prefix(MusicInfo musicInfo)
102 | {
103 | var runCond = !musicInfo.uid.StartsWith($"{AlbumManager.Uid}-");
104 | if (!runCond) Logger.Msg("Blocking custom album from being added to search analytics.");
105 | return runCond;
106 | }
107 | }
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/Patches/AnimatedCoverPatch.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Managers;
2 | using HarmonyLib;
3 | using Il2Cpp;
4 | using Il2CppAssets.Scripts.Database;
5 | using Il2CppAssets.Scripts.PeroTools.Nice.Interface;
6 | using UnityEngine;
7 | using Logger = CustomAlbums.Utilities.Logger;
8 |
9 | namespace CustomAlbums.Patches
10 | {
11 | internal class AnimatedCoverPatch
12 | {
13 | ///
14 | /// Enables animated album covers.
15 | ///
16 | [HarmonyPatch(typeof(MusicStageCell), nameof(MusicStageCell.Awake))]
17 | internal static class MusicStageCellPatch
18 | {
19 | private static readonly Logger Logger = new(nameof(MusicStageCellPatch));
20 | private static readonly LinkedList Cells = new();
21 | internal static string CurrentScene { get; set; }
22 |
23 | public static void AnimateCoversUpdate()
24 | {
25 | if (CurrentScene is not "UISystem_PC") return;
26 | var dbMusicTag = GlobalDataBase.dbMusicTag;
27 |
28 | if (dbMusicTag == null) return;
29 |
30 | for (var node = Cells.First; node is not null;)
31 | {
32 | var next = node.Next;
33 | var cell = node.Value;
34 | var index = cell?.m_VariableBehaviour?.Cast().GetResult() ?? -1;
35 |
36 | var uid = dbMusicTag?.GetShowStageUidByIndex(index) ?? "?";
37 |
38 | // If uid isn't defined
39 | if (uid is "?")
40 | {
41 | Cells.Remove(node);
42 | node = next;
43 | continue;
44 | }
45 |
46 | var musicInfo = dbMusicTag?.GetMusicInfoFromAll(uid);
47 |
48 | // If cell is not custom
49 | if (musicInfo?.albumJsonIndex < AlbumManager.Uid)
50 | {
51 | Cells.Remove(node);
52 | node = next;
53 | continue;
54 | }
55 |
56 | var album = AlbumManager.GetByUid(uid);
57 | var animatedCover = album?.AnimatedCover;
58 |
59 | // If cell is not animated
60 | if (animatedCover is null || animatedCover.FramesPerSecond is 0)
61 | {
62 | Cells.Remove(node);
63 | node = next;
64 | continue;
65 | }
66 |
67 | // Animate the cell, with one last null check
68 | var frame = (int)Mathf.Floor(Time.time * 1000) %
69 | (animatedCover.FramesPerSecond * animatedCover.FrameCount) / animatedCover.FramesPerSecond;
70 | if (cell != null) cell.m_StageImg.sprite = animatedCover.Frames[frame];
71 | node = next;
72 | }
73 | }
74 |
75 | private static void Prefix(MusicStageCell __instance)
76 | {
77 | Cells.AddLast(__instance);
78 | }
79 | }
80 | }
81 | }
--------------------------------------------------------------------------------
/Patches/AssetPatch.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.CompilerServices;
2 | using System.Runtime.InteropServices;
3 | using System.Text.Json;
4 | using System.Text.Json.Nodes;
5 | using CustomAlbums.Data;
6 | using CustomAlbums.Managers;
7 | using CustomAlbums.ModExtensions;
8 | using CustomAlbums.Utilities;
9 | using HarmonyLib;
10 | using Il2CppAssets.Scripts.Database;
11 | using Il2CppAssets.Scripts.PeroTools.Commons;
12 | using Il2CppAssets.Scripts.PeroTools.GeneralLocalization;
13 | using Il2CppAssets.Scripts.PeroTools.Managers;
14 | using Il2CppInterop.Common;
15 | using Il2CppInterop.Runtime;
16 | using Il2CppInterop.Runtime.InteropTypes.Arrays;
17 | using Il2CppPeroTools2.Resources;
18 | using MelonLoader.NativeUtils;
19 | using UnityEngine;
20 | using AudioManager = CustomAlbums.Managers.AudioManager;
21 | using Logger = CustomAlbums.Utilities.Logger;
22 | using Object = UnityEngine.Object;
23 |
24 | namespace CustomAlbums.Patches
25 | {
26 | internal class AssetPatch
27 | {
28 | private static readonly NativeHook Hook = new();
29 | private static readonly Dictionary AssetCache = new();
30 | private static readonly Dictionary> AssetHandler = new();
31 | private static readonly Logger Logger = new(nameof(AssetPatch));
32 |
33 | private static int _latestAlbumNum;
34 | private static bool _doneLoadingAlbumsFlag;
35 | internal static Events.LoadAssetEvent OnAssetLoaded;
36 |
37 | ///
38 | /// Binds the asset to a new key, while removing the old asset.
39 | ///
40 | /// The old assetName.
41 | /// The new assetName where the value should be bound.
42 | /// if the key was successfully bound; otherwise, .
43 | internal static bool ModifyCacheKey(string oldAssetName, string newAssetName)
44 | {
45 | var success = AssetCache.Remove(oldAssetName, out var asset);
46 | return success && AssetCache.TryAdd(newAssetName, asset);
47 | }
48 |
49 | ///
50 | /// Removes a KeyValuePair from the asset cache.
51 | ///
52 | /// The key corresponding to the value to be removed.
53 | /// if the entry was successfully removed; otherwise, .
54 | internal static bool RemoveFromCache(string key)
55 | {
56 | return AssetCache.Remove(key);
57 | }
58 |
59 | ///
60 | /// Adds methods to the AssetHandler.
61 | /// The AssetHandler modifies certain assets based on their name.
62 | ///
63 | internal static void InitializeHandler()
64 | {
65 | AssetHandler.Add("albums", (assetName, assetPtr, _) =>
66 | {
67 | var jsonArray = Json.Deserialize(new TextAsset(assetPtr).text);
68 |
69 | // adds the CustomAlbums "dlc" to the game
70 | jsonArray.Add(new
71 | {
72 | uid = AlbumManager.MusicPackage,
73 | title = "Custom Albums",
74 | prefabsName = $"AlbumDisco{AlbumManager.Uid}",
75 | price = "¥25.00",
76 | jsonName = AlbumManager.JsonName,
77 | needPurchase = false,
78 | free = true
79 | });
80 |
81 | // Create and add the new asset with the CustomAlbums "dlc"
82 | var newAsset = CreateTextAsset(assetName, JsonSerializer.Serialize(jsonArray));
83 | if (!Singleton.instance.m_Dictionary.ContainsKey(assetName))
84 | Singleton.instance.Add(assetName, newAsset.text);
85 |
86 | // Set cache and return newAsset's pointer if it non-null
87 | AssetCache[assetName] = newAsset;
88 | return newAsset?.Pointer ?? assetPtr;
89 | });
90 |
91 | AssetHandler.Add(AlbumManager.JsonName, (assetName, assetPtr, _) =>
92 | {
93 | var jsonArray = new JsonArray();
94 |
95 | // Add each custom charts' data to the album
96 | foreach (var (albumStr, albumObj) in AlbumManager.LoadedAlbums)
97 | {
98 | var albumInfo = albumObj.Info;
99 | var customChartJson = new
100 | {
101 | uid = albumObj.Uid,
102 | name = albumInfo.Name,
103 | author = albumInfo.Author,
104 | bpm = albumInfo.Bpm,
105 | music = $"{albumStr}_music",
106 | demo = $"{albumStr}_demo",
107 | cover = $"{albumStr}_cover",
108 | noteJson = $"{albumStr}_map",
109 | scene = albumInfo.Scene,
110 | unlockLevel = "0",
111 | levelDesigner = albumInfo.LevelDesigner,
112 | levelDesigner1 = albumInfo.LevelDesigner1 ?? albumInfo.LevelDesigner,
113 | levelDesigner2 = albumInfo.LevelDesigner2 ?? albumInfo.LevelDesigner,
114 | levelDesigner3 = albumInfo.LevelDesigner3 ?? albumInfo.LevelDesigner,
115 | levelDesigner4 = albumInfo.LevelDesigner4 ?? albumInfo.LevelDesigner,
116 | levelDesigner5 = albumInfo.LevelDesigner5 ?? albumInfo.LevelDesigner,
117 | difficulty1 = albumInfo.Difficulty1 ?? "0",
118 | difficulty2 = albumInfo.Difficulty2,
119 | difficulty3 = albumInfo.Difficulty3 ?? "0",
120 | difficulty4 = albumInfo.Difficulty4 ?? "0",
121 | difficulty5 = albumInfo.Difficulty5 ?? "0"
122 | };
123 | jsonArray.Add(customChartJson);
124 |
125 | // Configure the searchtaginfo
126 | var config = Singleton.instance.GetConfigObject();
127 | var searchTag = new MusicSearchTagInfo
128 | {
129 | uid = customChartJson.uid,
130 | listIndex = config.count
131 | };
132 |
133 | // Create the search tag itself
134 | var tags = new List { "custom albums" };
135 | if (albumInfo.SearchTags != null) tags.AddRange(albumInfo.SearchTags);
136 | if (!string.IsNullOrEmpty(albumInfo.NameRomanized)) tags.Add(albumInfo.NameRomanized);
137 | for (var i = 0; i < tags.Count; i++) tags[i] = tags[i].ToLower();
138 |
139 | searchTag.tag = new Il2CppStringArray(tags.ToArray());
140 |
141 | // Add it to the game
142 | config.m_Dictionary.Add(searchTag.uid, searchTag);
143 | config.list.Add(searchTag);
144 | }
145 |
146 | // Create and add the new asset with the custom charts' data
147 | var newAsset = CreateTextAsset(assetName, JsonSerializer.Serialize(jsonArray));
148 | if (!Singleton.instance.m_Dictionary.ContainsKey(assetName))
149 | Singleton.instance.Add(assetName, newAsset.text);
150 |
151 | // Set cache and return newAsset's pointer if it non-null
152 | AssetCache[assetName] = newAsset;
153 | return newAsset?.Pointer ?? assetPtr;
154 | });
155 |
156 | AssetHandler.Add("albums_", (assetName, assetPtr, language) =>
157 | {
158 | var jsonArray = Json.Deserialize(new TextAsset(assetPtr).text);
159 |
160 | // Adds the correct language for the "Custom Albums" album
161 | jsonArray.Add(new
162 | {
163 | title = AlbumManager.Languages[language]
164 | });
165 |
166 | // Create and add the new asset with the correct lingual name of "Custom Albums"
167 | var newAsset = CreateTextAsset(assetName, JsonSerializer.Serialize(jsonArray));
168 | if (!Singleton.instance.m_Dictionary.ContainsKey(assetName))
169 | Singleton.instance.Add(assetName, newAsset.text);
170 |
171 | // Set cache and return newAsset's pointer if it non-null
172 | AssetCache[assetName] = newAsset;
173 | return newAsset?.Pointer ?? assetPtr;
174 | });
175 |
176 | AssetHandler.Add($"{AlbumManager.JsonName}_", (assetName, assetPtr, _) =>
177 | {
178 | var jsonArray = new JsonArray();
179 |
180 | // This should technically be written to retrieve and add the name of the chart based on your selected language
181 | // However this only grabs whatever name is given in the info.json
182 | // Very likely not a big deal
183 | foreach (var (_, value) in AlbumManager.LoadedAlbums)
184 | jsonArray.Add(new
185 | {
186 | name = value.Info.Name,
187 | author = value.Info.Author
188 | });
189 |
190 | // Create and add the new asset with the names of each custom chart
191 | var newAsset = CreateTextAsset(assetName, JsonSerializer.Serialize(jsonArray));
192 | if (!Singleton.instance.m_Dictionary.ContainsKey(assetName))
193 | Singleton.instance.Add(assetName, newAsset.text);
194 |
195 | // Set cache and return newAsset's pointer if it non-null
196 | AssetCache[assetName] = newAsset;
197 | return newAsset?.Pointer ?? assetPtr;
198 | });
199 |
200 | AssetHandler.Add("album_", (assetName, assetPtr, _) =>
201 | {
202 | var cache = true;
203 | Object newAsset = null;
204 | var suffix = AssetIdentifiers.AssetSuffixes.FirstOrDefault(assetName.EndsWith);
205 | if (!string.IsNullOrEmpty(suffix))
206 | {
207 | var albumKey = assetName.Remove(assetName.Length - suffix.Length);
208 | AlbumManager.LoadedAlbums.TryGetValue(albumKey, out var album);
209 | if (suffix.StartsWith("_map"))
210 | {
211 | newAsset = album?.Sheets.GetValueOrDefault(suffix[^1].ToString().ParseAsInt())?.GetStage();
212 | // Do not cache the StageInfos, this should be loaded into memory only when we need it
213 | cache = false;
214 | }
215 | else
216 | {
217 | // Set the newAsset to the objects held in the album
218 | switch (suffix)
219 | {
220 | case "_demo":
221 | newAsset = album?.Demo;
222 | break;
223 | case "_music":
224 | newAsset = album?.Music;
225 | break;
226 | case "_cover":
227 | newAsset = album?.AnimatedCover?.Frames[0] ?? album?.Cover;
228 | break;
229 | default:
230 | Logger.Error($"Unknown suffix: {suffix}");
231 | break;
232 | }
233 | }
234 | }
235 |
236 | // Set cache if we should and return newAsset's pointer if it non-null
237 | if (cache) AssetCache[assetName] = newAsset;
238 | return newAsset?.Pointer ?? assetPtr;
239 | });
240 | }
241 |
242 | ///
243 | /// Gets where T : and detours it using a
244 | /// where T : to LoadFromNamePatch.
245 | ///
246 | internal static unsafe void AttachHook()
247 | {
248 | var loadFromNameMethod = AccessTools.Method(typeof(ResourcesManager),
249 | nameof(ResourcesManager.LoadFromName), new[] { typeof(string) },
250 | new[] { typeof(TextAsset) });
251 |
252 | if (loadFromNameMethod is null)
253 | {
254 | Logger.Error("FATAL ERROR: AssetPatch failed.");
255 | Thread.Sleep(1000);
256 | Environment.Exit(1);
257 | }
258 |
259 | // AttachHook should only be run once; create the handler
260 | InitializeHandler();
261 |
262 | var loadFromNamePointer = *(IntPtr*)(IntPtr)Il2CppInteropUtils
263 | .GetIl2CppMethodInfoPointerFieldForGeneratedMethod(loadFromNameMethod).GetValue(null)!;
264 |
265 | // Create a pointer for our new method to be called instead
266 | // This is Cdecl because this is going to be called in an unmanaged context
267 | delegate* unmanaged[Cdecl] detourPointer = &LoadFromNamePatch;
268 |
269 | // Set the hook so that LoadFromNamePatch runs instead of the original LoadFromName
270 | Hook.Detour = (IntPtr)detourPointer;
271 | Hook.Target = loadFromNamePointer;
272 | Hook.Attach();
273 | }
274 |
275 |
276 | ///
277 | /// Modifies certain game data as it get loaded.
278 | /// The game data that is modified directly adds support for custom albums.
279 | ///
280 | /// The instance of ResourceManager calling LoadFromName.
281 | /// The pointer to the string assetName.
282 | /// Method info used by the original method.
283 | ///
284 | /// An of either a newly created asset if it exists or the original asset if a new one was not
285 | /// created.
286 | ///
287 | [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
288 | private static IntPtr LoadFromNamePatch(IntPtr instance, IntPtr assetNamePtr, IntPtr nativeMethodInfo)
289 | {
290 | // Retrieve the pointer of the asset and the name of the asset
291 | var assetPtr = Hook.Trampoline(instance, assetNamePtr, nativeMethodInfo);
292 | var assetName = IL2CPP.Il2CppStringToManaged(assetNamePtr) ?? string.Empty;
293 |
294 | Logger.Msg($"Loading {assetName}!");
295 |
296 | OnAssetLoaded?.Invoke(typeof(AssetPatch), new AssetEventArgs(assetName, assetPtr));
297 |
298 | if (assetName.StartsWith("ALBUM") && assetName[5..].TryParseAsInt(out var albumNum) &&
299 | albumNum != AlbumManager.Uid + 1)
300 | {
301 | // If done loading albums, we've found the maximum actual album
302 | // If there's an attempt to load other albums (there will be if you open the tag menu), early return zero pointer
303 | // This provides a noticeable speedup when opening tags for the first time
304 | if (_doneLoadingAlbumsFlag && albumNum > _latestAlbumNum)
305 | return IntPtr.Zero;
306 |
307 | // Otherwise get the maximum number X of ALBUMX
308 | _latestAlbumNum = Math.Max(_latestAlbumNum, albumNum);
309 | }
310 |
311 | // If we're loading music_search_tag we're done loading albums
312 | if (assetName == "music_search_tag") _doneLoadingAlbumsFlag = true;
313 |
314 | // If the asset exists in the cache then retrieve it
315 | if (AssetCache.TryGetValue(assetName, out var cachedAsset))
316 | {
317 | if (cachedAsset != null)
318 | {
319 | Logger.Msg($"Returning {assetName} from cache");
320 | AudioManager.SwitchLoad(assetName);
321 | return cachedAsset.Pointer;
322 | }
323 |
324 | Logger.Msg("Removing null asset from cache");
325 | AssetCache.Remove(assetName);
326 | }
327 |
328 | // Allow original LoadFromName to run with LocalizationSettings
329 | if (assetName is "LocalizationSettings") return assetPtr;
330 |
331 | var language = SingletonScriptableObject.instance.GetActiveOption("Language");
332 |
333 | // Programmatically alters the asset name to remove the language if the language exists
334 | var handledAssetName = assetName.StartsWith("albums_") ? "albums_" : assetName;
335 | handledAssetName = handledAssetName.StartsWith($"{AlbumManager.JsonName}_")
336 | ? $"{AlbumManager.JsonName}_"
337 | : handledAssetName;
338 | handledAssetName = handledAssetName.StartsWith("album_") ? "album_" : handledAssetName;
339 |
340 | // Get the method from the AssetHandler if it exists and run it, otherwise return assetPtr
341 | return AssetHandler.TryGetValue(handledAssetName, out var value)
342 | ? value(assetName, assetPtr, language)
343 | : assetPtr;
344 | }
345 |
346 | ///
347 | /// Simple helper method to create a TextAsset.
348 | ///
349 | ///
350 | ///
351 | /// A new initialized with the parameters.
352 | private static TextAsset CreateTextAsset(string name, string text)
353 | {
354 | return new TextAsset(text)
355 | {
356 | name = name
357 | };
358 | }
359 |
360 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
361 | private delegate IntPtr LoadFromNameDelegate(IntPtr instance, IntPtr assetNamePtr, IntPtr nativeMethodInfo);
362 | }
363 | }
--------------------------------------------------------------------------------
/Patches/ChartDialogPatch.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Managers;
2 | using CustomAlbums.Utilities;
3 | using HarmonyLib;
4 | using Il2Cpp;
5 | using Il2CppAssets.Scripts.Database;
6 | using Il2CppAssets.Scripts.GameCore;
7 | using Il2CppAssets.Scripts.Structs;
8 |
9 | namespace CustomAlbums.Patches
10 | {
11 | internal class ChartDialogPatch
12 | {
13 | ///
14 | /// This method runs once when the chart loads, so init basic values to avoid computing again
15 | ///
16 | [HarmonyPatch(typeof(DialogMasterControl), nameof(DialogMasterControl.Init))]
17 | internal class InitPatch
18 | {
19 | private static readonly Logger Logger = new(nameof(InitPatch));
20 |
21 | private static void Prefix(DialogMasterControl __instance)
22 | {
23 | Logger.Msg("Setting talk file values.");
24 | var currentStageUid = GlobalDataBase.dbBattleStage.musicUid;
25 | PlayDialogAnimPatch.CurrentStageInfo = GlobalDataBase.dbStageInfo.m_StageInfo;
26 |
27 | if (!currentStageUid.StartsWith($"{AlbumManager.Uid}-"))
28 | {
29 | PlayDialogAnimPatch.HasVersion2 = false;
30 | return;
31 | }
32 |
33 | var currentAlbum = AlbumManager.GetByUid(currentStageUid);
34 |
35 | // Reset values that may have changed
36 | PlayDialogAnimPatch.HasVersion2 =
37 | (currentAlbum?.Sheets.TryGetValue(PlayDialogAnimPatch.CurrentStageInfo.difficulty, out var sheet) ??
38 | false) && sheet.TalkFileVersion2;
39 | PlayDialogAnimPatch.Index = 0;
40 | PlayDialogAnimPatch.CurrentLanguage = DataHelper.userLanguage;
41 |
42 | if (PlayDialogAnimPatch.CurrentStageInfo.dialogEvents == null) return;
43 | // Set this here to avoid repeatedly checking a dictionary
44 | PlayDialogAnimPatch.DialogEvents =
45 | PlayDialogAnimPatch.CurrentStageInfo.dialogEvents.ContainsKey(PlayDialogAnimPatch.CurrentLanguage)
46 | ? PlayDialogAnimPatch.CurrentStageInfo.dialogEvents[PlayDialogAnimPatch.CurrentLanguage]
47 | : PlayDialogAnimPatch.CurrentStageInfo.dialogEvents["English"];
48 | }
49 | }
50 |
51 |
52 | ///
53 | /// This patch allows support for setting the transparency of dialog boxes. Eventually, this patch will allow stronger
54 | /// control of dialog boxes using the "version": 2 property.
55 | ///
56 | [HarmonyPatch(typeof(DialogSubControl), nameof(DialogSubControl.PlayDialogAnim))]
57 | internal class PlayDialogAnimPatch
58 | {
59 | private static readonly Logger Logger = new(nameof(PlayDialogAnimPatch));
60 | internal static int Index { get; set; }
61 | internal static StageInfo CurrentStageInfo { get; set; }
62 | internal static bool HasVersion2 { get; set; }
63 | internal static string CurrentLanguage { get; set; } = string.Empty;
64 | internal static Il2CppSystem.Collections.Generic.List DialogEvents { get; set; }
65 |
66 | private static void Prefix(DialogSubControl __instance)
67 | {
68 | if (!HasVersion2 || DialogEvents == null) return;
69 |
70 | __instance.m_BgImg.color = DialogEvents[Index++].bgColor;
71 | }
72 | }
73 | }
74 | }
--------------------------------------------------------------------------------
/Patches/DifficultyGradeIconPatch.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Managers;
2 | using CustomAlbums.Utilities;
3 | using HarmonyLib;
4 | using Il2Cpp;
5 | using Il2CppAssets.Scripts.Database;
6 | using Il2CppAssets.Scripts.PeroTools.Commons;
7 | using Il2CppAssets.Scripts.UI.Panels;
8 |
9 | namespace CustomAlbums.Patches
10 | {
11 |
12 | [HarmonyPatch(typeof(PnlStage), nameof(PnlStage.RefreshDiffUI))]
13 | internal class DifficultyGradeIconPatch
14 | {
15 | private static int GetEvaluate(Dictionary highest, int diff) => highest.GetValueOrDefault(diff)?.Evaluate ?? -1;
16 |
17 | ///
18 | /// Enables the S logos on the difficulties for custom charts.
19 | ///
20 | // ReSharper disable once InconsistentNaming
21 | private static void Postfix(MusicInfo musicInfo, PnlStage __instance)
22 | {
23 | var uid = musicInfo?.uid;
24 | var specialSongInstance = Singleton.instance;
25 |
26 | if (string.IsNullOrEmpty(uid)) return;
27 |
28 | // For custom charts, we need to set the S logos for each difficulty
29 | if (uid.StartsWith($"{AlbumManager.Uid}-"))
30 | {
31 | // Gets the highest data from save data
32 | var customHighest = SaveManager.SaveData.GetChartSaveDataFromUid(uid).Highest;
33 |
34 | // Get the Evaluate value from each, set diff3 to diff4 if hidden is invoked
35 | var diff1 = GetEvaluate(customHighest, 1);
36 | var diff2 = GetEvaluate(customHighest, 2);
37 | var diff3 = Singleton.instance.IsInvokeHideBms(uid)
38 | ? GetEvaluate(customHighest, 4)
39 | : GetEvaluate(customHighest, 3);
40 |
41 | // Set the S logos for each difficulty
42 | __instance.m_Diff1Item.ChangeSchemeByEvalue(diff1, __instance.globalData);
43 | __instance.m_Diff2Item.ChangeSchemeByEvalue(diff2, __instance.globalData);
44 | __instance.m_Diff3Item.ChangeSchemeByEvalue(diff3, __instance.globalData);
45 | }
46 |
47 | // For vanilla and custom charts, this fixes the hidden difficulty icon for non-master charts
48 | if (!specialSongInstance.IsInvokeHideBms(uid)) return;
49 | if (!specialSongInstance.m_HideBmsInfos.TryGetValue(uid, out var info)) return;
50 |
51 | // Get the difficulty evaluates
52 | var hiddenEval = DataHelper.highest.GetIDataByUid(uid, 4).ToChartSave().Evaluate;
53 | var masterEval = DataHelper.highest.GetIDataByUid(uid, 3).ToChartSave().Evaluate;
54 |
55 | // The game handles case 3 already, don't need to reinvent the wheel here
56 | switch (info.triggerDiff)
57 | {
58 | case 1:
59 | __instance.m_Diff3Item.ChangeSchemeByEvalue(masterEval, __instance.globalData);
60 | __instance.m_Diff1Item.ChangeSchemeByEvalue(hiddenEval, __instance.globalData);
61 | break;
62 | case 2:
63 | __instance.m_Diff3Item.ChangeSchemeByEvalue(masterEval, __instance.globalData);
64 | __instance.m_Diff2Item.ChangeSchemeByEvalue(hiddenEval, __instance.globalData);
65 | break;
66 | }
67 | }
68 | }
69 | }
--------------------------------------------------------------------------------
/Patches/HiddenSupportPatch.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Managers;
2 | using CustomAlbums.Utilities;
3 | using HarmonyLib;
4 | using Il2Cpp;
5 | using Il2CppAssets.Scripts.Database;
6 | using Il2CppAssets.Scripts.PeroTools.Commons;
7 | using Il2CppAssets.Scripts.PeroTools.Managers;
8 | using Il2CppAssets.Scripts.UI.Tips;
9 | using Il2CppInterop.Runtime.InteropTypes.Arrays;
10 | using Il2CppPeroPeroGames.GlobalDefines;
11 | using MelonLoader;
12 |
13 | namespace CustomAlbums.Patches
14 | {
15 | internal class HiddenSupportPatch
16 | {
17 | internal static HashSet LoadedHiddens = new();
18 |
19 | internal static void UpdateHiddenCharts()
20 | {
21 | HideBmsInfoDicPatch.HasUpdate = true;
22 | MusicTagPatch.HasUpdate = true;
23 | }
24 |
25 | [HarmonyPatch(typeof(SpecialSongManager), nameof(SpecialSongManager.InitHideBmsInfoDic))]
26 | internal static class HideBmsInfoDicPatch
27 | {
28 | internal static bool HasUpdate { get; set; } = true;
29 | private static readonly Logger Logger = new(nameof(HideBmsInfoDicPatch));
30 |
31 | private static void Postfix(SpecialSongManager __instance)
32 | {
33 | if (!HasUpdate) return;
34 |
35 | foreach (var (key, value) in AlbumManager.LoadedAlbums.Where(kv => kv.Value.HasDifficulty(4) || kv.Value.HasDifficulty(5)))
36 | {
37 | // Quick check for Touhou charts
38 | if (value.HasDifficulty(5))
39 | {
40 | var newTouhouArray = new Il2CppStringArray(DBMusicTagDefine.s_BarrageModeSongUid.Length + 1);
41 | for (var i = 0; i < DBMusicTagDefine.s_BarrageModeSongUid.Length; i++)
42 | newTouhouArray[i] = DBMusicTagDefine.s_BarrageModeSongUid[i];
43 | newTouhouArray[^1] = value.Uid;
44 | DBMusicTagDefine.s_BarrageModeSongUid = newTouhouArray;
45 | }
46 | // Enable hidden mode for charts containing map4
47 | if (!LoadedHiddens.Contains(value.Uid)) continue;
48 |
49 | var albumUid = value.Uid;
50 |
51 | __instance.m_HideBmsInfos.Add(albumUid,
52 | new SpecialSongManager.HideBmsInfo(
53 | albumUid,
54 | value.Info.HideBmsDifficulty == "0"
55 | ? value.HasDifficulty(3) ? 3 : 2
56 | : value.Info.HideBmsDifficulty.ParseAsInt(),
57 | 4,
58 | $"{key}_map4",
59 | new Func(() => __instance.IsInvokeHideBms(albumUid))
60 | ));
61 |
62 | // Add chart to the appropriate list for their hidden type
63 | var hideMusicInfo = new HideMusicInfo
64 | {
65 | musicUid = albumUid,
66 | invokeType = value.Info.HideBmsMode switch
67 | {
68 | "CLICK" => (int)HiddenInvokeType.Click,
69 | "PRESS" => (int)HiddenInvokeType.LongPress,
70 | "TOGGLE" => (int)HiddenInvokeType.Toggle,
71 | _ => (int)HiddenInvokeType.None
72 | }
73 | };
74 |
75 | __instance.m_ConfigHideMusic.m_HideMusicObjectMapping[albumUid] = hideMusicInfo;
76 | }
77 | HasUpdate = false;
78 | }
79 | }
80 |
81 | ///
82 | /// Activates hidden charts when the conditions are met
83 | ///
84 | [HarmonyPatch(typeof(SpecialSongManager), nameof(SpecialSongManager.InvokeHideBms))]
85 | internal static class InvokeHideBmsPatch
86 | {
87 | private static readonly Logger Logger = new(nameof(InvokeHideBmsPatch));
88 |
89 | private static bool Prefix(MusicInfo musicInfo, SpecialSongManager __instance)
90 | {
91 | if (!musicInfo.uid.StartsWith($"{AlbumManager.Uid}-") ||
92 | !LoadedHiddens.Contains(musicInfo.uid)) return true;
93 |
94 | var hideBms = __instance.m_HideBmsInfos[musicInfo.uid];
95 | __instance.m_IsInvokeHideDic[hideBms.uid] = true;
96 |
97 | if (!hideBms.extraCondition.Invoke()) return false;
98 |
99 | var album = AlbumManager.LoadedAlbums.FirstOrDefault(kv => kv.Value.Index == musicInfo.musicIndex)
100 | .Value;
101 |
102 | ActivateHidden(hideBms);
103 |
104 | if (album.Info.HideBmsMessage != null)
105 | {
106 | var pnlTips = PnlTipsManager.instance;
107 | var msgBox = pnlTips.GetMessageBox("PnlSpecialsBmsAsk");
108 | msgBox.Show("TIPS", album.Info.HideBmsMessage);
109 | }
110 |
111 | SpecialSongManager.onTriggerHideBmsEvent?.Invoke();
112 | if (album.Info.HideBmsMode == "PRESS") Singleton.instance.Invoke("UI/OnSpecialsMusic");
113 | return false;
114 | }
115 |
116 | private static void ActivateHidden(SpecialSongManager.HideBmsInfo hideBms)
117 | {
118 | if (hideBms == null) return;
119 |
120 | var info = GlobalDataBase.dbMusicTag.GetMusicInfoFromAll(hideBms.uid);
121 | if (hideBms.triggerDiff == 0) return;
122 |
123 | var targetDifficulty = hideBms.triggerDiff;
124 |
125 | if (targetDifficulty == -1)
126 | {
127 | targetDifficulty = 2;
128 |
129 | // Disable the other difficulty options
130 | info.AddMaskValue("difficulty1", "0");
131 | info.AddMaskValue("difficulty3", "0");
132 | }
133 |
134 | var difficultyToHide = "difficulty" + targetDifficulty;
135 | var levelDesignToHide = "levelDesigner" + targetDifficulty;
136 | var difficulty = "?";
137 | var levelDesignStr = info.levelDesigner;
138 | switch (hideBms.m_HideDiff)
139 | {
140 | case 1:
141 | difficulty = info.difficulty1;
142 | levelDesignStr = info.levelDesigner1 ?? info.levelDesigner;
143 | break;
144 | case 2:
145 | difficulty = info.difficulty2;
146 | levelDesignStr = info.levelDesigner2 ?? info.levelDesigner;
147 | break;
148 | case 3:
149 | difficulty = info.difficulty3;
150 | levelDesignStr = info.levelDesigner3 ?? info.levelDesigner;
151 | break;
152 | case 4:
153 | difficulty = info.difficulty4;
154 | levelDesignStr = info.levelDesigner4 ?? info.levelDesigner;
155 | break;
156 | case 5:
157 | difficulty = info.difficulty5;
158 | levelDesignStr = info.levelDesigner5 ?? info.levelDesigner;
159 | break;
160 | }
161 |
162 | info.AddMaskValue(difficultyToHide, difficulty);
163 | info.AddMaskValue(levelDesignToHide, levelDesignStr);
164 | info.SetDifficulty(targetDifficulty, hideBms.m_HideDiff);
165 | }
166 | }
167 |
168 |
169 | [HarmonyPatch(typeof(MusicTagManager), nameof(MusicTagManager.InitDefaultInfo))]
170 | internal class MusicTagPatch
171 | {
172 | private const int HiddenId = 32776;
173 | private static readonly Logger Logger = new(nameof(MusicTagPatch));
174 | internal static bool HasUpdate { get; set; } = true;
175 |
176 | private static void Postfix()
177 | {
178 | if (!HasUpdate) return;
179 |
180 | Il2CppSystem.Collections.Generic.List newHiddenAlbums = new();
181 | foreach (var (_, value) in AlbumManager.LoadedAlbums)
182 | {
183 | if (value.HasDifficulty(DifficultyDefine.hide) && LoadedHiddens.Add(value.Uid))
184 | newHiddenAlbums.Add(value.Uid);
185 | }
186 |
187 | var newHiddenArray =
188 | new Il2CppStringArray(DBMusicTagDefine.s_HiddenLocal.Length + newHiddenAlbums.Count);
189 |
190 | // copying s_HiddenLocal to newHiddenArray
191 | for (var i = 0; i < DBMusicTagDefine.s_HiddenLocal.Length; ++i)
192 | newHiddenArray[i] = DBMusicTagDefine.s_HiddenLocal[i];
193 |
194 | // adding all new charts to newHiddenArray
195 | for (var i = 0; i < newHiddenAlbums.Count; i++)
196 | newHiddenArray[i + DBMusicTagDefine.s_HiddenLocal.Length] = newHiddenAlbums[i];
197 |
198 | // setting the local hidden data to our new one that has custom charts
199 | DBMusicTagDefine.s_HiddenLocal = newHiddenArray;
200 |
201 | // adding that data to the tag
202 | var tagInfo = GlobalDataBase.dbMusicTag.GetAlbumTagInfo(HiddenId);
203 | tagInfo.AddTagUids(newHiddenAlbums);
204 | HasUpdate = false;
205 | }
206 | }
207 | }
208 |
209 | internal enum HiddenInvokeType
210 | {
211 | None = 0,
212 | LongPress = 1,
213 | Toggle = 2,
214 | Click = 3,
215 | Special = 4
216 | }
217 | }
--------------------------------------------------------------------------------
/Patches/LongChartPatch.cs:
--------------------------------------------------------------------------------
1 | using HarmonyLib;
2 | using Il2CppDYUnityLib;
3 |
4 | namespace CustomAlbums.Patches
5 | {
6 | ///
7 | /// Changes the maximum length of a chart from 4 minutes to about 357913 minutes.
8 | /// This does not change the fact that the maximum amount of chart elements is 32767.
9 | ///
10 | [HarmonyPatch(typeof(FixUpdateTimer), "Run")]
11 | internal class LongChartPatch
12 | {
13 | private static void Prefix(FixUpdateTimer __instance)
14 | {
15 | if (__instance.totalTick is >= 24000 and < int.MaxValue) __instance.totalTick = int.MaxValue;
16 | }
17 | }
18 | }
--------------------------------------------------------------------------------
/Patches/MikuSceneSupportPatch.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Utilities;
2 | using HarmonyLib;
3 | using Il2CppGameLogic;
4 |
5 | namespace CustomAlbums.Patches
6 | {
7 | internal class MikuSceneSupportPatch
8 | {
9 |
10 | ///
11 | /// Fixes the purple background issue when using the BMS ID "1X" to switch to the Miku scene.
12 | ///
13 | [HarmonyPatch(typeof(GameMusicScene), nameof(GameMusicScene.SceneFestival))]
14 | internal class MikuFixPatch
15 | {
16 | private static void Finalizer(string sceneFestivalName, ref string __result)
17 | {
18 | var subStr = sceneFestivalName[6..];
19 |
20 | if (subStr.Length <= 2 || !subStr.TryParseAsInt(out var sceneIndex)) return;
21 |
22 | // For some reason, scene change 1X sets scene to scene_010, which is invalid
23 | // Just trim off "scene_" and parse the numbers after the underscore to int again to get 10 instead of 010
24 | __result = $"scene_{sceneIndex}";
25 | }
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Patches/MusicTagManagerPatch.cs:
--------------------------------------------------------------------------------
1 | using Il2Cpp;
2 | using Il2CppAssets.Scripts.Database;
3 | using HarmonyLib;
4 | using Il2CppAssets.Scripts.PeroTools.Commons;
5 | using Il2CppAssets.Scripts.PeroTools.Managers;
6 |
7 | namespace CustomAlbums.Patches
8 | {
9 | internal class MusicTagManagerPatch
10 | {
11 | ///
12 | /// Makes the game think (correctly) that there are not 1000 albums upon loading the tag menu.
13 | /// Increases performance substantially upon loading the tag menu.
14 | ///
15 | [HarmonyPatch(typeof(MusicTagManager), nameof(MusicTagManager.InitDatas))]
16 | internal static class Fix1000AlbumsPatch
17 | {
18 | private static void Postfix()
19 | {
20 | var configObject = Singleton.instance.GetConfigObject();
21 | configObject.m_MaxAlbumUid = configObject.count - 3;
22 | }
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Patches/PackPatch.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Data;
2 | using CustomAlbums.Managers;
3 | using CustomAlbums.Utilities;
4 | using HarmonyLib;
5 | using Il2Cpp;
6 | using Il2CppAssets.Scripts.Database;
7 |
8 | namespace CustomAlbums.Patches
9 | {
10 | internal class PackPatch
11 | {
12 | private static readonly Logger Logger = new(nameof(PackPatch));
13 |
14 | [HarmonyPatch(typeof(LongSongNameController), nameof(LongSongNameController.Refresh), new[] { typeof(string), typeof(bool), typeof(float) })]
15 | internal class RefreshPatch {
16 | private static void SetColor(string colorHex, LongSongNameController instance)
17 | {
18 | var fixedColor = UnityEngine.ColorUtility.TryParseHtmlString(colorHex, out var color) ? color : UnityEngine.Color.white;
19 | if (instance.m_MidSimpleName != null) instance.m_MidSimpleName.color = fixedColor;
20 | if (instance.m_TxtBackupName != null) instance.m_TxtBackupName.color = fixedColor;
21 | if (instance.m_TxtSimpleName != null) instance.m_TxtSimpleName.color = fixedColor;
22 | }
23 |
24 | private static void Prefix(ref string text, ref Pack __state)
25 | {
26 | var currentUid = DataHelper.selectedMusicUid;
27 | if (currentUid == null || !currentUid.StartsWith($"{AlbumManager.Uid}-") || text != AlbumManager.GetCustomAlbumsTitle()) return;
28 |
29 | __state = PackManager.GetPackFromUid(currentUid);
30 | text = __state?.Title ?? text;
31 | }
32 |
33 | private static void Postfix(ref Pack __state, LongSongNameController __instance)
34 | {
35 | if (__instance == null) return;
36 | SetColor(__state?.TitleColorHex, __instance);
37 | }
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Patches/ReportCardPatch.cs:
--------------------------------------------------------------------------------
1 | using System.Globalization;
2 | using System.Reflection;
3 | using CustomAlbums.Managers;
4 | using HarmonyLib;
5 | using Il2Cpp;
6 | using Il2CppAssets.Scripts.Database;
7 | using Il2CppAssets.Scripts.GameCore.Managers;
8 | using Il2CppAssets.Scripts.PeroTools.Commons;
9 | using Il2CppAssets.Scripts.UI.Panels;
10 |
11 | namespace CustomAlbums.Patches
12 | {
13 | [HarmonyPatch(typeof(PnlReportCard), nameof(PnlReportCard.RefreshBestRecord))]
14 | internal static class ReportCardPatch
15 | {
16 | // ReSharper disable once InconsistentNaming
17 | private static bool Prefix(PnlReportCard __instance)
18 | {
19 | var musicInfo = GlobalDataBase.s_DbMusicTag.CurMusicInfo();
20 | if (musicInfo.albumIndex != 999) return true;
21 |
22 | var mapDifficulty = GlobalDataBase.s_DbBattleStage.m_MapDifficulty;
23 | var curMusicBestRankOrder = Singleton.instance.GetCurMusicBestRankOrder();
24 |
25 | var album = AlbumManager.GetByUid(musicInfo.uid);
26 | if (album == null) return false;
27 |
28 | var save = SaveManager.SaveData.Highest[album.AlbumName][mapDifficulty];
29 | if (save == null) return false;
30 |
31 | __instance.RefreshRecord(musicInfo, mapDifficulty, save.Score, save.Combo, save.AccuracyStr, save.Evaluate, save.Clear.ToString(CultureInfo.InvariantCulture), curMusicBestRankOrder);
32 | return false;
33 | }
34 | }
35 |
36 | [HarmonyPatch]
37 | internal static class TogglePatch
38 | {
39 | private static IEnumerable TargetMethods()
40 | {
41 | return new[] { nameof(PnlPreparation.OnDiffTglChanged), nameof(PnlPreparation.OnEnable) }
42 | .Select(methodName => typeof(PnlPreparation).GetMethod(methodName))
43 | .ToArray();
44 | }
45 | // ReSharper disable once InconsistentNaming
46 | private static void Postfix(PnlPreparation __instance)
47 | {
48 | var musicInfo = GlobalDataBase.s_DbMusicTag.CurMusicInfo();
49 | if (musicInfo.albumIndex != 999) return;
50 |
51 | var mapDifficulty = GlobalDataBase.s_DbBattleStage.m_MapDifficulty;
52 | var gameObject = __instance.btnDownloadReport.gameObject;
53 |
54 | var album = AlbumManager.GetByUid(musicInfo.uid);
55 | if (album == null)
56 | {
57 | gameObject.SetActive(false);
58 | return;
59 | }
60 |
61 | if (!SaveManager.SaveData.Highest.TryGetValue(album.AlbumName, out var chart))
62 | {
63 | gameObject.SetActive(false);
64 | return;
65 | }
66 |
67 | if (!chart.ContainsKey(mapDifficulty))
68 | {
69 | gameObject.SetActive(false);
70 | return;
71 | }
72 |
73 | gameObject.SetActive(true);
74 | }
75 | }
76 | }
77 |
78 |
--------------------------------------------------------------------------------
/Patches/SceneEggPatch.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Data;
2 | using CustomAlbums.Managers;
3 | using CustomAlbums.Utilities;
4 | using HarmonyLib;
5 | using Il2Cpp;
6 | using Il2CppAssets.Scripts.Common.SceneEgg;
7 | using Il2CppAssets.Scripts.Database;
8 | using Il2CppAssets.Scripts.TouhouLogic;
9 | using Il2CppGameLogic;
10 | using Il2CppPeroPeroGames.GlobalDefines;
11 | using static CustomAlbums.Data.SceneEgg;
12 |
13 | namespace CustomAlbums.Patches
14 | {
15 | internal class SceneEggPatch
16 | {
17 | private static readonly Logger Logger = new(nameof(SceneEggPatch));
18 |
19 | internal static bool IgnoreSceneEggs(out Album outAlbum, params SceneEggs[] sceneEggs)
20 | {
21 | outAlbum = null;
22 | // If the chart is not custom then leave
23 | var uid = DataHelper.selectedMusicUid;
24 | if (!uid.StartsWith($"{AlbumManager.Uid}-")) return true;
25 |
26 | // If the album doesn't exist (?) or if there are no SceneEggs or if it's christmas SceneEgg (not really a SceneEgg) then leave
27 | var album = AlbumManager.GetByUid(uid);
28 | if (album is null) return true;
29 |
30 | outAlbum = album;
31 | return sceneEggs.Any(sceneEgg => sceneEgg == album.Info.SceneEgg);
32 | }
33 |
34 | ///
35 | /// Adds support for SceneEggs.
36 | ///
37 | [HarmonyPatch(typeof(SceneEggAbstractController), nameof(SceneEggAbstractController.SceneEggHandle))]
38 | internal class ControllerPatch
39 | {
40 | private static void Prefix(Il2CppSystem.Collections.Generic.List sceneEggIdsBuffer)
41 | {
42 | // Return if there are no scene eggs or if the scene eggs have special logic
43 | if (IgnoreSceneEggs(out var album, SceneEggs.None, SceneEggs.Christmas, SceneEggs.BadApple)) return;
44 |
45 | // Adds the scene egg to the buffer
46 | sceneEggIdsBuffer.Add((int)album.Info.SceneEgg);
47 | Logger.Msg("Added SceneEgg " + Enum.GetName(typeof(SceneEggs), album.Info.SceneEgg));
48 |
49 | // Removes all scene eggs from the buffer that are not the one that was added
50 | // This prevents a hierarchical issue where character choice would be used over chart choice
51 | sceneEggIdsBuffer.RemoveAll((Il2CppSystem.Predicate)(eggId => eggId != (int)album.Info.SceneEgg));
52 | }
53 | }
54 |
55 | ///
56 | /// Makes scene_05 be scene_05_christmas if the Christmas SceneEgg is enabled.
57 | ///
58 | [HarmonyPatch(typeof(GameMusicScene), nameof(GameMusicScene.SceneFestival))]
59 | internal class SceneFestivalPatch
60 | {
61 | private static bool Prefix(string sceneFestivalName, ref string __result)
62 | {
63 | // If the scene is not scene_05 or scene_08 then there is no Christmas
64 | if (sceneFestivalName != "scene_05") return true;
65 |
66 | // Ignore the actual SceneEggs
67 | if (IgnoreSceneEggs(out _, SceneEggs.Arknights, SceneEggs.Cytus, SceneEggs.None,
68 | SceneEggs.Queen, SceneEggs.Touhou, SceneEggs.Wacca, SceneEggs.Miku, SceneEggs.BadApple, SceneEggs.RinLen)) return true;
69 |
70 | if (sceneFestivalName == "scene_05") __result = "scene_05_christmas";
71 | return false;
72 | }
73 | }
74 |
75 | ///
76 | /// Makes the boss be the christmas boss if the Christmas SceneEgg is enabled.
77 | ///
78 | [HarmonyPatch(typeof(Boss), nameof(Boss.BossFestival))]
79 | internal class BossFestivalPatch
80 | {
81 | private static bool Prefix(string bossFestivalName, ref string __result)
82 | {
83 | // If the boss is not 0501_boss then there is no Christmas
84 | if (bossFestivalName != "0501_boss") return true;
85 | if (IgnoreSceneEggs(out _, SceneEggs.Arknights, SceneEggs.Cytus, SceneEggs.None,
86 | SceneEggs.Queen, SceneEggs.Touhou, SceneEggs.Wacca, SceneEggs.Miku, SceneEggs.BadApple, SceneEggs.RinLen)) return true;
87 |
88 | __result = "0501_boss_christmas";
89 | return false;
90 | }
91 | }
92 |
93 | ///
94 | /// Makes the game think (temporarily) that the chart is Bad Apple when the BadApple SceneEgg is enabled to load all
95 | /// the assets properly.
96 | ///
97 | [HarmonyPatch(typeof(DBTouhou), nameof(DBTouhou.AwakeInit))]
98 | internal class BadApplePatch
99 | {
100 | private static void Postfix()
101 | {
102 | if (IgnoreSceneEggs(out _, SceneEggs.Arknights, SceneEggs.Cytus, SceneEggs.None,
103 | SceneEggs.Queen, SceneEggs.Touhou, SceneEggs.Wacca, SceneEggs.Miku, SceneEggs.Christmas, SceneEggs.RinLen, SceneEggs.BlueArchive)) return;
104 |
105 | GlobalDataBase.dbTouhou.isBadApple = true;
106 |
107 | GlobalDataBase.s_DbOther.m_HpFx = TouhouLogic.ReplaceBadAppleString("fx_hp_ground");
108 | GlobalDataBase.s_DbOther.m_MusicFx = TouhouLogic.ReplaceBadAppleString("fx_score_ground");
109 | GlobalDataBase.s_DbOther.m_DustFx = TouhouLogic.ReplaceBadAppleString("dust_fx");
110 | }
111 | }
112 |
113 |
114 | ///
115 | /// Makes the game think that the chart is a RinLen chart when the RinLen SceneEgg is enabled to load all
116 | /// the assets properly.
117 | ///
118 | [HarmonyPatch(typeof(DBMusicTagDefine), nameof(DBMusicTagDefine.IsRinLenEggSong))]
119 | internal class RinLenPatch
120 | {
121 | private static void Postfix(string uid, ref bool __result)
122 | {
123 | if (uid.StartsWith($"{AlbumManager.Uid}-") && AlbumManager.GetByUid(uid).Info.SceneEgg is SceneEggs.RinLen)
124 | {
125 | __result = true;
126 | }
127 | }
128 | }
129 | }
130 | }
--------------------------------------------------------------------------------
/Patches/SilenceLogPatch.cs:
--------------------------------------------------------------------------------
1 | using HarmonyLib;
2 | using Il2CppPeroTools2.Log;
3 |
4 | namespace CustomAlbums.Patches
5 | {
6 | internal class SilenceLogPatch
7 | {
8 | ///
9 | /// Disables log write-to-file if it is set in MelonPreferences (it is by default).
10 | ///
11 | [HarmonyPatch(typeof(PeroLogConfig), nameof(PeroLogConfig.instance), MethodType.Getter)]
12 | internal class LoadConfigPatch
13 | {
14 | private static void Postfix(ref PeroLogConfig __result)
15 | {
16 | if (ModSettings.LoggingToFileEnabled) return;
17 | __result.m_IsLogToFile = false;
18 | }
19 | }
20 |
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Patches/TagPatch.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Managers;
2 | using CustomAlbums.Utilities;
3 | using HarmonyLib;
4 | using Il2Cpp;
5 | using Il2CppAssets.Scripts.Database;
6 | using Il2CppAssets.Scripts.Database.DataClass;
7 | using static Il2CppAssets.Scripts.Database.DBConfigCustomTags;
8 |
9 | namespace CustomAlbums.Patches
10 | {
11 | internal class TagPatch
12 | {
13 | [HarmonyPatch(typeof(MusicTagManager), nameof(MusicTagManager.InitAlbumTagInfo))]
14 | internal class MusicTagPatch
15 | {
16 | private static void Postfix()
17 | {
18 | var info = new AlbumTagInfo
19 | {
20 | name = AlbumManager.Languages["English"],
21 | tagUid = "tag-custom-albums",
22 | iconName = "IconCustomAlbums"
23 | };
24 | var customInfo = new CustomTagInfo
25 | {
26 | tag_name = AlbumManager.Languages.ToIl2Cpp(),
27 | tag_picture = "https://cdn.mdmc.moe/static/melon.png",
28 | music_list = AlbumManager.GetAllUid().ToIl2Cpp()
29 | };
30 |
31 | info.InitCustomTagInfo(customInfo);
32 |
33 | GlobalDataBase.dbMusicTag.m_AlbumTagsSort.Insert(GlobalDataBase.dbMusicTag.m_AlbumTagsSort.Count - 4,
34 | AlbumManager.Uid);
35 | GlobalDataBase.dbMusicTag.AddAlbumTagData(AlbumManager.Uid, info);
36 | }
37 | }
38 | }
39 | }
--------------------------------------------------------------------------------
/Patches/TreeItemPatch.cs:
--------------------------------------------------------------------------------
1 | using Il2Cpp;
2 | using CustomAlbums.Utilities;
3 | using HarmonyLib;
4 |
5 | namespace CustomAlbums.Patches
6 | {
7 | internal class TreeItemPatch
8 | {
9 | // TODO: Finish "Album" support
10 | private static readonly Logger Logger = new(nameof(TreeItemPatch));
11 |
12 | [HarmonyPatch(typeof(PnlMusicTagItem), nameof(PnlMusicTagItem.OnTagClicked))]
13 | internal class OnMusicTagClickedPatch
14 | {
15 | private static void Prefix(int tagIndex, PnlMusicTagItem __instance)
16 | {
17 | // STUB
18 | }
19 | }
20 |
21 | [HarmonyPatch(typeof(PnlMusicTagItem), nameof(PnlMusicTagItem.Enable))]
22 | internal class EnablePatch
23 | {
24 | private static void Prefix(PnlMusicTagItem __instance)
25 | {
26 | // STUB
27 | }
28 | }
29 |
30 | [HarmonyPatch(typeof(PnlMusicTagItem), nameof(PnlMusicTagItem.AddDataToMgr))]
31 | internal class AddDataPatch
32 | {
33 | // STUB
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/Patches/WebApiPatch.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Managers;
2 | using CustomAlbums.Utilities;
3 | using HarmonyLib;
4 | using Il2CppAccount;
5 | using Il2CppAssets.Scripts.Database;
6 | using Object = Il2CppSystem.Object;
7 |
8 | namespace CustomAlbums.Patches;
9 |
10 | internal class WebApiPatch
11 | {
12 | ///
13 | /// Patches the SendToUrl method to not attempt to send stats or high scores of custom charts to the official server.
14 | ///
15 | [HarmonyPatch(typeof(GameAccountSystem), nameof(GameAccountSystem.SendToUrl))]
16 | internal class SendToUrlPatch
17 | {
18 | private static readonly Logger Logger = new("WebApiPatch");
19 |
20 | private static bool Prefix(string url, string method,
21 | Il2CppSystem.Collections.Generic.Dictionary datas)
22 | {
23 | switch (url)
24 | {
25 | case "statistics/pc-play-statistics-feedback":
26 | if (datas["music_uid"].ToString().StartsWith($"{AlbumManager.Uid}"))
27 | {
28 | Logger.Msg("Blocked play feedback upload: " + datas["music_uid"].ToString());
29 | return false;
30 | }
31 |
32 | break;
33 | case "musedash/v2/pcleaderboard/high-score":
34 | if (GlobalDataBase.dbBattleStage.musicUid.StartsWith($"{AlbumManager.Uid}"))
35 | {
36 | Logger.Msg("Blocked high score upload v2: " + GlobalDataBase.dbBattleStage.musicUid);
37 | return false;
38 | }
39 |
40 | break;
41 | case "musedash/v3/pcleaderboard/high-score":
42 | if (GlobalDataBase.dbBattleStage.musicUid.StartsWith($"{AlbumManager.Uid}"))
43 | {
44 | Logger.Msg("Blocked high score upload v3: " + GlobalDataBase.dbBattleStage.musicUid);
45 | return false;
46 | }
47 |
48 | break;
49 | }
50 |
51 | return true;
52 | }
53 | }
54 | }
--------------------------------------------------------------------------------
/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 | using MelonLoader;
4 | using Main = CustomAlbums.Main;
5 |
6 | [assembly: AssemblyTitle(Main.MelonName)]
7 | [assembly: AssemblyDescription("")]
8 | [assembly: AssemblyConfiguration("")]
9 | [assembly: AssemblyCompany("")]
10 | [assembly: AssemblyProduct(Main.MelonName)]
11 | [assembly: AssemblyCopyright("Copyright © Muse Dash Modding Community 2025")]
12 | [assembly: AssemblyTrademark("")]
13 | [assembly: AssemblyCulture("")]
14 |
15 | [assembly: ComVisible(false)]
16 |
17 | [assembly: Guid("8ea4daf8-4ffd-465f-9b07-ac6925c6453f")]
18 |
19 | [assembly: AssemblyVersion($"{Main.MelonVersion}.0")]
20 | [assembly: AssemblyFileVersion($"{Main.MelonVersion}.0")]
21 | [assembly: MelonInfo(typeof(Main), Main.MelonName, Main.MelonVersion, Main.MelonAuthor)]
22 | [assembly: MelonGame("PeroPeroGames", "MuseDash")]
23 | [assembly: MelonColor(255, 0, 255, 150)]
24 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://discord.gg/mdmc)
2 | # CustomAlbums
3 | CustomAlbums is a MelonLoader mod for peropero's Muse Dash. It allows the loading of custom songs in MDM format into Muse Dash.
4 | This mod was written from the ground-up by [MDMC](https://github.com/MDMods), so joining the Discord server is the best way to reach us for help and information.
5 | ## Usage
6 | - Install MelonLoader into Muse Dash based on the dependency listed below
7 | - Download the [latest release](https://github.com/MDMods/CustomAlbums/releases/latest) of CustomAlbums and place it in your Mods folder
8 | - Place any custom chart (.mdm) files into the generated `Custom_Albums` folder and enjoy
9 | ## Dependencies
10 | - [MelonLoader v0.6.1](https://github.com/LavaGang/MelonLoader/releases/tag/v0.6.1)
11 | - [Muse Dash on Steam](https://store.steampowered.com/app/774171/Muse_Dash/)
12 | - [Muse Plus DLC on Steam](https://store.steampowered.com/app/2593750/Muse_Dash__Muse_Plus/) (or Just as Planned)
13 | ## Building
14 | - Install MelonLoader into Muse Dash and run it once
15 | - Run SetPath.cmd as administrator and follow the instructions
16 | - Build tested with Visual Studio 2022, MelonLoader v0.6.1, Muse Dash v5.3.0
17 | - Will NOT work on MelonLoader v0.6.2. Newer versions might work, but v0.6.1 is recommended
18 | ## Credits & Contributions
19 | - [ALLMarvelous](https://github.com/ALLMarvelous) - Lead Developer
20 | - [Mr. Talk](https://github.com/SB15-MD) - Lead Developer
21 | - [gamrguy](https://github.com/gamrguy) - Original Maintainer (Feb 2022 - Jul 2023)
22 | - [某10](https://github.com/mo10) - Original Developer (Feb 2021 - Dec 2021)
23 | ## Disclaimer
24 | This repository and its contributors maintain no affiliation with Muse Dash, PeroPeroGames (peropero Ltd.), hasuhasu, or any associated entities.
25 |
--------------------------------------------------------------------------------
/SetPath.cmd:
--------------------------------------------------------------------------------
1 | @ECHO OFF
2 | @REM This script must run as administrator, let user elevate
3 | NET SESSION >NUL 2>&1
4 | IF %ERRORLEVEL% EQU 0 (
5 | GOTO AUTH
6 | ) ELSE (
7 | ECHO This script must be run as adminstrator.
8 | PAUSE
9 | EXIT /B
10 | )
11 |
12 | @REM Sets the environment variable so we can use Directory.Build.Props
13 | :AUTH
14 | SET /P "directory=Enter your Muse Dash directory in quotations (should end in \Muse Dash): "
15 | SETX MD_DIRECTORY %directory%
16 | IF %ERRORLEVEL% NEQ 0 (
17 | ECHO An error occurred.
18 | ) ELSE (
19 | ECHO Directory set successfully.
20 | )
21 | PAUSE
22 | EXIT /B
23 |
--------------------------------------------------------------------------------
/Utilities/Backup.cs:
--------------------------------------------------------------------------------
1 | using System.IO.Compression;
2 | using System.Text.Json;
3 | using System.Text.Json.Nodes;
4 | using CustomAlbums.Data;
5 | using CustomAlbums.Managers;
6 | using Il2CppAssets.Scripts.PeroTools.Commons;
7 | using Il2CppAssets.Scripts.PeroTools.Nice.Datas;
8 | using Il2CppAssets.Scripts.PeroTools.Nice.Interface;
9 | using Il2CppInterop.Runtime.InteropTypes.Arrays;
10 |
11 | namespace CustomAlbums.Utilities
12 | {
13 | internal class Backup
14 | {
15 | private static readonly Logger Logger = new(nameof(Backup));
16 | private static string BackupPath => Path.Combine(Directory.GetCurrentDirectory(), "UserData/Backups");
17 | private static string BackupVanilla => Path.Combine(BackupPath, "Vanilla.sav.bak");
18 | private static string BackupVanillaDebug => Path.Combine(BackupPath, "VanillaDebug.json");
19 | private static string BackupCustom => Path.Combine(BackupPath, "CustomAlbums.json.bak");
20 | private static string BackupZip => Path.Combine(BackupPath, "Backups.zip");
21 | private static TimeSpan MaxBackupTime => TimeSpan.FromDays(30);
22 |
23 | internal static void InitBackups()
24 | {
25 | Directory.CreateDirectory(BackupPath);
26 |
27 | CompressBackups();
28 | CreateBackup(BackupVanilla, Singleton.instance.ToBytes());
29 | CreateBackup(BackupVanillaDebug,
30 | JsonSerializer.Serialize(ToJsonDict(Singleton.instance.datas)));
31 | CreateBackup(BackupCustom, SaveManager.SaveData);
32 | ClearOldBackups();
33 | }
34 |
35 | private static void CreateBackup(string filePath, object data)
36 | {
37 | try
38 | {
39 | if (data is null)
40 | {
41 | Logger.Warning("Could not create backup of null data!");
42 | return;
43 | }
44 |
45 | var wroteFile = false;
46 |
47 | switch (data)
48 | {
49 | case string str:
50 | File.WriteAllText(filePath, str);
51 | wroteFile = true;
52 | break;
53 |
54 | case byte[] bytes:
55 | File.WriteAllBytes(filePath, bytes);
56 | wroteFile = true;
57 | break;
58 |
59 | case Il2CppStructArray ilBytes:
60 | File.WriteAllBytes(filePath, ilBytes);
61 | wroteFile = true;
62 | break;
63 |
64 | case CustomAlbumsSave save:
65 | File.WriteAllText(filePath, JsonSerializer.Serialize(save));
66 | wroteFile = true;
67 | break;
68 |
69 | default:
70 | Logger.Warning("Could not create backup for unsupported data type " + data.GetType().FullName);
71 | break;
72 | }
73 |
74 | if (wroteFile) Logger.Msg($"Saved backup: {filePath}");
75 | }
76 | catch (Exception e)
77 | {
78 | Logger.Error("Backup failed: " + e);
79 | }
80 | }
81 |
82 | private static void ClearOldBackups()
83 | {
84 | try
85 | {
86 | var backups = Directory.EnumerateFiles(BackupPath).ToList();
87 | foreach (var backup in from backup in backups
88 | let backupDate = Directory.GetLastWriteTime(backup)
89 | where (DateTime.Now - backupDate).Duration() > MaxBackupTime.Duration()
90 | select backup)
91 | {
92 | Logger.Msg("Removing old backup: " + backup);
93 | File.Delete(backup);
94 | }
95 |
96 | if (!File.Exists(BackupZip)) return;
97 |
98 | using var zip = ZipFile.Open(BackupZip, ZipArchiveMode.Update);
99 | foreach (var entry in zip.Entries.ToList().Where(entry =>
100 | (DateTime.Now - entry.LastWriteTime).Duration() > MaxBackupTime.Duration()))
101 | {
102 | Logger.Msg("Removing compressed old backup: " + entry.Name);
103 | zip.GetEntry(entry.Name)?.Delete();
104 | }
105 | }
106 | catch (Exception e)
107 | {
108 | Logger.Error("Clearing old backups failed: " + e);
109 | }
110 | }
111 |
112 | private static void CompressBackups()
113 | {
114 | try
115 | {
116 | using var zip = ZipFile.Open(BackupZip, ZipArchiveMode.Update);
117 |
118 | var filesList = Directory.EnumerateFiles(BackupPath).Where(name => Path.GetExtension(name) != ".zip")
119 | .ToList();
120 | if (filesList.Any())
121 | filesList.ForEach(entry =>
122 | {
123 | var newFileName = Directory.GetLastWriteTime(entry).ToString("yyyy_MM_dd_H_mm_ss-") +
124 | Path.GetFileName(Path.GetFileName(entry));
125 | zip.CreateEntryFromFile(entry, newFileName);
126 | File.Delete(entry);
127 | });
128 | }
129 | catch (Exception e)
130 | {
131 | Logger.Error("Compressing previous backups failed: " + e);
132 | }
133 | }
134 |
135 | private static Dictionary ToJsonDict(
136 | Il2CppSystem.Collections.Generic.Dictionary dataList)
137 | {
138 | var dictionary = new Dictionary();
139 | foreach (var keyValuePair in dataList)
140 | {
141 | var singletonDataObject = keyValuePair.Value?.TryCast();
142 | if (singletonDataObject != null)
143 | dictionary.Add(keyValuePair.Key, Json.Deserialize(singletonDataObject.ToJson()));
144 | }
145 |
146 | return dictionary;
147 | }
148 | }
149 | }
--------------------------------------------------------------------------------
/Utilities/ConfigDataExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Nodes;
2 | using Il2CppGameLogic;
3 | using Il2CppPeroPeroGames.GlobalDefines;
4 |
5 | namespace CustomAlbums.Utilities
6 | {
7 | public static class ConfigDataExtensions
8 | {
9 | public static bool IsAprilFools(this NoteConfigData config)
10 | {
11 | return config.prefab_name.EndsWith("_fool");
12 | }
13 |
14 | public static NoteType GetNoteType(this NoteConfigData config)
15 | {
16 | return (NoteType)config.type;
17 | }
18 |
19 | public static bool IsAnyScene(this NoteConfigData config)
20 | {
21 | return config.scene == "0";
22 | }
23 |
24 | public static bool IsAnyPathway(this NoteConfigData config)
25 | {
26 | return config.pathway == 0 && config.score == 0 && config.fever == 0 && config.damage == 0;
27 | }
28 |
29 | public static bool IsPhase2BossGear(this NoteConfigData config)
30 | {
31 | return config.GetNoteType() == NoteType.Block && config.boss_action.EndsWith("_atk_2");
32 | }
33 |
34 | public static bool IsAnySpeed(this NoteConfigData config)
35 | {
36 | return config.GetNoteType() == NoteType.Boss
37 | || config.GetNoteType() == NoteType.None
38 | || config.ibms_id == "16"
39 | || config.ibms_id == "17";
40 | }
41 |
42 | public static MusicConfigData ToMusicConfigData(this JsonNode node)
43 | {
44 | var config = Interop.CreateTypeValue();
45 | config.id = node["id"]?.GetValue() ?? -1;
46 | config.time = node["time"].GetValueAsIl2CppDecimal();
47 | config.note_uid = node["note_uid"]?.GetValue() ?? string.Empty;
48 | config.length = node["length"].GetValueAsIl2CppDecimal();
49 | config.pathway = node["pathway"]?.GetValue() ?? 0;
50 | config.blood = node["blood"]?.GetValue() ?? false;
51 |
52 | return config;
53 | }
54 | }
55 | }
--------------------------------------------------------------------------------
/Utilities/Converters.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json;
2 | using System.Text.Json.Serialization;
3 |
4 | namespace CustomAlbums.Utilities
5 | {
6 | internal class Converters
7 | {
8 | public class NumberConverter : JsonConverter
9 | {
10 | public override string Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
11 | {
12 | return reader.TokenType is JsonTokenType.Number ? reader.GetInt32().ToString() : reader.GetString();
13 | }
14 |
15 | public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
16 | {
17 | writer.WriteStringValue(value);
18 | }
19 | }
20 | }
21 | }
--------------------------------------------------------------------------------
/Utilities/DataExtensions.cs:
--------------------------------------------------------------------------------
1 | using CustomAlbums.Data;
2 | using Il2CppAssets.Scripts.PeroTools.Nice.Interface;
3 |
4 | namespace CustomAlbums.Utilities
5 | {
6 | internal static class DataExtensions
7 | {
8 | ///
9 | /// Gets the uid field of the IData object.
10 | ///
11 | /// The IData object.
12 | /// The uid or an empty string if not found.
13 | public static string GetUid(this IData data)
14 | {
15 | var uidField = data.fields["uid"];
16 | return uidField == null ? string.Empty : uidField.GetResult();
17 | }
18 |
19 | ///
20 | /// Gets the index of a chart in an IData list by its uid and difficulty.
21 | ///
22 | /// The IData list.
23 | /// The uid of the chart.
24 | /// The difficulty of the chart.
25 | /// The index of the chart in the list, or -1 if not found.
26 | public static int GetIndexByUid(this Il2CppSystem.Collections.Generic.List dataList, string uid, int difficulty)
27 | {
28 | var i = 0;
29 |
30 | // For loop doesn't work here
31 | foreach (var data in dataList)
32 | {
33 | if (data.GetUid() == $"{uid}_{difficulty}")
34 | {
35 | return i;
36 | }
37 |
38 | i++;
39 | }
40 |
41 | return -1;
42 | }
43 |
44 | ///
45 | /// Gets the IData object from a list by its uid and difficulty.
46 | ///
47 | /// The IData list.
48 | /// The uid of the chart.
49 | /// The difficulty of the chart.
50 | /// The IData object, or null if not found.
51 | public static IData GetIDataByUid(this Il2CppSystem.Collections.Generic.List dataList, string uid, int difficulty)
52 | {
53 | foreach (var data in dataList)
54 | {
55 | if (data.GetUid() == $"{uid}_{difficulty}")
56 | {
57 | return data;
58 | }
59 | }
60 |
61 | return null;
62 | }
63 |
64 | public static ChartSave ToChartSave(this IData data)
65 | {
66 | return new ChartSave
67 | {
68 | Evaluate = data.fields["evaluate"].GetResult(),
69 | Score = data.fields["score"].GetResult(),
70 | Combo = data.fields["combo"].GetResult(),
71 | Accuracy = data.fields["accuracy"].GetResult(),
72 | AccuracyStr = data.fields["accuracyStr"].GetResult(),
73 | Clear = data.fields["clear"].GetResult()
74 | };
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/Utilities/Debug.cs:
--------------------------------------------------------------------------------
1 | using HarmonyLib;
2 |
3 | namespace CustomAlbums.Utilities
4 | {
5 | internal class Debug
6 | {
7 | [HarmonyPatch("Il2CppInterop.HarmonySupport.Il2CppDetourMethodPatcher", "ReportException")]
8 | internal static class Il2CppDetourMethodPatcherPatch
9 | {
10 | private static readonly Logger Logger = new(nameof(Il2CppDetourMethodPatcherPatch));
11 |
12 | private static bool Prefix(Exception ex)
13 | {
14 | Logger.Msg("During invoking native->managed trampoline: " + ex);
15 | return false;
16 | }
17 | }
18 | }
19 | }
--------------------------------------------------------------------------------
/Utilities/Formatting.cs:
--------------------------------------------------------------------------------
1 | using System.Globalization;
2 |
3 | namespace CustomAlbums.Utilities;
4 |
5 | public static class Formatting {
6 | public static int ParseAsInt(this string value)
7 | => int.Parse(value, NumberStyles.Number, CultureInfo.InvariantCulture);
8 |
9 | public static float ParseAsFloat(this string value)
10 | => float.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture);
11 |
12 | public static decimal ParseAsDecimal(this string value)
13 | => decimal.Parse(value, NumberStyles.Number, CultureInfo.InvariantCulture);
14 |
15 | public static bool TryParseAsInt(this string value, out int result)
16 | => int.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out result);
17 |
18 | public static bool TryParseAsFloat(this string value, out float result)
19 | => float.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out result);
20 |
21 | public static bool TryParseAsDecimal(this string value, out decimal result)
22 | => decimal.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out result);
23 |
24 | public static string ToStringInvariant(this int value, string format = "")
25 | => value.ToString(format, CultureInfo.InvariantCulture);
26 |
27 | public static string ToStringInvariant(this float value, string format = "")
28 | => value.ToString(format, CultureInfo.InvariantCulture);
29 |
30 | public static string ToStringInvariant(this decimal value, string format = "")
31 | => value.ToString(format, CultureInfo.InvariantCulture);
32 | }
--------------------------------------------------------------------------------
/Utilities/Il2CppExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.ObjectModel;
2 |
3 | namespace CustomAlbums.Utilities
4 | {
5 | public static class Il2CppExtensions
6 | {
7 | public static Il2CppSystem.Collections.Generic.List ToIl2Cpp(this List list)
8 | {
9 | var il2Cpp = new Il2CppSystem.Collections.Generic.List(list.Count);
10 | foreach (var item in list) il2Cpp.Add(item);
11 |
12 | return il2Cpp;
13 | }
14 |
15 | public static Il2CppSystem.Collections.Generic.List ToIl2Cpp(this IEnumerable list)
16 | {
17 | var array = list.ToArray();
18 | var il2Cpp = new Il2CppSystem.Collections.Generic.List(array.Length);
19 | foreach (var item in array) il2Cpp.Add(item);
20 |
21 | return il2Cpp;
22 | }
23 |
24 | public static Il2CppSystem.Collections.Generic.List ToIl2Cpp(this ReadOnlyCollection collection)
25 | {
26 | var il2Cpp = new Il2CppSystem.Collections.Generic.List(collection.Count);
27 | foreach (var item in collection) il2Cpp.Add(item);
28 |
29 | return il2Cpp;
30 | }
31 |
32 | public static Il2CppSystem.Collections.Generic.Dictionary ToIl2Cpp(
33 | this Dictionary dictionary)
34 | {
35 | var il2Cpp = new Il2CppSystem.Collections.Generic.Dictionary(dictionary.Count);
36 | foreach (var (key, value) in dictionary) il2Cpp.Add(key, value);
37 |
38 | return il2Cpp;
39 | }
40 |
41 | public static List ToManaged(this Il2CppSystem.Collections.Generic.List list)
42 | {
43 | var managed = new List(list.Count);
44 | foreach (var item in list) managed.Add(item);
45 |
46 | return managed;
47 | }
48 |
49 | public static Dictionary ToManaged(
50 | this Il2CppSystem.Collections.Generic.Dictionary dictionary)
51 | {
52 | var managed = new Dictionary(dictionary.Count);
53 | foreach (var entry in dictionary) managed.Add(entry.Key, entry.Value);
54 |
55 | return managed;
56 | }
57 |
58 | public static void AddManagedRange(this Il2CppSystem.Collections.Generic.List il2cpp,
59 | IEnumerable managed)
60 | {
61 | var array = managed.ToArray();
62 | il2cpp.Capacity += array.Length;
63 | foreach (var item in array) il2cpp.Add(item);
64 | }
65 |
66 | public static bool TryGetValuePossibleNullKey(
67 | this Il2CppSystem.Collections.Generic.Dictionary dict, TKey key, out TValue outValue)
68 | {
69 | outValue = default;
70 | if (key == null || !dict.ContainsKey(key)) return false;
71 | outValue = dict[key];
72 | return true;
73 | }
74 | }
75 | }
--------------------------------------------------------------------------------
/Utilities/Interop.cs:
--------------------------------------------------------------------------------
1 | using Il2CppInterop.Runtime;
2 |
3 | namespace CustomAlbums.Utilities
4 | {
5 | public class Interop
6 | {
7 | ///
8 | /// A workaround to a memory corruption issue of creating Il2CppSystem.TypeValue types using C#'s new operator.
9 | /// This will likely be deleted/become deprecated in the future.
10 | ///
11 | /// An Il2CppSystem.TypeValue type
12 | /// A new object of type T
13 | public static T CreateTypeValue()
14 | {
15 | return (T)Activator.CreateInstance(typeof(T),
16 | IL2CPP.il2cpp_object_new(Il2CppClassPointerStore.NativeClassPtr));
17 | }
18 | }
19 | }
--------------------------------------------------------------------------------
/Utilities/Json.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json;
2 | using System.Text.Json.Nodes;
3 | using System.Text.Json.Serialization;
4 | using Il2CppNewtonsoft.Json;
5 | using Decimal = Il2CppSystem.Decimal;
6 | using JsonSerializer = System.Text.Json.JsonSerializer;
7 |
8 | namespace CustomAlbums.Utilities
9 | {
10 | public static class Json
11 | {
12 | private static readonly JsonSerializerOptions DeserializeOptions = new()
13 | {
14 | PropertyNameCaseInsensitive = true,
15 | AllowTrailingCommas = true,
16 |
17 | // God this sucks
18 | ReadCommentHandling = JsonCommentHandling.Skip,
19 |
20 | Converters =
21 | {
22 | new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)
23 | }
24 | };
25 |
26 | public static T Deserialize(string json)
27 | {
28 | return JsonSerializer.Deserialize(json, DeserializeOptions);
29 | }
30 |
31 | public static T Deserialize(Stream stream)
32 | {
33 | return JsonSerializer.Deserialize(stream, DeserializeOptions);
34 | }
35 |
36 | public static JsonArray ToJsonArray(this IEnumerable