-
Notifications
You must be signed in to change notification settings - Fork 4
/
lib.rs
498 lines (427 loc) · 16.2 KB
/
lib.rs
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
#![feature(box_patterns)]
#![recursion_limit = "256"]
extern crate proc_macro;
extern crate proc_macro2;
extern crate syn;
#[macro_use]
extern crate quote;
use proc_macro::TokenStream;
use std::{cmp::Ordering, collections::HashMap};
// Bit flags indicating what occurs on a particular cycle
const DRAW_PIXEL: u32 = 1;
const SPRITE_DEC_X: u32 = 1 << 1;
const SHIFT_BG_REGISTERS: u32 = 1 << 2;
const FETCH_NT: u32 = 1 << 3;
const FETCH_AT: u32 = 1 << 4;
const FETCH_BG_LOW: u32 = 1 << 5;
const FETCH_BG_HIGH: u32 = 1 << 6;
const FILL_BG_REGISTERS: u32 = 1 << 7;
const INC_COARSE_X: u32 = 1 << 8;
const INC_FINE_Y: u32 = 1 << 9;
const HORI_V_EQ_HORI_T: u32 = 1 << 10;
const SET_VBLANK: u32 = 1 << 11;
const CLEAR_VBLANK_AND_SPRITE_ZERO_HIT: u32 = 1 << 12;
const VERT_V_EQ_VERT_T: u32 = 1 << 13;
const ODD_FRAME_SKIP_CYCLE: u32 = 1 << 14;
const FRAME_INC: u32 = 1 << 15;
const START_SPRITE_EVALUATION: u32 = 1 << 16;
const TICK_SPRITE_EVALUATION: u32 = 1 << 17;
const FILL_SPRITE_REGISTERS: u32 = 1 << 18;
// Timing
const SCANLINES: usize = 262;
const CYCLES_PER_SCANLINE: usize = 341;
const VBLANK_SCANLINE: usize = 241;
const LAST_SCANLINE: usize = 261;
#[derive(Clone)]
enum Action {
WhenRenderingEnabled(proc_macro2::TokenStream, isize),
NoReturnExpression(proc_macro2::TokenStream),
ReturnExpression(proc_macro2::TokenStream),
}
#[allow(clippy::cyclomatic_complexity)]
fn ppu_loop_impl() -> proc_macro2::TokenStream {
let mut cycle_number_map: Vec<u32> = Vec::with_capacity(SCANLINES * CYCLES_PER_SCANLINE);
let mut cycle_type_map: HashMap<u32, proc_macro2::TokenStream> = HashMap::new();
for scanline in 0..SCANLINES {
for x in 0..CYCLES_PER_SCANLINE {
let mut cycle_type = 0;
// Check for specific cycle actions
match (x, scanline) {
(1, VBLANK_SCANLINE) => cycle_type |= SET_VBLANK,
(1, LAST_SCANLINE) => cycle_type |= CLEAR_VBLANK_AND_SPRITE_ZERO_HIT,
(339, LAST_SCANLINE) => cycle_type |= ODD_FRAME_SKIP_CYCLE,
(340, LAST_SCANLINE) => cycle_type |= FRAME_INC,
(..) => (),
}
if nt_fetch_cycle(scanline, x) {
cycle_type |= FETCH_NT
}
if at_fetch_cycle(scanline, x) {
cycle_type |= FETCH_AT
}
if bg_low_fetch_cycle(scanline, x) {
cycle_type |= FETCH_BG_LOW
}
if bg_high_fetch_cycle(scanline, x) {
cycle_type |= FETCH_BG_HIGH
}
if fill_bg_shift_registers(scanline, x) {
cycle_type |= FILL_BG_REGISTERS;
}
if inc_hori_v_cycle(scanline, x) {
cycle_type |= INC_COARSE_X
}
if inc_vert_v_cycle(scanline, x) {
cycle_type |= INC_FINE_Y
}
if hori_v_eq_hori_t_cycle(scanline, x) {
cycle_type |= HORI_V_EQ_HORI_T
}
if vert_v_eq_vert_t_cycle(scanline, x) {
cycle_type |= VERT_V_EQ_VERT_T
}
if bg_shift_cycle(scanline, x) {
cycle_type |= SHIFT_BG_REGISTERS
}
if draw_pixel(scanline, x) {
cycle_type |= DRAW_PIXEL
}
if tick_sprite_evaluation(scanline, x) {
cycle_type |= TICK_SPRITE_EVALUATION
}
if fill_sprite_evaluation_registers(scanline, x) {
cycle_type |= FILL_SPRITE_REGISTERS
}
if sprite_dec_x(scanline, x) {
cycle_type |= SPRITE_DEC_X
}
if start_sprite_evaluation(scanline, x) {
cycle_type |= START_SPRITE_EVALUATION
}
cycle_number_map.push(cycle_type);
cycle_type_map.entry(cycle_type).or_insert_with(|| {
let actions = actions(cycle_type);
compile_cycle_actions(actions)
});
}
}
// Remap the cycle type to a sequential number that can be represented by a single byte
let mut compact_cycle_type_map: HashMap<u32, u8> = HashMap::new();
let mut compact_cycle_type = 0_u8;
for cycle_type in cycle_type_map.keys() {
compact_cycle_type_map.insert(*cycle_type, compact_cycle_type);
compact_cycle_type += 1;
}
let mut compact_cycle_number_map: Vec<u8> = Vec::with_capacity(SCANLINES * CYCLES_PER_SCANLINE);
for cycle_type in cycle_number_map {
compact_cycle_number_map.push(compact_cycle_type_map[&cycle_type]);
}
let match_arms: Vec<proc_macro2::TokenStream> = cycle_type_map
.iter()
.map(|(cycle_type, cycle_impl)| {
let compact_cycle_type = compact_cycle_type_map.get(cycle_type);
quote! { #compact_cycle_type => { #cycle_impl } }
})
.collect();
let total_cycles = SCANLINES * CYCLES_PER_SCANLINE;
quote! {
fn step<C: Cart>(&mut self, cart: &C) -> Interrupt {
const CYCLES_MAP: [u8; #total_cycles] = [#(#compact_cycle_number_map),*];
let frame_cycle = self.cycles % CYCLES_PER_FRAME;
let scanline = (frame_cycle / CYCLES_PER_SCANLINE) as u16;
let x = (frame_cycle % CYCLES_PER_SCANLINE) as u16;
self.cycles += 1;
match CYCLES_MAP[frame_cycle] {
#(#match_arms),*
_ => Interrupt::None
}
}
}
}
fn sprite_dec_x(scanline: usize, x: usize) -> bool {
// TODO: Determine for sure which cycles the sprite x counters are decremented
(scanline < 240 || scanline == LAST_SCANLINE) && x >= 2 && x <= 256
}
// This is an approximation, skipping all individual sprite pattern fetches
fn fill_sprite_evaluation_registers(scanline: usize, x: usize) -> bool {
(scanline < 240 || scanline == LAST_SCANLINE) && x == 320
}
fn start_sprite_evaluation(scanline: usize, x: usize) -> bool {
scanline < 240 && x == 65
}
fn tick_sprite_evaluation(scanline: usize, x: usize) -> bool {
scanline < 240 && x > 64 && x <= 256
}
fn nt_fetch_cycle(scanline: usize, x: usize) -> bool {
bg_rendering_cycle(scanline, x) && !(scanline == LAST_SCANLINE && x > 336) && x % 8 == 1
}
fn at_fetch_cycle(scanline: usize, x: usize) -> bool {
bg_rendering_cycle(scanline, x) && !(scanline == LAST_SCANLINE && x > 336) && x % 8 == 3
}
fn bg_low_fetch_cycle(scanline: usize, x: usize) -> bool {
bg_rendering_cycle(scanline, x) && !(scanline == LAST_SCANLINE && x > 336) && x % 8 == 5
}
fn bg_high_fetch_cycle(scanline: usize, x: usize) -> bool {
bg_rendering_cycle(scanline, x) && !(scanline == LAST_SCANLINE && x > 336) && x % 8 == 7
}
fn bg_rendering_cycle(scanline: usize, x: usize) -> bool {
bg_rendering_scanline(scanline) && ((x > 0 && x < 258) || x > 320)
}
fn bg_rendering_scanline(scanline: usize) -> bool {
scanline < 240 || scanline == 261
}
fn inc_hori_v_cycle(scanline: usize, x: usize) -> bool {
bg_rendering_cycle(scanline, x) && (x < 256 || x > 320) && x % 8 == 0
}
fn inc_vert_v_cycle(scanline: usize, x: usize) -> bool {
bg_rendering_scanline(scanline) && x == 256
}
fn hori_v_eq_hori_t_cycle(scanline: usize, x: usize) -> bool {
bg_rendering_scanline(scanline) && x == 257
}
fn vert_v_eq_vert_t_cycle(scanline: usize, x: usize) -> bool {
scanline == 261 && (x >= 280 && x <= 304)
}
fn bg_shift_cycle(scanline: usize, x: usize) -> bool {
bg_rendering_scanline(scanline) && (x >= 2 && x <= 257) || (x >= 322 && x <= 337)
}
fn fill_bg_shift_registers(scanline: usize, x: usize) -> bool {
bg_rendering_scanline(scanline) && ((x > 8 && x <= 257) && (x - 1) % 8 == 0)
|| (x == 329 || x == 337)
}
fn draw_pixel(scanline: usize, x: usize) -> bool {
x >= 2 && x <= 257 && scanline < 240
}
fn compile_cycle_actions(actions: Vec<Action>) -> proc_macro2::TokenStream {
let mut no_return: Vec<Action> = Vec::new();
let mut when_rendering_enabled: Vec<Action> = Vec::new();
let mut returns: Option<Action> = None;
for action in actions {
match action {
Action::ReturnExpression(_) => {
if returns.is_some() {
panic!("cannot have two return actions")
} else {
returns = Some(action.clone());
}
}
Action::WhenRenderingEnabled(..) => when_rendering_enabled.push(action.clone()),
Action::NoReturnExpression(_) => no_return.push(action.clone()),
}
}
let mut lines = Vec::<proc_macro2::TokenStream>::new();
for action in no_return {
if let Action::NoReturnExpression(token_stream) = action {
lines.push(token_stream);
} else {
panic!("only no return items should be in here")
}
}
if !when_rendering_enabled.is_empty() {
let mut rendering_enabled_tokens = Vec::<proc_macro2::TokenStream>::new();
when_rendering_enabled.sort_by(|a, b| {
let a = match *a {
Action::WhenRenderingEnabled(_, order) => order,
_ => 0,
};
let b = match *b {
Action::WhenRenderingEnabled(_, order) => order,
_ => 0,
};
a.cmp(&b)
});
for action in when_rendering_enabled {
if let Action::WhenRenderingEnabled(action_lines, _) = action {
rendering_enabled_tokens.push(action_lines);
} else {
panic!("only no return items should be in here")
}
}
let rendering_enabled_body = quote! {
if self.mask.rendering_enabled() {
#(#rendering_enabled_tokens)*
}
};
lines.push(rendering_enabled_body);
}
if let Some(action) = returns {
if let Action::ReturnExpression(action_lines) = action {
lines.push(action_lines);
} else {
panic!("only no return items should be in here")
}
} else {
let line = quote! { Interrupt::None };
lines.push(line)
}
let cycle_impl = quote! { #(#lines)* };
cycle_impl
}
fn actions(cycle_type: u32) -> Vec<Action> {
let mut actions = Vec::new();
if cycle_type == 0 {
let lines = quote! {};
actions.push(Action::NoReturnExpression(lines))
}
if cycle_type & START_SPRITE_EVALUATION > 0 {
let lines = quote! {
self.sprite_renderer.start_sprite_evaluation(scanline, self.control);
};
actions.push(Action::WhenRenderingEnabled(lines, 10))
}
if cycle_type & SPRITE_DEC_X > 0 {
let output = quote! { self.sprite_renderer.dec_x_counters(); };
actions.push(Action::WhenRenderingEnabled(output, 0))
}
if cycle_type & FILL_SPRITE_REGISTERS > 0 {
let lines = quote! {
self.sprite_renderer.fill_registers(self.vram.as_ref(), self.control, cart);
};
actions.push(Action::WhenRenderingEnabled(lines, 0))
}
if cycle_type & TICK_SPRITE_EVALUATION > 0 {
let lines = quote! {
self.sprite_renderer.tick_sprite_evaluation();
};
actions.push(Action::WhenRenderingEnabled(lines, 100))
}
if cycle_type & DRAW_PIXEL > 0 {
let lines = quote! {
self.draw_pixel(x, scanline);
};
actions.push(Action::WhenRenderingEnabled(lines, -10000))
}
if cycle_type & SET_VBLANK > 0 {
let lines = quote! {
self.status.set_in_vblank();
if self.control.nmi_on_vblank_start() {
Interrupt::Nmi
} else {
Interrupt::None
}
};
actions.push(Action::ReturnExpression(lines))
}
if cycle_type & CLEAR_VBLANK_AND_SPRITE_ZERO_HIT > 0 {
let lines = quote! {
// Updating palettes here isn't accurate, but should suffice for now
self.background_renderer.update_palettes(self.vram.as_ref());
self.sprite_renderer.update_palettes(self.vram.as_ref());
self.status.clear_in_vblank();
self.status.clear_sprite_zero_hit();
};
actions.push(Action::NoReturnExpression(lines))
}
if cycle_type & INC_COARSE_X > 0 {
let lines = quote! {
self.vram.as_ref().coarse_x_increment();
};
actions.push(Action::WhenRenderingEnabled(lines, 0))
}
if cycle_type & INC_FINE_Y > 0 {
let lines = quote! {
self.vram.as_ref().fine_y_increment();
};
actions.push(Action::WhenRenderingEnabled(lines, 0))
}
if cycle_type & HORI_V_EQ_HORI_T > 0 {
let lines = quote! {
self.vram.as_ref().copy_horizontal_pos_to_addr();
};
actions.push(Action::WhenRenderingEnabled(lines, 0))
}
if cycle_type & FETCH_AT > 0 {
let lines = quote! {
self.background_renderer.fetch_attribute_byte(self.vram.as_ref(), cart);
};
actions.push(Action::WhenRenderingEnabled(lines, 0))
}
if cycle_type & FETCH_NT > 0 {
let lines = quote! {
self.background_renderer.fetch_nametable_byte(self.vram.as_ref(), cart);
};
actions.push(Action::WhenRenderingEnabled(lines, 0))
}
if cycle_type & FETCH_BG_LOW > 0 {
let lines = quote! {
self.background_renderer.fetch_pattern_low_byte(self.vram.as_ref(), self.control, cart);
};
actions.push(Action::WhenRenderingEnabled(lines, 0))
}
if cycle_type & FETCH_BG_HIGH > 0 {
let lines = quote! {
self.background_renderer.fetch_pattern_high_byte(self.vram.as_ref(), self.control, cart);
};
actions.push(Action::WhenRenderingEnabled(lines, 0))
}
if cycle_type & ODD_FRAME_SKIP_CYCLE > 0 {
let lines = quote! {
// This is the last cycle for odd frames
// The additional cycle increment puts us to pixel 0,0
if self.odd_frame && self.mask.show_background() {
self.cycles += 1;
self.odd_frame = false;
}
};
actions.push(Action::NoReturnExpression(lines))
}
if cycle_type & FRAME_INC > 0 {
let lines = quote! {
// This is the last cycle for even frames and when rendering disabled
self.odd_frame = !self.odd_frame;
};
actions.push(Action::NoReturnExpression(lines))
}
if cycle_type & SHIFT_BG_REGISTERS > 0 {
let lines = quote! {
self.background_renderer.tick_shifters();
};
actions.push(Action::WhenRenderingEnabled(lines, 0))
}
if cycle_type & VERT_V_EQ_VERT_T > 0 {
let lines = quote! {
self.vram.as_ref().copy_vertical_pos_to_addr();
};
actions.push(Action::WhenRenderingEnabled(lines, 0))
}
if cycle_type & FILL_BG_REGISTERS > 0 {
let lines = quote! {
self.background_renderer.fill_shift_registers(self.vram.as_ref().addr());
};
actions.push(Action::WhenRenderingEnabled(lines, 0))
}
actions.sort_by(cmp_action);
actions
}
fn cmp_action(a: &Action, b: &Action) -> Ordering {
match *a {
Action::NoReturnExpression(_) => match *b {
Action::NoReturnExpression(_) => Ordering::Equal,
_ => Ordering::Less,
},
Action::ReturnExpression(_) => match *b {
Action::ReturnExpression(_) => Ordering::Equal,
_ => Ordering::Greater,
},
Action::WhenRenderingEnabled(_, order_a) => match *b {
Action::WhenRenderingEnabled(_, order_b) => order_a.cmp(&order_b),
Action::NoReturnExpression(_) => Ordering::Greater,
Action::ReturnExpression(_) => Ordering::Less,
},
}
}
#[proc_macro_attribute]
pub fn ppu_loop(_: TokenStream, input: TokenStream) -> TokenStream {
let input: proc_macro2::TokenStream = input.into();
let item: syn::Item = syn::parse2(input).unwrap();
match item {
syn::Item::Fn(ref function) => match function.decl.output {
syn::ReturnType::Type(_, ref ty) => match ty {
box syn::Type::Path(_) => ppu_loop_impl().into(),
_ => panic!("it's not path!"),
},
_ => panic!("It's not a type!"),
},
_ => panic!("`#[ppu_loop]` attached to an unsupported element!"),
}
}