|
| 1 | +// Wokwi Custom Chips with Rust |
| 2 | +// |
| 3 | +// Very rough prototype by Uri Shaked |
| 4 | +// |
| 5 | +// Look at chipInit() at the bottom, and open Chrome devtools console to see the debugPrint(). |
| 6 | + |
| 7 | +use std::ffi::{c_void, CString}; |
| 8 | + |
| 9 | +use wokwi_chip_ll::{ |
| 10 | + bufferWrite, debugPrint, framebufferInit, timerInit, timerStart, BufferId, TimerConfig, |
| 11 | +}; |
| 12 | + |
| 13 | +const MS: u32 = 1000; // micros |
| 14 | + |
| 15 | +// Colors: |
| 16 | +const DEEP_GREEN: u32 = 0xff003000; // ARGB |
| 17 | +const PURPLE: u32 = 0xffff00ff; // ARGB |
| 18 | + |
| 19 | +struct Chip { |
| 20 | + frame_buffer: BufferId, |
| 21 | + width: u32, |
| 22 | + height: u32, |
| 23 | + current_row: u32, |
| 24 | +} |
| 25 | + |
| 26 | +fn draw_line(chip: &Chip, row: u32, color: u32) { |
| 27 | + let color_bytes_ptr = &color as *const u32 as *const u8; |
| 28 | + |
| 29 | + let offset = chip.width * 4 * row; |
| 30 | + for x in (0..chip.width * 4).step_by(4) { |
| 31 | + unsafe { |
| 32 | + bufferWrite(chip.frame_buffer, offset + x, color_bytes_ptr, 4); |
| 33 | + } |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +pub unsafe fn on_timer_fired(user_data: *const c_void) { |
| 38 | + let chip = &mut *(user_data as *mut Chip); |
| 39 | + |
| 40 | + if chip.current_row == 0 { |
| 41 | + debugPrint( |
| 42 | + CString::new("First row!") |
| 43 | + .unwrap() |
| 44 | + .into_raw(), |
| 45 | + ); |
| 46 | + } |
| 47 | + |
| 48 | + draw_line(chip, chip.current_row, DEEP_GREEN); |
| 49 | + |
| 50 | + chip.current_row = (chip.current_row + 1) % chip.height; |
| 51 | + draw_line(chip, chip.current_row, PURPLE); |
| 52 | +} |
| 53 | + |
| 54 | +#[no_mangle] |
| 55 | +pub unsafe extern "C" fn chipInit() { |
| 56 | + debugPrint( |
| 57 | + CString::new("Hello from Framebuffer Chip!") |
| 58 | + .unwrap() |
| 59 | + .into_raw(), |
| 60 | + ); |
| 61 | + |
| 62 | + let mut width = 0; |
| 63 | + let mut height = 0; |
| 64 | + let frame_buffer = framebufferInit(&mut width, &mut height); |
| 65 | + |
| 66 | + let chip = Chip { |
| 67 | + frame_buffer: frame_buffer, |
| 68 | + width: width, |
| 69 | + height: height, |
| 70 | + current_row: 0, |
| 71 | + }; |
| 72 | + |
| 73 | + let timer_config = TimerConfig { |
| 74 | + user_data: &chip as *const _ as *const c_void, |
| 75 | + callback: on_timer_fired as *const c_void, |
| 76 | + }; |
| 77 | + |
| 78 | + let timer = timerInit(&timer_config); |
| 79 | + timerStart(timer, 10 * MS, true); |
| 80 | +} |
0 commit comments