Skip to content

Commit

Permalink
refactor!: update render dependencies & cleanup the code (#70)
Browse files Browse the repository at this point in the history
* chore: bump render deps versions

* refactor: replace EventLoopWindowTarget by ActiveEventLoop

* refactor: remove wasm32 target code

* refactor: update window init using deprecated method

I will further update it later, this is just enough for the crate to
compile

* refactor: add default compilation option to the state creation

* feat: add new basic structures

based on rust-windowing/winit#3626 (comment)

* fix: revert an IDE-induced rename

* fix: revert idem

* feat: complete GfxState constructor

* refactor: make GfxState::new synchronous using pollster

* feat: impl ApplicationHandler for App

* feat: add necessary update methods to gfx state

* fix: add handle vertex building code

* chore: cleanup imports & re-exports

* refactor: move shader_data & camera modules

* fix: update render examples

* chore: add cusotm lints to honeycomb-render

* fix: process some lints

* fix: add back the possibility to run default examples
  • Loading branch information
imrn99 committed May 6, 2024
1 parent 6aea900 commit 0087610
Show file tree
Hide file tree
Showing 19 changed files with 414 additions and 457 deletions.
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ bytemuck = "1.15.0"
cgmath = "0.18.0"
env_logger = "0.11.3"
pollster = "0.3.0"
smaa = "0.13.0"
wgpu = "0.19.4"
winit = "0.29.15"
smaa = "0.14.0"
wgpu = "0.20.0"
winit = "0.30.0"

[profile.bench]
debug = true
4 changes: 2 additions & 2 deletions honeycomb-examples/examples/render/default_no_aa.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use honeycomb_render::{RenderParameters, Runner, SmaaMode};
use honeycomb_render::{launch, RenderParameters, SmaaMode};

fn main() {
let render_params = RenderParameters {
smaa_mode: SmaaMode::Disabled,
..Default::default()
};
Runner::default().run::<f32>(render_params, None);
launch::<f32>(render_params, None);
}
2 changes: 1 addition & 1 deletion honeycomb-examples/examples/render/default_smaa1x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ fn main() {
smaa_mode: SmaaMode::Smaa1X,
..Default::default()
};
Runner::default().run::<f32>(render_params, None);
launch::<f32>(render_params, None);
}
2 changes: 1 addition & 1 deletion honeycomb-examples/examples/render/splitsquaremap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ fn main() {
..Default::default()
};
let map: CMap2<f32> = GridBuilder::split_unit_squares(4).build2().unwrap();
Runner::default().run(render_params, Some(&map));
launch(render_params, Some(&map));
}
2 changes: 1 addition & 1 deletion honeycomb-examples/examples/render/squaremap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ fn main() {
..Default::default()
};
let map: CMap2<f32> = GridBuilder::unit_squares(4).build2().unwrap();
Runner::default().run(render_params, Some(&map));
launch(render_params, Some(&map));
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ fn main() {
.len_per_cell_y(3.0_f64)
.build2()
.unwrap();
Runner::default().run(render_params, Some(&map));
launch(render_params, Some(&map));
}
2 changes: 1 addition & 1 deletion honeycomb-examples/examples/render/squaremap_shift.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,5 +60,5 @@ fn main() {
let elapsed = now.elapsed();
println!("I: Finished shifting in {}μs", elapsed.as_micros());

Runner::default().run(render_params, Some(&map));
launch(render_params, Some(&map));
}
2 changes: 1 addition & 1 deletion honeycomb-examples/examples/render/squaremap_split_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,5 @@ fn main() {
let elapsed = now.elapsed();
println!("I: Finished splitting in {}μs", elapsed.as_micros());

Runner::default().run(render_params, Some(&map));
launch(render_params, Some(&map));
}
2 changes: 1 addition & 1 deletion honeycomb-examples/examples/render/squaremap_split_some.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,5 +55,5 @@ fn main() {
let elapsed = now.elapsed();
println!("I: Finished splitting in {}μs", elapsed.as_micros());

Runner::default().run(render_params, Some(&map));
launch(render_params, Some(&map));
}
11 changes: 0 additions & 11 deletions honeycomb-render/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@ keywords.workspace = true
authors.workspace = true
publish = true

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
bytemuck = { workspace = true, features = ["derive"] }
cfg-if.workspace = true
Expand All @@ -25,11 +22,3 @@ pollster.workspace = true
smaa.workspace = true
wgpu.workspace = true
winit.workspace = true

[target.'cfg(target_arch = "wasm32")'.dependencies]
console_error_panic_hook = "0.1.6"
console_log = "1.0"
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
web-sys = { version = "0.3", features = ["Document", "Window", "Element"] }
wgpu = { workspace = true, features = ["webgl"] }
17 changes: 11 additions & 6 deletions honeycomb-render/src/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@

// ------ IMPORTS

use crate::representations::intermediates::{Entity, IntermediateFace};
use crate::shader_data::Coords2Shader;
use crate::SmaaMode;
use crate::{
representations::{
intermediates::{Entity, IntermediateFace},
shader_data::Coords2Shader,
},
MapRef, SmaaMode,
};
use honeycomb_core::{
CMap2, CoordsFloat, DartIdentifier, EdgeIdentifier, Orbit2, OrbitPolicy, Vertex2, NULL_DART_ID,
CoordsFloat, DartIdentifier, EdgeIdentifier, Orbit2, OrbitPolicy, Vertex2, NULL_DART_ID,
};

// ------ CONTENT
Expand All @@ -18,6 +22,7 @@ use honeycomb_core::{
///
/// The user can easily adjust parameters in this structure to obtain
/// the preferred output style.
#[derive(Clone, Copy)]
pub struct RenderParameters {
/// Anti-aliasing configuration.
pub smaa_mode: SmaaMode,
Expand All @@ -44,7 +49,7 @@ impl Default for RenderParameters {
}

pub struct CMap2RenderHandle<'a, T: CoordsFloat> {
handle: &'a CMap2<T>,
handle: MapRef<'a, T>,
params: RenderParameters,
intermediate_buffer: Vec<IntermediateFace<T>>,
dart_construction_buffer: Vec<Coords2Shader>,
Expand All @@ -54,7 +59,7 @@ pub struct CMap2RenderHandle<'a, T: CoordsFloat> {
}

impl<'a, T: CoordsFloat> CMap2RenderHandle<'a, T> {
pub fn new(map: &'a CMap2<T>, params: Option<RenderParameters>) -> Self {
pub fn new(map: MapRef<'a, T>, params: Option<RenderParameters>) -> Self {
Self {
handle: map,
params: params.unwrap_or_default(),
Expand Down
24 changes: 18 additions & 6 deletions honeycomb-render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//!
//! This crate implements a runner that can be used to display combinatorial maps.
//!
//! It currently only supports 2D maps as the core library only implements these (as [CMap2])
//! It currently only supports 2D maps as the core library only implements these (as [`honeycomb_core::CMap2`])
//!
//! ## Key bindings
//!
Expand All @@ -14,21 +14,33 @@
//!
//! Examples are available in the **honeycomb-examples** crate.

#[cfg(doc)]
use honeycomb_core::CMap2;
// ------ CUSTOM LINTS

// more lints
#![warn(clippy::pedantic)]
#![warn(missing_docs)]
// some exceptions
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::too_many_lines)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_sign_loss)]
#![allow(clippy::cast_precision_loss)]

// ------ MODULE DECLARATIONS

mod camera;
mod handle;
mod runner;
mod shader_data;
mod state;

mod representations;

// ------ RE-EXPORTS

pub use handle::RenderParameters;
pub use runner::Runner;
pub use runner::{launch, launch_async};
pub use state::SmaaMode;

// ------ CONTENT

/// Convenience type alias
type MapRef<'a, T> = &'a honeycomb_core::CMap2<T>;
1 change: 1 addition & 0 deletions honeycomb-render/src/representations/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod intermediates;
pub mod shader_data;
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@

// ------ IMPORTS

use crate::representations::intermediates::Entity;
use bytemuck::{Pod, Zeroable};

use crate::representations::intermediates::Entity;
use honeycomb_core::{CoordsFloat, Vertex2};

// ------ CONTENT
Expand Down
167 changes: 34 additions & 133 deletions honeycomb-render/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,145 +4,46 @@

// ------ IMPORTS

use winit::event::{Event, WindowEvent};
use winit::event_loop::EventLoop;
use winit::window::Window;

use crate::state::State;
use crate::RenderParameters;
use honeycomb_core::{CMap2, CoordsFloat};
use crate::{state::App, MapRef, RenderParameters};
use honeycomb_core::CoordsFloat;

// ------ CONTENT

cfg_if::cfg_if! {
if #[cfg(target_arch = "wasm32")] {
pub type MapRef<'a, T> = &'static CMap2<T>;
} else {
pub type MapRef<'a, T> = &'a CMap2<T>;
}
#[allow(clippy::missing_panics_doc)]
/// Main rendering function.
///
/// # Arguments
///
/// - `render_params: RenderParameters` -- Render parameterization.
/// - `map: Option<&CMap2>` -- Optional reference to the map that should be rendered
///
/// If no reference is passed to the method, a hardcoded example will be rendered instead.
///
/// # Example
///
/// Because the renderer uses the core and utils crates, examples are provided as standalone
/// files rather than in the doc. You can find them in the project's repository, under the
/// `honeycomb-examples` crate and run them using `cargo`:
///
/// ```shell
/// cargo run --example <EXAMPLE>
/// ```
///
pub fn launch<T: CoordsFloat>(render_params: RenderParameters, map: Option<MapRef<'_, T>>) {
// enable custom env logging
env_logger::init();
// build app & event loop
let mut app = App::new(render_params, map);
let event_loop = EventLoop::new().unwrap();
let _ = event_loop.run_app(&mut app);
}

const TARGET_FPS: f32 = 240.;

/// This yields an approximate 240 FPS
const MS_PER_FRAME: u128 = (1000. / TARGET_FPS) as u128;

async fn inner<T: CoordsFloat>(
event_loop: EventLoop<()>,
window: Window,
render_params: RenderParameters,
map: Option<MapRef<'_, T>>,
/// UNIMPLEMENTED
pub async fn launch_async<T: CoordsFloat>(
_render_params: RenderParameters,
_map: Option<MapRef<'_, T>>,
) {
let mut state = if let Some(val) = map {
State::new(&window, render_params, val).await
} else {
State::new_test(&window, render_params).await
};
println!("I: Press F1 to quit");
event_loop
.run(move |event, target| {
// process events
match event {
Event::WindowEvent {
window_id,
event: wevent,
} => {
if window_id == state.window().id() && !state.input(&wevent, target) {
match wevent {
WindowEvent::Resized(new_size) => state.resize(Some(new_size)),
WindowEvent::RedrawRequested => {
let start = std::time::Instant::now();
state.update();
match state.render() {
Ok(_) => {}
Err(wgpu::SurfaceError::Lost) => state.resize(None),
Err(wgpu::SurfaceError::OutOfMemory) => target.exit(), // kill if OOM
Err(e) => eprintln!("{:?}", e),
};
// put a hard cap on the rendering speed
std::thread::sleep(std::time::Duration::from_millis(
(MS_PER_FRAME - start.elapsed().as_millis()) as u64,
));
}
WindowEvent::CloseRequested => target.exit(),
_ => {}
};
}
}
Event::AboutToWait => {
state.window().request_redraw();
}
_ => {}
}
})
.unwrap();
}

/// Main rendering structure
pub struct Runner {
event_loop: EventLoop<()>,
window: Window,
}

impl Runner {
/// Main rendering method.
///
/// # Arguments
///
/// - `render_params: RenderParameters` -- Render parameterization.
/// - `map: Option<&CMap2>` -- Optionnal reference to the map that should be rendered
///
/// If no reference is passed to the method, a hardcoded example will be rendered instead.
///
/// # Example
///
/// Because the renderer uses the core and utils crates, examples are provided as standalone
/// files rather than in the doc. You can run them using the following command:
///
/// ```shell
/// cargo run --example <EXAMPLE>
/// ```
///
pub fn run<T: CoordsFloat>(self, render_params: RenderParameters, map: Option<MapRef<'_, T>>) {
cfg_if::cfg_if! {
if #[cfg(target_arch = "wasm32")] {
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
console_log::init().expect("could not initialize logger");
wasm_bindgen_futures::spawn_local(inner(self.event_loop, self.window, render_params, map));
} else {
env_logger::init();
pollster::block_on(inner(self.event_loop, self.window, render_params, map));
}
}
}

/// UNIMPLEMENTED
pub async fn run_async(&self) {
unimplemented!()
}
}

impl Default for Runner {
fn default() -> Self {
let event_loop = EventLoop::new().unwrap();
#[allow(unused_mut)]
let mut builder = winit::window::WindowBuilder::new();
#[cfg(target_arch = "wasm32")]
{
use wasm_bindgen::JsCast;
use winit::platform::web::WindowBuilderExtWebSys;
let canvas = web_sys::window()
.unwrap()
.document()
.unwrap()
.get_element_by_id("wasm-example")
.unwrap()
.dyn_into::<web_sys::HtmlCanvasElement>()
.unwrap();
builder = builder.with_canvas(Some(canvas));
}
let window = builder.build(&event_loop).unwrap();

Self { event_loop, window }
}
unimplemented!()
}

0 comments on commit 0087610

Please sign in to comment.