view clojure/com/aurellem/run/image.clj @ 511:964957680c11

got an image to display, but it doesn't tile correctly.
author Robert McIntyre <rlm@mit.edu>
date Fri, 22 Jun 2012 15:03:41 -0500
parents b9814e3114e4
children 7ba07a6adb0c
line wrap: on
line source
1 (ns com.aurellem.run.image
2 (:use (com.aurellem.gb saves gb-driver util constants
3 items vbm characters money
4 rlm-assembly))
5 (:use (com.aurellem.run util music title save-corruption
6 bootstrap-0 bootstrap-1))
7 (:require clojure.string)
8 (:import [com.aurellem.gb.gb_driver SaveState])
9 (:import java.io.File))
11 ;; want to display an image onto the screen.
12 ;; probably will be the six ponies, possibly with scrolling.
14 ;; probably don't need hi-color mode since the images shuld be
15 ;; simple.
17 ;; use background tiles? they provide greater color depth than
18 ;; sprites, and can still be scrolled, so why not?
20 ;; could also use sprites to get 3 more colors per tile for a total of
21 ;; 7 colors per tile, although not for all tiles...
25 ;; want a function to
27 ;; 1. read an image
28 ;; 2. split into a grid of 8x8 pixels
29 ;; 3. convert all RGB colors to gb-RGB colors
30 ;; 4. determine efficient color palletes for the image
31 ;; 5. output efficient assembly code to draw the image to the gb
32 ;; screen.
46 (def image-program-target 0xB000)
48 (def display-width 160)
49 (def display-height 144)
53 ;{:r :g :b }
55 (def character-data 0x8000)
56 (def character-data-end 0x97FF)
61 (def BG-data-1 0x9800)
63 (def BG-data-2 0x9C00)
65 (def OAM 0xFE00)
69 (def video-bank-select-register 0xFF4F)
71 (defn gb-rgb->bits [[r g b]]
72 (assert (<= 0 r 31))
73 (assert (<= 0 g 31))
74 (assert (<= 0 b 31))
75 [(bit-and
76 0xFF
77 (+
78 r
79 (bit-shift-left g 5)))
80 (+
81 (bit-shift-right g 3)
82 (bit-shift-left b 2))])
85 (def bg-palette-select 0xFF68)
86 (def bg-palette-data 0xFF69)
88 (def obj-palette-select 0xFF6A)
89 (def obj-palette-data 0xFF6B)
91 (def max-palettes 8)
93 (defn write-byte [target data]
94 (flatten
95 [0x3E ;; load literal to A
96 data
97 0xEA ;; load A into target
98 (reverse (disect-bytes-2 target))]))
100 (defn begin-sequential-palette-write
101 [palette-num palette-select-address]
102 (assert (<= 0 palette-num max-palettes))
103 (assert
104 (or (= palette-select-address bg-palette-select)
105 (= palette-select-address obj-palette-select)))
106 (let [palette-write-data
107 (Integer/parseInt
108 (str "1" ;; auto increment
109 "0" ;; not used
110 (format
111 "%03d"
112 (Integer/parseInt
113 (Integer/toBinaryString palette-num) 10))
114 "00" ;; color num
115 "0" ;; H/L
116 ) 2)]
117 (write-byte palette-select-address palette-write-data)))
119 (defn set-palettes [palette-select palette-data palettes]
120 (assert (<= (count palettes)) max-palettes)
121 (flatten
122 [(begin-sequential-palette-write 0 palette-select)
124 0x21 ;; target address to HL
125 (reverse (disect-bytes-2 palette-data))
128 (for [palette palettes]
129 (map (fn [byte]
130 [0x3E ;; literal to A
131 byte
132 0x77]) ;; A -> (HL)
134 (flatten
135 (map #(gb-rgb->bits (get palette % [0 0 0]))
136 (range 4)))))]))
139 (defn display-one-color
140 "Displayes a single color onto the gameboy screen. Input rgb in
141 gameboy rgb."
142 ([state [r g b]]
143 ;; construct a kernel that displays a single color
144 (let
145 [palettes (repeat 8 [[r g b] [r g b] [r g b] [r g b]])
146 kernel-address 0xC000
147 kernel
148 [0xF3 ;; disable interrupts
149 (clear-music-registers)
150 (frame-metronome)
151 ;;(set-palettes
152 ;; obj-palette-select obj-palette-data palettes)
153 (set-palettes
154 bg-palette-select bg-palette-data palettes)
155 (infinite-loop)]]
156 (-> (set-memory-range state
157 kernel-address (flatten kernel))
158 (PC! kernel-address))))
159 ([[r g b]]
160 (display-one-color @current-state [r g b])))
162 ;;(require 'cortex.sense)
163 (import java.awt.image.BufferedImage)
165 ;; (defn show-screenshot []
166 ;; (let [im (BufferedImage. 160 144 BufferedImage/TYPE_INT_RGB)
167 ;; pix (vec (pixels))
168 ;; view (cortex.sense/view-image)]
169 ;; (dorun (for [x (range 160) y (range 144)]
170 ;; (.setRGB im x y (pix (+ x (* 160 y))))))
171 ;; (view im)))
173 (defn gb-rgb->vga-rgb [[r g b]]
174 (let [vga-rgb
175 (first (pixels
176 (run-moves
177 (display-one-color
178 (tick @current-state)
179 [r g b])
180 [[][]])))]
181 [(bit-shift-right (bit-and vga-rgb 0xFF0000) 16)
182 (bit-shift-right (bit-and vga-rgb 0xFF00) 8)
183 (bit-and vga-rgb 0xFF)]))
185 (defn generate-gb-color-map []
186 (set-state! (mid-game))
187 (let [gb-colors
188 (for [r (range 32)
189 g (range 32)
190 b (range 32)]
191 [r g b])]
192 (zipmap gb-colors
193 (map gb-rgb->vga-rgb
194 gb-colors))))
196 (import java.io.FileWriter)
198 (def gb-color-map-file
199 (File. user-home "proj/vba-clojure/gb-color-map"))
201 (defn write-gb-color-map! []
202 (binding [*out*(FileWriter. gb-color-map-file)]
203 (let [out-str
204 (.replace
205 (str
206 (into (sorted-map) (generate-gb-color-map)))
207 "," ",\n")]
208 (println out-str))))
210 (def gb-color-map
211 (read-string (slurp gb-color-map-file)))
213 (import javax.imageio.stream.FileImageOutputStream)
214 (import '(javax.imageio ImageWriteParam IIOImage ImageIO))
217 (defn gen-gb-color-image! []
218 (let [im (BufferedImage. 68 69 BufferedImage/TYPE_INT_RGB)
219 pix (vec
221 (reduce
222 concat
223 (map (partial
224 sort-by
225 (fn [[r g b]]
226 (let [s (max r g b)
227 det
228 (cond
229 (= s r)
230 (+ -1000 (- g) b)
231 (= s b)
232 (+ (- r) g)
233 (= s g)
234 (+ 1000 (- b) r))]
235 det)))
236 (partition
237 68 68 []
238 (sort-by
239 (fn euclidean-distance [[r g b]]
240 (Math/sqrt (+ (* r r) (* g g) (* b b))))
241 (filter
242 (fn [[r g b]]
243 (= (max r g b) b ))
245 (seq (set (vals gb-color-map)))))))))
246 ;;view (cortex.sense/view-image)
247 target (File. user-home "proj/vba-clojure/gb-color-map-unique.png")]
248 (dorun (for [x (range 68) y (range 69)]
249 (let [[r g b] (get pix (+ x (* 68 y)) [0 0 0])
250 rgb (+ (bit-shift-left r 16)
251 (bit-shift-left g 8)
252 b)]
253 (.setRGB im x y rgb))))
254 ;;(view im)
255 (doto
256 (.next (ImageIO/getImageWritersByFormatName "png"))
257 (.setOutput (FileImageOutputStream. target))
258 (.write (IIOImage. im nil nil))
259 (.dispose))
260 im))
262 (defn gen-gb-color-image*! []
263 (let [im (BufferedImage. 213 213 BufferedImage/TYPE_INT_RGB)
264 squares
265 (vec
266 (for [r (range 32)]
267 (vec
268 (for [b (range 32) g (range 32)]
269 (gb-color-map [r g b])))))
270 ;;view (cortex.sense/view-image)
271 target (File. user-home "proj/vba-clojure/gb-color-map.png")]
273 (dorun
274 (for [s-index (range 32)]
275 (dorun
276 (for [x (range 32) y (range 32)]
278 (let [[r g b] ((squares s-index) (+ x (* 32 y)))
279 rgb (+ (bit-shift-left r 16)
280 (bit-shift-left g 8)
281 b)]
282 (.setRGB im
283 (+ 3 (* 35 (rem s-index 6)) x)
284 (+ 3 (* 35 (int (/ s-index 6))) y)
285 rgb))))))
286 ;;(view im)
287 (doto
288 (.next (ImageIO/getImageWritersByFormatName "png"))
289 (.setOutput (FileImageOutputStream. target))
290 (.write (IIOImage. im nil nil))
291 (.dispose))
292 im))
294 (def test-image
295 (ImageIO/read
296 (File. user-home "/proj/vba-clojure/images/test-gb-image.png")))
298 (defn rgb->triplet [rgb]
299 (let [r (bit-shift-right (bit-and rgb 0xFF0000) 16)
300 g (bit-shift-right (bit-and rgb 0xFF00) 8)
301 b (bit-and rgb 0xFF)]
302 [r g b]))
304 (def reverse-gb-color-map
305 (zipmap (vals gb-color-map)
306 (keys gb-color-map)))
308 (defn vga-rgb->gb-rgb [[r g b]]
309 (reverse-gb-color-map [r g b]))
311 (defn gb-tiles [^BufferedImage image]
312 (for [tile (range 360)]
313 (for [x (range 8) y (range 8)]
314 (vga-rgb->gb-rgb
315 (rgb->triplet
316 (.getRGB image (+ x (* 8 (rem tile 20)))
317 (+ y (* 8 (int (/ tile 20))))))))))
319 (defn tile->palette [tile]
320 (vec (sort (set tile))))
322 (require 'clojure.set)
324 (defn absorb-contract [objs]
325 (reduce
326 (fn [accepted new-element]
327 (if (some
328 (fn [obj]
329 (clojure.set/subset? (set new-element) (set obj)))
330 accepted)
331 accepted
332 (conj accepted new-element)))
333 []
334 (sort-by (comp - count) objs)))
336 (defn absorb-combine-4 [objs]
338 )
340 (defn palettes [^BufferedImage image]
341 (let [palettes (map tile->palette (gb-tiles image))
342 unique-palettes (absorb-contract (set palettes))]
343 unique-palettes))
345 (defn tile-pallete
346 "find the first appropirate palette for the tile in the
347 provided list of palettes."
348 [tile palettes]
349 (let [tile-colors (set tile)]
350 (swank.util/find-first
351 #(clojure.set/subset? tile-colors (set %))
352 palettes)))
355 (defn image->gb-image
356 "Returns the image in a format amenable to the gameboy's
357 internal representation. The format is:
358 {:width -- width of the image
359 :height -- height of the image
360 :palettes -- vector of all the palettes the image
361 needs, in proper order
362 :tiles -- vector of all the tiles the image needs,
363 in proper order. A tile is 64 palette
364 indices.
365 :data -- vector of pairs of the format:
366 [tile-index, palette-index]
367 in row-oriented order}"
368 [^BufferedImage image]
369 (let [image-palettes (palettes image)
370 palette-index (zipmap
371 image-palettes
372 (range (count image-palettes)))
373 tiles (gb-tiles image)
374 unique-tiles (vec (distinct tiles))
375 tile-index (zipmap unique-tiles
376 (range (count unique-tiles)))]
377 {:width (.getWidth image)
378 :height (.getHeight image)
379 :palettes image-palettes
380 :tiles
381 (vec
382 (for [tile unique-tiles]
383 (let [colors
384 (vec (tile-pallete tile image-palettes))
385 color-index
386 (zipmap colors (range (count colors)))]
387 (mapv color-index tile))))
388 :data
389 (vec
390 (for [tile tiles]
391 (let [tile-colors (set (tile->palette tile))]
392 [(tile-index tile)
393 (palette-index
394 (tile-pallete tile image-palettes))])))}))
398 (defn wait-until-v-blank
399 "Modified version of frame-metronome. waits untill LY == 144,
400 indicating start of v-blank period."
401 []
402 (let [timing-loop
403 [0x01 ; \
404 0x44 ; | load 0xFF44 into BC
405 0xFF ; /
406 0x0A] ;; (BC) -> A, now A = LY (vertical line coord)
407 continue-if-144
408 [0xFE
409 144 ;; compare LY (in A) with 144
410 0x20 ;; jump back to beginning if LY != 144 (not-v-blank)
411 (->signed-8-bit
412 (+ -4 (- (count timing-loop))))]]
413 (concat timing-loop continue-if-144)))
416 (def bg-character-data 0x9000)
418 (defn gb-tile->bytes
419 "Tile is a vector of 64 numbers between 0 and 3 that
420 represent a single 8x8 color tile in the GB screen.
421 It gets bit-packed into to 16 8-bit numbers in the following
422 form:
424 0-low 1-low ... 7-low
425 0-high 1-high ... 7-high
426 .
427 .
428 .
429 55-low ........ 63-low
430 55-high ........ 63-high"
431 [tile]
432 (let [row->bits
433 (fn [row]
434 (mapv
435 (fn [row*]
436 (Integer/parseInt (apply str row*) 2))
437 [(map #(bit-and 0x01 %) row)
438 (map #(bit-shift-right (bit-and 0x02 %) 1)
439 row)]))]
440 (vec
441 (flatten
442 (map row->bits
443 (partition 8 tile))))))
446 (defn write-data
447 "Efficient assembly to write a sequence of values to
448 memory, starting at a target address."
449 [base-address target-address data]
450 (let [len (count data)
451 program-length 21] ;; change this if program length
452 ;; below changes!
454 (flatten
455 [0x21 ;; load data address start into HL
456 (reverse (disect-bytes-2 (+ base-address program-length)))
458 0x01 ;; load target address into BC
459 (reverse (disect-bytes-2 target-address))
461 0x11 ;; load len into DE
462 (reverse (disect-bytes-2 len))
465 ;; data x-fer loop start
466 0x2A ;; (HL) -> A; HL++;
467 0x02 ;; A -> (BC);
468 0x03 ;; INC BC;
469 0x1B ;; DEC DE
471 0xAF
472 0xB2 ;; (OR D E) -> A
473 0xB3
476 0x20 ;; if DE is not now 0,
477 (->signed-8-bit -9) ;; GOTO start
479 0xC3
480 (reverse
481 (disect-bytes-2
482 (+ len base-address program-length)))
483 data])))
486 (defn test-write-data []
487 (let [test-data (concat (range 256)
488 (reverse (range 256)))
489 base-address 0xC000
490 target-address 0xD000
492 test-kernel
493 (flatten
494 [0xF3 ;; disable interrupts
495 (write-data (+ 1 base-address)
496 target-address test-data)
497 (infinite-loop)])]
498 (assert
499 (= test-data
500 (-> (mid-game)
501 tick tick tick
502 (set-memory-range base-address test-kernel)
503 (PC! base-address)
504 (run-moves (repeat 100 []))
505 (memory)
506 vec
507 (subvec target-address
508 (+ target-address
509 (count test-data))))))))
511 (def LCD-bank-select-address 0xFF4F)
513 (def BG-1-address 0x9800)
514 (def BG-2-address 0x9C00)
515 (def character-data-address 0x8000)
517 (def LCD-control-register 0xFF40)
518 (def STAT-register 0xFF41)
520 (def SCX-register 0xFF42)
521 (def SCY-register 0xFF43)
523 (defn select-LCD-bank [n]
524 (assert (or (= n 0) (= n 1)))
525 (write-byte LCD-bank-select-address n))
527 (defn display-image-kernel [base-address ^BufferedImage image]
528 (let [gb-image (image->gb-image image)
530 A [(clear-music-registers)
532 ;; [X] disable LCD protection circuit.
533 (write-byte LCD-control-register 0x00)
534 ;; now we can write to all video RAM anytime with
535 ;; impunity.
537 ;; we're only using background palettes; just set the
538 ;; minimum required bg palettes for this image,
539 ;; starting with palette #0.
541 (set-palettes bg-palette-select bg-palette-data
542 (:palettes gb-image))
544 ;; [X] switch to bank 0 to set BG character data.
545 (select-LCD-bank 0)
547 ;; [X] set SCX and SCY to 0
548 (write-byte SCX-register 0)
549 (write-byte SCY-register 0)
551 ]
552 A (flatten A)
554 B [;; [X] write minimum amount of tiles to BG character
555 ;; section
556 (write-data
557 (+ base-address (count A))
558 character-data-address
559 (flatten
560 (map gb-tile->bytes (:tiles gb-image))))]
561 B (flatten B)
564 C [;; [ ] write image to the screen in terms of tiles
565 (write-data
566 (+ base-address (+ (count A) (count B)))
567 BG-1-address
568 (map first (:data gb-image)))]
570 C (flatten C)
572 D [;; [ ] specifiy pallets for each character
573 (select-LCD-bank 1)
574 (write-data
575 (+ base-address (+ (count A) (count B) (count C)))
576 BG-1-address
577 (map second (:data gb-image)))
580 ;; [X] reactivate the LCD display
581 ;; we're using only BG images, located at
582 ;; BG-1 (0x9800), with background character data
583 ;; stored starting at 0x8000
585 (write-byte
586 LCD-control-register
587 (Integer/parseInt
588 (str
589 "1" ;; LCDC on/off
590 "0" ;; Window code area
591 "0" ;; Windowing on?
592 "1" ;; BG tile base (1 = 0x8000)
593 "0" ;; BG-1 or BG-2 ?
594 "0" ;; OBJ-block composition
595 "0" ;; OBJ-on flag
596 "1") ;; no-effect
597 2))
600 (infinite-loop)]
601 D (flatten D)]
603 (concat A B C D)))
606 (defn display-image [#^BufferedImage image]
607 (let [kernel-address 0xB000]
608 (-> (tick (tick (tick (mid-game))))
609 (set-memory-range
610 kernel-address
611 (display-image-kernel kernel-address image))
612 (PC! kernel-address))))