start work on map renderer
Some checks failed
build and test / wxbox - latest (push) Failing after 36m36s
Verify Latest Dependencies / Verify Latest Dependencies (push) Successful in 37m0s

This commit is contained in:
core 2025-03-06 22:47:37 -05:00
parent d7eaa28959
commit f06c11fb99
Signed by: core
GPG key ID: FDBF740DADDCEECF
10 changed files with 2308 additions and 0 deletions

1
Cargo.lock generated
View file

@ -5058,6 +5058,7 @@ dependencies = [
"console_error_panic_hook",
"eframe",
"egui",
"egui_glow",
"serde",
"tracing",
"tracing-subscriber",

18
crates/client/Cargo.toml Normal file
View file

@ -0,0 +1,18 @@
[package]
name = "wxbox-client"
version = "0.1.0"
edition = "2021"
[dependencies]
tracing = "0.1"
tracing-subscriber = "0.3"
eframe = { version = "0.31" }
egui = "0.31"
egui_glow = "0.31"
serde = { version = "1", features = ["derive"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
tracing-web = "0.1"
wasm-bindgen-futures = "0.4"
web-sys = "0.3"
console_error_panic_hook = "0.1"

254
crates/client/dist/index.html vendored Normal file
View file

@ -0,0 +1,254 @@
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- Disable zooming: -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<head>
<!-- change this to your project name -->
<title>wxbox</title>
<style>
html {
/* Remove touch delay: */
touch-action: manipulation;
}
body {
/* Light mode background color for what is not covered by the egui canvas,
or where the egui canvas is translucent. */
background: #909090;
}
@media (prefers-color-scheme: dark) {
body {
/* Dark mode background color for what is not covered by the egui canvas,
or where the egui canvas is translucent. */
background: #404040;
}
}
/* Allow canvas to fill entire web page: */
html,
body {
overflow: hidden;
margin: 0 !important;
padding: 0 !important;
height: 100%;
width: 100%;
}
/* Make canvas fill entire document: */
canvas {
margin-right: auto;
margin-left: auto;
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.centered {
margin-right: auto;
margin-left: auto;
display: block;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #f0f0f0;
font-size: 24px;
font-family: Ubuntu-Light, Helvetica, sans-serif;
text-align: center;
}
/* ---------------------------------------------- */
/* Loading animation from https://loading.io/css/ */
.lds-dual-ring {
display: inline-block;
width: 24px;
height: 24px;
}
.lds-dual-ring:after {
content: " ";
display: block;
width: 24px;
height: 24px;
margin: 0px;
border-radius: 50%;
border: 3px solid #fff;
border-color: #fff transparent #fff transparent;
animation: lds-dual-ring 1.2s linear infinite;
}
@keyframes lds-dual-ring {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
<link rel="modulepreload" href="/wxbox-client-cc3fc7938f2d1250.js" crossorigin="anonymous" integrity="sha384-D0+8/tuiAAACeiCFKoYCfiO4eY1qBcspDBAYo2/wlucgHDDd6q+iQbSI/oBAyjqc"><link rel="preload" href="/wxbox-client-cc3fc7938f2d1250_bg.wasm" crossorigin="anonymous" integrity="sha384-4sU1kmiOjDfWRKUTgecXG3cX++TTeotG02GlXDRHqwxFVxdy/hcCV7wm92ijUzmr" as="fetch" type="application/wasm"></head>
<body>
<!-- The WASM code will resize the canvas dynamically -->
<!-- the id is hardcoded in main.rs . so, make sure both match. -->
<canvas id="the_canvas_id"></canvas>
<!-- the loading spinner will be removed in main.rs -->
<div class="centered" id="loading_text">
<p style="font-size:16px">
Loading…
</p>
<div class="lds-dual-ring"></div>
</div>
<script type="module">
import init, * as bindings from '/wxbox-client-cc3fc7938f2d1250.js';
const wasm = await init({ module_or_path: '/wxbox-client-cc3fc7938f2d1250_bg.wasm' });
window.wasmBindings = bindings;
dispatchEvent(new CustomEvent("TrunkApplicationStarted", {detail: {wasm}}));
</script><script>"use strict";
(function () {
const address = '{{__TRUNK_ADDRESS__}}';
const base = '{{__TRUNK_WS_BASE__}}';
let protocol = '';
protocol =
protocol
? protocol
: window.location.protocol === 'https:'
? 'wss'
: 'ws';
const url = protocol + '://' + address + base + '.well-known/trunk/ws';
class Overlay {
constructor() {
// create an overlay
this._overlay = document.createElement("div");
const style = this._overlay.style;
style.height = "100vh";
style.width = "100vw";
style.position = "fixed";
style.top = "0";
style.left = "0";
style.backgroundColor = "rgba(222, 222, 222, 0.5)";
style.fontFamily = "sans-serif";
// not sure that's the right approach
style.zIndex = "1000000";
style.backdropFilter = "blur(1rem)";
const container = document.createElement("div");
// center it
container.style.position = "absolute";
container.style.top = "30%";
container.style.left = "15%";
container.style.maxWidth = "85%";
this._title = document.createElement("div");
this._title.innerText = "Build failure";
this._title.style.paddingBottom = "2rem";
this._title.style.fontSize = "2.5rem";
this._message = document.createElement("div");
this._message.style.whiteSpace = "pre-wrap";
const icon= document.createElement("div");
icon.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" fill="#dc3545" viewBox="0 0 16 16"><path d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"/></svg>';
this._title.prepend(icon);
container.append(this._title, this._message);
this._overlay.append(container);
this._inject();
window.setInterval(() => {
this._inject();
}, 250);
}
set reason(reason) {
this._message.textContent = reason;
}
_inject() {
if (!this._overlay.isConnected) {
// prepend it
document.body?.prepend(this._overlay);
}
}
}
class Client {
constructor(url) {
this.url = url;
this.poll_interval = 5000;
this._overlay = null;
}
start() {
const ws = new WebSocket(this.url);
ws.onmessage = (ev) => {
const msg = JSON.parse(ev.data);
switch (msg.type) {
case "reload":
this.reload();
break;
case "buildFailure":
this.buildFailure(msg.data)
break;
}
};
ws.onclose = () => this.onclose();
}
onclose() {
window.setTimeout(
() => {
// when we successfully reconnect, we'll force a
// reload (since we presumably lost connection to
// trunk due to it being killed, so it will have
// rebuilt on restart)
const ws = new WebSocket(this.url);
ws.onopen = () => window.location.reload();
ws.onclose = () => this.onclose();
},
this.poll_interval);
}
reload() {
window.location.reload();
}
buildFailure({reason}) {
// also log the console
console.error("Build failed:", reason);
console.debug("Overlay", this._overlay);
if (!this._overlay) {
this._overlay = new Overlay();
}
this._overlay.reason = reason;
}
}
new Client(url).start();
})()
</script></body>
</html>

File diff suppressed because it is too large Load diff

Binary file not shown.

114
crates/client/index.html Normal file
View file

@ -0,0 +1,114 @@
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- Disable zooming: -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<head>
<!-- change this to your project name -->
<title>wxbox</title>
<style>
html {
/* Remove touch delay: */
touch-action: manipulation;
}
body {
/* Light mode background color for what is not covered by the egui canvas,
or where the egui canvas is translucent. */
background: #909090;
}
@media (prefers-color-scheme: dark) {
body {
/* Dark mode background color for what is not covered by the egui canvas,
or where the egui canvas is translucent. */
background: #404040;
}
}
/* Allow canvas to fill entire web page: */
html,
body {
overflow: hidden;
margin: 0 !important;
padding: 0 !important;
height: 100%;
width: 100%;
}
/* Make canvas fill entire document: */
canvas {
margin-right: auto;
margin-left: auto;
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.centered {
margin-right: auto;
margin-left: auto;
display: block;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #f0f0f0;
font-size: 24px;
font-family: Ubuntu-Light, Helvetica, sans-serif;
text-align: center;
}
/* ---------------------------------------------- */
/* Loading animation from https://loading.io/css/ */
.lds-dual-ring {
display: inline-block;
width: 24px;
height: 24px;
}
.lds-dual-ring:after {
content: " ";
display: block;
width: 24px;
height: 24px;
margin: 0px;
border-radius: 50%;
border: 3px solid #fff;
border-color: #fff transparent #fff transparent;
animation: lds-dual-ring 1.2s linear infinite;
}
@keyframes lds-dual-ring {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
</head>
<body>
<!-- The WASM code will resize the canvas dynamically -->
<!-- the id is hardcoded in main.rs . so, make sure both match. -->
<canvas id="the_canvas_id"></canvas>
<!-- the loading spinner will be removed in main.rs -->
<div class="centered" id="loading_text">
<p style="font-size:16px">
Loading…
</p>
<div class="lds-dual-ring"></div>
</div>
</body>
</html>

57
crates/client/src/app.rs Normal file
View file

@ -0,0 +1,57 @@
use std::sync::{Arc, Mutex};
use eframe::{Frame, Storage};
use egui::{Context, Sense, Vec2};
use crate::map::Map;
pub struct App {
map: Arc<Mutex<Map>>,
angle: f32
}
impl App {
pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
let gl = cc.gl.as_ref().unwrap();
Self {
map: Arc::new(Mutex::new(Map::new(gl).unwrap())),
angle: 0.0
}
}
}
impl eframe::App for App {
fn update(&mut self, ctx: &Context, frame: &mut Frame) {
egui::SidePanel::left("sidebar")
.resizable(false)
.show(ctx, |ui| {
ui.heading("wxbox");
});
egui::CentralPanel::default()
.show(ctx, |ui| {
let (rect, response) = ui.allocate_exact_size(
ui.available_size(),
Sense::all()
);
self.angle += response.drag_motion().x * 0.01;
let angle = self.angle;
let map = self.map.clone();
let cb = egui_glow::CallbackFn::new(move |_info, painter| {
map.lock().unwrap().paint(painter.gl(), angle);
});
let callback = egui::PaintCallback {
rect,
callback: Arc::new(cb)
};
ui.painter().add(callback);
});
}
fn on_exit(&mut self, gl: Option<&eframe::glow::Context>) {
if let Some(gl) = gl {
self.map.lock().unwrap().destroy(gl);
}
}
}

3
crates/client/src/lib.rs Normal file
View file

@ -0,0 +1,3 @@
pub mod app;
pub mod map;

81
crates/client/src/main.rs Normal file
View file

@ -0,0 +1,81 @@
#[cfg(not(target_arch = "wasm32"))]
fn main() -> eframe::Result {
tracing_subscriber::fmt::init();
let native_options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default(),
..Default::default()
};
eframe::run_native(
"wxbox",
native_options,
Box::new(
|cc| Ok(Box::new(wxbox_client::app::App::new(cc)))
)
)
}
#[cfg(target_arch = "wasm32")]
fn main() {
use tracing::Level;
use tracing_subscriber::fmt::format::Pretty;
use tracing_subscriber::prelude::*;
use tracing_web::{performance_layer, MakeWebConsoleWriter};
console_error_panic_hook::set_once();
let fmt_layer = tracing_subscriber::fmt::layer()
.with_ansi(false) // not supported in browsers
.without_time() // std::time doesn't exist in wasm
.with_writer(MakeWebConsoleWriter::new().with_max_level(Level::DEBUG)); // wgpu spams the console, and this is slow as hell
let perf_layer = performance_layer() // enable performance tracing
.with_details_from_fields(Pretty::default()); // ... with pretty fields
tracing_subscriber::registry()
.with(fmt_layer)
.with(perf_layer)
.init(); // register the logger
use eframe::wasm_bindgen::JsCast as _;
let web_options = eframe::WebOptions::default();
wasm_bindgen_futures::spawn_local(async {
let document = web_sys::window()
.expect("No window")
.document()
.expect("No document");
let canvas = document
.get_element_by_id("the_canvas_id")
.expect("Failed to find the_canvas_id")
.dyn_into::<web_sys::HtmlCanvasElement>()
.expect("the_canvas_id was not a HtmlCanvasElement");
let start_result = eframe::WebRunner::new()
.start(
canvas,
web_options,
Box::new(|cc| Ok(Box::new(wxbox_client::app::App::new(cc)))),
)
.await;
// Remove the loading text and spinner:
if let Some(loading_text) = document.get_element_by_id("loading_text") {
match start_result {
Ok(_) => {
loading_text.remove();
}
Err(e) => {
loading_text.set_inner_html(
"<p> The app has crashed. See the developer console for details. </p>",
);
panic!("Failed to start eframe: {e:?}");
}
}
}
});
}

131
crates/client/src/map.rs Normal file
View file

@ -0,0 +1,131 @@
use eframe::glow;
use tracing::warn;
pub struct Map {
program: glow::Program,
vertex_array: glow::VertexArray
}
#[allow(unsafe_code)] // we need unsafe code to use glow
impl Map {
pub fn new(gl: &glow::Context) -> Option<Self> {
use glow::HasContext as _;
let shader_version = egui_glow::ShaderVersion::get(gl);
unsafe {
let program = gl.create_program().expect("Cannot create program");
if !shader_version.is_new_shader_interface() {
warn!(
"Custom 3D painting hasn't been ported to {:?}",
shader_version
);
return None;
}
let (vertex_shader_source, fragment_shader_source) = (
r#"
const vec2 verts[3] = vec2[3](
vec2(0.0, 1.0),
vec2(-1.0, -1.0),
vec2(1.0, -1.0)
);
const vec4 colors[3] = vec4[3](
vec4(1.0, 0.0, 0.0, 1.0),
vec4(0.0, 1.0, 0.0, 1.0),
vec4(0.0, 0.0, 1.0, 1.0)
);
out vec4 v_color;
uniform float u_angle;
void main() {
v_color = colors[gl_VertexID];
gl_Position = vec4(verts[gl_VertexID], 0.0, 1.0);
gl_Position.x *= cos(u_angle);
}
"#,
r#"
precision mediump float;
in vec4 v_color;
out vec4 out_color;
void main() {
out_color = v_color;
}
"#,
);
let shader_sources = [
(glow::VERTEX_SHADER, vertex_shader_source),
(glow::FRAGMENT_SHADER, fragment_shader_source),
];
let shaders: Vec<_> = shader_sources
.iter()
.map(|(shader_type, shader_source)| {
let shader = gl
.create_shader(*shader_type)
.expect("Cannot create shader");
gl.shader_source(
shader,
&format!(
"{}\n{}",
shader_version.version_declaration(),
shader_source
),
);
gl.compile_shader(shader);
assert!(
gl.get_shader_compile_status(shader),
"Failed to compile custom_3d_glow {shader_type}: {}",
gl.get_shader_info_log(shader)
);
gl.attach_shader(program, shader);
shader
})
.collect();
gl.link_program(program);
assert!(
gl.get_program_link_status(program),
"{}",
gl.get_program_info_log(program)
);
for shader in shaders {
gl.detach_shader(program, shader);
gl.delete_shader(shader);
}
let vertex_array = gl
.create_vertex_array()
.expect("Cannot create vertex array");
Some(Self {
program,
vertex_array,
})
}
}
pub fn destroy(&self, gl: &glow::Context) {
use glow::HasContext as _;
unsafe {
gl.delete_program(self.program);
gl.delete_vertex_array(self.vertex_array);
}
}
pub fn paint(&self, gl: &glow::Context, angle: f32) {
use glow::HasContext as _;
unsafe {
gl.use_program(Some(self.program));
gl.uniform_1_f32(
gl.get_uniform_location(self.program, "u_angle").as_ref(),
angle,
);
gl.bind_vertex_array(Some(self.vertex_array));
gl.draw_arrays(glow::TRIANGLES, 0, 3);
}
}
}