Skip to content

Allow storage of pipelines in custom shaders for WASM target #2895

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions examples/custom_shader/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,10 @@ glam.workspace = true
glam.features = ["bytemuck"]

rand = "0.8.5"

[target.'cfg(target_arch = "wasm32")'.dependencies]
iced.workspace = true
iced.features = ["debug", "image", "advanced", "webgl", "fira-sans"]
getrandom = { version = "0.2", features = ["js"] }
console_error_panic_hook = "0.1"
console_log = "1.0"
12 changes: 12 additions & 0 deletions examples/custom_shader/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Custom Shader - Iced</title>
<base data-trunk-public-url />
</head>
<body>
<link data-trunk rel="rust" href="Cargo.toml" data-wasm-opt="z" data-bin="custom_shader" />
</body>
</html>
2 changes: 2 additions & 0 deletions examples/custom_shader/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ use iced::window;
use iced::{Center, Color, Element, Fill, Subscription};

fn main() -> iced::Result {
#[cfg(target_arch = "wasm32")]
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
iced::application(IcedCubes::default, IcedCubes::update, IcedCubes::view)
.subscription(IcedCubes::subscription)
.run()
Expand Down
16 changes: 2 additions & 14 deletions examples/custom_shader/src/scene/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -499,13 +499,7 @@ impl DepthPipeline {
wgpu::PipelineCompilationOptions::default(),
},
primitive: wgpu::PrimitiveState::default(),
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: false,
depth_compare: wgpu::CompareFunction::Less,
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
Expand Down Expand Up @@ -574,13 +568,7 @@ impl DepthPipeline {
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(
wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_view,
depth_ops: None,
stencil_ops: None,
},
),
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
});
Expand Down
2 changes: 1 addition & 1 deletion examples/custom_shader/src/shaders/depth.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ fn fs_main(input: Output) -> @location(0) vec4<f32> {
discard;
}

let c = 1.0 - depth;
let c = (1.0 - depth) * 10.0;

return vec4<f32>(c, c, c, 1.0);
}
26 changes: 21 additions & 5 deletions wgpu/src/primitive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
use crate::core::{self, Rectangle};
use crate::graphics::Viewport;

use iced_graphics::futures::{MaybeSend, MaybeSync};
use rustc_hash::FxHashMap;
use std::any::{Any, TypeId};
use std::fmt::Debug;
Expand Down Expand Up @@ -58,10 +59,23 @@ pub trait Renderer: core::Renderer {
fn draw_primitive(&mut self, bounds: Rectangle, primitive: impl Primitive);
}

pub trait Storable: Any + MaybeSend + MaybeSync {}

impl<T: Any + MaybeSend + MaybeSync> Storable for T {}

/// Stores custom, user-provided types.
#[derive(Default, Debug)]
/// The stored type needs to be Sync and Send on native platforms, but not for WebAssembly.
/// See [MaybeSend] and [MaybeSync]
#[derive(Default)]
pub struct Storage {
pipelines: FxHashMap<TypeId, Box<dyn Any + Send + Sync>>,
pipelines: FxHashMap<TypeId, Box<dyn Storable>>,
}

// Manual Debug implementation is required to not impose a Debug bound on storable types.
impl Debug for Storage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Storage").finish_non_exhaustive()
}
}

impl Storage {
Expand All @@ -71,14 +85,15 @@ impl Storage {
}

/// Inserts the data `T` in to [`Storage`].
pub fn store<T: 'static + Send + Sync>(&mut self, data: T) {
pub fn store<T: 'static + Storable>(&mut self, data: T) {
let _ = self.pipelines.insert(TypeId::of::<T>(), Box::new(data));
}

/// Returns a reference to the data with type `T` if it exists in [`Storage`].
pub fn get<T: 'static>(&self) -> Option<&T> {
self.pipelines.get(&TypeId::of::<T>()).map(|pipeline| {
pipeline
let any_ref = pipeline.as_ref() as &dyn Any;
any_ref
.downcast_ref::<T>()
.expect("Value with this type does not exist in Storage.")
})
Expand All @@ -87,7 +102,8 @@ impl Storage {
/// Returns a mutable reference to the data with type `T` if it exists in [`Storage`].
pub fn get_mut<T: 'static>(&mut self) -> Option<&mut T> {
self.pipelines.get_mut(&TypeId::of::<T>()).map(|pipeline| {
pipeline
let any_mut = pipeline.as_mut() as &mut dyn Any;
any_mut
.downcast_mut::<T>()
.expect("Value with this type does not exist in Storage.")
})
Expand Down