Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

SG4a: the mesh share lets go of what no part holds

shinyobjectz8cc12db395d0
diff --git a/Cargo.lock b/Cargo.lock
index f0f08c40..67a7d7d5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -15516,6 +15516,7 @@ dependencies = [
"raea-sys-post",
"raea-sys-sampler",
"raea-sys-shader",
+ "raea-sys-share",
"serde_json",
]
@@ -16389,6 +16390,13 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "raea-sys-share"
+version = "0.1.0"
+dependencies = [
+ "bevy",
+]
+
[[package]]
name = "raea-sys-shots"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 09e0b1da..14c46aa7 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -129,6 +129,7 @@ members = [
"runtime/gpuframe",
"runtime/scene3d",
"systems/copies",
+ "systems/share",
"systems/screen",
"systems/matchmove",
"systems/grid",
diff --git a/runtime/scene3d/Cargo.toml b/runtime/scene3d/Cargo.toml
index 42193520..f982e05f 100644
--- a/runtime/scene3d/Cargo.toml
+++ b/runtime/scene3d/Cargo.toml
@@ -15,6 +15,8 @@ raea-sys-sampler = { path = "../../systems/sampler" }
raea-sys-shader = { path = "../../systems/shader" }
# an <Instances>' copies: a mesh's or a model's parts at each placement, sharing their material handles
raea-sys-copies = { path = "../../systems/copies" }
+# equal parts share one mesh and material, let go once no part holds them
+raea-sys-share = { path = "../../systems/share" }
raea-sys-fog = { path = "../../systems/fog" }
raea-sys-fog-half = { path = "../../systems/fog-half" }
raea-sys-post = { path = "../../systems/post" }
diff --git a/runtime/scene3d/src/lib.rs b/runtime/scene3d/src/lib.rs
index 1da32ac1..672ba033 100644
--- a/runtime/scene3d/src/lib.rs
+++ b/runtime/scene3d/src/lib.rs
@@ -61,8 +61,7 @@ mod shaded;
pub use shaded::*;
mod instance;
pub use instance::*;
-mod share;
-pub use share::*;
+pub use raea_sys_share::*;
pub use raea_sys_material::clay;
/// A model row's glTF: loaded by the asset server, then its scene spawned under the row's entity and its clip set up.
diff --git a/runtime/scene3d/src/share.rs b/runtime/scene3d/src/share.rs
deleted file mode 100644
index d41b073d..00000000
--- a/runtime/scene3d/src/share.rs
+++ /dev/null
@@ -1,58 +0,0 @@
-//! Equal parts share their assets (docs/control.feature FC1a, closing C1): a mesh row's Mesh is made once per shape and
-//! a plain StandardMaterial once per value, so N equal parts hold one Handle<Mesh> and one Handle<StandardMaterial>
-//! and Bevy's automatic batching draws them as one, as it does for an example that shares its handles.
-//! A shared material a frame changes (a part's colour animating) is first copied to that part alone (sync_meshes),
-//! so one part's change never shows on another. RAEA_SHARE_ASSETS=0 makes every part its own again.
-
-use std::collections::HashMap;
-use std::hash::{Hash, Hasher};
-
-use bevy::prelude::*;
-
-/// A part whose StandardMaterial other parts hold too: sync_meshes copies it before changing it.
-#[derive(Component)]
-pub struct SharedMaterial;
-
-#[derive(Resource, Default)]
-struct Shared {
- meshes: HashMap<u64, Handle<Mesh>>,
- materials: HashMap<String, Handle<StandardMaterial>>,
-}
-
-/// Whether parts share (on unless RAEA_SHARE_ASSETS=0).
-pub fn sharing() -> bool {
- std::env::var("RAEA_SHARE_ASSETS").map_or(true, |v| v != "0")
-}
-
-/// The mesh for `key` (everything that decides its vertices), made by `make` the first time.
-pub fn shared_mesh(world: &mut World, key: &str, make: impl FnOnce() -> Result<Mesh, String>) -> Result<Handle<Mesh>, String> {
- if !sharing() {
- let m = make()?;
- return Ok(world.resource_mut::<Assets<Mesh>>().add(m));
- }
- let mut h = std::collections::hash_map::DefaultHasher::new();
- key.hash(&mut h);
- let k = h.finish();
- if let Some(m) = world.get_resource::<Shared>().and_then(|s| s.meshes.get(&k)).cloned() {
- return Ok(m);
- }
- let m = make()?;
- let m = world.resource_mut::<Assets<Mesh>>().add(m);
- world.get_resource_or_insert_with(Shared::default).meshes.insert(k, m.clone());
- Ok(m)
-}
-
-/// The material equal to `m`, field for field (its Debug form is the key: every field, a texture by its handle), made
-/// the first time; and whether it's shared (to mark the part SharedMaterial).
-pub fn shared_material(world: &mut World, m: StandardMaterial) -> (Handle<StandardMaterial>, bool) {
- if !sharing() {
- return (world.resource_mut::<Assets<StandardMaterial>>().add(m), false);
- }
- let key = format!("{m:?}");
- if let Some(h) = world.get_resource::<Shared>().and_then(|s| s.materials.get(&key)).cloned() {
- return (h, true);
- }
- let h = world.resource_mut::<Assets<StandardMaterial>>().add(m);
- world.get_resource_or_insert_with(Shared::default).materials.insert(key, h.clone());
- (h, true)
-}
diff --git a/systems/share/Cargo.toml b/systems/share/Cargo.toml
new file mode 100644
index 00000000..de5beeb1
--- /dev/null
+++ b/systems/share/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "raea-sys-share"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "Equal parts share their assets (runtime/scene3d re-exports it): one Mesh per shape and one StandardMaterial per value, let go once no part holds them"
+
+[dependencies]
+bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }
diff --git a/systems/share/src/lib.rs b/systems/share/src/lib.rs
new file mode 100644
index 00000000..968715b4
--- /dev/null
+++ b/systems/share/src/lib.rs
@@ -0,0 +1,101 @@
+//! Equal parts share their assets (docs/control.feature FC1a, closing C1; runtime/scene3d re-exports this crate): a
+//! mesh row's Mesh is made once per shape and a plain StandardMaterial once per value, so N equal parts hold one
+//! Handle<Mesh> and one Handle<StandardMaterial> and Bevy's automatic batching draws them as one, as it does for an
+//! example that shares its handles. A shared material a frame changes (a part's colour animating) is first copied to
+//! that part alone (sync_meshes), so one part's change never shows on another. RAEA_SHARE_ASSETS=0 makes every part its
+//! own again. What no part holds any more is let go: a part whose size changes each frame is a new shape each frame,
+//! and the film (docs/stage-guards.feature SG4a) held 234,000 meshes a minute in, 450 MB and their GPU buffers, nearly
+//! all for shapes no part had any more.
+
+use std::collections::HashMap;
+use std::hash::{Hash, Hasher};
+
+use bevy::prelude::*;
+
+/// A part whose StandardMaterial other parts hold too: sync_meshes copies it before changing it.
+#[derive(Component)]
+pub struct SharedMaterial;
+
+#[derive(Resource, Default)]
+struct Shared {
+ meshes: HashMap<u64, Handle<Mesh>>,
+ materials: HashMap<String, Handle<StandardMaterial>>,
+ /// the meshes held after the last sweep: the next comes when they've doubled, so sweeping costs nothing a call
+ swept: usize,
+}
+
+impl Shared {
+ /// Let go of what only the share holds (Bevy drops the asset, and its GPU copy, once its last handle goes).
+ fn sweep(&mut self) {
+ if self.meshes.len() >= (2 * self.swept).max(1024) {
+ self.meshes.retain(|_, h| !unheld(h));
+ self.materials.retain(|_, h| !unheld(h));
+ self.swept = self.meshes.len();
+ }
+ }
+}
+
+/// Whether nothing but the share holds `h`.
+fn unheld<A: Asset>(h: &Handle<A>) -> bool {
+ matches!(h, Handle::Strong(a) if std::sync::Arc::strong_count(a) == 1)
+}
+
+/// Whether parts share (on unless RAEA_SHARE_ASSETS=0).
+pub fn sharing() -> bool {
+ std::env::var("RAEA_SHARE_ASSETS").map_or(true, |v| v != "0")
+}
+
+/// The mesh for `key` (everything that decides its vertices), made by `make` the first time.
+pub fn shared_mesh(world: &mut World, key: &str, make: impl FnOnce() -> Result<Mesh, String>) -> Result<Handle<Mesh>, String> {
+ if !sharing() {
+ let m = make()?;
+ return Ok(world.resource_mut::<Assets<Mesh>>().add(m));
+ }
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ key.hash(&mut h);
+ let k = h.finish();
+ if let Some(m) = world.get_resource::<Shared>().and_then(|s| s.meshes.get(&k)).cloned() {
+ return Ok(m);
+ }
+ let m = make()?;
+ let m = world.resource_mut::<Assets<Mesh>>().add(m);
+ let mut s = world.get_resource_or_insert_with(Shared::default);
+ s.sweep();
+ s.meshes.insert(k, m.clone());
+ Ok(m)
+}
+
+/// The material equal to `m`, field for field (its Debug form is the key: every field, a texture by its handle), made
+/// the first time; and whether it's shared (to mark the part SharedMaterial).
+pub fn shared_material(world: &mut World, m: StandardMaterial) -> (Handle<StandardMaterial>, bool) {
+ if !sharing() {
+ return (world.resource_mut::<Assets<StandardMaterial>>().add(m), false);
+ }
+ let key = format!("{m:?}");
+ if let Some(h) = world.get_resource::<Shared>().and_then(|s| s.materials.get(&key)).cloned() {
+ return (h, true);
+ }
+ let h = world.resource_mut::<Assets<StandardMaterial>>().add(m);
+ world.get_resource_or_insert_with(Shared::default).materials.insert(key, h.clone());
+ (h, true)
+}
+
+#[cfg(test)]
+mod tests {
+ use bevy::prelude::*;
+
+ /// A shape no part holds any more is let go once the share has doubled; one a part still holds stays shared.
+ #[test]
+ fn meshes_no_part_holds_are_let_go() {
+ let mut world = World::new();
+ world.init_resource::<Assets<Mesh>>();
+ let cube = || Ok(Mesh::from(Cuboid::new(1.0, 1.0, 1.0)));
+ let kept = super::shared_mesh(&mut world, "held", cube).unwrap();
+ for i in 0..3000 {
+ let _ = super::shared_mesh(&mut world, &format!("box {i}"), cube).unwrap();
+ }
+ let held = world.resource::<super::Shared>().meshes.len();
+ assert!(held < 1100, "{held} meshes still in the share");
+ assert_eq!(super::shared_mesh(&mut world, "held", cube).unwrap().id(), kept.id());
+ }
+}
diff --git a/tools/layers.toml b/tools/layers.toml
index 7ba507e5..1d5f479f 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -146,6 +146,8 @@ raea-sys-sampler = "systems"
raea-sys-shader = "systems"
raea-sys-shader-wgsl = "systems"
raea-sys-copies = "systems"
+# equal parts share one mesh and material, let go once no part holds them (runtime/scene3d re-exports it)
+raea-sys-share = "systems"
raea-sys-three-shader = "systems"
raea-sys-post = "systems"
raea-sys-fog = "systems"