5 Commits

Author SHA1 Message Date
53ba21084d implement random walk for enemies 2023-04-10 14:05:06 +02:00
3424976d40 start implementing a pacman-like game in zig 2023-04-10 13:26:58 +02:00
1a06ebbc95 update zig example 2023-04-08 15:10:09 +02:00
d1b6fa36e8 update frame pacing calculation in native runtime 2023-04-07 18:33:22 +02:00
b3a8512129 update frame pacing calculation in web runtime
fixes carts running too slow in chrome
2023-04-07 17:08:04 +02:00
24 changed files with 2695 additions and 3053 deletions

3200
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -11,21 +11,21 @@ native = ["wasmtime", "uw8-window", "cpal", "rubato" ]
browser = ["warp", "tokio", "tokio-stream", "webbrowser"]
[dependencies]
wasmtime = { version = "19.0.1", optional = true }
wasmtime = { version = "5.0.0", optional = true }
anyhow = "1"
env_logger = "0.11.3"
env_logger = "0.10"
log = "0.4"
uw8-window = { path = "uw8-window", optional = true }
notify-debouncer-mini = { version = "0.4.1", default-features = false }
notify-debouncer-mini = { version = "0.2.1", default-features = false }
pico-args = "0.5"
curlywas = { git = "https://github.com/exoticorn/curlywas.git", rev = "0e7ea50" }
wat = "1"
uw8-tool = { path = "uw8-tool" }
same-file = "1"
warp = { version = "0.3.6", optional = true }
tokio = { version = "1.37.0", features = ["sync", "rt"], optional = true }
tokio-stream = { version = "0.1.15", features = ["sync"], optional = true }
webbrowser = { version = "0.8.13", optional = true }
warp = { version = "0.3.3", optional = true }
tokio = { version = "1.24.0", features = ["sync", "rt"], optional = true }
tokio-stream = { version = "0.1.11", features = ["sync"], optional = true }
webbrowser = { version = "0.8.6", optional = true }
ansi_term = "0.12.1"
cpal = { version = "0.15.3", optional = true }
rubato = { version = "0.15.0", optional = true }
cpal = { version = "0.14.2", optional = true }
rubato = { version = "0.12.0", optional = true }

View File

@@ -1,14 +0,0 @@
include "../include/microw8-api.cwa"
export fn upd() {
printString(USER_MEM);
}
data USER_MEM {
// clear screen, switch to graphics text mode, text scale 4
i8(12, 5, 30, 4)
// text color, position, print two lines
i8(15, 86, 31, 8, 80) "Hello," i8(8, 8, 8, 8, 8, 10) "MicroW8!"
// print same two lines with different color and slight offset
i8(15, 47, 31, 10, 82) "Hello," i8(8, 8, 8, 8, 8, 10) "MicroW8!" i8(0)
}

View File

@@ -4,13 +4,13 @@ const SPRITE = 0x20000;
export fn upd() {
cls(0);
let t = time() / 2_f;
let t = time();
let i: i32;
loop spriteLoop {
let inline x = sin(t * -1.3 + i as f32 * (3.141 / 30_f)) * 180_f + 160_f;
let inline y = sin(t * 1.7 + i as f32 * (3.141 / 40_f)) * 140_f + 120_f;
blitSprite(SPRITE, 16, x as i32, y as i32, (i & 3) * 0x200 + 0x100);
branch_if (i +:= 1) < 100: spriteLoop;
let inline x = sin(t * -1.3 + i as f32 / 8_f) * 180_f + 160_f;
let inline y = sin(t * 1.7 + i as f32 / 9_f) * 140_f + 120_f;
blitSprite(SPRITE, 16, x as i32, y as i32, 0x100);
branch_if (i +:= 1) < 200: spriteLoop;
}
}

View File

@@ -1,2 +1,2 @@
/zig-cache/
/zig-out/
zig-cache/
zig-out/

View File

@@ -5,11 +5,7 @@ pub fn build(b: *std.build.Builder) void {
const lib = b.addSharedLibrary("cart", "main.zig", .unversioned);
lib.setBuildMode(mode);
lib.setTarget(.{
.cpu_arch = .wasm32,
.os_tag = .freestanding,
.cpu_features_add = std.Target.wasm.featureSet(&.{ .nontrapping_fptoint })
});
lib.setTarget(.{ .cpu_arch = .wasm32, .os_tag = .freestanding, .cpu_features_add = std.Target.wasm.featureSet(&.{.nontrapping_fptoint}) });
lib.import_memory = true;
lib.initial_memory = 262144;
lib.max_memory = 262144;
@@ -18,19 +14,13 @@ pub fn build(b: *std.build.Builder) void {
lib.install();
if (lib.install_step) |install_step| {
const run_filter_exports = b.addSystemCommand(&[_][]const u8{
"uw8", "filter-exports", "zig-out/lib/cart.wasm", "zig-out/lib/cart-filtered.wasm"
});
const run_filter_exports = b.addSystemCommand(&[_][]const u8{ "uw8", "filter-exports", "zig-out/lib/cart.wasm", "zig-out/lib/cart-filtered.wasm" });
run_filter_exports.step.dependOn(&install_step.step);
const run_wasm_opt = b.addSystemCommand(&[_][]const u8{
"wasm-opt", "-Oz", "-o", "zig-out/cart.wasm", "zig-out/lib/cart-filtered.wasm"
});
const run_wasm_opt = b.addSystemCommand(&[_][]const u8{ "wasm-opt", "--enable-nontrapping-float-to-int", "-Oz", "-o", "zig-out/cart.wasm", "zig-out/lib/cart-filtered.wasm" });
run_wasm_opt.step.dependOn(&run_filter_exports.step);
const run_uw8_pack = b.addSystemCommand(&[_][]const u8{
"uw8", "pack", "-l", "9", "zig-out/cart.wasm", "zig-out/cart.uw8"
});
const run_uw8_pack = b.addSystemCommand(&[_][]const u8{ "uw8", "pack", "-l", "5", "zig-out/cart.wasm", "zig-out/cart.uw8" });
run_uw8_pack.step.dependOn(&run_wasm_opt.step);
const make_opt = b.step("make_opt", "make size optimized cart");

142
examples/zig/game/main.zig Normal file
View File

@@ -0,0 +1,142 @@
const uw8 = @import("uw8.zig");
var redBallSprite: [16 * 16]u8 = undefined;
var greenBallSprite: [16 * 16]u8 = undefined;
var blueBallSprite: [16 * 16]u8 = undefined;
var wallSprite: [24 * 24]u8 = undefined;
const SphereConfigStep = struct { size: u8, color: u8 };
// zig fmt: off
const redSphereConfig: [4]SphereConfigStep = .{
.{ .size = 0, .color = 0x3d },
.{ .size = 2, .color = 0x48 },
.{ .size = 6, .color = 0x65 },
.{ .size = 9, .color = 0x55 }
};
const greenSphereConfig: [4]SphereConfigStep = .{
.{ .size = 0, .color = 0x7d },
.{ .size = 2, .color = 0x88 },
.{ .size = 6, .color = 0x96 },
.{ .size = 9, .color = 0xa3 }
};
const blueSphereConfig: [4]SphereConfigStep = .{
.{ .size = 0, .color = 0x2e },
.{ .size = 2, .color = 0x19 },
.{ .size = 6, .color = 0x17 },
.{ .size = 9, .color = 0x24 }
};
const levelData: [14] *const [19]u8 = .{
"xxxxxxxxxxxxxxxxxxx",
"x x x x",
"x x xx x xx x x",
"x x xxx x xxx x x",
"x xx x x xx x",
"x xx xxxxx xx x",
"x x x x",
"x xx xx xxx xx xx x",
"x x xx xx x x",
"xx x x x x xx",
"x xx xxx xxx xx x",
"x xx x x xx x",
"x x x x x",
"xxxxxxxxxxxxxxxxxxx",
};
// zig fmt: on
export fn start() void {
blitSphere(&redBallSprite, &redSphereConfig);
blitSphere(&greenBallSprite, &greenSphereConfig);
blitSphere(&blueBallSprite, &blueSphereConfig);
createWallSprite();
}
fn blitSphere(sprite: [*]u8, config: []const SphereConfigStep) void {
for (config) |circle| {
uw8.circle(8, 8, 8, circle.color);
uw8.circle(5, 6, @intToFloat(f32, circle.size), 0);
uw8.grabSprite(sprite, 16, 0, 0, 0x100);
}
}
fn createWallSprite() void {
uw8.cls(0xe4);
var i: i32 = 0;
while (i < 50) : (i += 1) {
const x = uw8.randomf() * 16;
const y = uw8.randomf() * 16;
const radius = uw8.randomf() * 2 + 1;
const c = @intCast(u8, (uw8.random() & 3)) + 0x95;
var j: i32 = 0;
while (j < 9) : (j += 1) {
uw8.circle(x + @intToFloat(f32, @rem(j, 3) * 16), y + @intToFloat(f32, @divFloor(j, 3) * 16), radius, c);
}
}
uw8.grabSprite(&wallSprite, 16, 16, 16, 0);
}
export fn upd() void {
uw8.cls(0);
var y: usize = 0;
while (y < levelData.len) : (y += 1) {
var x: usize = 0;
while (x < levelData[y].len) : (x += 1) {
if (levelData[y][x] == 'x') {
uw8.blitSprite(&wallSprite, 16, 8 + @intCast(i32, x) * 16, @intCast(i32, y) * 16, 0);
}
}
}
updateEnemy(&enemies[0], &redBallSprite);
updateEnemy(&enemies[1], &greenBallSprite);
updateEnemy(&enemies[2], &blueBallSprite);
}
const EntityState = struct { x: i32, y: i32, dir: u2 };
var enemies: [3]EntityState = .{
.{ .x = 16, .y = 16, .dir = 1 },
.{ .x = 16 * 18, .y = 16, .dir = 3 },
.{ .x = 16, .y = 16 * 12, .dir = 1 },
};
fn updateEnemy(enemy: *EntityState, sprite: [*]u8) void {
switch (enemy.dir) {
0 => enemy.y -= 1,
1 => enemy.x += 1,
2 => enemy.y += 1,
3 => enemy.x -= 1,
}
if (((enemy.x | enemy.y) & 15) == 0) {
const tx = @intCast(usize, enemy.x) / 16;
const ty = @intCast(usize, enemy.y) / 16;
var dir = enemy.dir;
var count: u32 = 0;
if (enemy.dir != 2 and levelData[ty - 1][tx] == ' ') {
dir = 0;
count += 1;
}
if (enemy.dir != 3 and levelData[ty][tx + 1] == ' ') {
count += 1;
if (uw8.random() % count == 0) {
dir = 1;
}
}
if (enemy.dir != 0 and levelData[ty + 1][tx] == ' ') {
count += 1;
if (uw8.random() % count == 0) {
dir = 2;
}
}
if (enemy.dir != 1 and levelData[ty][tx - 1] == ' ') {
count += 1;
if (uw8.random() % count == 0) {
dir = 3;
}
}
enemy.dir = dir;
}
uw8.blitSprite(sprite, 16, 8 + enemy.x, enemy.y, 0x100);
}

10
examples/zig/game/uw8.zig Normal file
View File

@@ -0,0 +1,10 @@
pub extern fn random() u32;
pub extern fn randomf() f32;
pub extern fn time() f32;
pub extern fn cls(color: u8) void;
pub extern fn circle(x: f32, y: f32, radiu: f32, color: u8) void;
pub extern fn blitSprite(spriteData: [*]u8, size: u32, x: i32, y: i32, ctrl: u32) void;
pub extern fn grabSprite(spriteData: [*]u8, size: u32, x: i32, y: i32, ctrl: u32) void;
pub extern fn printString(str: [*:0]u8) void;
pub extern fn printInt(value: i32) void;
pub extern fn printChar(char: u32) void;

View File

@@ -0,0 +1,31 @@
const std = @import("std");
pub fn build(b: *std.build.Builder) void {
const mode = std.builtin.Mode.ReleaseSmall;
const lib = b.addSharedLibrary("cart", "main.zig", .unversioned);
lib.setBuildMode(mode);
lib.setTarget(.{ .cpu_arch = .wasm32, .os_tag = .freestanding, .cpu_features_add = std.Target.wasm.featureSet(&.{.nontrapping_fptoint}) });
lib.import_memory = true;
lib.initial_memory = 262144;
lib.max_memory = 262144;
lib.global_base = 81920;
lib.stack_size = 8192;
lib.install();
if (lib.install_step) |install_step| {
const run_filter_exports = b.addSystemCommand(&[_][]const u8{ "uw8", "filter-exports", "zig-out/lib/cart.wasm", "zig-out/lib/cart-filtered.wasm" });
run_filter_exports.step.dependOn(&install_step.step);
const run_wasm_opt = b.addSystemCommand(&[_][]const u8{ "wasm-opt", "--enable-nontrapping-float-to-int", "-Oz", "-o", "zig-out/cart.wasm", "zig-out/lib/cart-filtered.wasm" });
run_wasm_opt.step.dependOn(&run_filter_exports.step);
const run_uw8_pack = b.addSystemCommand(&[_][]const u8{ "uw8", "pack", "-l", "9", "zig-out/cart.wasm", "zig-out/cart.uw8" });
run_uw8_pack.step.dependOn(&run_wasm_opt.step);
const make_opt = b.step("make_opt", "make size optimized cart");
make_opt.dependOn(&run_uw8_pack.step);
b.default_step = make_opt;
}
}

View File

@@ -1,11 +1,11 @@
extern fn atan2(x: f32, y: f32) f32;
extern fn time() f32;
pub const FRAMEBUFFER: *[320*240]u8 = @intToPtr(*[320*240]u8, 120);
pub const FRAMEBUFFER: *[320 * 240]u8 = @intToPtr(*[320 * 240]u8, 120);
export fn upd() void {
var i: u32 = 0;
while(true) {
while (true) {
var t = time() * 63.0;
var x = @intToFloat(f32, (@intCast(i32, i % 320) - 160));
var y = @intToFloat(f32, (@intCast(i32, i / 320) - 120));
@@ -13,8 +13,10 @@ export fn upd() void {
var u = atan2(x, y) * 512.0 / 3.141;
var c = @intCast(u8, (@floatToInt(i32, d + t * 2.0) ^ @floatToInt(i32, u + t)) & 255) >> 4;
FRAMEBUFFER[@as(usize, i)] = c;
FRAMEBUFFER[i] = c;
i += 1;
if(i >= 320*240) { break; }
if (i >= 320 * 240) {
break;
}
}
}
}

Binary file not shown.

View File

@@ -62,6 +62,7 @@ export fn sndGes(t: i32) -> f32 {
let phase = channelState!GesChannelState.Phase;
let inline pulseWidth = channelReg?1;
let phaseShift = (pulseWidth - 128) * 255;
let invPhaseInc = 1 as f32 / phaseInc as f32;
i = 0;
@@ -130,7 +131,7 @@ export fn sndGes(t: i32) -> f32 {
let phaseInc = (freq * (65536.0 / 44100.0)) as i32;
let phase = channelState!GesChannelState.Phase;
if modSrc < ch {
if modSrc > ch {
phase = phase - (phaseInc << 6);
}

View File

@@ -447,7 +447,6 @@ global mut textCursorY = 0;
global mut textColor = 15;
global mut bgColor = 0;
global mut outputChannel = 0;
global mut textScale = 1;
export fn printChar(char: i32) {
loop chars {
@@ -459,8 +458,6 @@ export fn printChar(char: i32) {
global mut controlCodeLength = 0;
fn printSingleChar(char: i32) {
let charSize = 8 * textScale;
if outputChannel >= 2 & (char < 4 | char > 6) {
logChar(char);
return;
@@ -494,9 +491,9 @@ fn printSingleChar(char: i32) {
}
if char == 8 {
textCursorX = textCursorX - charSize;
textCursorX = textCursorX - 8;
if !outputChannel & textCursorX < 0 {
textCursorX = 320-charSize;
textCursorX = 320-8;
printSingleChar(11);
}
return;
@@ -506,34 +503,34 @@ fn printSingleChar(char: i32) {
if !outputChannel & textCursorX >= 320 {
printChar(0xd0a);
}
textCursorX = textCursorX + charSize;
textCursorX = textCursorX + 8;
return;
}
if char == 10 {
textCursorY = textCursorY + charSize;
textCursorY = textCursorY + 8;
if !outputChannel & textCursorY >= 240 {
textCursorY = 240 - charSize;
textCursorY = 240 - 8;
let i: i32;
loop scroll_copy {
i!120 = (i + 320 * charSize)!120;
branch_if (i := i + 4) < 320 * (240 - charSize): scroll_copy;
i!120 = i!(120 + 320 * 8);
branch_if (i := i + 4) < 320 * (240 - 8): scroll_copy;
}
rectangle(0 as f32, (240 - charSize) as f32, 320 as f32, charSize as f32, bgColor);
rectangle(0 as f32, (240 - 8) as f32, 320 as f32, 8 as f32, bgColor);
}
return;
}
if char == 11 {
textCursorY = textCursorY - charSize;
textCursorY = textCursorY - 8;
if !outputChannel & textCursorY < 0 {
textCursorY = 0;
let i = 320 * (240 - charSize);
let i = 320 * (240 - 8);
loop scroll_copy {
(i + 320 * charSize)!116 = i!116;
i!(116 + 320 * 8) = i!116;
branch_if (i := i - 4): scroll_copy;
}
rectangle(0 as f32, 0 as f32, 320 as f32, charSize as f32, bgColor);
rectangle(0 as f32, 0 as f32, 320 as f32, 8 as f32, bgColor);
}
return;
}
@@ -565,12 +562,6 @@ fn printSingleChar(char: i32) {
return;
}
if char == 30 {
let scale = 0x12d20?1;
textScale = select(scale > 0 & scale <= 16, scale, 1);
return;
}
if char == 31 {
textCursorX = 0x12d20?1 * (8 - outputChannel * 6);
textCursorY = 0x12d20?2 * (8 - outputChannel * 7);
@@ -593,7 +584,7 @@ data(0x12d00) {
1, 1, 1, 1, // 16-19,
1, 1, 1, 1, // 20-23,
1, 1, 1, 1, // 24-27,
1, 1, 2, 3 // 28-31
1, 1, 1, 3 // 28-31
)
}
@@ -602,28 +593,26 @@ fn drawChar(char: i32) {
printChar(0xd0a);
}
let charSize = 8 * textScale;
let y: i32;
loop rows {
let bits = (char * 8 + y / textScale)?0x13400;
let bits = (char * 8 + y)?0x13400;
let x = 0;
if outputChannel {
loop pixels {
if (bits << (x / textScale)) & 128 {
if (bits := bits << 1) & 256 {
setPixel(textCursorX + x, textCursorY + y, textColor);
}
branch_if (x := x + 1) < charSize: pixels;
branch_if (x := x + 1) < 8: pixels;
}
} else {
loop pixels {
setPixel(textCursorX + x, textCursorY + y, select((bits << (x / textScale)) & 128, textColor, bgColor));
branch_if (x := x + 1) < charSize: pixels;
setPixel(textCursorX + x, textCursorY + y, select((bits := bits << 1) & 256, textColor, bgColor));
branch_if (x := x + 1) < 8: pixels;
}
}
branch_if (y := y + 1) < charSize: rows;
branch_if (y := y + 1) < 8: rows;
}
textCursorX = textCursorX + charSize;
textCursorX = textCursorX + 8;
}
export fn printString(ptr: i32) {

View File

@@ -5,7 +5,7 @@ description = "Docs"
# Overview
MicroW8 loads WebAssembly modules with a maximum size of 256kb. Your module needs to export
MicroW8 loads WebAssembly modules with a maximum size of 256kb. You module needs to export
a function `fn upd()` which will be called once per frame.
After calling `upd` MicroW8 will display the 320x240 8bpp framebuffer located
at offset 120 in memory with the 32bpp palette located at 0x13000.

View File

@@ -16,14 +16,16 @@ pub struct FileWatcher {
impl FileWatcher {
pub fn new() -> Result<FileWatcher> {
let (tx, rx) = mpsc::channel();
let debouncer = new_debouncer(Duration::from_millis(100), move |res| match res {
let debouncer = new_debouncer(Duration::from_millis(100), None, move |res| match res {
Ok(events) => {
for event in events {
let _ = tx.send(event);
}
}
Err(err) => {
eprintln!("Error watching for file changes: {err}");
Err(errs) => {
for err in errs {
eprintln!("Error watching for file changes: {err}");
}
}
})?;
Ok(FileWatcher {

View File

@@ -7,7 +7,7 @@ use cpal::traits::*;
use rubato::Resampler;
use uw8_window::{Window, WindowConfig};
use wasmtime::{
Engine, Func, GlobalType, Memory, MemoryType, Module, Mutability, Store, TypedFunc, ValType,
Engine, GlobalType, Memory, MemoryType, Module, Mutability, Store, TypedFunc, ValType,
};
pub struct MicroW8 {
@@ -90,7 +90,7 @@ impl super::Runtime for MicroW8 {
let memory = wasmtime::Memory::new(&mut store, MemoryType::new(4, Some(4)))?;
let mut linker = wasmtime::Linker::new(&self.engine);
linker.define(&store, "env", "memory", memory)?;
linker.define("env", "memory", memory)?;
let loader_instance = linker.instantiate(&mut store, &self.loader_module)?;
let load_uw8 = loader_instance.get_typed_func::<i32, i32>(&mut store, "load_uw8")?;
@@ -181,10 +181,12 @@ impl super::Runtime for MicroW8 {
if let Some(mut instance) = self.instance.take() {
let time = (now - instance.start_time).as_millis() as i32;
let next_frame = {
let offset = ((time as u32 as i64 * 6) % 100 - 50) / 6;
let max = now + Duration::from_millis(17);
let next_center = now + Duration::from_millis((16 - offset) as u64);
next_center.min(max)
let frame = (time as u32 as u64 * 6 / 100) as u32;
let cur_offset = (time as u32).wrapping_sub((frame as u64 * 100 / 6) as u32);
let next_time =
((frame as u64 + 1) * 100 / 6 + cur_offset.max(1).min(4) as u64) as u32;
let offset = next_time.wrapping_sub(time as u32);
now + Duration::from_millis(offset as u64)
};
{
@@ -255,12 +257,15 @@ fn add_native_functions(
}
})?;
for i in 0..16 {
let global = wasmtime::Global::new(
&mut *store,
GlobalType::new(ValType::I32, Mutability::Const),
0.into(),
linker.define(
"env",
&format!("g_reserved{}", i),
wasmtime::Global::new(
&mut *store,
GlobalType::new(ValType::I32, Mutability::Const),
0.into(),
)?,
)?;
linker.define(&store, "env", &format!("g_reserved{}", i), global)?;
}
Ok(())
@@ -273,18 +278,14 @@ fn instantiate_platform(
) -> Result<wasmtime::Instance> {
let platform_instance = linker.instantiate(&mut *store, &platform_module)?;
let exports: Vec<(String, Func)> = platform_instance
.exports(&mut *store)
.map(|e| {
(
e.name().to_owned(),
e.into_func()
.expect("platform surely only exports functions"),
)
})
.collect();
for (name, func) in exports {
linker.define(&store, "env", &name, func)?;
for export in platform_instance.exports(&mut *store) {
linker.define(
"env",
export.name(),
export
.into_func()
.expect("platform surely only exports functions"),
)?;
}
Ok(platform_instance)
@@ -311,7 +312,7 @@ fn init_sound(
let memory = wasmtime::Memory::new(&mut store, MemoryType::new(4, Some(4)))?;
let mut linker = wasmtime::Linker::new(engine);
linker.define(&store, "env", "memory", memory)?;
linker.define("env", "memory", memory)?;
add_native_functions(&mut linker, &mut store)?;
let platform_instance = instantiate_platform(&mut linker, &mut store, platform_module)?;
@@ -328,26 +329,23 @@ fn init_sound(
let mut configs: Vec<_> = device
.supported_output_configs()?
.filter(|config| {
config.channels() == 2
&& (config.sample_format() == cpal::SampleFormat::F32
|| config.sample_format() == cpal::SampleFormat::I16)
config.channels() == 2 && config.sample_format() == cpal::SampleFormat::F32
})
.collect();
configs.sort_by_key(|config| {
let rate = 44100
.max(config.min_sample_rate().0)
.min(config.max_sample_rate().0);
let prio = if rate >= 44100 {
if rate >= 44100 {
rate - 44100
} else {
(44100 - rate) * 1000
};
prio + (config.sample_format() == cpal::SampleFormat::I16) as u32
}
});
let config = configs
.into_iter()
.next()
.ok_or_else(|| anyhow!("Could not find float or 16bit signed output config"))?;
.ok_or_else(|| anyhow!("Could not find float output config"))?;
let sample_rate = cpal::SampleRate(44100)
.max(config.min_sample_rate())
.min(config.max_sample_rate());
@@ -358,7 +356,6 @@ fn init_sound(
cpal::BufferSize::Fixed(256.max(min).min(max))
}
};
let sample_format = config.sample_format();
let config = cpal::StreamConfig {
buffer_size,
..config.config()
@@ -378,8 +375,8 @@ fn init_sound(
None
} else {
let rs = rubato::FftFixedIn::new(44100, sample_rate, 128, 1, 2)?;
let input_buffers = rs.input_buffer_allocate(true);
let output_buffers = rs.output_buffer_allocate(true);
let input_buffers = rs.input_buffer_allocate();
let output_buffers = rs.output_buffer_allocate();
Some(Resampler {
resampler: rs,
input_buffers,
@@ -391,130 +388,96 @@ fn init_sound(
let mut sample_index = 0;
let mut pending_updates: Vec<RegisterUpdate> = Vec::with_capacity(30);
let mut current_time = 0;
let mut callback = move |mut outer_buffer: &mut [f32], _: &_| {
let mut first_update = true;
while let Ok(update) = rx.try_recv() {
if first_update {
current_time += update.time.wrapping_sub(current_time) / 8;
first_update = false;
}
pending_updates.push(update);
}
while !outer_buffer.is_empty() {
store.set_epoch_deadline(30);
while pending_updates
.first()
.into_iter()
.any(|u| u.time.wrapping_sub(current_time) <= 0)
{
let update = pending_updates.remove(0);
memory.write(&mut store, 80, &update.data).unwrap();
let stream = device.build_output_stream(
&config,
move |mut outer_buffer: &mut [f32], _| {
let mut first_update = true;
while let Ok(update) = rx.try_recv() {
if first_update {
current_time += update.time.wrapping_sub(current_time) / 8;
first_update = false;
}
pending_updates.push(update);
}
let duration = if let Some(update) = pending_updates.first() {
((update.time.wrapping_sub(current_time) as usize) * sample_rate + 999) / 1000
} else {
outer_buffer.len()
};
let step_size = (duration.max(64) * 2).min(outer_buffer.len());
while !outer_buffer.is_empty() {
store.set_epoch_deadline(30);
while pending_updates
.first()
.into_iter()
.any(|u| u.time.wrapping_sub(current_time) <= 0)
{
let update = pending_updates.remove(0);
memory.write(&mut store, 80, &update.data).unwrap();
}
let mut buffer = &mut outer_buffer[..step_size];
{
let mem = memory.data_mut(&mut store);
mem[64..68].copy_from_slice(&current_time.to_le_bytes());
}
fn clamp_sample(s: f32) -> f32 {
if s.is_nan() {
0.0
let duration = if let Some(update) = pending_updates.first() {
((update.time.wrapping_sub(current_time) as usize) * sample_rate + 999) / 1000
} else {
s.max(-1.0).min(1.0)
outer_buffer.len()
};
let step_size = (duration.max(64) * 2).min(outer_buffer.len());
let mut buffer = &mut outer_buffer[..step_size];
{
let mem = memory.data_mut(&mut store);
mem[64..68].copy_from_slice(&current_time.to_le_bytes());
}
}
if let Some(ref mut resampler) = resampler {
while !buffer.is_empty() {
let copy_size = resampler.output_buffers[0]
.len()
.saturating_sub(resampler.output_index)
.min(buffer.len() / 2);
if copy_size == 0 {
resampler.input_buffers[0].clear();
resampler.input_buffers[1].clear();
for _ in 0..resampler.resampler.input_frames_next() {
resampler.input_buffers[0].push(clamp_sample(
snd.call(&mut store, (sample_index,)).unwrap_or(0.0),
));
resampler.input_buffers[1].push(clamp_sample(
snd.call(&mut store, (sample_index + 1,)).unwrap_or(0.0),
));
sample_index = sample_index.wrapping_add(2);
}
if let Some(ref mut resampler) = resampler {
while !buffer.is_empty() {
let copy_size = resampler.output_buffers[0]
.len()
.saturating_sub(resampler.output_index)
.min(buffer.len() / 2);
if copy_size == 0 {
resampler.input_buffers[0].clear();
resampler.input_buffers[1].clear();
for _ in 0..resampler.resampler.input_frames_next() {
resampler.input_buffers[0]
.push(snd.call(&mut store, (sample_index,)).unwrap_or(0.0));
resampler.input_buffers[1]
.push(snd.call(&mut store, (sample_index + 1,)).unwrap_or(0.0));
sample_index = sample_index.wrapping_add(2);
}
resampler
.resampler
.process_into_buffer(
&resampler.input_buffers,
&mut resampler.output_buffers,
None,
)
.unwrap();
resampler.output_index = 0;
} else {
for i in 0..copy_size {
buffer[i * 2] = resampler.output_buffers[0][resampler.output_index + i];
buffer[i * 2 + 1] =
resampler.output_buffers[1][resampler.output_index + i];
resampler
.resampler
.process_into_buffer(
&resampler.input_buffers,
&mut resampler.output_buffers,
None,
)
.unwrap();
resampler.output_index = 0;
} else {
for i in 0..copy_size {
buffer[i * 2] =
resampler.output_buffers[0][resampler.output_index + i];
buffer[i * 2 + 1] =
resampler.output_buffers[1][resampler.output_index + i];
}
resampler.output_index += copy_size;
buffer = &mut buffer[copy_size * 2..];
}
resampler.output_index += copy_size;
buffer = &mut buffer[copy_size * 2..];
}
} else {
for v in buffer {
*v = snd.call(&mut store, (sample_index,)).unwrap_or(0.0);
sample_index = sample_index.wrapping_add(1);
}
}
} else {
for v in buffer {
*v = clamp_sample(snd.call(&mut store, (sample_index,)).unwrap_or(0.0));
sample_index = sample_index.wrapping_add(1);
}
outer_buffer = &mut outer_buffer[step_size..];
current_time =
current_time.wrapping_add((step_size * 500 / sample_rate).max(1) as i32);
}
outer_buffer = &mut outer_buffer[step_size..];
current_time = current_time.wrapping_add((step_size * 500 / sample_rate).max(1) as i32);
}
};
let stream = if sample_format == cpal::SampleFormat::F32 {
device.build_output_stream(
&config,
callback,
move |err| {
dbg!(err);
},
None,
)?
} else {
device.build_output_stream(
&config,
move |mut buffer: &mut [i16], info| {
let mut float_buffer = [0f32; 256];
while !buffer.is_empty() {
let step_size = buffer.len().min(float_buffer.len());
let step_buffer = &mut float_buffer[..step_size];
callback(step_buffer, info);
for (dest, src) in buffer.iter_mut().take(step_size).zip(step_buffer.iter()) {
*dest = (src.max(-1.0).min(1.0) * 32767.0) as i16;
}
buffer = &mut buffer[step_size..];
}
},
move |err| {
dbg!(err);
},
None,
)?
};
},
move |err| {
dbg!(err);
},
)?;
Ok(Uw8Sound { stream, tx })
}

View File

@@ -1 +0,0 @@
* add support for 16bit sound (not just float)

View File

@@ -8,7 +8,7 @@ pub fn filter_exports(in_path: &Path, out_path: &Path) -> Result<()> {
.exports
.iter()
.filter_map(|export| match export.name.as_str() {
"start" | "upd" | "snd" => None,
"upd" | "snd" | "start" => None,
_ => Some(export.id()),
})
.collect();

1729
uw8-window/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -6,13 +6,13 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
winit = "0.29.15"
env_logger = "0.11.3"
winit = "0.27.5"
env_logger = "0.10"
log = "0.4"
pico-args = "0.5"
wgpu = "0.19.3"
pollster = "0.3.0"
bytemuck = { version = "1.15", features = [ "derive" ] }
wgpu = "0.15"
pollster = "0.2.5"
bytemuck = { version = "1.13", features = [ "derive" ] }
anyhow = "1"
minifb = { version = "0.25.0", default-features = false, features = ["x11"] }
minifb = { version = "0.23.0", default-features = false, features = ["x11"] }
winapi = { version = "0.3.9", features = [ "timeapi" ] }

View File

@@ -30,8 +30,8 @@ fn row_factor(offset: f32) -> f32 {
}
fn col_factor(offset: f32) -> f32 {
let o = max(0.0, abs(offset) - 0.4);
return 1.0 / (1.0 + o * o * 16.0);
let offset = max(0.0, abs(offset) - 0.4);
return 1.0 / (1.0 + offset * offset * 16.0);
}
fn sample_screen(tex_coords: vec2<f32>) -> vec4<f32> {

View File

@@ -1,16 +1,16 @@
use crate::{Input, WindowConfig, WindowImpl};
use anyhow::{anyhow, Result};
use std::{sync::Arc, time::Instant};
use std::{num::NonZeroU32, time::Instant};
use winit::{
dpi::PhysicalSize,
event::{Event, WindowEvent},
event::{Event, VirtualKeyCode, WindowEvent},
event_loop::{ControlFlow, EventLoop},
keyboard::{Key, KeyCode, NamedKey, PhysicalKey},
platform::pump_events::{EventLoopExtPumpEvents, PumpStatus},
window::{Fullscreen, WindowBuilder},
};
use winit::platform::run_return::EventLoopExtRunReturn;
mod crt;
mod fast_crt;
mod square;
@@ -21,7 +21,7 @@ use square::SquareFilter;
pub struct Window {
_instance: wgpu::Instance,
surface: wgpu::Surface<'static>,
surface: wgpu::Surface,
_adapter: wgpu::Adapter,
device: wgpu::Device,
queue: wgpu::Queue,
@@ -29,7 +29,7 @@ pub struct Window {
surface_config: wgpu::SurfaceConfiguration,
filter: Box<dyn Filter>,
event_loop: EventLoop<()>,
window: Arc<winit::window::Window>,
window: winit::window::Window,
gamepads: [u8; 4],
next_frame: Instant,
is_fullscreen: bool,
@@ -39,12 +39,9 @@ pub struct Window {
impl Window {
pub fn new(window_config: WindowConfig) -> Result<Window> {
async fn create(window_config: WindowConfig) -> Result<Window> {
let event_loop = EventLoop::new()?;
let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.with_inner_size(PhysicalSize::new(
(320. * window_config.scale).round() as u32,
(240. * window_config.scale).round() as u32,
))
.with_inner_size(PhysicalSize::new(640u32, 480))
.with_min_inner_size(PhysicalSize::new(320u32, 240))
.with_title("MicroW8")
.with_fullscreen(if window_config.fullscreen {
@@ -56,10 +53,8 @@ impl Window {
window.set_cursor_visible(false);
let window = Arc::new(window);
let instance = wgpu::Instance::new(Default::default());
let surface = instance.create_surface(window.clone())?;
let surface = unsafe { instance.create_surface(&window) }?;
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::LowPower,
@@ -77,13 +72,7 @@ impl Window {
let surface_config = wgpu::SurfaceConfiguration {
present_mode: wgpu::PresentMode::AutoNoVsync,
..surface
.get_default_config(
&adapter,
window.inner_size().width,
window.inner_size().height,
)
.expect("Surface incompatible with adapter")
..surface.get_default_config(&adapter, window.inner_size().width, window.inner_size().height).expect("Surface incompatible with adapter")
};
let filter: Box<dyn Filter> = create_filter(
@@ -121,93 +110,88 @@ impl Window {
impl WindowImpl for Window {
fn begin_frame(&mut self) -> Input {
let mut reset = false;
self.event_loop
.set_control_flow(ControlFlow::WaitUntil(self.next_frame));
while self.is_open {
let timeout = self.next_frame.saturating_duration_since(Instant::now());
let status = self.event_loop.pump_events(Some(timeout), |event, elwt| {
let mut new_filter = None;
match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::Resized(new_size) => {
self.surface_config.width = new_size.width;
self.surface_config.height = new_size.height;
self.surface.configure(&self.device, &self.surface_config);
self.filter.resize(&self.queue, new_size);
}
WindowEvent::CloseRequested => {
elwt.exit();
}
WindowEvent::KeyboardInput { event, .. } => {
fn gamepad_button(input: &winit::event::KeyEvent) -> u8 {
match input.physical_key {
PhysicalKey::Code(KeyCode::KeyZ) => 16,
PhysicalKey::Code(KeyCode::KeyX) => 32,
PhysicalKey::Code(KeyCode::KeyA) => 64,
PhysicalKey::Code(KeyCode::KeyS) => 128,
_ => match input.logical_key {
Key::Named(NamedKey::ArrowUp) => 1,
Key::Named(NamedKey::ArrowDown) => 2,
Key::Named(NamedKey::ArrowLeft) => 4,
Key::Named(NamedKey::ArrowRight) => 8,
_ => 0,
},
}
self.event_loop.run_return(|event, _, control_flow| {
*control_flow = ControlFlow::WaitUntil(self.next_frame);
let mut new_filter = None;
match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::Resized(new_size) => {
self.surface_config.width = new_size.width;
self.surface_config.height = new_size.height;
self.surface.configure(&self.device, &self.surface_config);
self.filter.resize(&self.queue, new_size);
}
WindowEvent::CloseRequested => {
self.is_open = false;
*control_flow = ControlFlow::Exit;
}
WindowEvent::KeyboardInput { input, .. } => {
fn gamepad_button(input: &winit::event::KeyboardInput) -> u8 {
match input.scancode {
44 => 16,
45 => 32,
30 => 64,
31 => 128,
_ => match input.virtual_keycode {
Some(VirtualKeyCode::Up) => 1,
Some(VirtualKeyCode::Down) => 2,
Some(VirtualKeyCode::Left) => 4,
Some(VirtualKeyCode::Right) => 8,
_ => 0,
},
}
if event.state == winit::event::ElementState::Pressed {
match event.logical_key {
Key::Named(NamedKey::Escape) => {
elwt.exit();
}
Key::Character(ref c) => match c.as_str() {
"f" => {
let fullscreen = if self.window.fullscreen().is_some() {
None
} else {
Some(Fullscreen::Borderless(None))
};
self.is_fullscreen = fullscreen.is_some();
self.window.set_fullscreen(fullscreen);
}
"r" => reset = true,
"1" => new_filter = Some(1),
"2" => new_filter = Some(2),
"3" => new_filter = Some(3),
"4" => new_filter = Some(4),
"5" => new_filter = Some(5),
_ => (),
},
_ => (),
}
if input.state == winit::event::ElementState::Pressed {
match input.virtual_keycode {
Some(VirtualKeyCode::Escape) => {
self.is_open = false;
*control_flow = ControlFlow::Exit;
}
Some(VirtualKeyCode::F) => {
let fullscreen = if self.window.fullscreen().is_some() {
None
} else {
Some(Fullscreen::Borderless(None))
};
self.is_fullscreen = fullscreen.is_some();
self.window.set_fullscreen(fullscreen);
}
Some(VirtualKeyCode::R) => reset = true,
Some(VirtualKeyCode::Key1) => new_filter = Some(1),
Some(VirtualKeyCode::Key2) => new_filter = Some(2),
Some(VirtualKeyCode::Key3) => new_filter = Some(3),
Some(VirtualKeyCode::Key4) => new_filter = Some(4),
Some(VirtualKeyCode::Key5) => new_filter = Some(5),
_ => (),
}
self.gamepads[0] |= gamepad_button(&event);
} else {
self.gamepads[0] &= !gamepad_button(&event);
}
self.gamepads[0] |= gamepad_button(&input);
} else {
self.gamepads[0] &= !gamepad_button(&input);
}
_ => (),
},
}
_ => (),
},
Event::RedrawEventsCleared => {
if Instant::now() >= self.next_frame
// workaround needed on Wayland until the next winit release
&& self.window.fullscreen().is_some() == self.is_fullscreen
{
*control_flow = ControlFlow::Exit
}
}
if let Some(new_filter) = new_filter {
self.filter = create_filter(
&self.device,
&self.palette_screen_mode.screen_view,
self.window.inner_size(),
self.surface_config.format,
new_filter,
);
}
});
match status {
PumpStatus::Exit(_) => self.is_open = false,
_ => (),
}
if Instant::now() >= self.next_frame {
break;
if let Some(new_filter) = new_filter {
self.filter = create_filter(
&self.device,
&self.palette_screen_mode.screen_view,
self.window.inner_size(),
self.surface_config.format,
new_filter,
);
}
}
});
Input {
gamepads: self.gamepads,
reset,
@@ -243,12 +227,10 @@ impl WindowImpl for Window {
b: 0.0,
a: 1.0,
}),
store: wgpu::StoreOp::Store,
store: true,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
});
self.filter.render(&mut render_pass);
@@ -372,7 +354,7 @@ impl PaletteScreenMode {
format: wgpu::TextureFormat::R8Uint,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
label: None,
view_formats: &[],
view_formats: &[]
});
let palette_texture = device.create_texture(&wgpu::TextureDescriptor {
@@ -387,7 +369,7 @@ impl PaletteScreenMode {
format: wgpu::TextureFormat::Rgba8UnormSrgb,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
label: None,
view_formats: &[],
view_formats: &[]
});
let screen_texture = device.create_texture(&wgpu::TextureDescriptor {
@@ -402,7 +384,7 @@ impl PaletteScreenMode {
format: wgpu::TextureFormat::Rgba8UnormSrgb,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
label: None,
view_formats: &[],
view_formats: &[]
});
let framebuffer_texture_view =
@@ -509,7 +491,7 @@ impl PaletteScreenMode {
&bytemuck::cast_slice(pixels),
wgpu::ImageDataLayout {
offset: 0,
bytes_per_row: Some(320),
bytes_per_row: NonZeroU32::new(320),
rows_per_image: None,
},
wgpu::Extent3d {
@@ -531,7 +513,7 @@ impl PaletteScreenMode {
&bytemuck::cast_slice(palette),
wgpu::ImageDataLayout {
offset: 0,
bytes_per_row: Some(256 * 4),
bytes_per_row: NonZeroU32::new(256 * 4),
rows_per_image: None,
},
wgpu::Extent3d {
@@ -550,12 +532,10 @@ impl PaletteScreenMode {
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
store: true,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
});
render_pass.set_pipeline(&self.pipeline);

View File

@@ -15,7 +15,7 @@ struct FpsCounter {
}
impl Window {
pub fn new(mut config: WindowConfig) -> Result<Window> {
pub fn new(config: WindowConfig) -> Result<Window> {
let fps_counter = if config.fps_counter {
Some(FpsCounter {
start: Instant::now(),
@@ -24,7 +24,6 @@ impl Window {
} else {
None
};
config.scale = config.scale.max(1.).min(20.);
if config.enable_gpu {
match gpu::Window::new(config) {
Ok(window) => {
@@ -72,7 +71,6 @@ pub struct WindowConfig {
filter: u32,
fullscreen: bool,
fps_counter: bool,
scale: f32,
}
impl Default for WindowConfig {
@@ -82,7 +80,6 @@ impl Default for WindowConfig {
filter: 5,
fullscreen: false,
fps_counter: false,
scale: 2.,
}
}
}
@@ -105,10 +102,6 @@ impl WindowConfig {
}
self.fullscreen = args.contains("--fullscreen");
self.fps_counter = args.contains("--fps");
self.scale = args
.opt_value_from_str("--scale")
.unwrap()
.unwrap_or(self.scale);
}
}

View File

@@ -274,7 +274,7 @@ export default function MicroW8(screen, config = {}) {
try {
let restart = false;
let thisFrame;
let nextFrame = 0;
if (!isPaused) {
let gamepads = navigator.getGamepads();
let gamepad = 0;
@@ -321,13 +321,12 @@ export default function MicroW8(screen, config = {}) {
}
canvasCtx.putImageData(imageData, 0, 0);
let timeOffset = ((time * 6) % 100 - 50) / 6;
thisFrame = startTime + time - timeOffset / 8;
} else {
thisFrame = Date.now();
let thisFrame = Math.floor(time * 6 / 100);
let timeOffset = time - thisFrame * 100 / 6;
nextFrame = Math.ceil(startTime + (thisFrame + 1) * 100 / 6 + Math.min(4, timeOffset));
}
let now = Date.now();
let nextFrame = Math.max(thisFrame + timePerFrame, now);
nextFrame = Math.max(nextFrame, now);
if (restart) {
runModule(currentData);