-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbmp2sms.tcl
executable file
·1567 lines (1174 loc) · 48.3 KB
/
bmp2sms.tcl
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
#! /usr/bin/env tclsh
#
# bmp2sms by Julien Verneuil - 02/11/2014 - last updated : 28/01/2019
# License: BSDv2
#
# this tool was only tested with TCL 8.6.*
#
# this tool is basically a 'clone' of bmp2tile made by Maxim : http://www.smspower.org/maxim/Software/BMP2Tile
# rewrote it as a TCL study and most importantly with portability in mind
#
# its purpose is to convert 16 colors images files to a format suitable for inclusion in Sega Master System programs (written with wla-dx but other tools may work as well)
#
# bmp2sms support PNG/GIF/PPM/PGM by default without the TkImg package (see below)
# images should have a width / height that are multiples of 8 otherwise padding will be added.
#
# there is some things differing from bmp2tile:
# - target system is the Sega Master System (no support for Game Gear altough adding it would be easy)
# - the program perform 'smart' colours conversion if image colours does not match the SMS palette
# - indexed images are loaded as normal images (the palette is ignored), a palette is instead automatically generated
# - it load a complete directory instead of only one file at a time, there is planned support to save all files in one go
# - some features from bmp2tile are missing like 8x16 mode and cl123 palette output mode
# - allow negative tile start index (-1 = 0x3ff etc.) which may be useful for some effects
# - palette order may be different so tiles value may be different on the same image (because bmp2tile will load indexed images while bmp2sms always generate it)
# - no commandline mode
# - no status bar
#
# then there is some features:
# - palette index picker : select a palette index and click somewhere on the image to change the palette color
# - palette editor : double click on a palette color square or drag around a color square to organize the palette
#
# if the package TkImg is found then these additional images format will be supported: BMP/JPEG/PCX/XPM/TGA
#
# this program also support compression plugins made for bmp2tile : https://github.com/maxim-zhao/bmp2tile-compressors
# compression plugins support require the Ffidl TCL package
#
# Note for .bmp images: The image should not include colour space information (see BMP export compatibility options for GIMP) otherwise the image will fail to load.
#
# this is a first try at TCL programming, an interesting scripting language with great libraries
#
package require Tk
set use_tkimg 1
set use_ffidl 1
set dirName [pwd]
# === check program argument for options
foreach {name} $argv {
if {$name eq "-without_TkImg"} {
set use_tkimg 0
} elseif {$name eq "-without_Ffidl"} {
set use_ffidl 0
}
}
# === tkImg related
set img_format_support ".png,.PNG,.gif,.GIF,.ppm,.PPM,.pgm,.PGM"
if {$use_tkimg} {
if {[catch {package require Img}]} {
puts "\n BMP/JPEG/PCX/XPM/TGA support disabled because TkImg package cannot be found. \
\n * Solution : Install libtk-img from your package manager. \
\n Turn this warning off with '-without_TkImg' program argument.\n"
} else {
set img_format_support [append img_format_support ",.bmp,.BMP,.jpg,.jpeg,.JPG,.JPEG,.pcx,.PCX,.xpm,.XPM,.tga,.TGA"]
}
}
# === compression plugins related
set operating_system $tcl_platform(os)
set plugins_file_list [list]
set tiles_plugins [dict create]
set tilemap_plugins [dict create]
if {$use_ffidl} {
if {[catch {package require Ffidl}] ||
[catch {package require Ffidlrt}]} {
puts "\n Compression plugins support disabled because Ffidl package cannot be found. \
\n * Solution : Install Ffidl : http://elf.org/ffidl \
\n Turn this warning off with '-without_Ffidl' program argument.\n"
} else {
# scan the program folder to find the plugins shared libraries
if {$operating_system eq "Linux" ||
$operating_system eq "FreeBSD" ||
$operating_system eq "DragonFly" ||
$operating_system eq "NetBSD" ||
$operating_system eq "OpenBSD"} {
set plugins_file_list [glob -nocomplain -types {r f} *.so]
} elseif {[string match -nocase "*win*" $operating_system]} {
set plugins_file_list [glob -nocomplain -types {r f} *.dll]]
} elseif {$operating_system eq "MacOS" ||
$operating_system eq "Darwin"} {
set plugins_file_list [glob -nocomplain -types {r f} *.dylib]]
}
# for each libraries, check if it is a compression plugin based on the symbols name
# if it is then create a TCL command based on the library name and the symbol name
# and make it available for either tiles or tilemap export (or both)
foreach plugin_filename $plugins_file_list {
if {[catch {::ffidl::symbol "[pwd]/$plugin_filename" "getName"} gn_addr]} {
puts "Can't get \"getName\" symbol for the plugin \"$plugin_filename\", this plugin will be ignored."
continue
}
if {[catch {::ffidl::symbol "[pwd]/$plugin_filename" "getExt"} ge_addr]} {
puts "Can't get \"getExt\" symbol for the plugin \"$plugin_filename\", this plugin will be ignored."
continue
}
set library_rootname [file rootname $plugin_filename]
set cmd_get_name $library_rootname
append cmd_get_name "_getName"
set cmd_get_ext $library_rootname
append cmd_get_ext "_getExt"
set cmd_compress_tiles $library_rootname
append cmd_compress_tiles "_compressTiles"
set cmd_compress_tilemap $library_rootname
append cmd_compress_tilemap "_compressTilemap"
::ffidl::callout $cmd_get_name {} {pointer-utf8} $gn_addr
::ffidl::callout $cmd_get_ext {} {pointer-utf8} $ge_addr
if {[catch {::ffidl::symbol "[pwd]/$plugin_filename" "compressTiles"} ct_addr]} {
} else {
::ffidl::callout $cmd_compress_tiles {pointer-byte uint32 pointer-byte uint32} {uint32} $ct_addr
dict set tiles_plugins $library_rootname [list [$cmd_get_name] [$cmd_get_ext]]
}
if {[catch {::ffidl::symbol "[pwd]/$plugin_filename" "compressTilemap"} cm_addr]} {
} else {
::ffidl::callout $cmd_compress_tilemap {pointer-byte uint32 uint32 pointer-byte uint32} {uint32} $cm_addr
dict set tilemap_plugins $library_rootname [list [$cmd_get_name] [$cmd_get_ext]]
}
if {[dict exists $tiles_plugins $library_rootname] == 0 &&
[dict exists $tilemap_plugins $library_rootname] == 0} {
puts "Can't get \"compressTiles\" and \"compressTilemap\" symbols for the plugin \"$plugin_filename\", this plugin will be ignored."
}
}
}
}
# === main program
set window_width 800
set window_height 600
set window_x 0
set window_y 0
# the fixed font used for the palette read-only entry (font should be fixed because it should stay aligned with the palette rectangles)
set fixed_font [font create -size 10 -family Monospace -weight bold]
set TILE_WIDTH 8
set TILE_HEIGHT 8
set host_palette_data ""
set paletteEntryText ""
set currPalTag ""
set indexedImageData ""
set indexedImageData8x16 ""
set tilesData ""
set listBoxCurrentIndex 0
array set tiledImageData {}
array set tiledDataIndex {}
# store already loaded data (which save data between images selections)
set loaded_data [dict create]
# checkbox/spinbox-linked variables
set check_rmdup 0
set check_tmirror 0
set check_t8x16 0
set check_use_sprite_pal 0
set check_front_of_sprite 0
set tindex_value 0
proc initializeSMSPalette {} {
set pal [dict create]
for {set i 0} {$i < 64} {incr i} {
set hex_r [format %2.2x [expr {($i >> 0 & 3) * 85}]]
set hex_g [format %2.2x [expr {($i >> 2 & 3) * 85}]]
set hex_b [format %2.2x [expr {($i >> 4 & 3) * 85}]]
set hex_i [format %2.2X $i]
dict set pal "#$hex_r$hex_g$hex_b" "\$$hex_i"
}
return $pal
}
# the host full palette is stored here
# it is used for the color selection dialog and for colors checks
set dstPalette [initializeSMSPalette]
# if the argument is not an empty string this add an error message in the frame directory and set the directory input background to red
# if the argument is an empty string it remove the error message and set the directory input background back to white
proc setDirFrameError m {
if {[string eq $m ""]} then {
grid remove .frame_directory.m
.frame_directory.e configure -bg "#ffffff"
return
}
grid .frame_directory.m - -sticky we -row 1 -padx 1m -pady 1m -in .frame_directory
.frame_directory.m configure -text $m
.frame_directory.e configure -bg "#ff0000"
.frame_tabs.notebook tab 0 -state disabled
.frame_tabs.notebook tab 1 -state disabled
.frame_tabs.notebook tab 2 -state disabled
}
proc loadDir {} {
global dirName img_format_support loaded_data
.frame_files.list delete 0 end
preview_image blank
if {![file exists $dirName]} then {
setDirFrameError "Invalid path."
return
}
if {![file isdirectory $dirName]} then {
setDirFrameError "Not a directory."
return
}
if {[catch {glob -type f -directory $dirName *{$img_format_support}} file_list]} then {
setDirFrameError "There is no supported images in this directory."
return
}
# clear cache
set loaded_data [dict create]
setDirFrameError ""
.frame_directory.e configure -bg "#FFFFFF"
foreach i [lsort $file_list] {
.frame_files.list insert end [file tail $i]
}
.frame_files.list selection set 0
listBoxSelect
.frame_tabs.notebook select 0
}
proc selectAndLoadDir {} {
global dirName
set dir [tk_chooseDirectory -initialdir $dirName -parent . -mustexist 1]
if {$dir ne ""} {
set dirName $dir
loadDir
}
}
# generate map data
proc updateTileMapData {} {
global tiledImageData tiledDataIndex check_use_sprite_pal check_front_of_sprite TILE_WIDTH tindex_value
set width [image width preview_image]
set tw [expr {$width / $TILE_WIDTH}]
set i 0
set l 0
.tilemap_text delete 0.0 end
.tilemap_text insert end ".dw "
foreach index [lsort -dictionary [array names tiledImageData]] {
set tindex [expr {$tiledDataIndex($index) + $tindex_value}]
if {$tindex < 0} {
set tindex [expr {1024 + $tindex}]
}
if {$check_use_sprite_pal} {
set tindex [expr {$tindex | 2048}]
}
if {$check_front_of_sprite} {
set tindex [expr {$tindex | 4096}]
}
#if {[string range $tiledImageData($index) 0 0] eq " "} {
# .tilemap_text insert end "\$[format %04X [string range $tiledImageData($index) 1 end]] "
#puts [string range $tiledImageData($index) 1 end]]
#} else {
.tilemap_text insert end "\$[format %04X [expr {$tindex}]] "
#}
incr i
if {[expr {$i % $tw}] == 0} {
.tilemap_text insert end "\n.dw "
incr l
}
}
.tilemap_text delete [.tilemap_text count -lines 0.0 end].0 end
}
# generate tiles/map & update preview image
proc updateImage {} {
global tiledImageData tiledDataIndex host_palette_data indexedImageData tilesData TILE_WIDTH TILE_HEIGHT check_rmdup check_tmirror check_t8x16 tindex_value
set width [image width preview_image]
set height [image height preview_image]
array unset tiledImageData *
array set tiledImageData {}
array set tiledHFlipImageData {}
array set tiledVFlipImageData {}
array set tiledHVFlipImageData {}
set tw [expr {$width / $TILE_WIDTH}]
set y 0
set yi 0
set dst_data [list]
foreach line $indexedImageData {
set l ""
set x 0
set ti $yi
set xi 0
set b0 0
set b1 0
set b2 0
set b3 0
set hfb0 0
set hfb1 0
set hfb2 0
set hfb3 0
foreach pal_index [split $line " "] {
append l " [.canvas_palette itemcget pal_color_$pal_index -fill]"
set bpos [expr {7 - ($x & 7)}]
set b0 [expr {$b0 | (( $pal_index & 1) << $bpos)}]
set b1 [expr {$b1 | ((($pal_index & 2) >> 1) << $bpos)}]
set b2 [expr {$b2 | ((($pal_index & 4) >> 2) << $bpos)}]
set b3 [expr {$b3 | ((($pal_index & 8) >> 3) << $bpos)}]
# hflip the easy way
set bpos [expr {$x & 7}]
set hfb0 [expr {$hfb0 | (( $pal_index & 1) << $bpos)}]
set hfb1 [expr {$hfb1 | ((($pal_index & 2) >> 1) << $bpos)}]
set hfb2 [expr {$hfb2 | ((($pal_index & 4) >> 2) << $bpos)}]
set hfb3 [expr {$hfb3 | ((($pal_index & 8) >> 3) << $bpos)}]
incr x
if {[expr {$x % $TILE_WIDTH}] == 0} {
# HFlip
set hfb0 [format %02X $hfb0]
set hfb1 [format %02X $hfb1]
set hfb2 [format %02X $hfb2]
set hfb3 [format %02X $hfb3]
if {[catch {
set hfliptdata [concat $tiledHFlipImageData($ti) " \$$hfb0 \$$hfb1 \$$hfb2 \$$hfb3"]
}]} then {
set hfliptdata "\$$hfb0 \$$hfb1 \$$hfb2 \$$hfb3"
}
# tile data
set b0 [format %02X $b0]
set b1 [format %02X $b1]
set b2 [format %02X $b2]
set b3 [format %02X $b3]
if {[catch {
set tdata [concat $tiledImageData($ti) " \$$b0 \$$b1 \$$b2 \$$b3"]
}]} then {
set tdata "\$$b0 \$$b1 \$$b2 \$$b3"
}
# first pass VFlip (flip bitplanes)
if {[catch {
set vfliptdata [concat $tiledVFlipImageData($ti) " \$$b3 \$$b2 \$$b1 \$$b0"]
}]} then {
set vfliptdata "\$$b3 \$$b2 \$$b1 \$$b0"
}
# first pass HFlip + VFlip (flip bitplanes)
if {[catch {
set hvfliptdata [concat $tiledHVFlipImageData($ti) " \$$hfb3 \$$hfb2 \$$hfb1 \$$hfb0"]
}]} then {
set hvfliptdata "\$$hfb3 \$$hfb2 \$$hfb1 \$$hfb0"
}
set b0 0
set b1 0
set b2 0
set b3 0
set hfb0 0
set hfb1 0
set hfb2 0
set hfb3 0
set tiledImageData($ti) $tdata
set tiledHFlipImageData($ti) $hfliptdata
set tiledVFlipImageData($ti) $vfliptdata
set tiledHVFlipImageData($ti) $hvfliptdata
incr xi
incr ti
}
}
set dst_data "$dst_data {$l}"
incr y
if {[expr {$y % $TILE_HEIGHT}] == 0} {
incr yi $tw
}
}
foreach index [lsort -dictionary [array names tiledVFlipImageData]] {
# second pass VFlip
set tiledVFlipImageData($index) [join [lreverse [split $tiledVFlipImageData($index)]] " "]
# second pass VFlip for HFlip + VFlip
set tiledHVFlipImageData($index) [join [lreverse [split $tiledHVFlipImageData($index)]] " "]
}
# remove trailing newline at the end of tiles/tilemap
#string trimright $string \n
.tiles_text delete 0.0 end
# generate tiles data
array unset tiledDataIndex *
array set tiledDataIndex {}
array set tiledDataDuplicate {}
array set tiledDataMirrored {}
array set tiledDataHMirrored {}
array set tiledDataVMirrored {}
set tiles_count [array size tiledImageData]
set i 0
for {set index 0} {$index < $tiles_count} {incr index} {
if {$check_rmdup} {
# remove duplicate
for {set index2 [expr {$index+1}]} {$index2 < $tiles_count} {incr index2} {
if {$tiledImageData($index) eq $tiledImageData($index2)} {
if {![info exists tiledDataDuplicate($index)] &&
![info exists tiledDataMirrored($index)]} {
set tiledDataDuplicate($index2) 0
set tiledDataIndex($index2) $i
}
}
}
# remove mirrored tiles & flag it into the tilemap
if {$check_tmirror} {
for {set index2 [expr {$index+1}]} {$index2 < $tiles_count} {incr index2} {
if {![info exists tiledDataDuplicate($index)] &&
![info exists tiledDataDuplicate($index2)] &&
![info exists tiledDataMirrored($index)]} {
# remove H mirrored
if {$tiledHFlipImageData($index) eq $tiledImageData($index2)} {
set tiledDataMirrored($index2) 0
set tiledDataIndex($index2) [expr {$i | 512}]
# remove V mirrored
} elseif {$tiledVFlipImageData($index) eq $tiledImageData($index2)} {
set tiledDataMirrored($index2) 0
set tiledDataIndex($index2) [expr {$i | 1024}]
# remove H+V mirrored
} elseif {$tiledHVFlipImageData($index) eq $tiledImageData($index2)} {
set tiledDataMirrored($index2) 0
set tiledDataIndex($index2) [expr {$i | 1536}]
}
}
}
}
}
# regular tile
if {![info exists tiledDataDuplicate($index)] &&
![info exists tiledDataMirrored($index)]} {
set tiledDataIndex($index) $i
incr i
}
}
# tiles output
set i $tindex_value
for {set index 0} {$index < [array size tiledImageData]} {incr index} {
if {![info exists tiledDataDuplicate($index)] &&
![info exists tiledDataMirrored($index)]} {
set tid $i
if {$i < 0} {
set tid [expr {1024 + $i}]
}
.tiles_text insert end "; Tile index \$[format %03X $tid]\n.db $tiledImageData($index)\n"
incr i
}
}
# generate tilemap
updateTileMapData
preview_image put $dst_data
}
# create a new palette filled with black color
proc initializePalette {} {
for {set i 0} {$i < 16} {incr i} {
.canvas_palette itemconfigure "pal_color_$i" -fill "#000000"
setPaletteColor $i "#000000"
}
}
proc setPaletteData {i color} {
global host_palette_data dstPalette loaded_data listBoxCurrentIndex
lset host_palette_data $i [dict get $dstPalette $color]
set selectionName [.frame_files.list get $listBoxCurrentIndex]
dict set loaded_data "pal $selectionName" $host_palette_data
}
proc updatePaletteData {} {
global host_palette_data paletteEntryText loaded_data
for {set i 0} {$i < 16} {incr i} {
setPaletteData $i [.canvas_palette itemcget "pal_color_$i" -fill]
}
set paletteEntryText [lindex $host_palette_data 0]
for {set i 1} {$i < 16} {incr i} {
set paletteEntryText "$paletteEntryText [lindex $host_palette_data $i]"
}
}
proc setPaletteColor {index color} {
set x1 [expr {$index * 32 + 1}]
set x2 [expr {$x1 + 31}]
.canvas_palette itemconfigure "pal_color_$index" -fill $color
}
proc loadImage {file} {
if {[catch {
preview_image configure -file $file
}]} then {
return -1
}
return 0
}
proc selectionLoadFailed {msg detail} {
set currSelectionIndex [.frame_files.list curselection]
.frame_files.list itemconfigure $currSelectionIndex -bg \#ff0000 -selectbackground \#ff0000
.frame_tabs.notebook tab 0 -state disabled
.frame_tabs.notebook tab 1 -state disabled
.frame_tabs.notebook tab 2 -state disabled
tk_messageBox -message $msg -detail $detail -icon error -title "Error"
}
proc listBoxSelect {} {
global dirName dstPalette indexedImageData indexedImageData8x16 host_palette_data listBoxCurrentIndex
global TILE_WIDTH TILE_HEIGHT
global loaded_data
if {[.frame_files.list curselection] eq ""} {
return
}
set currSelectionIndex [.frame_files.list curselection]
set selectionName [.frame_files.list get $currSelectionIndex]
set file [file join $dirName $selectionName]
preview_image configure -width 0 -height 0
if {[loadImage $file] eq -1} {
if {[string tolower [file extension $file]] eq ".bmp"} {
selectionLoadFailed "Image format not supported" "NOTE : the image should not include colour space informations"
} else {
selectionLoadFailed "Image format not supported" ""
}
return
}
set listBoxCurrentIndex $currSelectionIndex
set fixed_img_width [expr {int(ceil([image width preview_image] / double($TILE_WIDTH)) * $TILE_WIDTH)}]
set fixed_img_height [expr {int(ceil([image height preview_image] / double($TILE_HEIGHT)) * $TILE_HEIGHT)}]
.frame_image_name configure -text "[file rootname $selectionName] ([append "" $fixed_img_width x $fixed_img_height])"
preview_image configure -width $fixed_img_width -height $fixed_img_height
set src_data [preview_image data -background "#000000"]
# 8x16 temporary data structure
set line8x16 { }
initializePalette
if {[catch {set indexedImageData [dict get $loaded_data "image $selectionName"]
set palette [dict get $loaded_data "pal $selectionName"]}]} {
set dst_data [list]
set palette [dict create]
set i 0
set indexedImageData ""
set host_palette_data ""
set v 0
foreach line $src_data {
set l ""
set hl ""
set k 0
set sb { }
foreach hex_color [split $line " "] {
lassign [winfo rgb . $hex_color] r g b
set color ""
if {[dict size $palette] >= 16} {
selectionLoadFailed "The image have too many colours" "(max: 16)"
return
}
if {[dict exists $dstPalette $hex_color]} {
set color $hex_color
} else {
set r [format "%02x" [expr {int($r / 256 / 85.0) * 85}]]
set g [format "%02x" [expr {int($g / 256 / 85.0) * 85}]]
set b [format "%02x" [expr {int($b / 256 / 85.0) * 85}]]
set color "#$r$g$b"
}
if {![dict exists $palette $color]} {
dict set palette $color $i
setPaletteColor $i $color
incr i
}
append hl "[dict get $palette $color] "
append l "$color "
# 8x16 construction (90° rotated data)
#lappend sb [dict get $palette $color]
#incr k
#if {[expr { $k % 8 }] == 0} {
# set sb { }
# if { [lindex $line8x16 $v] eq "" } {
# linsert $line8x16 { }
# }
#}
#
}
set hl [string trimleft $hl " "]
set l [string trimleft $l " "]
set hl [string trimright $hl " "]
set l [string trimright $l " "]
set dst_data "$dst_data {$l}"
set indexedImageData "$indexedImageData {$hl}"
}
updatePaletteData
dict set loaded_data "image $selectionName" $indexedImageData
# cached image data (eg. previously loaded)
} else {
set i 0
foreach {pal_index} $palette {
dict for {key value} $dstPalette {
if {$value == $pal_index} {
setPaletteColor $i $key
break
}
}
incr i
}
updatePaletteData
}
#preview_image put $dst_data
updateImage
if {[.frame_tabs.notebook tab 0 -state] ne "normal"} {
.frame_tabs.notebook tab 0 -state normal
.frame_tabs.notebook select 0
}
.frame_tabs.notebook tab 1 -state normal
.frame_tabs.notebook tab 2 -state normal
}
# === Color dragging of the palette
proc itemStartDrag {c x y} {
global lastX lastY currPalTag
set i [expr {int([$c canvasx $x]/32.0)}]
set lastX [expr {$i *32}]
set tag_list [.canvas_palette gettags current]
set index [lsearch $tag_list "pal_color_*"]
if {$index != -1} {
set currPalTag [lindex $tag_list $index]
$c moveto "selection" [expr {$i * 32 + 11}] ""
}
}
proc itemDrag {c x y} {
global lastX lastY indexedImageData currPalTag
set tag_list [.canvas_palette gettags current]
set index [lsearch $tag_list "pal_color_*"]
if {$index == -1} {
return
}
set i [expr {int([$c canvasx $x]/32.0)}]
if {$i < 0 || $i >= 16} {
return
}
set x [expr {$i * 32}]
$c raise current "pal_color_$i"
set old_tag [lindex [$c gettags current] 0]
set new_tag "pal_color_$i"
set old_index [lindex [split $old_tag "_"] 2]
set new_index [lindex [split $new_tag "_"] 2]
if {$old_tag eq $new_tag} {
return
}
set old_id [$c find withtag $new_tag]
set current_id [$c find withtag $old_tag]
$c dtag "pal_color_$i" $new_tag
$c dtag current $old_tag
$c move $old_id [expr {-($x-$lastX)}] 0
$c itemconfigure $old_id -tags $old_tag
$c itemconfigure current -tags [list $new_tag current]
set currPalTag $new_tag
$c moveto "selection" [expr {$i * 32 + 11}] ""
$c move current [expr {$x-$lastX}] 0
set lastX $x
updatePaletteData
}
proc stopDrag { } {
updateImage
}
# center a window in its parent
proc centerWindow {parent w} {
update idletasks
set parent_x [winfo rootx $parent]
set parent_y [winfo rooty $parent]
set parent_width [winfo width $parent]
set parent_height [winfo height $parent]
set w_width [winfo width $w]
set w_height [winfo height $w]
wm geom $w +[expr {$parent_x + abs($parent_width / 2 - $w_width / 2)}]+[expr {$parent_y + abs($parent_height / 2 - $w_height / 2)}]
}
# called when a color is selected in the color chooser window
proc changeColor {color} {
global currPalTag
.canvas_palette itemconfigure $currPalTag -fill $color
updatePaletteData
updateImage
}
proc imageClick {x y} {
global indexedImageData
set i [lindex [lindex $indexedImageData $y] $x]
if {[string length $i] > 0} {
.canvas_palette moveto "selection" [expr {$i * 32 + 11}] ""
}
}
# === export procedures (TODO: clean code duplicata)
proc savePalette {type multiple} {
global paletteEntryText listBoxCurrentIndex indexedImageData
set selectedFile [file rootname [.frame_files.list get $listBoxCurrentIndex]]
set selectedFile [append selectedFile " (palette)"]
set selectedFile [append selectedFile $type]
if {$multiple == 0} {
set types [list [list [list] [list $type]]]
set file [tk_getSaveFile -defaultextension $type -initialfile $selectedFile -filetypes $types -parent .]
} else {
set dir [tk_chooseDirectory -title "Choose a directory"]
#set file [append $path $selectedFile]
if {$dir eq ""} {
return
}
}
.frame_files.list select set $listBoxCurrentIndex
if {$file == ""} {
return
}
set max_pal_index 0
foreach line $indexedImageData {
foreach pal_index [split $line " "] {
if {$pal_index > $max_pal_index} {
set max_pal_index $pal_index
}
}
}
set n 0
set d 0
set f [catch {set fid [open $file w+]}]
if {$type eq ".inc"} {
set inc_data ".db"
foreach c [split $paletteEntryText " "] {
set inc_data "$inc_data $c"
incr n
if {$n > $max_pal_index} {
break
}
}
set d [catch {puts $fid $inc_data}]
} else {
catch {fconfigure $fid -translation binary}
foreach i [split $paletteEntryText "$"] {
if {$i eq ""} {
continue
}
if {[catch {puts -nonewline $fid [binary decode hex [string trim $i " "]]}]} {
set d 1
}
incr n
if {$n > $max_pal_index} {
break
}
}
}
set c [catch {close $fid}]
if {$f || $d || $c || ![file exists $file] || ![file isfile $file] || ![file readable $file]} {
tk_messageBox -parent . -icon error -message "An error occurred while saving \"$file\"."
}
}
proc saveTiles {type multiple} {
global listBoxCurrentIndex tiles_plugins
if {![catch {set plugin [dict get $tiles_plugins $type]}]} {
set plugin_name $type
set type .[lindex $plugin 1]
}
set selectedFile [file rootname [.frame_files.list get $listBoxCurrentIndex]]
set selectedFile [append selectedFile " (tiles)"]
set selectedFile [append selectedFile $type]
if {$multiple == 0} {
set types [list [list [list] [list $type]]]
set file [tk_getSaveFile -defaultextension $type -initialfile $selectedFile -filetypes $types -parent .]
} else {
set dir [tk_chooseDirectory -title "Choose a directory"]
#set file [append $path $selectedFile]
if {$dir eq ""} {
return
}
}
.frame_files.list select set $listBoxCurrentIndex
if {$file == ""} {
return
}
set tilesData [.tiles_text get 0.0 end]
set ti 0
set n 0
set d 0
set f [catch {set fid [open $file w+]}]
if {$type eq ".inc"} {
set d [catch {puts $fid $tilesData}]
} else {
catch {fconfigure $fid -translation binary}
set tilesData [string map {".db " ""} $tilesData]
set tilesData [split $tilesData "\n"]
set bin [list]
foreach l $tilesData {
if {[expr {$n % 2} == 0]} {
incr n
incr ti
continue
}
foreach i [split $l "$"] {
if {$i eq ""} {
continue
}