-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAnalogueOSLibraryImageGenerator.ps1
More file actions
1656 lines (1396 loc) · 56 KB
/
AnalogueOSLibraryImageGenerator.ps1
File metadata and controls
1656 lines (1396 loc) · 56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
[CmdletBinding()]
Param(
[switch]$OutputConvertedFiles,
[ValidateSet('Minimal', 'Extra', 'Noisy')]
[string]$Verbosity = 'Minimal' # Dev note: don't bother writing checks for 'Minimal'
)
#Requires -PSEdition Desktop
#Requires -Version 5.1
# Variables
$ErrorActionPreference = 'Stop'
$tempWorkspace = if ( $env:USERPROFILE ) {
"$env:USERPROFILE\.aostool"
}
else {
"$env:HOME\.aostool"
}
$tempZipPath = "$tempWorkspace\console.zip"
$tempExtractionPath = "$tempWorkspace"
$tempConversionRootDir = "$tempWorkspace"
$tempConversionBoxArtsDir = "$tempConversionRootDir\conv\BoxArts"
$tempConversionSnapsDir = "$tempConversionRootDir\conv\Snaps"
$tempConversionTitlesDir = "$tempConversionRootDir\conv\Titles"
$libretro_base = 'https://github.com/libretro-thumbnails'
$libretro_repo = "$libretro_base/libretro-thumbnails"
$datomatic_site = 'https://datomatic.no-intro.org'
# Titles for special handling during conversion
$specialCaseTitles = @'
# GBC
Castlevania - The Adventure DX (USA)::Romhack
Castlevania II - Belmont's Revenge DX (USA)::Romhack
Donkey Kong Land - DX (USA)::Romhack
Donkey Kong Land 2 - DX (USA)::Romhack
Donkey Kong Land III DX (USA)::Romhack
Kirby's Dream Land - DX (USA)::Romhack
Kirby's Dream Land 2 - DX (USA)::Romhack
Legend of Zelda, The - Link's Awakening DX - Redux (USA)::Romhack
Metroid II - Return of Samus DX (USA)::Romhack
Pokemon - Blue Version DX (USA)::Romhack
Pokemon - Red Version DX (USA)::Romhack
Pokemon - Yellow Version - Special Pikachu Edition DX (USA)::Romhack
Pokemon Picross (USA)::Romhack
Pokemon Trading Card Game 2 - The Invasion of Team GR (USA)::Romhack
Super Mario Bros. Deluxe (Japan) (En) (Rev 1) (NP)::Redirect::Super Mario Bros. Deluxe (Japan) (NP)
Super Mario Land - DX (USA)::Romhack
Super Mario Land 2 - 6 Golden Coins DX (USA)::Romhack
Survival Kids 2 - Escape the Twin Islands! (USA)::Romhack
Wario Land - Super Mario Land 3 DX (USA)::Romhack
# GB
Mario's Picross 2 (USA) (SGB Enhanced)::Romhack
Pokemon - Brown Version::Romhack
Pokemon - Green Version (USA, Europe) (SGB Enhanced)::Romhack
Super Mario Land 4 (Unknown) (Ja) (Unl) (Pirate)::Romhack
# GBA
Action Replay GBX (Europe) (En,Fr,De,It) (Alt 1) (Unl)::Redirect::Action Replay GBX (Europe) (En,Fr,De,It) (Unl) (Alt)
Aero the Acro-Bat - Rascal Rival Revenge (Europe)::Redirect::Aero the Acro-Bat (Europe)
Aero the Acro-Bat - Rascal Rival Revenge (USA)::Redirect::Aero the Acro-Bat (USA)
AGS Aging Cartridge (World) (v7.0)::Redirect::AGS Aging Cartridge (World) (Rev 1) (v7.0) (Test Program)
AGS Aging Cartridge (World) (v7.1)::Redirect::AGS Aging Cartridge (World) (v7.1) (Test Program)
Care Bears - The Care Quests (Europe) (En,Fr,De,Es,It,Nl,Pt,Da)::Redirect::Care Bears - The Care Quest (Europe) (En,Fr,De,Es,It,Nl
Care Bears - The Care Quests (USA) (En,Fr,Es)::Redirect::Care Bears - The Care Quest (USA) (En,Fr,Es)
Celeste Classic::Homebrew
Donchan Puzzle - Hanabi de Dohn! Advance (Japan)::Redirect::Don-chan Puzzle - Hanabi de Doon! Advance (Japan)
Fear Factor Unleashed (USA)::Redirect::Fear Factor - Unleashed (USA)
Fire Emblem - The Binding Blade (USA)::Romhack
GameShark GBA (USA) (Alt 1) (Unl)::Redirect::GameShark GBA (USA) (Unl) (Alt)
GBA TV Tuner PAL (China) (v1.3) (Unl)::Redirect::GB-A TV Tuner PAL (China) (v1.3) (Unl)
GBA TV Tuner PAL (China) (v2.0) (Unl)::Redirect::GB-A TV Tuner PAL (China) (v2.0) (Unl)
Jump (Japan)::e-Reader
Mandrake the Magician (Italy) (Proto)::Redirect::Mandrake the Magician (Italy) (It) (Proto)
Memory Dumps - Promotional (USA, Australia)::e-Reader
Mother 1+2 (USA)::Romhack
Mother 3 (USA)::Romhack
Motoracer Advance (Europe) (En,Fr,De,Es,It)::Redirect::Moto Racer Advance (Europe) (En,Fr,De,Es,It)
Motoracer Advance (USA) (En,Fr,De,Es,It)::Redirect::Moto Racer Advance (USA) (En,Fr,De,Es,It)
Overstorm (Unknown) (Proto)::Redirect::Overstorm (Europe) (Proto)
Phantom, The (Italy) (Proto)::Redirect::Phantom, The (Italy) (It) (Proto)
Pokemon (USA)::Unknown bootleg or romhack
Pokemon - Doel Deoxys Distribution (Netherlands) (Kiosk)::Redirect::Pokemon - Doel Deoxys Distribution (Netherlands) (En) (Kiosk)
Pokemon Channel - Line Art Card - 11-A101 - The Pikachu Star (USA, Australia) (Promo)::e-Reader
Pokemon Channel - Line Art Card - 11-A102 - The Kyogre Constellation (USA) (Promo)::e-Reader
Pokemon Channel - Line Art Card - 11-P101 - Jirachi (Australia) (Promo)::e-Reader
Pokemon Channel - Paint Pattern Card - 11-A103 - Poke A La Card (USA, Australia) (Promo)::e-Reader
Ratatouille (Greece) (En)::Redirect::Ratatouille (Australia, Greece) (En)
SN Systems (Europe)::Redirect::SN Systems (Europe) (Test Program) (Unl)
Tiny Chao Garden (USA) (Ja) (Phantasy Star Online Episode I _ II)::Gamecube rom
Toyrobo Force (Japan)::Redirect::Toy Robo Force (Japan)
Travis Pastrana's Pro MotoX (USA, Europe) (Proto) (2002-12-12)::Redirect::Travis Pastrana's Pro MotoX (USA) (Proto) (2002-12-12)
Xploder Advance (Europe) (Alt 1) (Unl)::Redirect::Xploder Advance (Europe) (Unl) (Alt)
'@ -split '\r?\n' | Where-Object {
# Filter out empty lines and lines beginning with #
$_ -notmatch '(^#|^\s*$)'
}
#Functions
Function Remove-CacheDir {
Param(
[switch]$Init
)
if ( Get-Item -EA Ignore $tempWorkspace\* ) {
if ( $Init ) {
Write-Warning "Removing stale temporary workspace files at $tempWorkspace"
}
Remove-Item $tempWorkspace\* -Force -Recurse 2> $null
}
}
Function New-CacheDir {
if ( !( Test-Path -PathType Container $tempWorkspace ) ) {
New-Item -ItemType Directory $tempWorkspace > $null
}
}
Function Initialize-CacheDir {
Remove-CacheDir -Init
New-CacheDir
}
Function Copy-ToClipboard {
# This will work on Windows
# Best effort for *nix. xclip must be present to work
[CmdletBinding()]
Param(
[string]$String,
[switch]$NoNewLines
)
if ( ( $clipBin = ( Get-Command -EA SilentlyContinue -CommandType Application clip.exe ).Source ) ) {
$String | & $clipBin *> $null
}
elseif ( ( $clipBin = ( Get-Command -EA SilentlyContinue -CommandType Application xclip ).Source ) ) {
$String | & $clipBin *> $null
}
}
## BEGIN MENU FRAMEWORK
Function Show-Menu {
Param(
[string]$Title = 'Menu',
[string]$InputPrompt = 'Enter the corresponding number to make a menu selection',
[string[]]$Options = @(),
[string]$Message,
[string]$CancelSelectionLabel = 'Cancel',
[int]$CancelOptionValue = -1,
[switch]$NoAutoCancel
)
[string[]]$useOptions = if ( !$NoAutoCancel ) {
$Options + $CancelSelectionLabel
}
else {
$Options
}
# Keep track of empty lines
[int[]]$subtractAtIndices = for ( $o = 0; $o -lt $useOptions.Count; $o++ ) {
$option = $useOptions[$o]
if ( [string]::IsNullOrWhiteSpace($option) ) {
$o
}
}
Clear-Host
Write-Host "===== $Title =====$([Environment]::NewLine)" -ForegroundColor Blue
if ( $Message ) {
Write-Host "$Message$([Environment]::NewLine)" -ForegroundColor Cyan
}
# Don't increase the input counter for empty lines
$offset = 1
for ( $i = 0; $i -lt $useOptions.Count; $i++ ) {
$option = $useOptions[$i]
if ( $i -in $subtractAtIndices ) {
$offset -= 1
Write-Host
}
else {
Write-Host "`t$($i+$offset): $($useOptions[$i])" -ForegroundColor Green
}
}
Write-Host
do {
try {
[int]$selection = Read-Host -Prompt $InputPrompt
}
catch {
Write-Warning 'Numeric entries only'
}
} while ( ( $selection -lt 1 ) -or ( $selection -gt ( $useOptions.Count - $subtractAtIndices.Count ) ) )
if ( !$NoAutoCancel -and $selection -eq ( $useOptions.Count - $subtractAtIndices.Count ) ) {
$CancelOptionValue
}
else {
$selection
}
}
Function Show-OKMenu {
Param(
[string]$Title = 'Menu',
[string]$Message
)
Show-Menu -Title $Title -Options 'OK' -Message $Message -NoAutoCancel > $null
}
## END MENU FRAMEWORK
Function Show-Instructions {
Show-OKMenu -Title Instructions -Message @"
Workspace Folder: $tempWorkspace
This is an interactive tool to assist with downloading image libraries from the
libretro-thumbnail repositories available on Github at:
https://github.com/libretro-thumbnails/libretro-thumbnails
and converting them to Analogue OS' ``.bin`` format. Each step is meant to be
worked in order, but you can skip downloading the console library and DAT
file if you already have them from a previous run.
The "Download Console Image Library" step now enumerates the available image
libraries so you don't have to go to Github and get the archive link yourself.
However, if the site parsing breaks at any time, the old method of obtaining
the ZIP link yourself is still supported with the legacy step
"Download Console Image Library (Manual)". Use this if you have problems with
the new download step.
This tool can only download and convert images for one console at a time.
Downloading a new console's images or cleaning the working directory will erase
all working images along with the working diretory itself. Use the "Move"
options to move the converted libraries to a permanent location on disk.
At this time of writing only GBA, GB, GBC, and GG images are useful for
conversion, but any libretro-thumbnail repository should be compatible.
This ensures future compatibility as new cores are released and Library
images become supported on openFPGA cores.
The step ``How to copy to Analogue OS`` will have further details on installing
the image library to your SD card, but in a nutshell Library images should be
placed in the following folder, where CONSOLE is an identifier for the
target game console: ``/System/Library/Images/CONSOLE/``
This tool is only supported on Windows as it relies on .NET types which are
not available on MacOS or Linux.
"@
}
Function Show-GetConsoleImages {
Param(
[switch]$Manual
)
if ( $Manual ) {
Copy-ToClipboard $libretro_repo
Show-OKMenu -Title 'Download Console Image Library' -Message @"
Follow these steps, then select option 1 to continue:
0. If you already have the image archive downloaded, you may simply provide the path to the archive
rather than the URL to skip the download. Otherwise, follow the instructions below. Note that
an alternative archive location will not be cleaned up when the working directory initializes,
unless you have saved the archive under "$tempWorkspace".
1. Go to $libretro_repo in a web browser.
**The URL has been copied to your clipboard for your convenience**
2. Find the folder for the system you want to generate an image pack for. Click its link
to be taken to the repository for that console's images.
3. Obtain the URL to this repo's ZIP archive by clicking the "Code" button, then right click
"Download ZIP" and select "Copy Link" or "Copy Link Address".
**Note that right clicking will paste in the terminal**
4. We will use this link in the next step. Select OK once you have copied the ZIP archive URL.
"@
Write-Host
$packUrl = Read-Host 'Please paste the libretro-thumbnail console repo ZIP link now'
}
else {
Write-Host @'
A picker will open up with consoles to select from. Please select a console you wish to
generate an Analogue OS image library for. You can use the search filter to narrow down the
selection list.
'@
do {
$packUrl = ( Get-LibretroThumbnailConsoleImageLinks | Out-GridView -Title 'Select a console' -OutputMode Single ).ZipLink
if ( !$packUrl ) {
Write-Warning 'No console was selected. Please select a console using the picker.'
Pause
}
} while ( !$packUrl )
}
Write-Host 'Initializing working directory'
Initialize-CacheDir
# Download the file if it's a URL
if ( [uri]::IsWellFormedUriString($packUrl, 'Absolute') ) {
Write-Host "Downloading $packUrl to $tempWorkspace"
# Sidestep time-consuming byte-counting bug with the progress bar
$oldProgressPreference = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
$startTime = Get-Date
try {
Invoke-WebRequest -OutFile $tempZipPath -UseBasicParsing $packUrl
}
finally {
$ProgressPreference = $oldProgressPreference
Write-Host "Download finished in $(( Get-Date ) - $startTime)"
}
}
else {
# Otherwise assume it's a path to the archive on disk
$tempZipPath = ( ( $packUrl ) -replace '^["'']' ) -replace '["'']$'
if ( Test-Path -LiteralPath $tempZipPath -PathType Leaf ) {
Write-Host "Using provided archive location on disk: $tempZipPath"
}
else {
Write-Warning "A URL was not provided and the value of ""$packUrl"" does not appear to be an existing file. Aborting."
Pause
return
}
}
Write-Host "Unzipping $tempZipPath to $tempExtractionPath"
Expand-ImageArchive -Path $tempZipPath -DestinationPath $tempExtractionPath
Write-Host 'Done'
Pause
}
Function Show-DatFileHowTo {
Copy-ToClipboard $datomatic_site
Show-OKMenu -Title 'Download DAT file from DAT-O-MATIC' -Message @"
Follow these instructions to obtain a suitable no-intro DAT file for use with
identifying each image:
1. Go to https://datomatic.no-intro.org in a web browser.
**The URL has been copied to your clipboard for your convenience**
2. Click the "Download" button in the site header, then click "Standard DAT".
3. Pick the target system from the "System" dropdown.
You should not need to change the defaults.
4. Click the "Prepare" button, then click the resulting "Download" button.
5. Extract the .dat file from the downloaded ZIP archive.
6. Make a note of the path to the downloaded ZIP file.
You will need to provide the path to the DAT file for any of the "Create"
selections from the main menu.
If you have obtained a DAT file from DAT-O-MATIC previously, you can skip this
step. Just remember to provide the path to the DAT file in the "Create" steps.
DAT-O-MATIC ``.dat`` files do not have records for every game available in
libratro-thumbnails and may be missing romhacks as well. However, you can add
additional entries to your DAT file if you know the cartridge ROM information
using any text editor.
"@
}
Function Show-ConvertPrompt {
Param(
[Parameter(Mandatory)]
[ValidateSet('BoxArts', 'Snaps', 'Titles')]
[string]$LibraryType
)
# Make sure to remove any surrounding quotes from the input string
$datPath = ( ( Read-Host 'Paste the path to your DAT file for the target console' ) -replace '^["'']' ) -replace '["'']$'
$dat = Get-Dat -DatFile $datPath
$outdir = Get-Variable -ValueOnly "tempConversion${LibraryType}Dir"
# Determine scaling mode to use
$scaleMode = if ( $LibraryType -eq 'BoxArts' ) {
'BoxArts'
}
else {
'Original'
}
Convert-Images -InputDirectory "$tempExtractionPath\$LibraryType" -OutputDirectory $outdir -Dat $dat -ScaleMode $scaleMode
Pause
}
Function Show-MovePrompt {
Param(
[ValidateSet('BoxArts', 'Snaps', 'Titles')]
[string]$LibraryType
)
# Make sure any surrounding quotes are removed
$path = if ( [string]::IsNullOrWhiteSpace($LibraryType) ) {
( ( Read-Host 'Provide a directory to move your converted image library folders to' ) -replace '^["'']' ) -replace '["'']$'
}
else {
( ( Read-Host "Provide a directory to move your $LibraryType image library to" ) -replace '^["'']' ) -replace '["'']$'
}
if ( !( Test-Path -PathType Container $path ) ) {
Write-Host "Creating directory: $path"
try {
New-Item -ItemType Directory -Force $path > $null
}
catch {
Write-Warning "An error occurred creating the directory: $($_.Exception.Message)"
return
}
}
Write-Host "Moving $LibraryType library to $path"
$source = switch ( $LibraryType ) {
'BoxArts' {
if ( ( Test-Path -PathType Container $tempConversionBoxArtsDir ) ) {
"$tempConversionBoxArtsDir\*"
}
break
}
'Snaps' {
if ( ( Test-Path -PathType Container $tempConversionSnapsDir ) ) {
"$tempConversionSnapsDir\*"
}
break
}
'Titles' {
if ( ( Test-Path -PathType Container $tempConversionTitlesDir ) ) {
"$tempConversionTitlesDir\*"
}
break
}
# All if no specified type
{ [string]::IsNullOrWhiteSpace($LibraryType) } {
if ( ( Test-Path -PathType Container $tempConversionBoxArtsDir ) ) {
$tempConversionBoxArtsDir
}
if ( ( Test-Path -PathType Container $tempConversionSnapsDir ) ) {
$tempConversionSnapsDir
}
if ( ( Test-Path -PathType Container $tempConversionTitlesDir ) ) {
$tempConversionTitlesDir
}
break
}
}
if ( $source ) {
Move-Item -Force -Path $source -Destination $path > $null
}
else {
Write-Warning 'Could not find converted images (did you convert the images yet?)'
}
Pause
}
Function Show-HowToInstallMenu {
Show-OKMenu -Title 'How to copy to Analogue OS' -Message @'
You can use one of the "Move" steps to either copy your image library to a
location on your PC, or if your Analogue OS SD card is mounted you can move
them directly to the image path for your console on the SD card.
The path is as follows from the root of the SD card:
/System/Library/Images/CONSOLE/*.bin
The only known console identifiers for the CONSOLE portion of the path at this
time of writing are:
- Gameboy Advance: GBA
- Gameboy/Gameboy Color: GB
- Game Gear: GG
If you use the "Move All Libraries" step it will create subfolders for any
library type you previously converted to `.bin` format. This is not
compatible with the Analogue OS Library image layout, so you should not
"Move All Libraries" directly to the SD card.
Instead, "Move All Libraries" to a location on your PC, then using File
Explorer copy the subfolder contents for the Library image type you want
to the SD card using the layout above.
'@
}
Function Show-OtherToolsMenu {
$options = ,
'Create Custom Palette File', # 1
'Create Custom Pallete File (Color Picker)', # 2
'Create GBC Boot Rom Palettes' # 3
$selection = Show-Menu -Title 'Other Tools' -Options $options -CancelSelectionLabel Back -Message @'
Functions and features not necessarily related to image generation
'@
switch ( $selection ) {
# Create Custom Palette File
1 {
Clear-Host
$path = ( ( Read-Host -Prompt 'Please enter the filepath to save the palette file to (*.pal)' ) -replace '^["'']' ) -replace '["'']$'
if ( $path -notmatch '\.\S+$' ) {
$path = "$path.pal"
}
New-PaletteFile -FilePath $path
Pause
break
}
# Create Custom Pallete File (Color Picker)
2 {
Clear-Host
Show-ColorPickerPrompt
Pause
break
}
# Create GBC Boot Rom Palettes
3 {
Clear-Host
if ( !( Get-InstalledModule -EA Ignore 7Zip4Powershell ) ) {
$newline = [Environment]::NewLine
while ( ( $consent = Read-Host -Prompt "This operation requires the ''7Zip4Powershell'' module.${NEWLINE}Would you like to install it in the user scope? (Y/N)") -notin 'y', 'n' ) {}
if ( $consent -eq 'n' ) {
break
}
}
Show-GBCBootRomInstructions
Pause
Break
}
}
}
Function Show-GBCBootRomInstructions {
Show-OKMenu -Message @'
Once this prompt is dismissed, information about the palettes stored inside
the GBC boot rom will be obtained from https://tcrf.net, then will use that
information to generate the following palettes:
- Game Palettes
- Button Combo Palettes
- Unused Palettes
They will be saved in the current directory under the "gbc_palettes" folder.
Game Palettes are the palettes used for certain GB games on the GBC that were
not GB-enhanced, such as Metroid II and Pokemon Red/Blue. The "_.pal"
file is a "dummy" palette used for unrecognized and unlicensed GB games.
Button Combo Palettes are the alternative palettes that non-enhanced GB
games could be set to with button presses and combinations.
Unused Palettes are palettes available in the GBC boot rom but have colors or
color combinations that are not used by any game.
To install on your Pocket, copy the palette folders to
"/Assets/gb/common/Palettes" on the Pocket's SD card.
'@
Invoke-BootRomPaletteCreation
}
Function Show-ColorPickerPrompt {
Show-OKMenu -Message @'
A color picker will pop up for each palette color (12 total).
There are 4 colors each for the BG, OBJ0, and OBJ1 palette groups.
Generally, for each palette type, usually the color should get darker
per index but this is not a requirement.
Inputting values for each color into the picker is valid, but you
must use numeric values 0-255, it does not accept hex values like
FF (255). These values will be converted to hexadecimal digits when
creating the palette file.
LCDOff is set to FFFFFF by default.
If you are unsure of what these colors represent, you may reference the
following site if you wish to re-create one of the built-in palettes from
the Game Boy Color:
https://tcrf.net/Notes:Game_Boy_Color_Bootstrap_ROM
Click cancel to abort at any time, except when canceling while setting LCDOff which
will continue with FFFFFF (White) as the LCDOff color.
'@
$path = ( ( Read-Host -Prompt 'Please enter the filepath to save the palette file to (*.pal)' ) -replace '^["'']' ) -replace '["'']$'
# Give an extension if none provided
if ( $path -notmatch '\.\S+$' ) {
$path = "$path.pal"
}
$paletteHash = Invoke-ColorPicker
New-PaletteFile -FilePath $path @paletteHash
}
Function Get-TcrfBootRomPaletteArchive {
Param(
[Uri]$Url = 'https://tcrf.net/images/a/af/CGB_Bootstrap_ROM_tables.7z',
[string]$OutFile = './boot_rom_tables/palettedefs.7z'
)
$outDir = Split-Path -Parent $OutFile
if ( !( Test-Path -PathType Container $outDir ) ) {
New-Item -ItemType Directory $outDir > $null
}
$oldProgressPreference = $ProgressPreference
try {
Invoke-WebRequest $Url -OutFile "$OutFile"
}
finally {
$ProgressPreference = $oldProgressPreference
}
[System.IO.FileInfo]$OutFile
}
Function Expand-PaletteArchive {
Param(
[Parameter(Mandatory)]
[Alias('Path')]
[string]$ArchivePath,
[string]$OutDir = './'
)
# Check for and install module
if ( !( Get-InstalledModule -EA SilentlyContinue 7Zip4Powershell ) ) {
Write-Host 'Installing required module for this operation: 7Zip4Powershell'
Install-Module 7Zip4Powershell -Force -Scope CurrentUser
}
Expand-7Zip -ArchiveFileName $ArchivePath -TargetPath $OutDir
}
Function Invoke-BootRomPaletteCreation {
Param(
[string]$OutDir = './gbc_palettes'
)
Write-Host 'Downloading boot rom palette archive'
$file = Get-TcrfBootRomPaletteArchive
Write-Host 'Expanding archive'
Write-Host "ArchivePath: $($file.FullName)"
Write-Host "OutDir: $($file.DirectoryName)"
Expand-PaletteArchive -ArchivePath $file.FullName -OutDir $file.DirectoryName
# Note that these CSVs are TAB delimited
$buttonCombosCsv = Import-Csv -Delimiter `t "$($file.DirectoryName)/listButtonCombos.csv"
$unusedColorsCsv = Import-Csv -Delimiter `t "$($file.DirectoryName)/listUnusedColors.csv"
$usedWithNamesCsv = Import-Csv -Delimiter `t "$($file.DirectoryName)/listUsedWNames.csv"
# Button Combo Palettes
$subdir = "$OutDir/Button Combo Palettes"
if ( !(Test-Path -PathType Container $subdir ) ) {
New-Item -ItemType Directory $subdir > $null
}
foreach ( $config in $buttonCombosCsv ) {
# For name use Table Number followed by Table Entry in 2 digit hex form e.g. 0102 for TN 0x01 with TE 0x02
$name = $config.'Button Combo'
try {
# Remove # from the hex code in the csv
$paletteHash = @{
BG0 = $config.'BG Color 0x00'.Remove(0, 1)
BG1 = $config.'BG Color 0x01'.Remove(0, 1)
BG2 = $config.'BG Color 0x02'.Remove(0, 1)
BG3 = $config.'BG Color 0x03'.Remove(0, 1)
OBJ00 = $config.'OBJ0 Color 0x00'.Remove(0, 1)
OBJ01 = $config.'OBJ0 Color 0x01'.Remove(0, 1)
OBJ02 = $config.'OBJ0 Color 0x02'.Remove(0, 1)
OBJ03 = $config.'OBJ0 Color 0x03'.Remove(0, 1)
OBJ10 = $config.'OBJ1 Color 0x00'.Remove(0, 1)
OBJ11 = $config.'OBJ1 Color 0x01'.Remove(0, 1)
OBJ12 = $config.'OBJ1 Color 0x02'.Remove(0, 1)
OBJ13 = $config.'OBJ1 Color 0x03'.Remove(0, 1)
}
Write-Host "Creating palette for button combo ""$name"""
New-PaletteFile -FilePath "$subdir/$name.pal" @paletteHash
}
catch {
Write-Warning "Failed to create palette file for ""NAMEHERE"": $_"
}
}
# Unused Palettes
$subdir = "$OutDir/Unused Palettes"
if ( !(Test-Path -PathType Container $subdir ) ) {
New-Item -ItemType Directory $subdir > $null
}
foreach ( $config in $unusedColorsCsv ) {
# For name use Table Number followed by Table Entry in 2 digit hex form e.g. 0102 for TN 0x01 with TE 0x02
$name = 'Unused {0}{1}' -f $config.'Table Number'.Remove(0, 2), $config.'Table Entry'.Remove(0, 2)
try {
# Remove # from the hex code in the csv
$paletteHash = @{
BG0 = $config.'BG Color 0x00'.Remove(0, 1)
BG1 = $config.'BG Color 0x01'.Remove(0, 1)
BG2 = $config.'BG Color 0x02'.Remove(0, 1)
BG3 = $config.'BG Color 0x03'.Remove(0, 1)
OBJ00 = $config.'OBJ0 Color 0x00'.Remove(0, 1)
OBJ01 = $config.'OBJ0 Color 0x01'.Remove(0, 1)
OBJ02 = $config.'OBJ0 Color 0x02'.Remove(0, 1)
OBJ03 = $config.'OBJ0 Color 0x03'.Remove(0, 1)
OBJ10 = $config.'OBJ1 Color 0x00'.Remove(0, 1)
OBJ11 = $config.'OBJ1 Color 0x01'.Remove(0, 1)
OBJ12 = $config.'OBJ1 Color 0x02'.Remove(0, 1)
OBJ13 = $config.'OBJ1 Color 0x03'.Remove(0, 1)
}
Write-Host "Creating palette for ""$name"""
New-PaletteFile -FilePath "$subdir/$name.pal" @paletteHash
}
catch {
Write-Warning "Failed to create palette file for ""NAMEHERE"": $_"
}
}
# Game Palettes
$subdir = "$OutDir/Game Palettes"
if ( !(Test-Path -PathType Container $subdir ) ) {
New-Item -ItemType Directory $subdir > $null
}
foreach ( $config in $usedWithNamesCsv ) {
# multiple titles/revs sharing a palette are delimited by ;;
$games = $config.Games -split ';;\s*'
# Remove # from the hex code in the csv
$paletteHash = @{
BG0 = $config.'BG Color 0x00'.Remove(0, 1)
BG1 = $config.'BG Color 0x01'.Remove(0, 1)
BG2 = $config.'BG Color 0x02'.Remove(0, 1)
BG3 = $config.'BG Color 0x03'.Remove(0, 1)
OBJ00 = $config.'OBJ0 Color 0x00'.Remove(0, 1)
OBJ01 = $config.'OBJ0 Color 0x01'.Remove(0, 1)
OBJ02 = $config.'OBJ0 Color 0x02'.Remove(0, 1)
OBJ03 = $config.'OBJ0 Color 0x03'.Remove(0, 1)
OBJ10 = $config.'OBJ1 Color 0x00'.Remove(0, 1)
OBJ11 = $config.'OBJ1 Color 0x01'.Remove(0, 1)
OBJ12 = $config.'OBJ1 Color 0x02'.Remove(0, 1)
OBJ13 = $config.'OBJ1 Color 0x03'.Remove(0, 1)
}
foreach ( $game in $games ) {
$useGame = if ( [string]::IsNullOrWhiteSpace($game)) {
'_'
}
else {
$game
}
try {
Write-Host "Creating palette for ""$useGame"""
New-PaletteFile -FilePath "$subdir/$useGame.pal" @paletteHash
}
catch {
Write-Warning "Failed to create palette file for ""$useGame"": $_"
}
}
}
}
Function Invoke-ColorPicker {
Param(
[switch]$PickLCDOff
)
# Prepare required resources for color picker
if ( !( 'System.Windows.Forms.ColorDialog' -as [type] ) ) {
Write-Verbose 'Loading System.Windows.Forms'
Add-Type -AssemblyName System.Windows.Forms
}
$picker = New-Object System.Windows.Forms.ColorDialog -Property @{
SolidColorOnly = $true
FullOpen = $true
AnyColor = $false
}
$hexFormatString = '{0:X2}{1:X2}{2:X2}'
try {
$paletteHash = @{}
foreach ( $type in 'BG', 'OBJ0', 'OBJ1' ) {
foreach ($i in 0..3) {
$name = "$type$i"
Write-Host "${name}: " -NoNewline
if ( $picker.showDialog() -eq 'Cancel' ) {
Write-Host
throw 'User canceled the operation'
}
$paletteHash[$name] = $hexFormatString -f $picker.Color.R, $picker.Color.G, $picker.Color.B
Write-Host $paletteHash[$name]
}
}
if ( $PickLCDOff -and $picker.ShowDialog() -ne 'Cancel' ) {
$paletteHash['LCDOff'] = $hexFormatString -f $picker.Color.R, $picker.Color.G, $picker.Color.B
}
}
finally {
if ( $picker ) {
$picker.Dispose()
$picker = $null
}
}
# return the palette hash object
$paletteHash
}
Function New-PaletteFile {
[CmdletBinding(DefaultParameterSetName = 'HexValues')]
Param(
[Parameter(ParameterSetName = 'HexValues', Mandatory)]
[ValidateLength(6, 6)]
[string]$BG0,
[Parameter(ParameterSetName = 'HexValues', Mandatory)]
[ValidateLength(6, 6)]
[string]$BG1,
[Parameter(ParameterSetName = 'HexValues', Mandatory)]
[ValidateLength(6, 6)]
[string]$BG2,
[Parameter(ParameterSetName = 'HexValues', Mandatory)]
[ValidateLength(6, 6)]
[string]$BG3,
[Parameter(ParameterSetName = 'HexValues', Mandatory)]
[ValidateLength(6, 6)]
[string]$OBJ00,
[Parameter(ParameterSetName = 'HexValues', Mandatory)]
[ValidateLength(6, 6)]
[string]$OBJ01,
[Parameter(ParameterSetName = 'HexValues', Mandatory)]
[ValidateLength(6, 6)]
[string]$OBJ02,
[Parameter(ParameterSetName = 'HexValues', Mandatory)]
[ValidateLength(6, 6)]
[string]$OBJ03,
[Parameter(ParameterSetName = 'HexValues', Mandatory)]
[ValidateLength(6, 6)]
[string]$OBJ10,
[Parameter(ParameterSetName = 'HexValues', Mandatory)]
[ValidateLength(6, 6)]
[string]$OBJ11,
[Parameter(ParameterSetName = 'HexValues', Mandatory)]
[ValidateLength(6, 6)]
[string]$OBJ12,
[Parameter(ParameterSetName = 'HexValues', Mandatory)]
[ValidateLength(6, 6)]
[string]$OBJ13,
[Parameter(ParameterSetName = 'HexValues')]
[ValidateLength(6, 6)]
[string]$LCDOff = 'FFFFFF',
[Parameter(Mandatory)]
[string]$FilePath
)
# .pal files must be 56 bytes per the analogue spec
$bytes = [System.Collections.Generic.List[byte]]::new(56)
foreach ( $type in 'BG', 'OBJ0', 'OBJ1' ) {
# Analogue expects each color per type in reverse order from TCRF's docs
$paramNames = $PSBoundParameters.Keys | Where-Object { $_ -match "^$type" } | Sort-Object -Descending
foreach ( $param in $paramNames ) {
# chunk the hex string into three pieces for R, G, and B values
$splitColorHex = $PSBoundParameters[$param] -split '(.{2})' -ne ''
if ( $splitColorHex[0] -eq '0x' ) {
throw 'Hex values should not be prefixed with "0x"'
}
foreach ( $hex in $splitColorHex ) {
$bytes.Add([byte]"0x$hex")
}
}
}
# Set Window to be same as background (per Analogue this is "normal")
# TODO: Consider picker for Window colors once it's better understood how
# this affects the palette.
$W0Split = $PSBoundParameters['BG0'] -split '(.{2})' -ne ''
$W1Split = $PSBoundParameters['BG1'] -split '(.{2})' -ne ''
$W2Split = $PSBoundParameters['BG2'] -split '(.{2})' -ne ''
$W3Split = $PSBoundParameters['BG3'] -split '(.{2})' -ne ''
# Once again, Analogue expects reverse order from TCRF
foreach ( $split in $W3Split, $W2Split, $W1Split, $W0Split) {
foreach ( $hex in $split ) {
$bytes.Add([byte]"0x$hex")
}
}
$lcdoffSplit = $LCDOff -split '(.{2})' -ne ''
foreach ( $hex in $lcdoffSplit ) {
$bytes.Add([byte]"0x$hex")
}
# Write the footer
# 0x81 APGB
$bytes.AddRange([byte[]]@( 129, 65, 80, 71, 66 ))
# Write to file
[System.IO.File]::WriteAllBytes($FilePath, $bytes)
}
Function Get-LibretroThumbnailConsoleImageLinks {
$oldProgressPreference = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
try {
[array]$consoleLinks = ( Invoke-WebRequest -UseBasicParsing $libretro_repo ).Links | Where-Object {
# Submodule links don't have a class
!$_.class -and
$_.href -match 'libretro-thumbnails/.+/tree'
}
}
finally {
$ProgressPreference = $oldProgressPreference
}
foreach ( $link in $consoleLinks ) {
$Name = [regex]::Match($link.outerHTML, '(?<=\<a\s+.*\>).+(?=\<\/a\>)').Value -replace '\s+@.*$'
$linkPath = $link.href
$targetZipName = "$([regex]::Match($linkPath, '(?<=tree/)\S+$')).zip"
$targetRepoName = "$([regex]::Match($linkPath, '(?<=libretro-thumbnails\/)\S+?(?=\/)'))"
# Write-Warning "ZipName: $targetZipName"
# Write-Warning "RepoName: $targetRepoName"
[PSCustomObject]@{
# Remove submodule commit ref from the text
Name = $Name
ZipLink = "$libretro_base/$targetRepoName/archive/$targetZipName"
}
}
}
function Confirm-Png {
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[string]$FilePath
)
try {
# Signature for PNG files
[byte[]]$pngHeader = 137, 80, 78, 71, 13, 10, 26, 10
# Read the first 8 bytes
[System.IO.FileStream]$fStream = [System.IO.FileStream]::new($FilePath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
[byte[]]$actualHeader = [byte[]]::new(8)
$fStream.Read($actualHeader, 0, 8) > $null
if ( $Verbosity -eq 'Noisy' ) {
Write-Verbose "Actual Header: $actualHeader"
Write-Verbose " PNG Header: $pngHeader"
}
# Check that the bytes match the expected signature for PNG files
# Return false on first mismatch
for ( $i = 0; $i -lt 8; $i++ ) {