Native quickstart
ComingA minimal 0x native game in Rust with sg-guest and stock wgpu, built for wasm32-unknown-unknown, packaged with a manifest and run in sg-runtime.
This builds a minimal native game: a window cleared to a slowly changing colour, using
ordinary wgpu code through sg-guest. The code on this page compiles as shown against
sg-guest 0.1.0 and wgpu 30.0.1, and runs in sg-runtime as described in step 6.
Preview
sg-guest is not on a package registry yet and the runtime is not in the 0x app download.
The steps are the ones the 0x test games use; see the overview.
#1. Toolchain
Rust 1.96 or newer with the WebAssembly target:
rustup toolchain install 1.96.0
rustup target add wasm32-unknown-unknown --toolchain 1.96.0#2. Cargo.toml
The game is a cdylib. wgpu is used without default features, with custom (the sg backend)
and wgsl:
[package]
name = "hello-sg"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
sg-guest = { path = "../sg-guest" } # until the crate is published
wgpu = { version = "30.0.1", default-features = false, features = ["custom", "wgsl", "std"] }
log = "0.4"
[profile.release]
opt-level = 3
lto = true
panic = "abort"#3. src/lib.rs
A game exports sg_init (return 0 on success) and sg_frame(t, dt). sg_guest::gpu::instance()
returns a normal wgpu::Instance whose calls go to the host GPU, so everything after it is
plain wgpu.
use sg_guest::abi::input::{self, kind};
use std::cell::RefCell;
struct Game {
device: wgpu::Device,
queue: wgpu::Queue,
surface: wgpu::Surface<'static>,
config: wgpu::SurfaceConfiguration,
hue: f64,
}
thread_local!(static GAME: RefCell<Option<Game>> = const { RefCell::new(None) });
fn init() -> Result<Game, String> {
let instance = sg_guest::gpu::instance();
let surface = sg_guest::gpu::surface(&instance);
// Futures from the sg backend are already resolved: block_on returns at once.
let adapter = sg_guest::gpu::block_on(instance.request_adapter(&Default::default())).map_err(|e| e.to_string())?;
let (device, queue) = sg_guest::gpu::block_on(adapter.request_device(&Default::default())).map_err(|e| e.to_string())?;
let (width, height) = sg_guest::surface_size();
let caps = surface.get_capabilities(&adapter);
let format = caps.formats.iter().copied().find(|f| f.is_srgb()).unwrap_or(caps.formats[0]);
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format,
width,
height,
present_mode: wgpu::PresentMode::AutoVsync,
desired_maximum_frame_latency: 2,
alpha_mode: caps.alpha_modes[0],
view_formats: vec![],
color_space: Default::default(),
};
surface.configure(&device, &config);
sg_guest::set_title("Hello, 0x");
Ok(Game { device, queue, surface, config, hue: 0.0 })
}
#[no_mangle]
pub extern "C" fn sg_init() -> i32 {
sg_guest::init(log::LevelFilter::Info);
match init() {
Ok(g) => {
GAME.with(|s| *s.borrow_mut() = Some(g));
0
}
Err(e) => {
log::error!("init failed: {e}");
1
}
}
}
#[no_mangle]
pub extern "C" fn sg_frame(_t: f64, dt: f64) {
// Runs wgpu callbacks (buffer maps, errors, device loss): once per frame.
sg_guest::gpu::pump();
GAME.with(|s| {
let mut s = s.borrow_mut();
let g = s.as_mut().unwrap();
for e in sg_guest::poll_input() {
match e.kind {
kind::KEY_DOWN if input::key_name(e.code) == "Escape" => sg_guest::quit(),
kind::RESIZE => {
g.config.width = e.x as u32;
g.config.height = e.y as u32;
g.surface.configure(&g.device, &g.config);
}
_ => {}
}
}
g.hue = (g.hue + dt * 0.1) % 1.0;
let frame = match g.surface.get_current_texture() {
wgpu::CurrentSurfaceTexture::Success(f) | wgpu::CurrentSurfaceTexture::Suboptimal(f) => f,
_ => {
let (w, h) = sg_guest::surface_size();
g.config.width = w;
g.config.height = h;
g.surface.configure(&g.device, &g.config);
return;
}
};
let view = frame.texture.create_view(&Default::default());
let mut enc = g.device.create_command_encoder(&Default::default());
enc.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color { r: g.hue, g: 0.4, b: 1.0 - g.hue, a: 1.0 }),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
g.queue.submit([enc.finish()]);
g.queue.present(frame);
});
}Things to know:
- Futures resolve at once. The sg backend answers every request synchronously, so
sg_guest::gpu::block_onis all the executor you need. - Call
sg_guest::gpu::pump()once per frame. It runs wgpu callbacks: buffer mapping, work-done, uncaptured errors and device loss, the way a browser runs them from its event loop. - Command buffers are recorded in the guest and sent to the host in one request when finished, so a frame costs a handful of host calls.
- Logging.
sg_guest::initinstalls alogbackend and a panic hook that write to the host log.
#4. Build
cargo +1.96.0 build --release --target wasm32-unknown-unknown
# -> target/wasm32-unknown-unknown/release/hello_sg.wasm#5. The manifest
Every file is named by its SHA-256 and size, so the runtime can cache and verify it. A minimal
manifest.json next to the module:
{
"name": "Hello 0x",
"entry": {"name": "main", "path": "hello_sg.wasm", "sha256": "<hex sha256 of the file>", "size": 484512},
"assets": [],
"permissions": {}
}This script writes it:
f=hello_sg.wasm
printf '{"name":"Hello 0x","entry":{"name":"main","path":"%s","sha256":"%s","size":%d},"assets":[],"permissions":{}}\n' \
"$f" "$(sha256sum "$f" | cut -d' ' -f1)" "$(stat -c %s "$f")" > manifest.jsonThe game above asks for nothing. Network access, storage, workers, audio, WebRTC, more memory,
experimental GPU features and platform services are all requested in permissions: see
Permissions and grants.
#6. Run
Serve the directory over HTTP and point the runtime at the manifest URL:
python3 -m http.server 8000 &
sg-runtime http://127.0.0.1:8000/manifest.json --size 1280x720| Flag | Effect |
|---|---|
--size WxH | Window size. |
--vsync / --no-vsync, --present-mode, --latency 1-3, --fps-cap N | Presentation; the player's choice always wins over the game's (see Graphics). |
--grants FILE | The player's approval of the game's permissions (the 0x app writes it). |
--trust-manifest | Local development: grant whatever the manifest asks for. |
--frames N, --screenshot PATH | Run N frames, save the last one as a PNG, exit (tests). |
--cache DIR, --data DIR | The content-addressed asset cache and the per-game storage directory. |
--display-info | Print what the GPU and display offer, and exit. |
Launched this way, without --grants, the game runs under the default policy, and the log says
so: grants: default policy (no --grants): no network, platform services or experimental GPU features.
The manifest URL's query string is passed to the game as its launch arguments
(sg_guest::args(), sg_guest::arg("name")).
