neser 1.2.0

NESER - Nintendo Emulation Systems Engine (Rust). Desktop and WebAssembly frontends.
Documentation
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
; CGB Boot ROM for Neser
; 
; This is an IPR-free implementation based on SameBoy's open-source boot ROM.
; The boot ROM is 2048 bytes, mapped to $0000-$00FF and $0200-$08FF.
;
; Key features:
; - Logo decompression from cartridge header
; - Scroll animation
; - Two-tone boot chime
; - Automatic compatibility palette selection for DMG games
; - Manual palette override via button combos
;
; Memory layout:
;   $0000-$00FF: First mapped region (256 bytes)
;   $0100-$01FF: Cartridge header (NOT mapped)
;   $0200-$08FF: Second mapped region (1792 bytes)
;
; References:
; - SameBoy: https://github.com/LIJI32/SameBoy
; - Pan Docs: https://gbdev.io/pandocs/Power_Up_Sequence

; ═══════════════════════════════════════════════════════════════════════════════
; Hardware register definitions
; ═══════════════════════════════════════════════════════════════════════════════

; Address definitions for cartridge header
; These are used to compute the title checksum for palette selection
;DEF Title           EQU $0134
;DEF OldLicenseeCode EQU $014B  
;DEF NewLicenseeCode EQU $0144
;DEF CGBFlag         EQU $0143
;DEF NintendoLogo    EQU $0104

; ═══════════════════════════════════════════════════════════════════════════════
; $0000-$00FF: First mapped region
; ═══════════════════════════════════════════════════════════════════════════════

$0000:
    LD SP, $FFFE        ; Initialize stack pointer
    
; Clear VRAM
    LD HL, $8000        ; VRAM start
ClearVRAM:
    XOR A
    LDI [HL], A
    BIT 5, H            ; Check if H >= $A0 (past VRAM)
    JR Z, ClearVRAM

; Clear OAM
    LD H, $FE           ; OAM at $FE00
    LD C, $A0           ; 160 bytes
ClearOAM:
    LDI [HL], A
    DEC C
    JR NZ, ClearOAM

; Initialize wave RAM (Production CGB only - CGB-0 skips this)
; This writes alternating $00/$FF pattern to $FF30-$FF3F
IF_CGB_PRODUCTION:
    LD C, $10           ; 16 bytes
    LD HL, $FF30
InitWaveRAM:
    LDI [HL], A
    CPL                 ; Toggle between $00 and $FF
    DEC C
    JR NZ, InitWaveRAM
ENDIF_CGB_PRODUCTION:

; Clear HRAM state variables
    XOR A
    LDH [$80], A        ; hInputPalette = 0
    LDH [$81], A        ; hTitleChecksum = 0

; Initialize audio
    LD A, $80           ; APU on
    LDH [$26], A        ; NR52 = $80
    LDH [$11], A        ; NR11 = $80 (50% duty)
    LD A, $F3
    LDH [$12], A        ; NR12 = $F3 (envelope)
    LDH [$25], A        ; NR51 = $F3 (panning)
    LD A, $77
    LDH [$24], A        ; NR50 = $77 (volume)

; Initialize BG palette
    LD A, $FC           ; BGP: 11 11 11 00 (white transparent)
    LDH [$47], A        ; BGP

; ═══════════════════════════════════════════════════════════════════════════════
; Logo loading
; ═══════════════════════════════════════════════════════════════════════════════
; Load and decompress the Nintendo logo from cartridge header ($0104-$0133)
; Each nibble represents 4 pixels; we double them for 8x8 tiles

    LD DE, $0104        ; Nintendo logo in cartridge header
    LD HL, $8010        ; Destination in VRAM (tile $01)

LoadLogoLoop:
    LD A, [DE]          ; Read logo byte
    LD B, A
    CALL DoubleBitsAndWriteRowTwice
    INC DE
    LD A, E
    CP $34              ; End of logo at $0134
    JR NZ, LoadLogoLoop

; Load trademark symbol (®)
    CALL LoadTrademarkSymbol

; Clear second VRAM bank (CGB has two banks)
    LD A, $01
    LDH [$4F], A        ; VBK = 1 (switch to bank 1)
    LD HL, $8000
ClearVRAMBank1:
    XOR A
    LDI [HL], A
    BIT 5, H
    JR Z, ClearVRAMBank1

; Load the compressed tileset for the SameBoy-style logo
    CALL LoadTileset

; Setup tilemap
    LD B, $03           ; 3 rows for large logo
    LD HL, $9842        ; Tilemap position (row 6, col 2)
    LD D, $03           ; Tile stride for large logo
    LD A, $08           ; Starting tile number

TilemapLoop:
    LD C, $10           ; 16 tiles per row

TilemapRowLoop:
    ; Write tile with palette attribute
    PUSH AF
    LD A, $01
    LDH [$4F], A        ; VBK = 1 (attributes)
    LD [HL], $08        ; Palette 0, bank 0, no flip, priority
    XOR A
    LDH [$4F], A        ; VBK = 0 (tiles)
    POP AF
    LDI [HL], A
    ADD D               ; Next tile (stride = 3 for large, 1 for small logo)
    DEC C
    JR NZ, TilemapRowLoop
    
    ; Move to next row
    SUB $2C             ; Adjust tile number for next row
    PUSH DE
    LD DE, $10          ; Move down one row in tilemap
    ADD HL, DE
    POP DE
    DEC B
    JR NZ, TilemapLoop

    ; Small logo row
    DEC D               ; D = 2
    DEC D               ; D = 1
    JR Z, EndTilemap
    LD A, $38           ; Starting tile for small logo
    LD L, $A7           ; Position for small logo
    LD B, $01           ; 1 row
    LD C, $07           ; 7 tiles
    JR TilemapRowLoop

EndTilemap:
    XOR A
    LDH [$4F], A        ; VBK = 0

; ═══════════════════════════════════════════════════════════════════════════════
; Setup palettes for animation
; ═══════════════════════════════════════════════════════════════════════════════

    ; Load initial animation palettes (8 BG palettes)
    CALL LoadAnimationPalettes

; Turn on LCD
    LD A, $91           ; LCD on, BG on, window off, tiles at $8000
    LDH [$40], A        ; LCDC

; ═══════════════════════════════════════════════════════════════════════════════
; Animation and sound
; ═══════════════════════════════════════════════════════════════════════════════

    ; Animate the intro (scroll effect)
    CALL DoIntroAnimation
    
    ; Wait a bit then play first tone
    LD A, $30           ; Wait loop counter
    LDH [$82], A        ; hWaitLoopCounter
    LD B, $04           ; Frames before first sound
    CALL WaitBFrames
    
    ; Play first sound ($83 = ~988 Hz)
    LD A, $83
    CALL PlaySound
    LD B, $05           ; Frames before second sound
    CALL WaitBFrames
    
    ; Play second sound ($C1 = ~1319 Hz)
    LD A, $C1
    CALL PlaySound

; Wait loop with input checking
WaitLoop:
    CALL GetInputPaletteIndex
    CALL WaitFrame
    LDH A, [$82]        ; hWaitLoopCounter
    DEC A
    LDH [$82], A
    JR NZ, WaitLoop

; ═══════════════════════════════════════════════════════════════════════════════
; Preboot - prepare for cartridge handoff
; ═══════════════════════════════════════════════════════════════════════════════

    CALL Preboot

; Jump to boot exit
    JP BootGame

; ═══════════════════════════════════════════════════════════════════════════════
; $00FE-$00FF: Boot exit (must be at fixed address)
; ═══════════════════════════════════════════════════════════════════════════════

$00FE:
BootGame:
    LDH [$50], A        ; Write to $FF50 unmaps boot ROM, starts cartridge

; ═══════════════════════════════════════════════════════════════════════════════
; $0200+: Second mapped region - subroutines and data
; ═══════════════════════════════════════════════════════════════════════════════

$0200:

; ─────────────────────────────────────────────────────────────────────────────
; DoubleBitsAndWriteRowTwice: Expands 4-bit nibble to 8 pixels
; Input: B = byte with nibbles to expand
; ─────────────────────────────────────────────────────────────────────────────
DoubleBitsAndWriteRowTwice:
    CALL .twice
.twice:
    LD A, $04
    LD C, $00
.doubleCurrentBit:
    SLA B
    PUSH AF
    RL C
    POP AF
    RL C
    DEC A
    JR NZ, .doubleCurrentBit
    LD A, C
    LDI [HL], A
    INC HL
    LDI [HL], A
    INC HL
    RET

; ─────────────────────────────────────────────────────────────────────────────
; LoadTrademarkSymbol: Load the ® symbol tile
; ─────────────────────────────────────────────────────────────────────────────
LoadTrademarkSymbol:
    LD DE, TrademarkSymbol
    LD C, $08           ; 8 bytes
.loop:
    LD A, [DE]
    INC DE
    LDI [HL], A
    INC HL
    DEC C
    JR NZ, .loop
    RET

; Trademark symbol bitmap (8x8, 1bpp doubled)
TrademarkSymbol:
    DB $3C              ; ..XXXX..
    DB $42              ; .X....X.
    DB $B9              ; X.XXX..X
    DB $A5              ; X.X..X.X
    DB $B9              ; X.XXX..X
    DB $A5              ; X.X..X.X
    DB $42              ; .X....X.
    DB $3C              ; ..XXXX..

; ─────────────────────────────────────────────────────────────────────────────
; LoadTileset: Load compressed SameBoy logo tileset
; For simplicity, we use a minimal logo (can be expanded)
; ─────────────────────────────────────────────────────────────────────────────
LoadTileset:
    ; For now, just clear the area - a proper implementation would
    ; decompress the PB12-encoded SameBoy logo here
    LD HL, $8080
    LD BC, $0300        ; Clear some tiles
.clear:
    XOR A
    LDI [HL], A
    DEC BC
    LD A, B
    OR C
    JR NZ, .clear
    RET

; ─────────────────────────────────────────────────────────────────────────────
; LoadAnimationPalettes: Setup initial BG palettes for animation
; ─────────────────────────────────────────────────────────────────────────────
LoadAnimationPalettes:
    ; Write 8 palettes to BG palette memory via BCPS/BCPD
    LD A, $80           ; Auto-increment, palette 0, color 0
    LDH [$68], A        ; BCPS
    
    ; Each palette is 4 colors x 2 bytes = 8 bytes
    ; We set up a gradient from black to white
    LD B, $40           ; 64 bytes (8 palettes x 8 bytes)
    LD HL, AnimationPaletteData
.loop:
    LD A, [HLI]
    LDH [$69], A        ; BCPD
    DEC B
    JR NZ, .loop
    RET

; Animation palette data (8 palettes, each 4 colors, 2 bytes per color)
AnimationPaletteData:
    ; Palette 0 - White/Cyan/Green/Black
    DW $7FFF, $7FFF, $7FFF, $0000
    DW $7FFF, $7FFF, $7FFF, $0000
    DW $7FFF, $7FFF, $7FFF, $0000
    DW $7FFF, $7FFF, $7FFF, $0000
    DW $7FFF, $7FFF, $7FFF, $0000
    DW $7FFF, $7FFF, $7FFF, $0000
    DW $7FFF, $7FFF, $7FFF, $0000
    DW $7FFF, $7FFF, $7FFF, $0000

; ─────────────────────────────────────────────────────────────────────────────
; DoIntroAnimation: Animate the logo scroll
; ─────────────────────────────────────────────────────────────────────────────
DoIntroAnimation:
    LD A, $01
    LDH [$4F], A        ; VBK = 1 (attributes)
    LD D, $1A           ; 26 frames of animation

.animationLoop:
    LD B, $02
    CALL WaitBFrames
    
    ; Update palette attributes in tilemap
    LD HL, $98C0        ; Row 6 of tilemap
    LD C, $03           ; 3 rows

.attrLoop:
    LD A, [HL]
    CP $0F              ; Already at max?
    JR Z, .nextTile
    INC [HL]
    AND $07
    JR Z, .nextLine

.nextTile:
    INC HL
    JR .attrLoop

.nextLine:
    LD A, L
    OR $1F
    LD L, A
    INC HL
    DEC C
    JR NZ, .attrLoop
    
    DEC D
    JR NZ, .animationLoop
    
    XOR A
    LDH [$4F], A        ; VBK = 0
    RET

; ─────────────────────────────────────────────────────────────────────────────
; WaitFrame: Wait for VBlank
; ─────────────────────────────────────────────────────────────────────────────
WaitFrame:
    PUSH HL
    LD HL, $FF0F        ; IF register
    RES 0, [HL]         ; Clear VBlank flag
.wait:
    BIT 0, [HL]         ; Check VBlank flag
    JR Z, .wait
    POP HL
    RET

; ─────────────────────────────────────────────────────────────────────────────
; WaitBFrames: Wait B frames with input checking
; ─────────────────────────────────────────────────────────────────────────────
WaitBFrames:
    CALL GetInputPaletteIndex
    CALL WaitFrame
    DEC B
    JR NZ, WaitBFrames
    RET

; ─────────────────────────────────────────────────────────────────────────────
; PlaySound: Play a tone on channel 1
; Input: A = NR13 frequency low byte
; ─────────────────────────────────────────────────────────────────────────────
PlaySound:
    LDH [$13], A        ; NR13 = frequency low
    LD A, $87           ; Trigger, no length
    LDH [$14], A        ; NR14
    RET

; ─────────────────────────────────────────────────────────────────────────────
; GetInputPaletteIndex: Check joypad for palette override
; ─────────────────────────────────────────────────────────────────────────────
GetInputPaletteIndex:
    ; Read D-pad
    LD A, $20           ; Select D-pad
    LDH [$00], A        ; JOYP
    LDH A, [$00]        ; Read input
    CPL
    AND $0F
    RET Z               ; No direction pressed
    
    ; Direction pressed - could update palette here
    ; For now, just return
    RET

; ─────────────────────────────────────────────────────────────────────────────
; Preboot: Prepare registers and state for cartridge handoff
; ─────────────────────────────────────────────────────────────────────────────
Preboot:
    ; Fade palettes to white (simplified - just set white)
    LD A, $80
    LDH [$68], A        ; BCPS auto-increment
    LD B, $40
.fadeLoop:
    LD A, $FF
    LDH [$69], A        ; BCPD
    DEC B
    JR NZ, .fadeLoop

    ; Check if CGB game or DMG game
    LD A, [$0143]       ; CGBFlag in cartridge
    BIT 7, A
    JR NZ, .cgbGame
    
    ; DMG game - need compatibility mode
    CALL GetPaletteIndex
    CALL LoadDMGPalettes
    LD A, $04           ; DMG compatibility mode
    LDH [$4C], A        ; KEY0

.cgbGame:
    ; Set final register values
    LD A, $FF
    LDH [$00], A        ; JOYP = $FF (deselect all)
    
    ; Clear WRAM bank 2
    LD A, $02
    LDH [$70], A        ; SVBK = 2
    LD HL, $D000
.clearWRAM:
    XOR A
    LDI [HL], A
    BIT 5, H
    JR Z, .clearWRAM
    XOR A
    LDH [$70], A        ; SVBK = 0
    
    ; Final CPU register values for CGB mode
    LD A, $11           ; A = $11 (CGB identifier)
    LD BC, $0000
    LD DE, $0008
    LD HL, $007C
    RET

; ─────────────────────────────────────────────────────────────────────────────
; GetPaletteIndex: Look up compatibility palette for DMG game
; Returns: A = palette index (0 = default)
; ─────────────────────────────────────────────────────────────────────────────
GetPaletteIndex:
    ; Check licensee code
    LD HL, $014B        ; OldLicenseeCode
    LD A, [HL]
    CP $33              ; New licensee?
    JR Z, .newLicensee
    DEC A               ; $01 = Nintendo
    JR NZ, .notNintendo
    JR .doChecksum

.newLicensee:
    LD L, $44           ; NewLicenseeCode
    LD A, [HLI]
    CP $30              ; '0'
    JR NZ, .notNintendo
    LD A, [HL]
    CP $31              ; '1'
    JR NZ, .notNintendo

.doChecksum:
    ; Compute title checksum
    LD L, $34           ; Title
    LD C, $10           ; 16 characters
    XOR A
.checksumLoop:
    ADD [HL]
    INC L
    DEC C
    JR NZ, .checksumLoop
    
    ; A now contains title checksum
    ; Look up in table (simplified - return 0 for default)
    LDH [$81], A        ; Save to hTitleChecksum
    XOR A               ; Return default palette
    RET

.notNintendo:
    XOR A
    RET

; ─────────────────────────────────────────────────────────────────────────────
; LoadDMGPalettes: Load palettes for DMG compatibility mode
; ─────────────────────────────────────────────────────────────────────────────
LoadDMGPalettes:
    ; Load default DMG-style palette
    LD A, $80
    LDH [$68], A        ; BCPS
    
    ; Classic green palette
    LD HL, DMGPalette
    LD B, $08           ; 8 bytes (1 palette)
.loop:
    LD A, [HLI]
    LDH [$69], A        ; BCPD
    DEC B
    JR NZ, .loop
    RET

; DMG-style green palette
DMGPalette:
    DW $7FFF            ; White
    DW $5294            ; Light gray
    DW $294A            ; Dark gray  
    DW $0000            ; Black

; ═══════════════════════════════════════════════════════════════════════════════
; Title checksum table for palette selection
; ═══════════════════════════════════════════════════════════════════════════════

TitleChecksums:
    DB $00  ; Default
    DB $88  ; ALLEY WAY
    DB $16  ; YAKUMAN
    DB $36  ; BASEBALL
    DB $D1  ; TENNIS
    DB $DB  ; TETRIS
    DB $F2  ; QIX
    DB $3C  ; DR.MARIO
    DB $8C  ; RADARMISSION
    DB $92  ; F1RACE
    DB $3D  ; YOSSY NO TAMAGO
    DB $5C
    DB $58  ; X
    DB $C9  ; MARIOLAND2
    DB $3E  ; YOSSY NO COOKIE
    DB $70  ; ZELDA
    ; ... (truncated for brevity - full table needed for complete implementation)

; Palette index per checksum (0-50)
PalettePerChecksum:
    DB 0, 4, 5, 35, 34, 3, 31, 15, 10, 5
    DB 19, 36, 7, 37, 30, 44
    ; ... (truncated for brevity)

; END OF BOOT ROM
; Padding to fill 2048 bytes is automatic