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.

WR4: the weathering bake's copied code folded (tools/dupes.sh)

shinyobjectzce16bf200302
diff --git a/Cargo.lock b/Cargo.lock
index 2c3591ff..efbebc21 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -16467,6 +16467,7 @@ version = "0.1.0"
dependencies = [
"image",
"parry3d",
+ "raea-core-meshcheck",
"raea-sys-exposure",
"raea-sys-glb",
"raea-sys-runoff",
diff --git a/core/meshcheck/src/lib.rs b/core/meshcheck/src/lib.rs
index ce847909..e4870dd2 100644
--- a/core/meshcheck/src/lib.rs
+++ b/core/meshcheck/src/lib.rs
@@ -10,6 +10,7 @@
pub mod blender;
mod glb;
mod topo;
+pub use topo::find;
pub use glb::Glb;
use serde_json::{Value, json};
diff --git a/core/meshcheck/src/topo.rs b/core/meshcheck/src/topo.rs
index 08cc9b34..de9bf3b9 100644
--- a/core/meshcheck/src/topo.rs
+++ b/core/meshcheck/src/topo.rs
@@ -12,7 +12,8 @@ pub struct Topo {
pub degenerate: usize,
}
-fn find(p: &mut [u32], mut i: u32) -> u32 {
+/// The root of `i`'s set in a union-find's parents `p`, halving the path as it goes.
+pub fn find(p: &mut [u32], mut i: u32) -> u32 {
while p[i as usize] != i {
p[i as usize] = p[p[i as usize] as usize];
i = p[i as usize];
diff --git a/runtime/wear/src/lib.rs b/runtime/wear/src/lib.rs
index e72b8bde..e91b915d 100644
--- a/runtime/wear/src/lib.rs
+++ b/runtime/wear/src/lib.rs
@@ -54,7 +54,11 @@ pub fn cli(args: &[String], media: fn(&Path, &str) -> PathBuf) -> R<String> {
let req = args.get(2).filter(|a| !a.starts_with('-')).ok_or(USAGE)?;
let v: Value = serde_json::from_slice(&std::fs::read(req).map_err(|e| format!("{req}: {e}"))?).map_err(|e| format!("{req}: {e}"))?;
let out = bake_in(Path::new("."), media, &v)?;
- match args.iter().position(|a| a == "-o").map(|i| args.get(i + 1).ok_or(USAGE)).transpose()? {
+ let o = match args.iter().position(|a| a == "-o") {
+ Some(i) => Some(args.get(i + 1).ok_or(USAGE)?),
+ None => None,
+ };
+ match o {
Some(o) => {
std::fs::write(o, serde_json::to_string_pretty(&out).map_err(|e| e.to_string())?).map_err(|e| format!("{o}: {e}"))?;
Ok(o.clone())
diff --git a/systems/exposure/src/lib.rs b/systems/exposure/src/lib.rs
index e2c7972f..0c9ba902 100644
--- a/systems/exposure/src/lib.rs
+++ b/systems/exposure/src/lib.rs
@@ -191,7 +191,8 @@ fn across(n: Vec3) -> (Vec3, Vec3) {
(t, n.cross(t))
}
-fn cone(axis: Vec3, half: f32, (u1, u2): (f32, f32)) -> Vec3 {
+/// A direction within `half` radians of `axis`, uniform over that cap, from two uniform numbers.
+pub fn cone(axis: Vec3, half: f32, (u1, u2): (f32, f32)) -> Vec3 {
let c = 1.0 - u1 * (1.0 - half.cos());
let s = (1.0 - c * c).max(0.0).sqrt();
let (t, b) = across(axis);
diff --git a/systems/runoff/src/walk.rs b/systems/runoff/src/walk.rs
index 1ea6963e..a9b0a82c 100644
--- a/systems/runoff/src/walk.rs
+++ b/systems/runoff/src/walk.rs
@@ -191,7 +191,7 @@ pub(crate) fn drop(s: &Surface, adj: &Adjacency, acc: &Acc, up: Vec3, d0: &Drop,
}
if n2.dot(up) < UNDERSIDE {
// about to drip: a wall met head on along this edge takes it into the corner, else it falls
- match capture(s, t, q, n, ev).or_else(|| fall(s, q + dir * 0.003 + n * 0.003, up)) {
+ match drip(s, t, q, n, dir, ev, up) {
Some((t3, q3)) => (t, p, water, along) = (t3, q3, water * SPLASH, None),
None => return,
}
@@ -211,7 +211,7 @@ pub(crate) fn drop(s: &Surface, adj: &Adjacency, acc: &Acc, up: Vec3, d0: &Drop,
(t, p) = (t2, q2 + downhill(s, t2, up, heading).unwrap_or(dir) * 0.001);
}
}
- None => match capture(s, t, q, n, ev).or_else(|| fall(s, q + dir * 0.003 + n * 0.003, up)) {
+ None => match drip(s, t, q, n, dir, ev, up) {
Some((t3, q3)) => (t, p, water, along) = (t3, q3, water * SPLASH, None),
None => return,
},
@@ -238,6 +238,11 @@ fn probe(s: &Surface, t: u32, q: Vec3, dir: Vec3) -> Option<(u32, Vec3)> {
}
/// The foot of an end face about to drip: a wall along the edge within CAPTURE, met head on, takes the drop.
+/// Where a drop leaving a face at `q` goes: into the corner of a wall met head on, else falling from just off the face.
+fn drip(s: &Surface, t: u32, q: Vec3, n: Vec3, dir: Vec3, ev: Vec3, up: Vec3) -> Option<(u32, Vec3)> {
+ capture(s, t, q, n, ev).or_else(|| fall(s, q + dir * 0.003 + n * 0.003, up))
+}
+
fn capture(s: &Surface, t: u32, q: Vec3, n: Vec3, ev: Vec3) -> Option<(u32, Vec3)> {
[ev, -ev].into_iter().filter_map(|e| {
let (t2, h) = cast(s, q + n * 0.004, e, CAPTURE)?;
diff --git a/systems/touch/src/spots.rs b/systems/touch/src/spots.rs
index e5c91fdf..cc7780cb 100644
--- a/systems/touch/src/spots.rs
+++ b/systems/touch/src/spots.rs
@@ -90,7 +90,7 @@ fn thin_if(mut c: Vec<Spot>, gap: f32, ok: impl Fn(&Spot) -> bool) -> Vec<Spot>
c.sort_by_key(|s| seed(s.at));
let mut kept: Vec<Spot> = Vec::new();
for s in c {
- if kept.iter().all(|k| (k.at - s.at).length() >= gap) && ok(&s) {
+ if !kept.iter().any(|k| k.at.distance(s.at) < gap) && ok(&s) {
kept.push(s);
}
}
@@ -117,9 +117,10 @@ pub(crate) fn spots(s: &Surface, doors: &[Door], pts: &[Point]) -> Vec<Spot> {
for q in pts.iter().filter(|q| wall(q) && q.edge > 0.8 && q.ground < 4.0) {
arris.entry(cell(q.p)).or_default().push(q);
}
+ const NINE: [(i64, i64); 9] = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 0), (0, 1), (1, -1), (1, 0), (1, 1)];
let near = |p: Vec3| {
let (c, (x, y)) = (cell(p), flat(p));
- (-1..=1).flat_map(move |i| (-1..=1).map(move |j| (c.0 + i, c.1 + j))).flat_map(|k| arris.get(&k).into_iter().flatten()).filter(move |q| {
+ NINE.iter().map(move |&(i, j)| (c.0 + i, c.1 + j)).flat_map(|k| arris.get(&k).into_iter().flatten()).filter(move |q| {
let (a, b) = flat(q.p);
(a - x).hypot(b - y) <= CORNER
})
diff --git a/systems/weathering/Cargo.toml b/systems/weathering/Cargo.toml
index f23d2e43..96861cf8 100644
--- a/systems/weathering/Cargo.toml
+++ b/systems/weathering/Cargo.toml
@@ -16,4 +16,6 @@ image = { version = "0.25", default-features = false, features = ["png"] }
raea-sys-runoff = { path = "../runoff" }
raea-sys-touch = { path = "../touch" }
raea-sys-exposure = { path = "../exposure" }
+# a union-find's root (charts merged by shared edges)
+raea-core-meshcheck = { path = "../../core/meshcheck" }
raea-sys-glb = { path = "../glb" }
diff --git a/systems/weathering/src/charts.rs b/systems/weathering/src/charts.rs
index fbc498b7..4b1bebc7 100644
--- a/systems/weathering/src/charts.rs
+++ b/systems/weathering/src/charts.rs
@@ -53,10 +53,15 @@ pub(crate) struct Atlas {
}
impl Atlas {
+ /// A texel's index in a map over the atlas.
+ pub fn px(&self, x: u16, y: u16) -> usize {
+ y as usize * self.w as usize + x as usize
+ }
+
pub fn covered(&self) -> Vec<bool> {
let mut c = vec![false; (self.w * self.h) as usize];
for t in &self.texels {
- c[t.y as usize * self.w as usize + t.x as usize] = true;
+ c[self.px(t.x, t.y)] = true;
}
c
}
@@ -364,7 +369,10 @@ pub(crate) fn build(sc: &Scene, env: &Env, mesh: &TriMesh) -> R<Atlas> {
index.push(ix);
uv.push(us);
}
- let rects = cs.iter().map(|c| [c.ox, c.oy, c.w, c.h]).collect();
+ let mut rects = Vec::with_capacity(cs.len());
+ for c in cs.iter() {
+ rects.push([c.ox, c.oy, c.w, c.h]);
+ }
let chart_dens = cs.iter().map(|c| c.dens * d).collect();
Ok(Atlas { w, h, density: env.density * d, chart_dens, charts: cs.len(), hidden: hidden.len(), texels, chart_of, verts, index, uv, rects })
}
diff --git a/systems/weathering/src/flow.rs b/systems/weathering/src/flow.rs
index c464f4a7..c6097912 100644
--- a/systems/weathering/src/flow.rs
+++ b/systems/weathering/src/flow.rs
@@ -24,14 +24,13 @@ pub(crate) fn flow(sc: &Scene, at: &Atlas, env: &Env, mesh: &TriMesh, c0: &[[u8;
let role: Vec<Role> = (0..sc.tri.len()).map(|t| role_of(sc, env, t)).collect();
let s = Surface { pos: &sc.pos, tri: &sc.tri, nrm: &sc.nrm, role: &role, uv: &uv, mesh };
let dens = |t: u32| at.chart_dens[at.chart_of[t as usize] as usize];
- let at_px = |x: u16, y: u16| y as usize * at.w as usize + x as usize;
let drops: Vec<Drop> = at.texels.iter().filter_map(|tx| {
- let sky = c0[at_px(tx.x, tx.y)][0] as f32 / 255.0;
+ let sky = c0[at.px(tx.x, tx.y)][0] as f32 / 255.0;
(sky > 0.02).then(|| Drop { p: tx.p + tx.n * 0.002, tri: tx.tri, water: sky / dens(tx.tri).powi(2) })
}).collect();
let out = run(&s, &drops, env.up, at.w, at.h);
for tx in &at.texels {
- let i = at_px(tx.x, tx.y);
+ let i = at.px(tx.x, tx.y);
let [f, d, k] = out.bytes(i, dens(tx.tri));
c1[i] = [f, d, k, c1[i][3]];
}
diff --git a/systems/weathering/src/merge.rs b/systems/weathering/src/merge.rs
index 8a278e2f..3445a9d9 100644
--- a/systems/weathering/src/merge.rs
+++ b/systems/weathering/src/merge.rs
@@ -7,6 +7,7 @@
use std::collections::HashMap;
use parry3d::glamx::Vec3;
+use raea_core_meshcheck::find;
use crate::Env;
use crate::charts::Chart;
@@ -22,13 +23,6 @@ const AREA: f32 = 6.0;
/// a sparse chart is cut into cells this many texels square
const SPLIT: f32 = 64.0;
-fn find(p: &mut [u32], mut i: u32) -> u32 {
- while p[i as usize] != i {
- p[i as usize] = p[p[i as usize] as usize];
- i = p[i as usize];
- }
- i
-}
/// Coplanar charts (the same plane to 1/64 in the normal and 2 cm in offset) whose rectangles touch, joined.
pub(crate) fn merge(cs: Vec<Chart>, sc: &Scene, up: Vec3) -> Vec<Chart> {
@@ -134,10 +128,8 @@ pub(crate) fn absorb(cs: Vec<Chart>, sc: &Scene, env: &Env) -> Vec<Chart> {
c.n != Vec3::ZERO && (w.min(h) < THIN || w * h < AREA)
};
let bounds = |c: &Chart| {
- c.tris.iter().flat_map(|&t| sc.tri[t as usize]).fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(l, h), v| {
- let p = sc.pos[v as usize];
- (l.min(p), h.max(p))
- })
+ let ps = c.tris.iter().flat_map(|&t| sc.tri[t as usize].map(|v| sc.pos[v as usize]));
+ ps.fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(l, h), p| (l.min(p), h.max(p)))
};
const CELL: f32 = 4.0;
let cell = |v: Vec3| ((v.x / CELL).floor() as i32, (v.y / CELL).floor() as i32, (v.z / CELL).floor() as i32);
diff --git a/systems/weathering/src/rays.rs b/systems/weathering/src/rays.rs
index 911b9270..908ca193 100644
--- a/systems/weathering/src/rays.rs
+++ b/systems/weathering/src/rays.rs
@@ -15,6 +15,8 @@
use std::collections::HashMap;
use std::f32::consts::TAU;
+use raea_sys_exposure::cone;
+
use parry3d::glamx::Vec3;
use parry3d::query::{Ray, RayCast};
use parry3d::shape::TriMesh;
@@ -53,13 +55,6 @@ pub(crate) fn across(n: Vec3) -> (Vec3, Vec3) {
(t, n.cross(t))
}
-fn cone(axis: Vec3, half: f32, (u1, u2): (f32, f32)) -> Vec3 {
- let c = 1.0 - u1 * (1.0 - half.cos());
- let s = (1.0 - c * c).max(0.0).sqrt();
- let (t, b) = across(axis);
- (axis * c + t * (s * (TAU * u2).cos()) + b * (s * (TAU * u2).sin())).normalize()
-}
-
fn hemi(n: Vec3, (u1, u2): (f32, f32)) -> Vec3 {
let r = u1.sqrt();
let (t, b) = across(n);
@@ -198,7 +193,7 @@ pub(crate) fn causes(sc: &Scene, at: &Atlas, env: &Env, mesh: &TriMesh, c0: &mut
let from = -env.rain;
let k = env.sky_rays;
let level: f32 = (0..k).map(|j| cone(from, env.spread, sample(0, j)).dot(env.up).max(0.0)).sum::<f32>() / k as f32;
- let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
+ let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
let hit = |o: Vec3, d: Vec3, far: f32| mesh.cast_local_ray(&Ray::new(o, d), far, false).is_some();
let vals: Vec<([u8; 4], [u8; 4], [u8; 4])> = at
.texels
diff --git a/systems/weathering/src/scene.rs b/systems/weathering/src/scene.rs
index 63c6f36d..8929e38f 100644
--- a/systems/weathering/src/scene.rs
+++ b/systems/weathering/src/scene.rs
@@ -177,7 +177,7 @@ pub(crate) fn read(bytes: &[u8], classes: &Classes) -> R<Scene> {
}
let mesh = meshes.get(mi).ok_or_else(|| format!("mesh {mi} missing"))?;
// a mesh drawn by a second node is baked again as a copy (written as a new mesh)
- let baked_as = if used[mi] { meshes.len() + sc.node_mesh.iter().filter(|(_, b)| *b >= meshes.len()).count() } else { mi };
+ let baked_as = if used[mi] { meshes.len() + sc.node_mesh.iter().filter(|nb| nb.1 >= meshes.len()).count() } else { mi };
used[mi] = true;
sc.node_mesh.push((n, baked_as));
for (pi, p) in arr(mesh, "primitives").iter().enumerate() {
diff --git a/systems/weathering/src/touch.rs b/systems/weathering/src/touch.rs
index 530a99c9..bcae5e24 100644
--- a/systems/weathering/src/touch.rs
+++ b/systems/weathering/src/touch.rs
@@ -28,20 +28,19 @@ pub(crate) fn touch(sc: &Scene, at: &Atlas, env: &Env, mesh: &TriMesh, c0: &[[u8
let mats: Vec<Mat> = sc.class.iter().map(|&c| mat(c)).collect();
let walk: Vec<bool> = (0..sc.tri.len()).map(|t| walks(sc, env, t)).collect();
let s = Surface { pos: &sc.pos, tri: &sc.tri, nrm: &sc.nrm, mat: &mats, walk: &walk, mesh, up: env.up };
- let px = |x: u16, y: u16| y as usize * at.w as usize + x as usize;
let f = |b: u8| b as f32 / 255.0;
let pts: Vec<Point> = at.texels.iter().map(|tx| {
- let i = px(tx.x, tx.y);
+ let i = at.px(tx.x, tx.y);
Point { p: tx.p, n: tx.n, tri: tx.tri, ground: f(c2[i][0]) * GROUND_RANGE, rain: f(c0[i][0]), flow: f(c1[i][0]), edge: f(c0[i][3]) }
}).collect();
let (touch, spots) = mark(&s, &pts);
for (tx, v) in at.texels.iter().zip(touch) {
- c1[px(tx.x, tx.y)][3] = (v.clamp(0.0, 1.0) * 255.0).round() as u8;
+ c1[at.px(tx.x, tx.y)][3] = (v.clamp(0.0, 1.0) * 255.0).round() as u8;
}
let v3 = |v: Vec3| json!([round(v.x), round(v.y), round(v.z)]);
json!(spots.iter().map(|s: &Spot| json!({ "what": s.what, "by": s.by, "at": v3(s.at), "n": v3(s.n), "size": s.size })).collect::<Vec<_>>())
}
fn round(v: f32) -> f64 {
- (v as f64 * 1000.0).round() / 1000.0
+ (f64::from(v) * 1000.0).round() / 1000.0
}