mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 08:46:06 -10:00
Compare commits
8
Commits
bake
..
scene-faults
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af8a5f48f0 | ||
|
|
ac18bdf4ea | ||
|
|
13177768cc | ||
|
|
ba02f5f5de | ||
|
|
9d076c1e3c | ||
|
|
1538a0a764 | ||
|
|
223e424d68 | ||
|
|
bff2a1858f |
No files matched your search
Generated
+31
-13
@@ -13986,13 +13986,17 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"dunce",
|
||||
"image",
|
||||
"raea-core-facts",
|
||||
"raea-core-scene",
|
||||
"raea-runtime-bundle",
|
||||
"raea-runtime-export",
|
||||
"raea-runtime-lod-plan",
|
||||
"raea-sys-body",
|
||||
"raea-sys-contact",
|
||||
"raea-sys-light-meter",
|
||||
"raea-sys-motionfaults",
|
||||
"raea-sys-notice",
|
||||
"raea-sys-stage",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -15396,6 +15400,7 @@ dependencies = [
|
||||
"raea-core-scene",
|
||||
"raea-runtime-lod-plan",
|
||||
"raea-sys-contact",
|
||||
"raea-sys-notice",
|
||||
"raea-sys-stage",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -16359,23 +16364,14 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "raea-sys-lightbake"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"gltf",
|
||||
"image",
|
||||
"parry3d",
|
||||
"raea-sys-atlas",
|
||||
"raea-sys-lighttrace",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-lighttrace"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"parry3d",
|
||||
"pollster 0.4.0",
|
||||
"raea-gpu-device",
|
||||
"raea-sys-atlas",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
@@ -16505,6 +16501,27 @@ dependencies = [
|
||||
"mlx-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-motionfaults"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"glam 0.33.12",
|
||||
"raea-core-ease",
|
||||
"raea-sys-body",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-notice"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-ease",
|
||||
"raea-core-scene",
|
||||
"raea-io-home",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-page"
|
||||
version = "0.1.0"
|
||||
@@ -16725,6 +16742,7 @@ name = "raea-sys-splat"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-ease",
|
||||
"raea-core-program",
|
||||
"raea-sys-frame",
|
||||
"serde_json",
|
||||
|
||||
+2
-1
@@ -105,6 +105,8 @@ members = [
|
||||
"systems/a11y",
|
||||
"systems/bake",
|
||||
"systems/contact",
|
||||
"systems/notice",
|
||||
"systems/motionfaults",
|
||||
"systems/light-meter",
|
||||
"systems/measure",
|
||||
"systems/canvas",
|
||||
@@ -208,7 +210,6 @@ members = [
|
||||
"apps/ask",
|
||||
"apps/lightbake",
|
||||
"systems/lightbake",
|
||||
"systems/lighttrace",
|
||||
"systems/atlas",
|
||||
"apps/double",
|
||||
"apps/check",
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al. All Rights Reserved.
|
||||
Copyright (c) 2011-2022 Blender Foundation
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
|
||||
following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
|
||||
disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
|
||||
disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
|
||||
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -13,12 +13,6 @@ HyperFrames: https://github.com/heygen-com/hyperframes
|
||||
font rules. The ported files carry a header saying so: sdk/ui/src/html.ts and sdk/ui/src/html/compile.ts, fonts.ts
|
||||
and runtime.ts. raea renamed the format's runtime names (window.__raea, data-raea-* attributes, the "html" profile).
|
||||
|
||||
Cycles: https://github.com/blender/cycles
|
||||
Copyright 2009-2010 Sony Pictures Imageworks Inc., et al., and 2011-2022 Blender Foundation. BSD-3-Clause
|
||||
(LICENSES/cycles-BSD-3-Clause.txt). systems/lighttrace's glossy layers (src/glossy.rs and src/wgsl/glossy.wgsl) are
|
||||
written from its microfacet, Fresnel and sampling code (src/kernel/closure/bsdf_microfacet.h and bsdf_util.h,
|
||||
src/kernel/sample/mapping.h), in part adapted from Open Shading Language.
|
||||
|
||||
muxide: vendor/muxide, MIT OR Apache-2.0 (its LICENSE-MIT and LICENSE-APACHE).
|
||||
|
||||
animato (MIT OR Apache-2.0), usvg and resvg (Apache-2.0 OR MIT), mediabunny (MPL-2.0, used unmodified), manifold-rust
|
||||
|
||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea scene lint|explain|light|stage|lod: a composition's frames stepped without drawing and held to the contact, light and stage checks"
|
||||
description = "raea scene lint|explain|faults|light|stage|lod: a composition's frames stepped without drawing and held to the contact, light and stage checks"
|
||||
|
||||
[dependencies]
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
@@ -12,6 +12,11 @@ raea-runtime-export = { path = "../../runtime/export" }
|
||||
raea-sys-contact = { path = "../../systems/contact" }
|
||||
raea-sys-light-meter = { path = "../../systems/light-meter" }
|
||||
raea-sys-stage = { path = "../../systems/stage" }
|
||||
# raea scene faults: whether a viewer would notice each lint finding, and the judge learning from verdicts
|
||||
raea-sys-notice = { path = "../../systems/notice" }
|
||||
# raea scene faults --clip: a character's motion held to what a body does
|
||||
raea-sys-motionfaults = { path = "../../systems/motionfaults" }
|
||||
raea-sys-body = { path = "../../systems/body" }
|
||||
# each part's planned detail beside how large the frames show it (MK21, MK23)
|
||||
raea-runtime-lod-plan = { path = "../../runtime/lod-plan" }
|
||||
# its results as Findings (docs/direction.feature DR3)
|
||||
@@ -20,4 +25,6 @@ raea-core-facts = { path = "../../core/facts" }
|
||||
raea-core-scene = { path = "../../core/scene" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
|
||||
dunce = "1"
|
||||
# --ask: the fault ringed on its frame for the vision model
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,109 @@
|
||||
//! `raea scene faults EDIT.tsx --composition ID --ask N` (docs/notice.feature NT12): a vision model asked only what
|
||||
//! geometry can't say, whether a likely fault is meant. The judge has already found it, measured it and found the
|
||||
//! frame it shows largest on; that frame is rendered, the fault's spots ringed on it, and `raea ask` (clef-omni) is
|
||||
//! handed the picture with the scene's own words for it: which part, what it's on or in, by how much. Its answer,
|
||||
//! meant or a mistake, is kept as a verdict (`by: "ask"`) when it's SURE or more, and any person's verdict on the same
|
||||
//! finding outranks it.
|
||||
//! The ringed pictures stay in the project's review/faults-ask/ for a person to look at.
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use raea_sys_notice::{FAULT, Judged, labels};
|
||||
|
||||
/// Rendered this wide (its height kept to the composition's shape).
|
||||
const WIDE: u32 = 960;
|
||||
/// An answer this sure or more is kept as a verdict; under it, said as unsure and kept out of training. On room
|
||||
/// 106's shot-window (2026-11-27) the model was 0.52-0.65 sure on chair feet pressed into carpet and a leg through a
|
||||
/// strap, and 0.72-0.78 on a sunk kit, a floating hat and a part sunk into a door.
|
||||
const SURE: f64 = 0.7;
|
||||
|
||||
/// One ring around every spot of the fault on the picture, a little out from them, in red.
|
||||
fn ring(png: &Path, marks: &[[f32; 2]]) -> Result<(), String> {
|
||||
let mut img = image::open(png).map_err(|e| format!("{}: {e}", png.display()))?.to_rgb8();
|
||||
let (w, h) = (img.width() as f32, img.height() as f32);
|
||||
let pts: Vec<(f32, f32)> = marks.iter().map(|m| ((m[0] + 1.0) * 0.5 * w, (1.0 - m[1]) * 0.5 * h)).collect();
|
||||
let (cx, cy) = (pts.iter().map(|p| p.0).sum::<f32>() / pts.len() as f32, pts.iter().map(|p| p.1).sum::<f32>() / pts.len() as f32);
|
||||
let r = pts.iter().map(|p| (p.0 - cx).hypot(p.1 - cy)).fold(0.0f32, f32::max) + 0.03 * w;
|
||||
for y in 0..img.height() {
|
||||
for x in 0..img.width() {
|
||||
let d = (x as f32 - cx).hypot(y as f32 - cy);
|
||||
if (d - r).abs() <= 2.5 {
|
||||
img.put_pixel(x, y, image::Rgb([255, 30, 30]));
|
||||
}
|
||||
}
|
||||
}
|
||||
img.save(png).map_err(|e| format!("{}: {e}", png.display()))
|
||||
}
|
||||
|
||||
fn question(j: &Judged) -> String {
|
||||
let f = &j.fault;
|
||||
let what = match &f.into {
|
||||
Some(into) => format!("{} (against {into})", f.part),
|
||||
None => f.part.clone(),
|
||||
};
|
||||
format!(
|
||||
"This is a frame of a 3D scene. Inside the red ring is {what}. A geometry check measured: {}. Judge only what is inside the ring. Is it meant to be like this (cloth draped over an edge, something hung, feet pressed into soft carpet, something set into a wall), or a mistake a viewer would notice (something floating, sunk into something, passing through something, faces flickering)?",
|
||||
f.says
|
||||
)
|
||||
}
|
||||
|
||||
/// The likeliest `n` faults asked about, their answers kept as verdicts.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn run(tsx: &Path, shot: &str, judged: &[Judged], frames: &[i64], w: u32, h: u32, n: usize, dry: bool) -> Result<String, String> {
|
||||
let project = labels::project_of(tsx);
|
||||
let dir = project.join("review").join("faults-ask");
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let me = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let tall = ((WIDE as f32 * h as f32 / w as f32 / 2.0).round() as u32 * 2).max(2);
|
||||
let (mut out, mut rows) = (Vec::new(), Vec::new());
|
||||
for j in judged.iter().filter(|j| j.p >= FAULT && j.seen.best.is_some() && !j.seen.marks.is_empty()).take(n) {
|
||||
let frame = frames[j.seen.best.unwrap()];
|
||||
let name = format!("{shot}-{}", j.fault.key).replace(|c: char| !(c.is_ascii_alphanumeric() || c == '-'), "_");
|
||||
let (png, mp4) = (dir.join(format!("{name}.png")), dir.join(format!("{name}.mp4")));
|
||||
// the frame as the render draws it, its own end checks left out (they'd judge the scene again)
|
||||
let drawn = Command::new(&me)
|
||||
.args(["render", &tsx.to_string_lossy(), "--composition", shot, "--frame", &frame.to_string(), "--w", &WIDE.to_string(), "--h", &tall.to_string(), "-o", &png.to_string_lossy()])
|
||||
.env("RAEA_FAULTS_CHECK", "0")
|
||||
.env("RAEA_CLIP_CHECK", "0")
|
||||
.output()
|
||||
.map_err(|e| format!("raea render: {e}"))?;
|
||||
if !drawn.status.success() {
|
||||
return Err(format!("raea render frame {frame}: {}", String::from_utf8_lossy(&drawn.stderr).lines().last().unwrap_or("")));
|
||||
}
|
||||
ring(&png, &j.seen.marks)?;
|
||||
// raea ask watches a picture move: the still as a second of video
|
||||
let made = Command::new("ffmpeg").args(["-y", "-loglevel", "error", "-loop", "1", "-i", &png.to_string_lossy(), "-t", "1", "-r", "10", "-pix_fmt", "yuv420p", &mp4.to_string_lossy()]).status().map_err(|e| format!("ffmpeg: {e}"))?;
|
||||
if !made.success() {
|
||||
return Err(format!("ffmpeg couldn't make {}", mp4.display()));
|
||||
}
|
||||
let mut cmd = Command::new(&me);
|
||||
cmd.args(["ask", &mp4.to_string_lossy(), &question(j), "--choose", "meant,mistake", "--brief", "none", "--json"]);
|
||||
if dry {
|
||||
cmd.arg("--dry");
|
||||
}
|
||||
let asked = cmd.output().map_err(|e| format!("raea ask: {e}"))?;
|
||||
let text = String::from_utf8_lossy(&asked.stdout);
|
||||
let first: Value = text.lines().find_map(|l| serde_json::from_str::<Value>(l).ok()).unwrap_or(Value::Null);
|
||||
let choice = first["choice"].as_str().or_else(|| first["answer"].as_str()).map(str::to_lowercase);
|
||||
let says = first["says"].as_str().unwrap_or("").to_string();
|
||||
let sure = first["value"].as_f64().unwrap_or(0.0);
|
||||
match choice.as_deref() {
|
||||
Some(c) if (c.contains("mistake") || c.contains("meant")) && sure < SURE => {
|
||||
out.push(format!("{:.2} {} -> unsure ({says}), not kept (frame {frame}, {})", j.p, j.fault.key, png.display()));
|
||||
}
|
||||
Some(c) if c.contains("mistake") || c.contains("meant") => {
|
||||
let real = c.contains("mistake");
|
||||
rows.push(labels::row(&j.fault.key, real, "ask", shot, &j.x, &j.toks));
|
||||
out.push(format!("{:.2} {} -> {}{} (frame {frame}, {})", j.p, j.fault.key, if real { "a mistake" } else { "meant" }, if says.is_empty() { String::new() } else { format!(": {says}") }, png.display()));
|
||||
}
|
||||
_ if dry => out.push(format!("{:.2} {} would be asked on frame {frame} ({})", j.p, j.fault.key, png.display())),
|
||||
_ => out.push(format!("{:.2} {} not answered: {}", j.p, j.fault.key, first["not_asked"].as_str().or(first["problem"].as_str()).unwrap_or(text.lines().next().unwrap_or("")))),
|
||||
}
|
||||
}
|
||||
labels::append(&project, &rows)?;
|
||||
out.push(format!("{} asked, {} answers kept as verdicts (by ask; a person's verdict outranks them) in {}", out.len(), rows.len(), project.join("review").join("faults.labels.jsonl").display()));
|
||||
Ok(out.join("\n"))
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
//! `raea scene faults EDIT.tsx --composition ID --motion`: the composition's characters held to what a body does
|
||||
//! (raea-sys-motionfaults), read from the scene itself, with no clip written out. raea/character's `<Character>` draws
|
||||
//! each joint as a marker part named `<name>-<joint>` (its joint.glb) at the joint's place and turn, and every joint's
|
||||
//! rest frame is the world's, so a joint's turn from rest against its parent is its parent's world turn undone from its
|
||||
//! own: each frame's pose comes back exactly. The skeleton is the body's skeleton.json beside its joint.glb.
|
||||
//!
|
||||
//! And the hands against the scene: each finger bone, the thumb's too, as a segment from its joint toward its tip,
|
||||
//! tested against every other part's real triangles (raea-sys-notice's BVH). A bone that crosses a surface has gone in
|
||||
//! at least a finger's half thickness: a thumb through a grip, fingers through a mug's wall. And the other way: while
|
||||
//! two or more fingertips rest on a surface (the hand holds something), a tip left 3 cm or more off it hasn't closed:
|
||||
//! the thumb not wrapping round a post.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use bevy::math::{Quat, Vec3};
|
||||
use raea_core_scene::Item;
|
||||
use raea_sys_body::rig::{FINGERS, Pose, Side, Skeleton};
|
||||
use raea_sys_motionfaults::{Clip, Fault, Hit, grip, stretches};
|
||||
use serde_json::Value;
|
||||
|
||||
/// A distal bone is tested this far toward its tip (its tip is the skin's end, which rests on what it touches).
|
||||
const ALONG: f32 = 0.85;
|
||||
|
||||
fn name(it: &Item) -> Option<&str> {
|
||||
it.props.get("name").and_then(Value::as_str)
|
||||
}
|
||||
|
||||
/// The characters on a frame: each one's name and the folder its joint.glb is in.
|
||||
fn characters(its: &[Item]) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for it in its {
|
||||
let (Some(n), Some(src)) = (name(it), it.props.get("src").and_then(Value::as_str)) else { continue };
|
||||
if let (Some(body), true) = (n.strip_suffix("-body"), src.ends_with("/body.glb")) {
|
||||
let folder = src.trim_end_matches("/body.glb").to_string();
|
||||
if !out.iter().any(|o| o.0 == body) {
|
||||
out.push((body.to_string(), folder));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The body's skeleton.json, its folder as the scene names it found from the composition's folder up.
|
||||
fn skeleton(dir: &Path, folder: &str) -> Option<(PathBuf, Skeleton)> {
|
||||
let rel = folder.trim_start_matches('/');
|
||||
for up in dir.ancestors().take(4) {
|
||||
for sub in ["", "media", "assets", "public", "compositions/media"] {
|
||||
let p = up.join(sub).join(rel).join("skeleton.json");
|
||||
if let Ok(t) = std::fs::read_to_string(&p) {
|
||||
return Skeleton::from_json(&t).ok().map(|s| (p, s));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A part's place and turn (its scale taken out).
|
||||
fn placed(it: &Item) -> (Vec3, Quat) {
|
||||
let (_, r, t) = it.world.to_scale_rotation_translation();
|
||||
(t, r)
|
||||
}
|
||||
|
||||
/// One character's frames as a clip, and each frame's joint places in the scene (for the hands against it).
|
||||
fn clip_of(skel: &Skeleton, who: &str, frames: &[Vec<Item>], fps: f32) -> (Clip, Vec<Vec<Option<(Vec3, Quat)>>>) {
|
||||
let (mut poses, mut places) = (Vec::new(), Vec::new());
|
||||
for its in frames {
|
||||
let at: Vec<Option<(Vec3, Quat)>> = skel.joints.iter().map(|j| its.iter().find(|it| name(it) == Some(&format!("{who}-{}", j.name))).map(placed)).collect();
|
||||
let mut p: Pose = skel.rest();
|
||||
for (i, j) in skel.joints.iter().enumerate() {
|
||||
let Some((pos, rot)) = at[i] else { continue };
|
||||
match j.parent.and_then(|q| at[q]) {
|
||||
Some((_, prot)) => p.turns[i] = (prot.inverse() * rot).normalize(),
|
||||
None if j.parent.is_none() => {
|
||||
p.turns[i] = rot;
|
||||
p.root = pos;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
poses.push(p);
|
||||
places.push(at);
|
||||
}
|
||||
(Clip { skel: skel.clone(), fps, poses, held: None }, places)
|
||||
}
|
||||
|
||||
/// The hands against the scene's other parts, frame by frame: finger bones through a surface (`through`), and tips
|
||||
/// left off what the hand holds (`grip`), as faults over the stretches they last.
|
||||
fn hands(skel: &Skeleton, who: &str, frames: &[Vec<Item>], places: &[Vec<Option<(Vec3, Quat)>>], numbers: &[i64]) -> Vec<Fault> {
|
||||
let mut hits: Vec<Hit> = Vec::new();
|
||||
let bones: Vec<usize> = Side::BOTH.iter().flat_map(|&s| FINGERS.iter().filter_map(move |f| skel.finger(f, s))).flatten().collect();
|
||||
let tips: Vec<Vec<usize>> = Side::BOTH.iter().map(|&s| FINGERS.iter().filter_map(|f| skel.finger(f, s).map(|b| b[2])).collect()).collect();
|
||||
for (k, its) in frames.iter().enumerate() {
|
||||
// the scene but the character itself (its skin is drawn at its bind pose in the parts, its markers are specks)
|
||||
let mine = format!("{who}-");
|
||||
let others: Vec<Item> = its.iter().filter(|it| !name(it).is_some_and(|n| n.starts_with(&mine))).cloned().collect();
|
||||
// every part: a mesh's place is often in its own vertices, its transform the world's origin (gambit's ladder lab),
|
||||
// so nothing can be left out by where its transform sits
|
||||
if bones.iter().all(|&i| places[k][i].is_none()) {
|
||||
continue;
|
||||
}
|
||||
let near: Vec<Item> = others.into_iter().filter(|it| it.kind != "camera").collect();
|
||||
let scene = raea_sys_notice::Scene::of(&near);
|
||||
let bone = |i: usize, along: f32| places[k][i].map(|(a, rot)| (a, a + rot * ((skel.joints[i].tail - skel.joints[i].head) * along)));
|
||||
for &i in &bones {
|
||||
if let Some((a, b)) = bone(i, ALONG)
|
||||
&& scene.blocked(a, b, 0.0)
|
||||
{
|
||||
hits.push(Hit { check: "through", joint: skel.joints[i].name.clone(), f: k, value: 0.0, unit: "m", what: String::new() });
|
||||
}
|
||||
}
|
||||
for side in &tips {
|
||||
let off: Vec<(usize, f32)> = side.iter().filter_map(|&i| bone(i, 1.0).map(|(_, tip)| (i, scene.reach(tip, grip::LOOK)))).collect();
|
||||
for o in grip::open(&off.iter().map(|o| o.1).collect::<Vec<_>>()) {
|
||||
hits.push(Hit { check: "grip", joint: skel.joints[off[o].0].name.clone(), f: k, value: off[o].1, unit: "m", what: String::new() });
|
||||
}
|
||||
}
|
||||
}
|
||||
// one fault per check and joint while the frames run on, as a clip's are (motionfaults' stretches)
|
||||
let mut out = stretches(hits);
|
||||
for f in &mut out {
|
||||
(f.from, f.to, f.peak) = (numbers[f.from] as usize, numbers[f.to] as usize, numbers[f.peak] as usize);
|
||||
f.says = match f.check {
|
||||
"grip" => format!("{} is {:.0} mm off what the hand holds (it hasn't closed on it), frames {}-{}", f.joint, f.value * 1000.0, f.from, f.to),
|
||||
_ => format!("{} passes through a part of the scene, frames {}-{}", f.joint, f.from, f.to),
|
||||
};
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One character's findings over the composition's frames.
|
||||
pub struct Found {
|
||||
pub who: String,
|
||||
pub skeleton: PathBuf,
|
||||
pub frames: usize,
|
||||
pub faults: Vec<Fault>,
|
||||
}
|
||||
|
||||
/// Every character's motion faults over the frames given (their numbers alongside); a character whose skeleton.json
|
||||
/// can't be found is said in the second list.
|
||||
pub fn run(dir: &Path, frames: &[(i64, Vec<Item>)], fps: f32) -> Result<(Vec<Found>, Vec<String>), String> {
|
||||
let Some((_, first)) = frames.first() else { return Err("no frames".into()) };
|
||||
let found = characters(first);
|
||||
if found.is_empty() {
|
||||
return Err("no characters in the composition (a <Character> draws <name>-body and <name>-<joint> parts)".into());
|
||||
}
|
||||
let numbers: Vec<i64> = frames.iter().map(|f| f.0).collect();
|
||||
let items: Vec<Vec<Item>> = frames.iter().map(|f| f.1.clone()).collect();
|
||||
let (mut out, mut missing) = (Vec::new(), Vec::new());
|
||||
for (who, folder) in found {
|
||||
let Some((path, skel)) = skeleton(dir, &folder) else {
|
||||
missing.push(format!("{who}: no skeleton.json for {folder}, not checked"));
|
||||
continue;
|
||||
};
|
||||
let (clip, places) = clip_of(&skel, &who, &items, fps);
|
||||
let mut faults = raea_sys_motionfaults::check(&clip);
|
||||
// the clip's frames are the composition's from its first
|
||||
for f in &mut faults {
|
||||
(f.from, f.to, f.peak) = (numbers[f.from] as usize, numbers[f.to.min(numbers.len() - 1)] as usize, numbers[f.peak] as usize);
|
||||
}
|
||||
faults.extend(hands(&skel, &who, &items, &places, &numbers));
|
||||
out.push(Found { who, skeleton: path, frames: clip.poses.len(), faults });
|
||||
}
|
||||
Ok((out, missing))
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
//! `raea scene faults EDIT.tsx`: the lint's findings judged as a viewer of the shot would see them (raea-sys-notice):
|
||||
//! every frame's camera asked where each one shows and how large, a small model saying how likely it is to read as a
|
||||
//! fault, the likeliest first. Hidden ones (walls meeting the ceiling inside the slab) are counted, not listed.
|
||||
//!
|
||||
//! It learns: `--real KEY` and `--fine KEY` keep a verdict on a finding beside the project (review/
|
||||
//! faults.labels.jsonl), and a finding the last run said that's gone while both its parts remain is kept as fixed,
|
||||
//! so real. `raea scene faults train [FOLDER]` fits the model to every project's verdicts under FOLDER.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use raea_runtime_bundle::{bundle_composition, comp_opts};
|
||||
use raea_runtime_export::{frame_of, items};
|
||||
use raea_sys_notice::{FAULT, Judged, Model, labels};
|
||||
|
||||
/// The most frames whose cameras are asked (evenly over the shot).
|
||||
const CAMERAS: usize = 48;
|
||||
|
||||
pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
let Some(edit) = args.get(2) else { return Err(crate::USAGE.into()) };
|
||||
if edit == "train" {
|
||||
return train(args.get(3).map(String::as_str));
|
||||
}
|
||||
if edit == "--clip" {
|
||||
return crate::motion::cli(args);
|
||||
}
|
||||
let tsx = dunce::canonicalize(std::path::PathBuf::from(edit)).map_err(|e| format!("{edit}: {e}"))?;
|
||||
let dir = tsx.parent().unwrap().to_path_buf();
|
||||
let frame = frame_of(args)?;
|
||||
let opts = comp_opts(args)?;
|
||||
let shot = opts.composition.clone().unwrap_or_default();
|
||||
let js = std::env::temp_dir().join(format!("raea-faults-{}.js", std::process::id()));
|
||||
bundle_composition(&tsx, &js, &opts, None)?;
|
||||
let got = raea_runtime_export::scene_frames(&js, &dir, 0, true, &[]);
|
||||
let _ = std::fs::remove_file(&js);
|
||||
let (frames, w, h, fps) = got?.ok_or("the composition has no 3D")?;
|
||||
// the composition's characters held to what a body does, read from the scene (chars.rs)
|
||||
if args.iter().any(|a| a == "--motion") {
|
||||
let all: Vec<(i64, Vec<raea_core_scene::Item>)> = frames.iter().map(|fr| (fr.0, items(&fr.1))).collect();
|
||||
let (text, v, n) = crate::motion::composition(&tsx, &shot, &dir, &all, fps as f32, args)?;
|
||||
return finish(if args.iter().any(|a| a == "--json") { serde_json::to_string_pretty(&v).unwrap_or_default() } else { text }, n);
|
||||
}
|
||||
let k = frames.iter().position(|(f, _)| *f == frame).ok_or_else(|| format!("no frame {frame}"))?;
|
||||
let other = if k + 1 < frames.len() { k + 1 } else { k.saturating_sub(1) };
|
||||
let (now, next) = (items(&frames[k].1), items(&frames[other].1));
|
||||
let (found, _) = raea_sys_contact::lint(&now, &next);
|
||||
// the cameras: the frame's own and evenly over the rest of the shot
|
||||
let step = frames.len().div_ceil(CAMERAS).max(1);
|
||||
// and each view's frame number, for the frame a fault shows largest on (--ask)
|
||||
let (mut views, mut view_frames) = (vec![now.clone()], vec![frame]);
|
||||
for (i, (f, fr)) in frames.iter().enumerate() {
|
||||
if i != k && i % step == 0 {
|
||||
views.push(items(fr));
|
||||
view_frames.push(*f);
|
||||
}
|
||||
}
|
||||
let model = Model::load();
|
||||
let judged = raea_sys_notice::judge(&found, &views, w, h, &model);
|
||||
// faults of known size planted and judged: the judge measured, nothing kept (seed.rs)
|
||||
if let Some(n) = raea_runtime_bundle::flag(args, "--seed") {
|
||||
let n = n.parse::<usize>().map_err(|_| "--seed takes how many faults to plant")?;
|
||||
return Ok(crate::seed::run(&now, &next, &views, &found, w, h, &model, n));
|
||||
}
|
||||
|
||||
// a vision model asked whether the likeliest faults are meant (ask.rs), its answers kept as verdicts
|
||||
if let Some(n) = raea_runtime_bundle::flag(args, "--ask") {
|
||||
let n = n.parse::<usize>().map_err(|_| "--ask takes how many of the likeliest faults to ask about")?;
|
||||
return crate::ask::run(&tsx, &shot, &judged, &view_frames, w, h, n, args.iter().any(|a| a == "--dry"));
|
||||
}
|
||||
|
||||
// what it learns from: this run against the last, and any verdict given now
|
||||
let project = labels::project_of(&tsx);
|
||||
let keys: Vec<String> = judged.iter().map(|j| j.fault.key.clone()).collect();
|
||||
let parts: Vec<String> = found.iter().flat_map(|v| ["part", "on", "into"].into_iter().filter_map(move |n| v[n].as_str())).map(String::from).collect();
|
||||
let mut rows = labels::fixed(&labels::last(&project, &shot), &keys, &parts);
|
||||
let fixed = rows.len();
|
||||
for (name, real) in [("--real", true), ("--fine", false)] {
|
||||
for key in raea_runtime_bundle::flags(args, name) {
|
||||
let j = judged.iter().find(|j| j.fault.key == key).ok_or_else(|| format!("{name} {key}: no finding by that key on this shot (keys are listed with --json, or after each line)"))?;
|
||||
rows.push(labels::row(&key, real, "marked", &shot, &j.x, &j.toks));
|
||||
}
|
||||
}
|
||||
labels::append(&project, &rows)?;
|
||||
let last: Vec<Value> = judged.iter().map(|j| json!({"key": j.fault.key, "part": j.fault.part, "into": j.fault.into, "x": j.x, "toks": j.toks, "shot": shot})).collect();
|
||||
labels::keep_last(&project, &shot, last)?;
|
||||
|
||||
let faults: Vec<&Judged> = judged.iter().filter(|j| j.p >= FAULT).collect();
|
||||
let hidden = judged.iter().filter(|j| j.seen.shown == 0).count();
|
||||
if args.iter().any(|a| a == "--json") {
|
||||
let rows: Vec<Value> = judged
|
||||
.iter()
|
||||
.map(|j| json!({"key": j.fault.key, "check": j.fault.check, "part": j.fault.part, "into": j.fault.into, "p": (j.p * 1e3).round() / 1e3, "fault": j.p >= FAULT,
|
||||
"seen": {"frames": j.seen.frames, "shown": j.seen.shown, "px": (j.seen.px * 10.0).round() / 10.0, "near": (j.seen.near * 1e3).round() / 1e3}, "says": j.fault.says}))
|
||||
.collect();
|
||||
let text = serde_json::to_string_pretty(&json!({"frame": frame, "model": model.from, "labels": model.labels, "findings": rows, "faults": faults.len(), "hidden": hidden, "fixed": fixed})).unwrap_or_default();
|
||||
return finish(text, faults.len());
|
||||
}
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for j in &judged {
|
||||
if j.seen.shown == 0 && j.p < FAULT {
|
||||
continue;
|
||||
}
|
||||
let tag = if j.p >= FAULT { "FAULT" } else { "maybe" };
|
||||
out.push(format!("{:.2} {tag} {} (seen on {}/{} frames, {:.1} px, {:.2} m off) key: {}", j.p, j.fault.says, j.seen.shown, j.seen.frames, j.seen.px, j.seen.near, j.fault.key));
|
||||
}
|
||||
out.push(format!(
|
||||
"frame {frame}: {} findings, {} likely faults, {} seen but likely fine, {hidden} no camera sees; judged by {} ({} labels){}",
|
||||
judged.len(),
|
||||
faults.len(),
|
||||
judged.len() - faults.len() - judged.iter().filter(|j| j.seen.shown == 0 && j.p < FAULT).count(),
|
||||
model.from,
|
||||
model.labels,
|
||||
if fixed > 0 { format!("; {fixed} fixed since the last run, kept as real") } else { String::new() }
|
||||
));
|
||||
finish(out.join("\n"), faults.len())
|
||||
}
|
||||
|
||||
/// Faults fail it, as the lint's errors do.
|
||||
fn finish(text: String, faults: usize) -> Result<String, String> {
|
||||
if faults > 0 {
|
||||
println!("{text}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// `raea scene faults train [FOLDER]`: every project's verdicts under FOLDER (default: here) fitted, the model kept in
|
||||
/// raea's models folder for every run after.
|
||||
fn train(root: Option<&str>) -> Result<String, String> {
|
||||
let root = std::path::PathBuf::from(root.unwrap_or("."));
|
||||
let files = labels::files(&root, 4);
|
||||
let ex: Vec<_> = files.iter().flat_map(|f| labels::examples(f)).collect();
|
||||
if ex.is_empty() {
|
||||
return Err(format!("no verdicts under {} (review/faults.labels.jsonl: --real KEY, --fine KEY, and fixes)", root.display()));
|
||||
}
|
||||
let m = Model::fit(&ex);
|
||||
let right = ex.iter().filter(|(x, t, y)| (m.score(x, t) >= FAULT) == (*y >= 0.5)).count();
|
||||
let before = ex.iter().filter(|(x, t, y)| (Model::prior().score(x, t) >= FAULT) == (*y >= 0.5)).count();
|
||||
let p = raea_sys_notice::model::path();
|
||||
std::fs::create_dir_all(p.parent().unwrap()).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&p, serde_json::to_string_pretty(&m.to_json()).unwrap_or_default()).map_err(|e| format!("{}: {e}", p.display()))?;
|
||||
let real = ex.iter().filter(|e| e.2 >= 0.5).count();
|
||||
// held out: each finding (one finding judged on two shots shares its words) fitted without, then asked
|
||||
let (held, finds) = held_out(&ex.iter().map(|e| (e.1.clone(), e.0.clone(), e.1.clone(), e.2)).collect::<Vec<_>>());
|
||||
// and a shot at a time (each project's own shot names, so a shot is a project's view): a scene it has never seen
|
||||
let by_shot: Vec<_> = files.iter().enumerate().flat_map(|(n, f)| labels::shots(f).into_iter().map(move |(s, x, t, y)| (format!("{n}/{s}"), x, t, y))).collect();
|
||||
let (unseen, names) = held_out(&by_shot);
|
||||
Ok(format!(
|
||||
"{} verdicts on {} findings from {} projects ({real} real, {} fine): the prior agreed with {before}, the fitted judge with {right}, with {held} each fitted without its own finding (held out), and with {unseen} each fitted without its whole shot ({} shots, a scene it hasn't seen); kept in {}\n{}",
|
||||
ex.len(),
|
||||
finds,
|
||||
files.len(),
|
||||
ex.len() - real,
|
||||
names,
|
||||
p.display(),
|
||||
crate::motion::train()?
|
||||
))
|
||||
}
|
||||
|
||||
/// Verdicts a judge gets right fitted without their own group (a finding's words, a shot): each group left out in
|
||||
/// turn, fitted on the rest, then asked. With how many groups there were.
|
||||
fn held_out<K: Ord>(rows: &[(K, Vec<f32>, Vec<String>, f32)]) -> (usize, usize) {
|
||||
let mut groups: Vec<&K> = rows.iter().map(|r| &r.0).collect();
|
||||
groups.sort();
|
||||
groups.dedup();
|
||||
let (mut right, n) = (0, groups.len());
|
||||
for g in groups {
|
||||
let rest: Vec<_> = rows.iter().filter(|r| &r.0 != g).map(|r| (r.1.clone(), r.2.clone(), r.3)).collect();
|
||||
let m = Model::fit(&rest);
|
||||
right += rows.iter().filter(|r| &r.0 == g && (m.score(&r.1, &r.2) >= FAULT) == (r.3 >= 0.5)).count();
|
||||
}
|
||||
(right, n)
|
||||
}
|
||||
@@ -10,12 +10,19 @@ use raea_runtime_export::{frame_of, items};
|
||||
|
||||
// how near the camera passes to each solid part, every frame (`--clearance M`, MK16)
|
||||
pub mod clearance;
|
||||
// the lint's findings judged as a viewer of the shot would see them, learning from verdicts (raea-sys-notice)
|
||||
mod ask;
|
||||
mod chars;
|
||||
mod faults;
|
||||
mod motion;
|
||||
// faults of known size planted, to measure the judge (`faults --seed N`)
|
||||
mod seed;
|
||||
mod light;
|
||||
// each part's planned detail beside how large the frames show it (MK23)
|
||||
pub mod lod;
|
||||
mod stage;
|
||||
|
||||
pub const USAGE: &str = "raea scene lint|explain|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--json]";
|
||||
pub const USAGE: &str = "raea scene lint|explain|faults|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--real KEY] [--fine KEY] [--seed N] [--ask N [--dry]] [--motion] [--json] | raea scene faults train [FOLDER] | raea scene faults --clip CLIP.json|FOLDER [--real KEY] [--fine KEY] [--fine-from N] [--fine-upto N] [--real-from N] [--real-upto N] [--by NAME] [--seed N] [--json]";
|
||||
|
||||
/// `raea scene lint|explain EDIT.tsx [--composition ID] [--frame N] [--json]`: the frame's parts measured
|
||||
/// (frame 0 by default). `lint` says the faults (errors fail it: floating, sunk, clipping; warnings: in the air,
|
||||
@@ -28,6 +35,7 @@ pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
"light" => return light::cli(args),
|
||||
"stage" => return stage::cli(args),
|
||||
"lod" => return lod::cli(args),
|
||||
"faults" => return faults::cli(args),
|
||||
"lint" | "explain" => {}
|
||||
_ => return Err(usage.into()),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
//! `raea scene faults --clip CLIP.json|FOLDER [--clip ...]`: a character's motion held to what a body does, frame by frame
|
||||
//! (raea-sys-motionfaults): knees that buckle while the foot stands, feet that skate, joints past their range, fingers
|
||||
//! twisted or bent back, jolts, and fingers through what the hand holds. A clip is the skeleton's `joints` (and its
|
||||
//! `surface`, for the palm), `fps`, and `frames` of `{ root, turns }` (with `thing` for what the hand holds).
|
||||
//!
|
||||
//! It learns: `--fine KEY` and `--real KEY` on a clip's finding (each line ends with its key: check and joint role)
|
||||
//! move that key's line for every run after (raea-sys-motionfaults' verdicts, kept beside the scene judge's model).
|
||||
|
||||
use raea_sys_motionfaults::critic;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
// each --clip a clip's JSON, or a folder of them
|
||||
let mut files: Vec<String> = Vec::new();
|
||||
for given in args.windows(2).filter(|w| w[0] == "--clip").map(|w| &w[1]) {
|
||||
match std::fs::read_dir(given) {
|
||||
Ok(dir) => {
|
||||
let mut v: Vec<String> = dir.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "json")).map(|p| p.to_string_lossy().into()).collect();
|
||||
v.sort();
|
||||
files.extend(v);
|
||||
}
|
||||
Err(_) => files.push(given.clone()),
|
||||
}
|
||||
}
|
||||
if let Some(n) = args.windows(2).find(|w| w[0] == "--seed").map(|w| &w[1]) {
|
||||
let n = n.parse::<usize>().map_err(|_| "--seed takes how many faults of each kind to plant in each clip")?;
|
||||
return seed(&files, n);
|
||||
}
|
||||
let as_json = args.iter().any(|a| a == "--json");
|
||||
let (mut text, mut out, mut faults) = (String::new(), Vec::new(), 0);
|
||||
let store = verdicts_path();
|
||||
let mut verdicts = raea_sys_motionfaults::verdicts::Verdicts::load(&store);
|
||||
let (cpath, epath) = critic::paths(&store);
|
||||
let judge = critic::Critic::load(&cpath);
|
||||
let mut examples = Vec::new();
|
||||
let (mut given, mut held) = (0usize, 0usize);
|
||||
for file in &files {
|
||||
let v: Value = serde_json::from_str(&std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?).map_err(|e| format!("{file}: {e}"))?;
|
||||
let clip = raea_sys_motionfaults::clip_of(&v).map_err(|e| format!("{file}: {e}"))?;
|
||||
let mut found = raea_sys_motionfaults::check(&clip);
|
||||
// verdicts given now, on this clip's findings by key, then every verdict's lines applied
|
||||
for (flag, real) in [("--real", true), ("--fine", false)] {
|
||||
for k in args.windows(2).filter(|w| w[0] == flag).map(|w| &w[1]) {
|
||||
let hit: Vec<_> = found.iter().filter(|f| raea_sys_motionfaults::verdicts::key(f) == *k).collect();
|
||||
if hit.is_empty() {
|
||||
return Err(format!("{file}: no finding has the key {k} (each line ends with its key)"));
|
||||
}
|
||||
let (from, upto) = sizes(args, real);
|
||||
for f in hit {
|
||||
if f.value < from || f.value > upto {
|
||||
continue;
|
||||
}
|
||||
verdicts.give(f, real);
|
||||
examples.push(critic::row(f, real, by(args)));
|
||||
given += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let before = found.len();
|
||||
found.retain(|f| stands(f, &verdicts, &judge));
|
||||
held += before - found.len();
|
||||
faults += found.len();
|
||||
let name = std::path::Path::new(file).file_stem().map_or(file.to_string(), |s| s.to_string_lossy().into());
|
||||
text += &format!("{name}: {} frames, {} fault{}\n", clip.poses.len(), found.len(), if found.len() == 1 { "" } else { "s" });
|
||||
for f in &found {
|
||||
text += &format!(" {:<8} {} key: {}\n", f.check, f.says, raea_sys_motionfaults::verdicts::key(f));
|
||||
}
|
||||
out.push(json!({"clip": file, "frames": clip.poses.len(), "faults": found.iter().map(|f| f.to_json()).collect::<Vec<_>>()}));
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err("--clip takes a clip's JSON (joints, fps, frames of root and turns)".into());
|
||||
}
|
||||
if given > 0 {
|
||||
if let Some(dir) = store.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
}
|
||||
std::fs::write(&store, serde_json::to_string_pretty(&verdicts.to_json()).unwrap()).map_err(|e| format!("{}: {e}", store.display()))?;
|
||||
critic::append(&epath, &examples)?;
|
||||
text += &format!("{given} verdict{} kept in {}\n", if given == 1 { "" } else { "s" }, store.display());
|
||||
}
|
||||
if held > 0 {
|
||||
text += &format!("{held} finding{} held back by earlier verdicts (fine at that size)\n", if held == 1 { " is" } else { "s are" });
|
||||
}
|
||||
if as_json {
|
||||
return Ok(serde_json::to_string_pretty(&json!({"clips": out, "faults": faults, "held": held})).unwrap());
|
||||
}
|
||||
if faults > 0 {
|
||||
eprint!("{text}");
|
||||
return Err(format!("{faults} motion fault{} in {} clip{}", if faults == 1 { "" } else { "s" }, out.len(), if out.len() == 1 { "" } else { "s" }));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// Faults of each kind planted in every clip (raea-sys-motionfaults' plant), and how many `check` finds: one that is
|
||||
/// new against the clip's own faults, of its kind, on its joint (any joint for a grip), over its frame.
|
||||
fn seed(files: &[String], n: usize) -> Result<String, String> {
|
||||
use raea_sys_motionfaults::plant::{KINDS, Rng, plant};
|
||||
use std::collections::BTreeMap;
|
||||
let mut tally: BTreeMap<&str, (usize, usize, Vec<f32>, Vec<f32>)> = BTreeMap::new();
|
||||
let mut text = String::new();
|
||||
for (k, file) in files.iter().enumerate() {
|
||||
let v: Value = serde_json::from_str(&std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?).map_err(|e| format!("{file}: {e}"))?;
|
||||
let clip = raea_sys_motionfaults::clip_of(&v).map_err(|e| format!("{file}: {e}"))?;
|
||||
let own = raea_sys_motionfaults::check(&clip);
|
||||
let mut rng = Rng(0x9e37_79b9_7f4a_7c15 ^ (k as u64 + 1) * 0x1000_0001);
|
||||
for kind in KINDS {
|
||||
for _ in 0..n {
|
||||
let Some((moved, p)) = plant(&clip, kind, &mut rng) else { continue };
|
||||
let near = |f: &raea_sys_motionfaults::Fault| f.check == p.check && (p.check == "through" || p.check == "skate" || f.joint == p.joint) && f.from <= p.frame + 2 && p.frame <= f.to + 2;
|
||||
let found = raea_sys_motionfaults::check(&moved);
|
||||
let caught = found.iter().any(|f| near(f) && !own.iter().any(|o| o.check == f.check && o.joint == f.joint && o.from <= f.to && f.from <= o.to));
|
||||
let t = tally.entry(p.check).or_default();
|
||||
t.0 += 1;
|
||||
if caught {
|
||||
t.1 += 1;
|
||||
t.2.push(p.size);
|
||||
} else {
|
||||
t.3.push(p.size);
|
||||
let name = std::path::Path::new(file).file_stem().map_or(String::new(), |s| s.to_string_lossy().into());
|
||||
text += &format!(" missed in {name}: {}\n", p.says);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = format!("planted in {} clips:\n", files.len());
|
||||
for (kind, (planted, caught, got, missed)) in &tally {
|
||||
out += &format!(" {kind:<8} {caught}/{planted} caught{}{}\n", if got.is_empty() { String::new() } else { format!(", smallest caught {:.3}", raea_sys_motionfaults::bounds(got).0) }, if missed.is_empty() { String::new() } else { format!(", smallest missed {:.3}", raea_sys_motionfaults::bounds(missed).0) });
|
||||
}
|
||||
Ok(out + text.as_str())
|
||||
}
|
||||
|
||||
/// Where the motion verdicts are kept: beside the scene judge's model (notice/motion.json), or RAEA_NOTICE_MOTION.
|
||||
/// `raea scene faults EDIT.tsx --composition ID --motion`: the composition's characters (chars.rs) held to the motion
|
||||
/// checks, verdicts given (`--real`/`--fine KEY`) and applied as `--clip`'s are. And what a change shows: each run's
|
||||
/// findings are kept (review/motion.last/<shot>.json), and one the last run reported that's gone now, the character
|
||||
/// and its frames the same, was fixed, so it's kept as a real verdict at its size (raea-sys-motionfaults `fixed`).
|
||||
pub fn composition(tsx: &std::path::Path, shot: &str, dir: &std::path::Path, frames: &[(i64, Vec<raea_core_scene::Item>)], fps: f32, args: &[String]) -> Result<(String, Value, usize), String> {
|
||||
use raea_sys_motionfaults::verdicts::{fixed, key, record};
|
||||
let (found, missing) = crate::chars::run(dir, frames, fps)?;
|
||||
let store = verdicts_path();
|
||||
let mut verdicts = raea_sys_motionfaults::verdicts::Verdicts::load(&store);
|
||||
let (cpath, epath) = critic::paths(&store);
|
||||
let judge = critic::Critic::load(&cpath);
|
||||
let mut examples = Vec::new();
|
||||
let lastp = raea_sys_notice::labels::project_of(tsx).join("review").join("motion.last").join(format!("{shot}.json"));
|
||||
let last: Value = std::fs::read_to_string(&lastp).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null);
|
||||
let (mut text, mut rows, mut total, mut given, mut fixes, mut held) = (missing.join("\n"), Vec::new(), 0, 0, 0, 0);
|
||||
let mut keep = serde_json::Map::new();
|
||||
for c in &found {
|
||||
for (flag, real) in [("--real", true), ("--fine", false)] {
|
||||
for k in args.windows(2).filter(|w| w[0] == flag).map(|w| &w[1]) {
|
||||
let (from, upto) = sizes(args, real);
|
||||
for f in c.faults.iter().filter(|f| key(f) == *k && f.value >= from && f.value <= upto) {
|
||||
verdicts.give(f, real);
|
||||
examples.push(critic::row(f, real, by(args)));
|
||||
given += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut lines = String::new();
|
||||
let was = &last["characters"][&c.who];
|
||||
if was["frames"].as_u64() == Some(c.frames as u64) && last["checks"] == raea_sys_motionfaults::CHECKS {
|
||||
for (k, v, n) in fixed(was["faults"].as_array().map(Vec::as_slice).unwrap_or(&[]), &c.faults) {
|
||||
verdicts.give_at(&k, v, true);
|
||||
let (check, joint) = k.split_once(':').unwrap_or((&k, ""));
|
||||
examples.push(critic::row_of(check, joint, v, n, true, "fixed"));
|
||||
fixes += 1;
|
||||
lines += &format!(" fixed {k} at {v:.3}: gone since the last run, kept as real\n");
|
||||
}
|
||||
}
|
||||
keep.insert(c.who.clone(), json!({"frames": c.frames, "faults": c.faults.iter().map(record).collect::<Vec<_>>()}));
|
||||
let mut stand: Vec<&raea_sys_motionfaults::Fault> = Vec::new();
|
||||
for f in &c.faults {
|
||||
if stands(f, &verdicts, &judge) {
|
||||
stand.push(f);
|
||||
}
|
||||
}
|
||||
held += c.faults.len() - stand.len();
|
||||
total += stand.len();
|
||||
for f in &stand {
|
||||
lines += &format!(" {:<8} {} key: {}\n", f.check, f.says, key(f));
|
||||
}
|
||||
text += &format!("{} ({}): {} frames, {} fault{}\n{lines}", c.who, c.skeleton.display(), c.frames, stand.len(), if stand.len() == 1 { "" } else { "s" });
|
||||
rows.push(json!({"character": c.who, "skeleton": c.skeleton, "frames": c.frames, "faults": stand.iter().map(|f| f.to_json()).collect::<Vec<_>>()}));
|
||||
}
|
||||
if given + fixes > 0 {
|
||||
std::fs::create_dir_all(store.parent().unwrap_or(std::path::Path::new("."))).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&store, serde_json::to_string_pretty(&verdicts.to_json()).unwrap_or_default()).map_err(|e| format!("{}: {e}", store.display()))?;
|
||||
}
|
||||
critic::append(&epath, &examples)?;
|
||||
if let Some(dir) = lastp.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
|
||||
}
|
||||
std::fs::write(&lastp, serde_json::to_string_pretty(&json!({"checks": raea_sys_motionfaults::CHECKS, "characters": keep})).unwrap_or_default()).map_err(|e| format!("{}: {e}", lastp.display()))?;
|
||||
text += &format!("{held} held back by verdicts and the critic ({} labels), {given} verdicts given, {fixes} fixed since the last run (kept as real) in {}", judge.labels, store.display());
|
||||
Ok((text, json!({"characters": rows, "faults": total, "held": held, "fixed": fixes}), total))
|
||||
}
|
||||
|
||||
/// `--fine-upto N` / `--fine-from N` (`--real-upto`, `--real-from`): that call's verdicts only on findings of the key
|
||||
/// within those sizes, in the finding's own units (degrees past the range for a finger or a limit): a pinky's small
|
||||
/// bends fine, its big one real.
|
||||
/// A fault that stands: marked real, or not marked fine and scored a fault by the judge.
|
||||
fn stands(f: &raea_sys_motionfaults::Fault, verdicts: &raea_sys_motionfaults::verdicts::Verdicts, judge: &critic::Critic) -> bool {
|
||||
verdicts.real_at(f) || (verdicts.stands(f) && judge.score(f) >= critic::SAY)
|
||||
}
|
||||
|
||||
fn sizes(args: &[String], real: bool) -> (f32, f32) {
|
||||
let (a, b) = if real { ("--real-from", "--real-upto") } else { ("--fine-from", "--fine-upto") };
|
||||
let get = |flag: &str, or: f32| args.windows(2).find(|w| w[0] == flag).and_then(|w| w[1].parse().ok()).unwrap_or(or);
|
||||
(get(a, f32::NEG_INFINITY), get(b, f32::INFINITY))
|
||||
}
|
||||
|
||||
/// Who a verdict is by: `--by NAME` (an agent that looked: claude), else a person (marked).
|
||||
fn by(args: &[String]) -> &str {
|
||||
args.windows(2).find(|w| w[0] == "--by").map_or("marked", |w| w[1].as_str())
|
||||
}
|
||||
|
||||
/// The motion critic fitted to every example kept, held out by key, written beside the verdicts.
|
||||
pub fn train() -> Result<String, String> {
|
||||
let (cpath, epath) = critic::paths(&verdicts_path());
|
||||
let ex = critic::examples(&std::fs::read_to_string(&epath).unwrap_or_default());
|
||||
if ex.is_empty() {
|
||||
return Ok(format!("motion critic: no examples yet ({})", epath.display()));
|
||||
}
|
||||
let c = critic::Critic::fit(&ex);
|
||||
let right = ex.iter().filter(|e| (c.score_x(&e.0, &e.1) >= critic::SAY) == (e.2 >= 0.5)).count();
|
||||
let prior = ex.iter().filter(|e| (critic::Critic::prior().score_x(&e.0, &e.1) >= critic::SAY) == (e.2 >= 0.5)).count();
|
||||
let mut keys: Vec<&String> = ex.iter().map(|e| &e.1[2]).collect();
|
||||
keys.sort();
|
||||
keys.dedup();
|
||||
let held = keys.iter().map(|k| {
|
||||
let m = critic::Critic::fit(&ex.iter().filter(|e| &e.1[2] != *k).cloned().collect::<Vec<_>>());
|
||||
ex.iter().filter(|e| &e.1[2] == *k && (m.score_x(&e.0, &e.1) >= critic::SAY) == (e.2 >= 0.5)).count()
|
||||
}).sum::<usize>();
|
||||
std::fs::write(&cpath, serde_json::to_string_pretty(&c.to_json()).unwrap_or_default()).map_err(|e| format!("{}: {e}", cpath.display()))?;
|
||||
let real = ex.iter().filter(|e| e.2 >= 0.5).count();
|
||||
Ok(format!("motion critic: {} examples on {} keys ({real} real, {} fine): the prior agreed with {prior}, the fitted critic with {right}, and with {held} each fitted without its own key (held out); kept in {}", ex.len(), keys.len(), ex.len() - real, cpath.display()))
|
||||
}
|
||||
|
||||
fn verdicts_path() -> std::path::PathBuf {
|
||||
match std::env::var_os("RAEA_NOTICE_MOTION").filter(|v| !v.is_empty()) {
|
||||
Some(p) => p.into(),
|
||||
None => raea_sys_notice::model::path().with_file_name("motion.json"),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! `raea scene faults EDIT.tsx --seed N`: the judge measured on faults of known size. N props that rest as they should
|
||||
//! are each moved once (sunk into what they stand on, lifted a few millimetres off it, or lifted into the air), the
|
||||
//! lint run again, and the planted fault's finding judged. What it says: how many the lint found, and of those a camera
|
||||
//! sees at two pixels or more, how many the judge calls faults; of those no camera sees, how many it still calls one.
|
||||
//! Nothing is written: a planted fault's truth is its size, which the judge's own features already carry, so it
|
||||
//! measures the judge rather than teaching it.
|
||||
|
||||
use bevy::math::{Mat4, Vec3};
|
||||
use serde_json::Value;
|
||||
|
||||
use raea_core_scene::{Item, label};
|
||||
use raea_sys_motionfaults::plant::Rng;
|
||||
use raea_sys_notice::{Cam, FAULT, Model, Scene, camera};
|
||||
|
||||
/// Props this big across or smaller are moved.
|
||||
const PROP: f32 = 1.2;
|
||||
/// Pixels a planted fault covers at the least to count as plain to see.
|
||||
const PLAIN: f32 = 2.0;
|
||||
|
||||
|
||||
fn moved(its: &[Item], name: &str, by: Vec3) -> Vec<Item> {
|
||||
its.iter().cloned().map(|mut it| {
|
||||
if (it.kind == "mesh" || it.kind == "model") && label(&it, "") == name {
|
||||
it.world = Mat4::from_translation(by) * it.world;
|
||||
}
|
||||
it
|
||||
}).collect()
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn run(now: &[Item], next: &[Item], views: &[Vec<Item>], found: &[Value], w: u32, h: u32, model: &Model, n: usize) -> String {
|
||||
let count = |name: &str| now.iter().filter(|it| (it.kind == "mesh" || it.kind == "model") && label(it, "") == name).count();
|
||||
let props: Vec<&str> = found
|
||||
.iter()
|
||||
.filter(|v| v["check"] == "rests")
|
||||
.filter(|v| {
|
||||
let (lo, hi) = (&v["box"]["min"], &v["box"]["max"]);
|
||||
(0..3).all(|k| hi[k].as_f64().unwrap_or(9.0) - lo[k].as_f64().unwrap_or(0.0) <= PROP as f64)
|
||||
})
|
||||
.filter_map(|v| v["part"].as_str())
|
||||
.filter(|p| count(p) == 1)
|
||||
.collect();
|
||||
let cams: Vec<Cam> = views.iter().filter_map(|f| camera(f)).collect();
|
||||
// only props some camera of the shot sees (the middle of the box's top): a fault planted out of view tells
|
||||
// nothing of how the judge weighs one in it
|
||||
let scene = Scene::of(now);
|
||||
let in_view = |p: &str| {
|
||||
let Some(v) = found.iter().find(|v| v["part"] == p) else { return false };
|
||||
let at = |k: usize, e: &str| v["box"][e][k].as_f64().unwrap_or(0.0) as f32;
|
||||
let top = Vec3::new((at(0, "min") + at(0, "max")) / 2.0, at(1, "max") + 0.01, (at(2, "min") + at(2, "max")) / 2.0);
|
||||
raea_sys_notice::seen(&[raea_sys_notice::sight::Spot { at: top, facing: None, size: 0.0 }], false, &cams, &scene, w as f32, h as f32).shown > 0
|
||||
};
|
||||
let props: Vec<&str> = props.into_iter().filter(|p| in_view(p)).collect();
|
||||
if props.is_empty() {
|
||||
return "no prop the shot sees rests on anything to plant a fault in".into();
|
||||
}
|
||||
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
|
||||
let (mut lines, mut lint_found, mut plain, mut plain_flagged, mut hidden, mut hidden_flagged, mut small, mut small_flagged) = (Vec::new(), 0, 0, 0, 0, 0, 0, 0);
|
||||
for i in 0..n {
|
||||
let part = props[(rng.next() * props.len() as f32) as usize % props.len()];
|
||||
let r = rng.next();
|
||||
let (kind, d) = if r < 0.4 { ("floats", 0.002 + rng.next() * 0.028) } else if r < 0.8 { ("sunk", 0.005 + rng.next() * 0.035) } else { ("air", 0.08 + rng.next() * 0.22) };
|
||||
let by = Vec3::new(0.0, if kind == "sunk" { -d } else { d }, 0.0);
|
||||
let (a, b) = (moved(now, part, by), moved(next, part, by));
|
||||
let (again, _) = raea_sys_contact::lint(&a, &b);
|
||||
let want = |c: &str| c == kind || (kind == "sunk" && c == "seated") || (kind == "air" && c == "floats") || (kind != "sunk" && c == "mounted");
|
||||
let Some(f) = again.iter().find(|v| v["part"] == part && v["check"].as_str().is_some_and(want)) else {
|
||||
// what it said of the part instead (a prop lifted against a wall reads as mounted on it)
|
||||
let said: Vec<&str> = again.iter().filter(|v| v["part"] == part).filter_map(|v| v["check"].as_str()).collect();
|
||||
lines.push(format!("{i:>3} {kind:<6} {:>6.1} mm {part}: not found as {kind} (the lint said {})", d * 1000.0, said.join(", ")));
|
||||
eprintln!("{}", lines.last().unwrap());
|
||||
continue;
|
||||
};
|
||||
lint_found += 1;
|
||||
let scene = Scene::of(&a);
|
||||
let j = raea_sys_notice::judge_in(std::slice::from_ref(f), &scene, &cams, w, h, model);
|
||||
let Some(j) = j.first() else { continue };
|
||||
let flagged = j.p >= FAULT;
|
||||
if j.seen.shown == 0 {
|
||||
hidden += 1;
|
||||
hidden_flagged += flagged as usize;
|
||||
} else if j.seen.px >= PLAIN {
|
||||
plain += 1;
|
||||
plain_flagged += flagged as usize;
|
||||
} else {
|
||||
small += 1;
|
||||
small_flagged += flagged as usize;
|
||||
}
|
||||
lines.push(format!("{i:>3} {kind:<6} {:>6.1} mm {part}: seen {}/{} frames, {:.1} px -> {:.2}{}", d * 1000.0, j.seen.shown, j.seen.frames, j.seen.px, j.p, if flagged { " FAULT" } else { "" }));
|
||||
// each trial lints the scene again (half a minute on a furnished room): said as it goes
|
||||
eprintln!("{}", lines.last().unwrap());
|
||||
}
|
||||
lines.push(format!(
|
||||
"planted {n} in {} props: the lint found {lint_found}; plain to see (>= {PLAIN} px) {plain}, judged faults {plain_flagged}; seen under {PLAIN} px {small}, judged faults {small_flagged}; no camera sees {hidden}, judged faults {hidden_flagged}",
|
||||
props.len()
|
||||
));
|
||||
lines.join("\n")
|
||||
}
|
||||
@@ -8,6 +8,11 @@ pub mod easing;
|
||||
pub mod interpolate;
|
||||
pub mod spring;
|
||||
|
||||
/// The logistic curve, 1 / (1 + e^-z): a score in log-odds as a chance (a judge's), or a stored logit as an opacity.
|
||||
pub fn sigmoid(z: f32) -> f32 {
|
||||
1.0 / (1.0 + (-z).exp())
|
||||
}
|
||||
|
||||
/// 0 below `a`, 1 above `b`, and between them the cubic Hermite ease (WGSL's smoothstep), for a value that fades in
|
||||
/// over a range rather than a key's time.
|
||||
pub fn smoothstep(a: f32, b: f32, x: f32) -> f32 {
|
||||
|
||||
@@ -142,8 +142,14 @@ pub struct Overlaps {
|
||||
/// Between two parts, faces looking straight down in the plane both parts stand on (two boxes on one floor, one
|
||||
/// set into the other): their undersides, which the floor hides.
|
||||
pub bases: Option<(usize, f32, Vec3)>,
|
||||
/// The fight's shared patches, largest first (at most SPOTS): each one's middle, the way its faces look, and its
|
||||
/// area. Where a viewer could see it flicker (raea-sys-notice asks each camera).
|
||||
pub spots: Vec<(Vec3, Vec3, f32)>,
|
||||
}
|
||||
|
||||
/// The most shared patches a fight keeps for where it shows.
|
||||
const SPOTS: usize = 32;
|
||||
|
||||
/// Corners this close (metres) are one corner.
|
||||
const CORNER: f32 = 0.0005;
|
||||
|
||||
@@ -178,11 +184,15 @@ pub fn sorted(a: &[[Vec3; 3]], b: Option<&[[Vec3; 3]]>) -> Overlaps {
|
||||
let mut out = Overlaps::default();
|
||||
// the largest patch each kind has seen, for where to point
|
||||
let mut most = [0.0f32; 3];
|
||||
let mut spots = Vec::new();
|
||||
let mut add = |kind: usize, to: &mut Option<(usize, f32, Vec3)>, f: &Face, g: &Face| {
|
||||
let (area, mid) = shared(f, g);
|
||||
if area <= 0.0 {
|
||||
return;
|
||||
}
|
||||
if kind == 2 {
|
||||
spots.push((mid, f.n, area));
|
||||
}
|
||||
let e = to.get_or_insert((0, 0.0, mid));
|
||||
e.0 += 1;
|
||||
e.1 += area;
|
||||
@@ -215,6 +225,9 @@ pub fn sorted(a: &[[Vec3; 3]], b: Option<&[[Vec3; 3]]>) -> Overlaps {
|
||||
}
|
||||
}
|
||||
}
|
||||
spots.sort_by(|a, b| b.2.total_cmp(&a.2));
|
||||
spots.truncate(SPOTS);
|
||||
out.spots = spots;
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
+10
-149
@@ -22,9 +22,9 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
|
||||
2. What is baked is the light that bounces: the sky, emissive surfaces and the lights marked baked, through every
|
||||
bounce, plus the sun's bounce. The sun's direct light stays live (as lightbake.py subtracts it), so anything
|
||||
that moves still casts its shadow and is lit as before.
|
||||
3. It runs on wgpu ray queries (Metal on Apple silicon's ray hardware, Vulkan, DX12), over a BLAS and TLAS the bake
|
||||
builds from the meshes raea draws, not systems/rt's (BK3 says why). Every OS raea ships on; never Mac-only. A
|
||||
device without ray queries is told so, with the reason, and the composition renders unbaked.
|
||||
3. It runs on systems/rt: the same BLAS and TLAS the traced shadows and raea GI read, through wgpu ray queries
|
||||
(Metal on Apple silicon's ray hardware, Vulkan, DX12). Every OS raea ships on; never Mac-only. A device without
|
||||
ray queries is told so, with the reason, and the composition renders unbaked.
|
||||
4. Shading is Cycles', from tools/cycles-port (each function held to Cycles' own output), so the bake and the
|
||||
reference agree by construction, and LT5's path tracer (docs/realism.feature) reuses the same kernel.
|
||||
5. It lights raea's own meshes (Mesh3d, solids, raea/room) directly, as well as a <Model>'s, with no export.
|
||||
@@ -32,7 +32,6 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
|
||||
Background:
|
||||
Given systems/rt (raea-sys-rt): BLAS per mesh from Bevy's own buffers, a TLAS of visible opaque instances,
|
||||
glass left out so sky and sun reach through windows; its traced AO, raea GI's world probes and cache (LT2, LT3)
|
||||
And raea-sys-lighttrace, the kernel of BK3, split from the bake so systems/rt and LT5's path tracer can build on it
|
||||
And tools/cycles-port/cycles_bsdf.wgsl: GGX/Beckmann D, G2, Fresnel, F82 conductors, VNDF sampling, passing against
|
||||
Cycles on an M5 Pro; diffuse and energy-conserving Oren-Nayar next
|
||||
And <Lightmap> (sdk/render/src/bevy3d/lightmap.tsx, systems/material lightmap.rs): Bevy's lightmap on a <Model>'s
|
||||
@@ -148,8 +147,7 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
|
||||
And built 11-23: `raea_sys_lightbake::texels::texels(glb, request)` lays the model out (BK1's layout, raea_sys_atlas::laid; the
|
||||
light-only request is `request(texels, max_side)`, a worn model passes its wear bake's), takes
|
||||
the model's world triangles as the parry3d BVH the atlas was laid out over, moves each point
|
||||
off its surface by 1e-6 of the model's size or farthest coordinate (at least a micron; 1e-5 and 10 until BK3 found
|
||||
what it costs), and casts 16
|
||||
off its surface by 1e-5 of the model's size or farthest coordinate (at least 10 microns), and casts 16
|
||||
cosine-weighted rays from each: a texel is inside when at least half its rays meet a back face and more meet
|
||||
back faces than front ones (a floor that is one plane is met from below one way and not at all the other).
|
||||
CPU and rayon for now, as weathering's own rays; BK3's GPU pass may take the test over
|
||||
@@ -180,15 +178,10 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
|
||||
Scenario: BK3. The light that bounces, traced on raea's ray tracer
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-lightbake | systems/lightbake/src/trace_tests.rs | 240 | a white furnace, a wall's form factor, a glowing box, a red wall's bleed, the sun at a texel and at a hit, a panorama's direction, a ray straight up, a textured floor, the same bytes twice; the measured run |
|
||||
| raea-sys-lightbake | systems/lightbake/src/own.rs | 185 | a model read on its own second UVs (a map a mesh, as lightbake.py lays them): its world triangles, base colour and textures, and each map's texels |
|
||||
| raea-sys-lightbake | systems/lightbake/src/own/tests.rs | 150 | its texels on a known quad; the ignored run against a Cycles bake of the same .glb |
|
||||
| raea-sys-lighttrace | systems/lighttrace/src/wgsl/diffuse.wgsl | 40 | the diffuse BSDF and the paths' random numbers, a module systems/rt and LT5's path tracer can include as it is |
|
||||
| raea-sys-lighttrace | systems/lighttrace/src/glossy.rs | 130 | GGX on the CPU (Cycles'), and the table of a rough lobe's albedo the kernel reads |
|
||||
| raea-sys-lighttrace | systems/lighttrace/src/wgsl/glossy.wgsl | 130 | a metal's and a dielectric's layers over Lambert: weights, evaluation, sampling |
|
||||
| raea-sys-lighttrace | systems/lighttrace/src/tests.rs | 130 | white surfaces keep all their light; the sun and a panel off a floor against a CPU sum |
|
||||
| raea-sys-lighttrace | systems/lighttrace/src/lib.rs | 265 | the passes: dispatch per atlas, samples accumulated over passes, progress, cancel |
|
||||
| raea-sys-lighttrace | systems/lighttrace/src/wgsl/trace.wgsl | 250 | per texel: cosine-weighted paths against the bake's own TLAS; the sky from the composition's <Environment>, emissives, baked lights; Russian roulette; Cycles' BSDFs from cycles-port at each bounce |
|
||||
| raea-sys-lightbake | systems/lightbake/src/trace/tests.rs | 160 | a white furnace, a wall's form factor, a glowing box, a red wall's bleed, the same bytes twice; the measured run |
|
||||
| raea-sys-lightbake | systems/lightbake/src/wgsl/diffuse.wgsl | 60 | the diffuse BSDF and the paths' random numbers, a module systems/rt and LT5's path tracer can include as it is |
|
||||
| raea-sys-lightbake | systems/lightbake/src/trace.rs | 260 | the passes: dispatch per atlas, samples accumulated over passes, progress, cancel |
|
||||
| raea-sys-lightbake | systems/lightbake/src/wgsl/trace.wgsl | 320 | per texel: cosine-weighted paths against the bake's own TLAS; the sky from the composition's <Environment>, emissives, baked lights; Russian roulette; Cycles' BSDFs from cycles-port at each bounce |
|
||||
Then each texel integrates the incoming diffuse light over its hemisphere along paths of up to `bounces`
|
||||
(default 4) through a BLAS and TLAS the bake builds itself from the meshes raea draws, by the wgpu ray queries
|
||||
systems/rt uses. (Not rt's own: a bake runs offline, before any frame, with no Bevy render world to hold them,
|
||||
@@ -199,126 +192,6 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
|
||||
the cause maps (sdk/wear), so a grimy brick wall bounces grimy brick. The kernel evaluates them from one WGSL
|
||||
module shared with the raster, not a copy (Shane, 11-23); Blender's export drops these materials, so this is
|
||||
a bake Cycles' round trip can't make
|
||||
And what a module must take as arguments to be shared, read from the three sources 11-23 (nothing built): a
|
||||
compute kernel has no screen derivatives, no implicit-level texture reads and no eye
|
||||
| what the raster uses | where | what the kernel gives |
|
||||
| fwidth of the normal over the position's (edges) | procmat.wesl, worn.ts | the turn of the triangle's vertex normals over its edges |
|
||||
| fwidth of the plane, fading fine threads | procmat.wesl (fabric, brushed) | the hit's texel size |
|
||||
| a pixel's size (cracks no thinner than one) | sdk/wear index.ts, wear_geo's px | the hit's texel size |
|
||||
| textureSample of the four cause maps | sdk/wear causes.ts | textureSampleLevel, level 0 |
|
||||
| the eye, for the parallax behind lost render | sdk/wear causes.ts, wear_geo | the normal (no parallax: a bounce has no one eye) |
|
||||
| metallic, which the marks also change | worn.ts; iron, zinc, copper, brass | the bounce is base colour x (1 - metallic) |
|
||||
| u_NAME(), tex_NAME, samp_NAME, from the hook | systems/shader's module() | the same names over the kernel's own bindings |
|
||||
And systems/procmat's module is written as systems/procmat/src/drawn.wesl, not compiled or used yet; procmat.wesl
|
||||
takes it, its own copy deleted, in the commit that builds it, with a frame before and after held to the same
|
||||
bytes (fabric and brushed to one step of 8 bits: their scale moves outside the derivative). WearExtension and raea/wear are text made in TypeScript (worn.ts, sdk/wear), so the kernel gets theirs
|
||||
from the composition's material, not from a file
|
||||
And the atelier's static set is traced and held to the Cycles bake its own agent made of it (lightbake.py; the
|
||||
eighth bake read 11-23: 202 meshes of one primitive, 699 902 triangles, 198 maps of 128-1024 a side), as soon as
|
||||
the trace can: each mesh's map against Cycles' by map_stops, with its time and memory. Its light is a panorama (strength
|
||||
0.366, rotation 2.449 in the blend its bake used), one sun and no lamps
|
||||
And measured 11-23 on the M5 Pro, in progress: own.rs reads the .glb on its own second UVs, the .glb's positions
|
||||
and second UVs being equal in every bake compared. Cycles 512 samples, 56 texels a metre, smooth 2; the trace
|
||||
1024 samples, 4 bounces, with no fitted gain; 2 358 922 texels of 198 meshes, the same in every row. "biased" is
|
||||
meshes whose mean signed error is over 1/3 stop; light is total over total. Rows 1-4 and 6 bake the scene with
|
||||
every material plain diffuse (base colour x (1 - metallic)), unclamped, in a scratch copy, so the trace and
|
||||
Cycles differ only in the tracing
|
||||
| compared | mean stops | bias | light | over 1/3 | biased |
|
||||
| noise: Cycles / Cycles, another seed | 0.161 | -0.001 | 1.000 | 54 | 2 |
|
||||
| Cycles' clamp 3 / no clamp | 0.017 | -0.017 | 0.963 | 5 | 5 |
|
||||
| materials: Cycles diffuse-only / real, no clamp | 0.284 | -0.272 | 0.863 | 132 | 128 |
|
||||
| trace / Cycles, diffuse-only, no clamp | 0.218 | -0.064 | 0.994 | 94 | 46 |
|
||||
| trace / Cycles, real materials, no clamp | 0.389 | -0.336 | 0.857 | 157 | 140 |
|
||||
| trace / the atelier's own bake (clamp 3) | 0.384 | -0.319 | 0.889 | 155 | 135 |
|
||||
And what they say: on matched materials the trace's total light is within 0.6% of Cycles' and the floor, deck,
|
||||
walls and door are within 0.02 stops at the median. 14% of the light is the metals' and speculars' bounces, so
|
||||
GGX and F82 were needed (built, below). The 46 "biased" meshes are not an
|
||||
error of the trace's, except 5 of them (4 the footprint's, bench_strips the offset's): that count is by mean log error on smoothed maps and it drops texels
|
||||
where one side is 0. By each mesh's total light, zeros counted and no smoothing, 8 of 198 are over 1/3 stop (Cycles
|
||||
against itself, smoothed: 1, and 95% of meshes within 0.05). Time: the trace 17-25 s, 10 s at 256 samples and
|
||||
119 s at 4096, peak 1.2 GB, setup 70-200 s in a debug build; Cycles' diffuse-only bake 5m33s, 2.7 GB, the
|
||||
atelier's own 5m36s, 3.4 GB for its whole script
|
||||
And the 8, by the trace's light over Cycles': 4 are the footprint. The trace starts every ray at the texel's
|
||||
centre, and Cycles jitters its samples over the texel; on 30 mm texels a sheet's 6 mm ledge is all or nothing.
|
||||
Traced 8x8 points a texel and averaged, over the same texels: bench_stock 0.333 -> 0.960, bench_mat 1.333 ->
|
||||
1.006, dt_ledge 1.291 -> 0.997, dt_rule 0.765 -> 1.068; bench_strips only 0.616 -> 0.679 (the offset, below). Built after it:
|
||||
a texel starts from the open ones of 16 points over its footprint (on its triangle, clear of its edges, not
|
||||
inside other geometry, as BK2's rays judge them), so a partly buried texel is lit by what can be seen of it. A texel
|
||||
under a sheet's edge, three quarters of it covered, reads 0.2495 for 0.249 where its centre alone reads 0; one
|
||||
three quarters inside a block reads 0.52 from its open quarter
|
||||
And 3 are the reference's (mug_coffee, books_5 and tower_base): Cycles' adaptive sampling (on by default, threshold 0.01; lightbake.py doesn't turn
|
||||
it off) stops a dark pocket's pixel before it has seen the light, so a cup or a shelf's back bakes too dark. With
|
||||
it off (1024 samples, the same meshes, raw floats): mug_coffee 1.94 -> 1.012, books_5 1.279 -> 1.021, meet_tea
|
||||
1.216 -> 1.030, tower_base 1.183 -> 1.040, books_0 1.199 -> 1.072. Neither the sun's subtraction nor the PNGs'
|
||||
16-bit clipping (0.92-1.05 of the raw floats) nor the sheets' gaps (a fixture of sheets 0.05-5 mm apart: both
|
||||
black at 0.2 mm) explain it. BK0's own references were baked the same way
|
||||
And against the honest reference, measured 11-23 with jittered starts, a release build: Cycles' diffuse-only atelier
|
||||
with adaptive sampling off, unsmoothed, unclamped, 512 samples, raw floats (12m49s against 3m55s with it on, the
|
||||
same scene), by each mesh's total light, zeros counted; the trace 1024 samples, 4 bounces. (Cycles' own second
|
||||
seed, smoothed, is over 1/3 stop on 1 of 198.) The atelier's own bakes were made with adaptive sampling on
|
||||
| a texel's samples start from | over 1/3 stop | over 1/10 | total light |
|
||||
| the open part of it (what the bake does) | 3 of 198 | 21 | 0.997 |
|
||||
| all of it, buried points too (as Cycles averages) | 1 of 198 | 10 | 0.993 |
|
||||
| the open part, at the offset below | 1 of 198 | 15 | 1.000 |
|
||||
| all of it, at the offset below | 0 of 198 | 5 | 0.995 |
|
||||
They differ where a texel is partly buried: Cycles' average counts the dark inside, so it bakes such a texel darker
|
||||
than what can be seen of it; the bake keeps the open part. Left, over the whole footprint: bench_stock 1.188,
|
||||
site_base, site_contours, house_base and house_roof about 1.10, bench_strips 1.068; not explained
|
||||
And the offset was bench_strips: rays started 1e-5 of the model's size off a surface, 0.15 mm in the atelier, whose
|
||||
strips are stacked 0.2 mm apart, so a ray had 0.05 mm of each gap and the sun's first half millimetre in it was
|
||||
lost. By offset (bench_strips, lamp_shade_in, dt_tape; whole footprint, over Cycles'): 0.15 mm 0.558, 1.376,
|
||||
0.865; 50 microns 0.638, 1.117, 0.954; 20 1.007, 1.049, 0.980; 10 1.063, 1.022, 0.989; 2 1.059, 1.002, 0.997. It is
|
||||
1e-6 now. No ray off a tilted plane meets it, from the texel or from a bounce, down to 3e-7 of its distance from
|
||||
the origin (1 m to 5 km); the first do at 1e-7, on Metal. Vulkan and DX12 haven't run it. A fixed 0.1 mm under a
|
||||
40 km floor does meet it (0.8% of the light lost)
|
||||
And the times: setup in release, the atelier's own .glb 12.8 s to read and lay out, 2 992 000 texels on
|
||||
its own UVs, and 16.7 s to trace 1024 samples, peak 1.5 GB. On the atlas bake of BK2 (64 texels a metre): the table
|
||||
set 0.85 s with its texels, 0.84 s to trace 512 samples (1.5 M texels), and the atelier 19.9 s and 8.5 s (4.3 M texels).
|
||||
Other sessions were rendering. The bar is 60 s on the table set, all in: not yet timed with reading,
|
||||
cleaning (BK4) and writing in it. The 16-ray probe on the CPU is fast enough there, and 20 of the atelier's 28 s
|
||||
And each bounce goes on by the surface's glossy layers over Lambert, as Cycles' Principled does: a metal (GGX, F82
|
||||
with a white tint) and a dielectric of IOR 1.5 at Specular 0.5, what a rough lobe loses given back from a table
|
||||
glossy.rs makes. GGX, its sampling and the Fresnels are Cycles' formulas (bsdf_microfacet.h, bsdf_util.h,
|
||||
mapping.h at 6ea3d9bcd81a: BSD-3-Clause, in NOTICE, not Apache-2.0), written in systems/lighttrace until
|
||||
tools/cycles-port is on main and then swapped for its functions; three cases of its oracle are copied into the
|
||||
tests (D, G, lambda, the visible-normal sample). Filter glossy is Cycles' default 1: after a texel's diffuse turn a
|
||||
lobe's alpha is at least 0.41. Held to a CPU sum: the sun off five surfaces within 0.03%, a panel found by the
|
||||
paths' own turns within 0.6%, white surfaces keep 0.997-0.9998 of their light
|
||||
And against Cycles' real materials, adaptive sampling off (unclamped, unsmoothed, 512 samples, 15m02s, peak 2.7 GB;
|
||||
all 202 materials MULTI_GGX, IOR 1.5, Specular 0.5), the trace 1024 samples, 4 bounces, by each mesh's total light
|
||||
| the trace | over 1/3 stop | over 1/10 | total light | time |
|
||||
| Lambert only, the whole of a texel | 108 of 198 | 190 | 0.858 | 20.3 s |
|
||||
| glossy layers, the whole of a texel | 0 of 198 | 5 | 0.997 | 22.1 s |
|
||||
| glossy layers, its open part (what the bake does) | 1 of 198 | 16 | 1.002 | 18.1 s |
|
||||
Off most over the whole: bench_stock 1.166 and the dim house, site and roof models 1.08-1.10, not explained; over
|
||||
the open part: meet_sheet_0 1.325. (Other sessions' renders ran beside these.)
|
||||
And where the energy table is read is ours: at the blurred alpha, so a blurred lobe keeps its light; Cycles reads it at
|
||||
the material's own alpha, before the blur. Measured, the trace's light over Cycles' for ours, then Cycles' way:
|
||||
all meshes 0.9972, 0.9952; the 36 with any metal 1.0021, 1.0002; the 17 of metallic 0.5 and over 0.9997, 0.9974.
|
||||
Cycles' way is darker by at most 3.4% on one mesh (mug_coffee); the mean error a mesh is 0.0177 and 0.0175 stops
|
||||
And trace() refuses a texel without the samples asked for, or light that isn't finite
|
||||
And a picture a material reads that isn't there is refused by lightbake.py and look.py before they write (Cycles draws
|
||||
it magenta and bounces it: a first reference made from a copy without its textures was 6 times too bright and is
|
||||
discarded). They also have --no-adaptive, not the default. Both files are another lane's, not on main
|
||||
And the trace's own indirect clamp is gone: at 3 it kept 0.869 of Cycles' light at the same clamp where unclamped
|
||||
it keeps 0.994 (Cycles' own clamp keeps 0.963), so it was not Cycles' clamp. A bake is unclamped
|
||||
And a ray straight up gave a non-finite value on Metal (a panorama's longitude, atan2(0, 0)), one texel of the
|
||||
atelier at 1024 samples; a test casts 134 million of them
|
||||
And that comparison is read knowing what the reference is: Cycles' own materials as the .glb has them, not raea's
|
||||
drawn ones (the export drops uv_transform, _arm maps and tints; 39 materials are metal, which Cycles reflects
|
||||
and Lambert here doesn't); clamped at 3, smoothed twice, its maps' light only where Cycles has some. Cycles'
|
||||
map times its scale is the mean incoming light, as the trace's is, so the two are compared with no fitted gain
|
||||
And a <ShaderExtension> a user wrote can't run in the kernel in general (its hook reads Bevy's PbrInput, the view
|
||||
and its own textures): it bounces its base colour, and `raea bake light` names each material it did that for
|
||||
And raea/wear's caused wear (touch, edges, cavity, run-off's stains and deposits, sun fade, soot, crumbling, age and
|
||||
neglect) comes from the baked cause maps and the scene's settings, the same every frame, and bounces as any other
|
||||
albedo does. Only its per-frame layer over that (wx: wet, snow, storm, ice; season: damp, dust, leaves, melt) is
|
||||
not the surface's own, and the bake bounces it at the values the composition gives; with no weather given it
|
||||
bakes dry (decided 11-23; BK5's key)
|
||||
# Considered and not taken 11-23: drawing each material into the atlas in texture space, which would give a user's
|
||||
# shader too but needs a Bevy render in the bake.
|
||||
And the bounce matches the frame: the season's values are those wearShader draws, so "dry" is wx all 0 with the
|
||||
season as drawn (with no weather given that is day 172, whose dust is 0.595, kept in the bake; decided 11-23)
|
||||
And the sky is the composition's <Environment> panorama at its intensity and rotation; emissive surfaces light
|
||||
the set; the sun's direct light is left out at the first hit and kept at every later bounce (so a sunlit floor
|
||||
lights the ceiling), and a light marked `bake` is carried whole
|
||||
@@ -334,10 +207,8 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
|
||||
reads 2.004 for 2; breaking the cosine, the offset, the roulette, its weight, the emission or their order each
|
||||
fails one of them. Only Metal has run it. At 512 samples and 4 bounces, every surface 0.7 grey under a white
|
||||
sky, the trace alone takes 0.8 s on the table set, 0.3 s on the Cornell box and 0.9 s on the window room
|
||||
(M5 Pro; linear in samples, 5.6 s at 4096). Built since: the panorama
|
||||
with its strength and rotation, the sun at later hits by shadow rays and out at the first, base colour textures.
|
||||
Not built: baked lights, and the albedo raea draws under procmat, wear and sdk/wear; a metallic-roughness texture
|
||||
(a material's factors only) and smooth normals at a hit (the triangle's own)
|
||||
(M5 Pro; linear in samples, 5.6 s at 4096). Not built: the <Environment> panorama, baked lights, the sun left
|
||||
out at the first hit, textures, and the albedo raea draws under procmat, wear and sdk/wear
|
||||
|
||||
@needs:BK3
|
||||
Scenario: BK4. A clean map: denoised, dilated, no seams
|
||||
@@ -363,18 +234,8 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
|
||||
| @raea/render | sdk/render/src/bevy3d/lightbake.tsx | 120 | <LightBake samples bounces texels> around the static parts it bakes; re-exported from raea/3d |
|
||||
Then `<LightBake>` around a composition's static parts bakes them on the first frame a render, a play or a
|
||||
`render --at` needs it, and every later frame and run reads the kept bake
|
||||
And the BLAS come from the composition's own mesh data (Mesh3d, solids and room parts with their transforms, a
|
||||
<Model>'s meshes), never from a re-export
|
||||
And it lights raea's own Mesh3d, solids and raea/room parts in place, as well as a <Model>'s meshes, so the
|
||||
parts stay parts: `raea scene lint`, `raea render --review` and `raea make` see each one, not one baked model
|
||||
And the key holds each worn material's wear settings (age: years, soot, upkeep), its cause maps and its weather
|
||||
and season values (wx, season), so each combination bakes once, when it's first used, and is kept; with no
|
||||
weather given it bakes dry (wx 0, the season as wearShader draws it)
|
||||
And a weather or season animated over the shot bakes once, at its values on the composition's first frame with the
|
||||
<LightBake> in it, whichever frame is rendered first (so `render --at` and a full render read one bake and a
|
||||
frame has one look); it isn't refused and isn't baked each frame, and the bake's report and `raea bake light`
|
||||
name the values used and say the weather moves over the shot (decided 11-23)
|
||||
# Not built, a later scenario: two bakes, at the start and the end of a weather change, mixed by its uniform.
|
||||
And a change to a static part, a material, the sky or a setting changes the key and bakes again; a change to
|
||||
anything outside <LightBake> (the camera, a moving part, the sun's direct light) doesn't
|
||||
And `raea bake light EDIT.tsx` bakes ahead of a render and says what it baked (meshes, texels, samples, time)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
title: "raea scene"
|
||||
summary: "Find floating, sunk and clipping 3D parts, say what each part rests on, meter a shot's light, hold every frame to the stage checks a render runs, and list each part's planned detail beside how large the frames show it."
|
||||
order: 47
|
||||
sources: ["apps/scene/src/lib.rs", "apps/scene/src/light.rs", "apps/scene/src/stage.rs", "apps/scene/src/lod.rs", "runtime/lod-plan/src/lib.rs", "runtime/lod-plan/src/report.rs", "runtime/lod-plan/src/plan.rs", "systems/stage/src/lib.rs", "systems/stage/src/clearance.rs", "systems/contact/src/lint.rs", "systems/contact/src/zfight.rs"]
|
||||
sources: ["apps/scene/src/lib.rs", "apps/scene/src/light.rs", "apps/scene/src/stage.rs", "apps/scene/src/lod.rs", "runtime/lod-plan/src/lib.rs", "runtime/lod-plan/src/report.rs", "runtime/lod-plan/src/plan.rs", "systems/stage/src/lib.rs", "systems/stage/src/clearance.rs", "systems/contact/src/lint.rs", "systems/contact/src/zfight.rs", "apps/scene/src/faults.rs", "apps/scene/src/seed.rs", "systems/notice/src/lib.rs", "apps/scene/src/motion.rs", "systems/motionfaults/src/lib.rs", "runtime/endchecks/src/faults.rs", "apps/scene/src/ask.rs", "apps/scene/src/chars.rs"]
|
||||
---
|
||||
|
||||
`raea scene` steps a composition's frames and measures its 3D scene without rendering pictures. `lint` reports
|
||||
@@ -43,8 +43,41 @@ is an error, and `lod` exits 1. `raea render`, `raea scene stage` and `raea chec
|
||||
`raea make status` holds a job at it. A part hidden behind other meshes isn't counted as seen; RAEA_LOD_CHECK=0
|
||||
leaves the check out of a render.
|
||||
|
||||
`faults` judges the lint's findings as a viewer of the shot would see them. Every frame's camera (up to 48 over the
|
||||
shot) is asked whether each finding is in frame, facing it and not behind any part, measured against the scene's real
|
||||
triangles, and how many pixels its gap, depth or overlapping patch covers there. A small model turns that, the kind of
|
||||
fault and the words of the parts' names into the chance it reads as a fault. It lists likely faults (0.5 or more,
|
||||
FAULT) and seen ones under that (maybe), counts the findings no camera sees, and exits 1 on any fault. Each line ends
|
||||
with the finding's key. `--real KEY` and `--fine KEY` keep a verdict beside the project, and a finding the last run
|
||||
reported that is gone while both its parts remain is kept as fixed, so real. `raea scene faults train [FOLDER]` fits
|
||||
the model to every project's verdicts under FOLDER and keeps it in raea's models folder (notice/faults.json), which
|
||||
every run after uses. It reports how many verdicts it gets right fitted without each one's finding, and without each one's whole shot (a scene it hasn't seen). Until then it judges by a written prior (systems/notice/src/model.rs). See docs/notice.feature.
|
||||
|
||||
`faults --clip` holds a character's motion to what a body does, frame by frame (raea-sys-motionfaults): a knee that
|
||||
gives and comes back in a snap while its foot stands (a buckle), a standing foot that slides or glides along the
|
||||
ground (a skate), a joint past its anatomical range, a finger bent back, sideways or twisted past its range, a joint or
|
||||
the root jolting in one frame, and a finger, the thumb or the palm inside what the hand holds. A clip is JSON: the
|
||||
skeleton's `joints` (and `surface`, for the palm), `fps`, and `frames` of `{ root, turns }`, with `thing` (a ball, box,
|
||||
capsule or cylinder) and each frame's `thing: { at, turn }` for what the hand holds. `--clip` takes a file or a folder
|
||||
of them. The lines sit just above what 107 retargeted ACCAD captures do; `--seed N` plants N faults of each kind in
|
||||
every clip and says how many are caught.
|
||||
|
||||
`--motion` reads the characters from the composition itself, no clip written out, and also tests every finger bone
|
||||
against the scene's real triangles. Motion findings also pass a critic, a tiny logistic model fitted by `raea scene faults train` to every motion verdict (fixes, `--real`, `--fine`): what it learns of one joint carries to its neighbours, and a verdict on the finding's own key at its size outranks it. `--ask N` puts the N likeliest faults to a vision model, the fault ringed on its
|
||||
frame and described in the scene's own words, so it answers only whether it's meant; see docs/notice.feature NT12.
|
||||
|
||||
A render runs the judge too: at its end the first frame's floating, sunk, lifted and doubled-face findings are judged
|
||||
through the render's own cameras, and only the likely faults are said (RAEA_FAULTS_CHECK=0 leaves it out).
|
||||
|
||||
```sh
|
||||
raea scene lint room.tsx
|
||||
raea scene faults room.tsx --composition shot-in # the findings a viewer of shot-in would notice
|
||||
raea scene faults room.tsx --composition shot-tv --fine 'air:r106_map|' # the draped map is meant
|
||||
raea scene faults train ~/Documents/raea # fit the judge to every project's verdicts
|
||||
raea scene faults --clip walk.json # a clip's buckles, skates, bent fingers, jolts
|
||||
raea scene faults --clip clips/ --seed 2 # what it catches of faults planted in real motion
|
||||
raea scene faults take.tsx --composition take --motion # the composition's characters, hands against the scene
|
||||
raea scene faults room.tsx --composition shot-case --ask 3 # a vision model on whether the 3 likeliest are meant
|
||||
raea scene explain room.tsx --frame 90 --json
|
||||
raea scene light room.tsx --part hero
|
||||
raea scene light film.tsx --composition shot1,shot2,shot3 # the light across the cuts
|
||||
@@ -59,22 +92,34 @@ raea scene lod walk.tsx # every part's pl
|
||||
|
||||
```sh
|
||||
raea scene export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B] (the composition's 3D as data other tools build: DIR/scene.json, each part placed (y up, metres) with its shape, material or light, and the camera; meshes/ and models/ beside it)
|
||||
raea scene lint|explain|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--json] (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)
|
||||
raea scene lint|explain|faults|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--real KEY] [--fine KEY] [--seed N] [--ask N [--dry]] [--motion] [--json] | raea scene faults train [FOLDER] | raea scene faults --clip CLIP.json|FOLDER [--real KEY] [--fine KEY] [--fine-from N] [--fine-upto N] [--real-from N] [--real-upto N] [--by NAME] [--seed N] [--json] (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes up to 2 arguments besides its flags.
|
||||
Headless: it needs nothing running and opens no window. Takes up to 3 arguments besides its flags.
|
||||
|
||||
## Flags
|
||||
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--ask` | `N` | `faults`: render the frame each of the N likeliest faults shows largest on, ring it, and ask a vision model (`raea ask`) whether it's meant or a mistake, handing it the scene's own words for the fault. An answer 0.7 sure or more is kept as a verdict (by ask), which a person's verdict outranks. The ringed pictures stay in review/faults-ask/. |
|
||||
| `--at` | `A-B` | `export`: each part's placement and the camera's field of view on every frame from A to B, for keyframes in Blender or Godot. |
|
||||
| `--by` | `NAME` | With `--real`/`--fine` on motion findings: who made the call, kept with each example (`claude` for an agent that looked at the render); a person's by default. |
|
||||
| `--clearance` | `M` | `stage`: every run of frames where the camera is nearer a solid part than M metres (0.45 carried, 0.15 on a rig). |
|
||||
| `--clip` | `CLIP.json\|FOLDER` | `faults`: a character's motion (joints, fps, frames of root and turns) held to what a body does: buckles, skates, joints and fingers past their range, jolts, fingers through what the hand holds. A folder takes every .json in it. |
|
||||
| `--composition` | `ID` | Which composition to measure. `light` takes several, comma-separated, to compare the light across their cuts. |
|
||||
| `--dry` | – | With `faults --ask`: render and ring the pictures and say what would be asked, spending nothing. |
|
||||
| `--fine` | `KEY` | `faults`: keep a verdict that the finding with this key (printed after its line) is meant as it is, in the project's review/faults.labels.jsonl. With `--clip`: the motion finding's line for that check and joint (its key, such as skate:foot_l) rises to just above its size, for every run after (notice/motion.json in raea's models folder). May repeat. |
|
||||
| `--fine-from` | `N` | With `--fine` on motion findings: only findings of the key this size or bigger, in the finding's own units (degrees past the range for a finger or a joint limit). |
|
||||
| `--fine-upto` | `N` | With `--fine` on motion findings: only findings of the key this size or smaller (a pinky's small bends fine, its big one not). |
|
||||
| `--frame` | `N` | The frame to measure (0 by default; `light` also takes `last`). |
|
||||
| `--from` | `N` | With `stage` and `lod`: the first frame held to the checks (0 when left out). Every frame before it is still stepped, so a scene that builds over time is as it would render. |
|
||||
| `--json` | – | Print as JSON: `lint` its findings (check, level, the parts they are about, frames, says, measure, fix), `explain` every part with its support, gap and box, `lod` every part's row (planned, seen, largest, at, frames, closer), the plan's names no part goes by, and its findings. |
|
||||
| `--motion` | – | `faults`: the composition's characters (each `<Character>`'s joint parts, its skeleton.json beside its joint.glb) held to what a body does on every frame, as `--clip` does, and each finger bone tested against the scene's other parts: a thumb through a grip, or left off what the hand holds. Takes `--real`/`--fine KEY` as `--clip` does, and a finding the last run reported that's gone now (review/motion.last/) is kept as a real verdict: a fix teaches it. |
|
||||
| `--part` | `NAME` | With `light`: the part to meter, in place of the shot's subject. |
|
||||
| `--real` | `KEY` | `faults`: keep a verdict that the finding with this key is a real fault, in the project's review/faults.labels.jsonl. With `--clip`: that check's line for that joint falls to the finding's size. May repeat. |
|
||||
| `--real-from` | `N` | With `--real` on motion findings: only findings of the key this size or bigger. |
|
||||
| `--real-upto` | `N` | With `--real` on motion findings: only findings of the key this size or smaller. |
|
||||
| `--seed` | `N` | `faults`: plant N faults of known size in props that rest (sunk, lifted, in the air), lint again and say how many the judge calls faults among those plain to see, seen smaller, and hidden. With `--clip`: plant N of each motion fault (buckle, skate, jolt, limit, finger, through) in every clip and say how many are caught. Writes nothing. |
|
||||
| `--to` | `N` | With `stage` and `lod`: the last frame held to the checks (the composition's last when left out). |
|
||||
| `-o` | `DIR` | `export`: the folder scene.json is written to, with meshes/ and models/ beside it. |
|
||||
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
@spec
|
||||
Feature: Notice: a 3D scene's faults judged as a viewer of the shot would see them, by a small model that learns
|
||||
Shane, 2026-11-27: "we often have props that clip into things or walls ... everything always clips, and then a vision
|
||||
model just never picks it up because it doesn't know the context." He asked whether a model could read a scene from
|
||||
its own 3D (its parts, their names, their geometry) and say what's wrong semantically (a cup not on its surface, a
|
||||
prop through a wall, two faces in one plane flickering like camo), and learn more of it over time, small and fast
|
||||
enough to run everywhere (Core ML). Motion too: knees buckling in a walk, fingers twisting round a grip, a thumb
|
||||
through a gun's handle, which no still shows.
|
||||
|
||||
What raea already had. The geometry checks were further along than the clipping suggests: `raea scene lint`
|
||||
(raea-sys-contact) finds floating, sunk, in-the-air and clipping parts from their real triangles, and z-fighting
|
||||
(core/zfight, MK8); the render's own clip check reports overlaps where the camera sees them; the motion lint
|
||||
(sdk/character lint.ts) finds jerks and knee buckles against the motion library's own range.
|
||||
|
||||
Why clipping still got through, measured 11-27 on room 106 of the Halcyon (approved that day): `raea scene lint`
|
||||
said 32 errors and 11 warnings. Most were a room's shell meeting itself where no camera can look (wall slabs into
|
||||
the ceiling slab, the carpet's edge under the walls), beside real ones (socks 3.4 mm over the carpet, a sun hat 4 mm
|
||||
over the table). A list where most errors don't matter gets skimmed, and the clip that shows goes with the rest.
|
||||
Every exception so far was a hand-set constant (SEATED, CARCASS, ENCLOSED, INSIDE ...), one per scene's new noise.
|
||||
So what was missing was judgment, not detection: is it seen, is it large enough on screen to read, and is it meant.
|
||||
|
||||
What others do (11-27 survey). No published system finds clipping from pixels: Holodeck, LayoutVLM, Scenethesis,
|
||||
PAT3D and phi-Scene all measure collisions, penetration depth and floating distance from geometry, and use a
|
||||
vision-language model only for intent, on marked-up renders. VLMs remain weak at physical plausibility, and a CVPR
|
||||
2026 study (the Motion Turing Test) found multimodal LLMs inadequate at judging motion. For motion the
|
||||
strongest result is a small learned critic: MotionCritic (ICLR 2025, a 3-layer DSTformer on SMPL joints) agrees with
|
||||
people's preferences 85% of the time where jerk, foot contact and penetration heuristics get 54-72%.
|
||||
|
||||
The model this file sets:
|
||||
1. Geometry finds every candidate (the lint, unchanged: make's gates read it as they did).
|
||||
2. Sight judges each one per shot: every frame's camera, the scene's real triangles in a BVH, whether the fault's
|
||||
spots are in frame, facing the camera and not behind any part, and how many pixels its gap, depth or patch
|
||||
covers (systems/notice sight.rs).
|
||||
3. A small model says how likely each is to read as a fault: logistic regression over 16 features (kind, seen,
|
||||
share of frames, log pixels, log millimetres, structural, soft, small) plus learned weights for the words of
|
||||
the parts' names keyed by kind ("air:map"), starting from a written prior (model.rs). It runs in microseconds;
|
||||
Core ML isn't needed for it. A model that needs one (the motion critic, NT11) runs on MLX or Core ML.
|
||||
4. It learns from verdicts kept beside each project: findings marked real or fine, and findings that went away
|
||||
because someone moved a part (labels.rs). `raea scene faults train` fits it to every project's verdicts.
|
||||
|
||||
Rule: Judging the lint's findings by sight (built: systems/notice, apps/scene faults.rs)
|
||||
|
||||
@done
|
||||
Scenario: NT1. Every frame's camera asked
|
||||
Given `raea scene faults EDIT.tsx [--composition ID] [--frame N]`
|
||||
Then the composition is stepped without drawing, the lint runs on frame N, and each fault it finds is judged
|
||||
over up to 48 frames' cameras spread over the shot
|
||||
And a finding's spots come from the lint: a z-fight's shared patches (core/zfight `spots`, each with the way
|
||||
its faces look and its area, the largest 32), a clip's seam, a gap's foot all round the part's base at the
|
||||
surface's height (drawn in 15% from its box's corners) and its nearest point
|
||||
And a spot shows on a frame when it is inside the frame, in front, nearer than the fog's far edge, facing the
|
||||
camera (a z-fight's faces) and no triangle of any part lies between it and the eye (3 mm off it first)
|
||||
|
||||
@done
|
||||
Scenario: NT2. Size on screen, not in the world
|
||||
Then a gap's or a depth's metres are turned into pixels at the depth it shows (focal x height / 2 / depth), and
|
||||
a z-fight's patches into the square root of the pixels they cover, summed over the spots that show
|
||||
And a 4 mm gap at 1.2 m is a fault and the same gap at 5 m is less sure (systems/notice tests.rs)
|
||||
|
||||
@done
|
||||
Scenario: NT3. The prior, written down
|
||||
Then before any verdict, a finding no camera sees scores 0.05, one seen on every frame at 3 px about 0.9;
|
||||
seated parts, a room's shell meeting itself, doubled faces inside one model and soft things weigh less, and
|
||||
a thing with weight in the air weighs more at any size
|
||||
And 0.5 or more is a fault: listed as FAULT, and `faults` exits 1 on any, as `lint` does on its errors
|
||||
And seen findings under 0.5 are listed as "maybe"; findings no camera sees are counted, not listed
|
||||
|
||||
Rule: Learning from verdicts (built: systems/notice labels.rs, model.rs)
|
||||
|
||||
@done
|
||||
Scenario: NT4. Marked real or fine
|
||||
Given a finding's key, printed after its line (`floats:r106_socks|r106_carpet`)
|
||||
Then `--real KEY` or `--fine KEY` (each may repeat) keeps a verdict in the project's review/faults.labels.jsonl
|
||||
with the finding's features and words as they were, so training never re-runs a scene
|
||||
|
||||
@done
|
||||
Scenario: NT5. A fix is a verdict
|
||||
Then each run keeps its findings in review/faults.last.json per shot, and a finding the last run said that is
|
||||
gone while both its parts are still in the scene is kept as real (by "fixed"): someone moved a part for it
|
||||
|
||||
@done
|
||||
Scenario: NT6. Training
|
||||
Given `raea scene faults train [FOLDER]`
|
||||
Then every review/faults.labels.jsonl under FOLDER (4 folders deep) is read, the newest verdict on each finding
|
||||
winning, and the model fitted: each weight held toward its prior and each word's toward nothing, so a few
|
||||
verdicts nudge it and many move it; it says how many verdicts the prior and the fitted judge agree with
|
||||
And the model is kept at raea's models folder notice/faults.json, which every run after loads
|
||||
(RAEA_NOTICE_MODEL names another file, for a trial fit kept apart)
|
||||
And three maps in the air marked fine and three mugs marked real teach it that an office's map in the air is
|
||||
fine and a mug in the air is not (tests.rs)
|
||||
|
||||
Scenario: NT7. Measured on room 106 and the office (2026-11-27)
|
||||
Then see "Results" below, filled in from the runs
|
||||
|
||||
@done
|
||||
Scenario: NT8. Faults of known size
|
||||
Given `raea scene faults EDIT.tsx --seed N`
|
||||
Then N props that rest as they should are each moved once (sunk 5-40 mm, lifted 2-30 mm, or lifted 8-30 cm into
|
||||
the air), the lint run again and the planted finding judged; it says how many the lint found, and how many the
|
||||
judge calls faults among those plain to see (2 px or more), those seen smaller, and those no camera sees
|
||||
And nothing is written: a planted fault's truth is its size, which the judge already reads
|
||||
And faults are planted only in props a camera of the shot sees (the top of the prop's box in view on some frame):
|
||||
on shot-window no resting prop is in view, so it plants none and says so
|
||||
|
||||
@done
|
||||
Scenario: NT8a. Lifted against a wall, found by what it is
|
||||
Given NT8 on shot-in, where `r106_lamp_b` lifted 7 mm to 27 cm read as mounted on the wall it touches (6 of 6
|
||||
lifts missed: the lint's mount test can't tell a lamp that stands from a sconce that hangs)
|
||||
Then the lint gives a mounted part's gap to what's under it (`gap`, `under`), and a mounted part more than 3 mm over
|
||||
it is a candidate whose size counts for nothing on screen (a picture hangs a metre up)
|
||||
And two features weigh it: mounted (prior -1.5) and mounted while named as a thing that stands (lamp, phone, cup,
|
||||
mug, glass, bottle, book, vase, plant, chair, table, clock, box, bag, case: prior +4.0)
|
||||
And a lamp lifted 27 cm against the wall scores 0.88 and a picture 1.2 m up scores 0.12 (tests.rs); verdicts move
|
||||
the words further ("mounted:sconce" fine)
|
||||
|
||||
Scenario: NT9. A render judges the lint's other faults at its end (@done 2026-11-27)
|
||||
Given a render's end checks (runtime/endchecks), which already follow parts clipping each other through every
|
||||
frame with the clipping check's own sight test
|
||||
Then the first frame's parts are linted but for clips (raea_sys_contact::lint_but_clips) and each floating, sunk,
|
||||
lifted or doubled-face finding judged through the render's own cameras (up to 48), and only the likely faults
|
||||
said, as warnings, with the chance and how large they show
|
||||
And RAEA_FAULTS_CHECK=0 leaves it out
|
||||
Measured: halcyon shot-bed, a 640x360 still of frame 30: the same one fault `raea scene faults` says there
|
||||
(r106_small_kit's doubled faces, 0.93, 6.3 px). It first added 30.6 s, nearly all the lint's older `touching`
|
||||
test (every axis-aligned ray against every nearby triangle); its rays now skip what their line can't meet (the
|
||||
part's box, then each side's candidate triangles once), the lint's output the same on the same scene (60 of 60
|
||||
findings, old binary against new), and the render's judged check takes 8.5 s, the lint 7.7 of it
|
||||
|
||||
Scenario: NT10. Faults that only show in motion (@done 2026-11-27, raea-sys-motionfaults)
|
||||
Given a clip: the skeleton's joints, fps, and each frame's root and turns (and what the hand holds, if anything)
|
||||
When `raea scene faults --clip CLIP.json|FOLDER` holds every frame to what a body does
|
||||
Then it says, each once per stretch of frames with its worst frame and size:
|
||||
| check | what |
|
||||
| buckle | a standing knee that gives (folds or snaps straight) 12° or more and back in 2 frames |
|
||||
| skate | a standing foot drifting 8 cm from where it stood down, or gliding along the ground |
|
||||
| limit | a joint 10° or more past raea-sys-body's anatomical range |
|
||||
| finger | a finger joint bent back, sideways or twisted 8° or more past its range (fingers.rs) |
|
||||
| jolt | a joint's turn changing 25°/frame² or more (at 30 fps), the root's 80 mm/frame² |
|
||||
| through | a finger, the thumb or the palm more than 4 mm inside what the hand holds |
|
||||
And the lines sit just above what clean capture does: 107 ACCAD takes retargeted onto the flannel body (12,472
|
||||
frames of walks, runs, turns, crouches, lifts), whose sharpest standing knee give is 9.4°, furthest standing
|
||||
foot drift 10.5 cm, worst jolt 34°/frame² but for a retarget's 168° forearm flip
|
||||
And `--seed N` plants N of each kind in every clip as an animation tool gets it wrong (plant.rs) and counts what's
|
||||
caught (results below)
|
||||
And it learns: each finding's key is its check and joint role (skate:foot_l); `--fine KEY` raises that key's
|
||||
line to just above the finding's size and `--real KEY` lowers it, kept in raea's models folder
|
||||
(notice/motion.json; verdicts.rs)
|
||||
And `--motion` reads them from a composition itself (apps/scene/src/chars.rs): each <Character>'s joint parts
|
||||
give every frame's pose exactly (rest frames are the world's), and each finger bone is tested as a segment
|
||||
against the scene's other parts' triangles
|
||||
Measured: projects/sheet3d compositions/take.tsx, teal over 1,470 frames: 268 findings, most fingers "bent back".
|
||||
At frame 1391 (the hand model driven to 2.5 on its first axis) the render shows the right hand's fingers kinked
|
||||
and knotted: real. A pinky 20-25° back through much of the take is unconfirmed at the shot's distance, and
|
||||
values hovering at a line split one stretch into many; verdicts (--fine finger:pinky_02_r) are for that
|
||||
And a grip check: while two or more fingertips rest on a surface, a finger or thumb tip 3 cm or more off any
|
||||
surface hasn't closed on what the hand holds
|
||||
Measured on a real fault: projects/gambit fp-lab-ladder, fixed in 68a505a ("the thumb not wrapping round what the
|
||||
hand holds"). Before the fix, on the grab posts (frames 155-273), thumb and index grip findings on both hands at
|
||||
51-54 and 42-46 mm (the commit measured 3.7 and 4.1 cm); after it, none there (thumb 22 mm at most, closed over
|
||||
the fingers). Renders agree: a loose claw beside the post, then fingers round it. The rung stretches (25-155),
|
||||
untouched by the fix, are flagged in both: from across the palm (fp-lab-ladder-wrap-r, frames 100 and 140) the
|
||||
thumb points straight up past the rung, not round it, the fault 68a505a fixed on the posts, so real; the index
|
||||
looks hooked over the rung where the check measures 41 mm, so it stays unconfirmed. Through findings came up only once every part counted (a mesh's place is often
|
||||
in its vertices, its transform at the origin)
|
||||
The grip rule is raea-sys-motionfaults grip::open and the distance raea-sys-notice Scene::reach, both tested
|
||||
(the ladder's frame 200 before and after the fix among them)
|
||||
And a fix teaches it: each `--motion` run keeps its findings (review/motion.last/<shot>.json), and one the last
|
||||
run reported that's gone now, the character and its frames the same, is kept as a real verdict at its size
|
||||
(raea-sys-motionfaults verdicts::fixed, tested). Run before and at 68a505a, the ladder lab's fix kept 29: the
|
||||
thumb and index left off the posts (43-54 mm), fingers through them, the index knuckle bent 35°; a rerun keeps 0
|
||||
And the pinky, looked at close (a scratch copy of take.tsx with its hand camera on pinky_02_r, frames 448 and
|
||||
1077): bent back 20-25° it reads relaxed, round the cup, so finger:pinky_02_l/r fine at 15 past the range; frame
|
||||
1391's 34°, in the hand that knots, still stands
|
||||
Still open: the skin against what the hand holds, not bone segments; stretches that hover at a line merged
|
||||
|
||||
Scenario: NT12. A vision model given the scene's context (@done 2026-11-27, apps/scene/src/ask.rs)
|
||||
When `raea scene faults EDIT.tsx --composition ID --ask N`
|
||||
Then each of the N likeliest faults is rendered on the frame it shows largest on, ringed (its spots' places on
|
||||
that camera, raea-sys-notice's sight), and `raea ask` (clef-omni, about $0.0001 a question) asked whether it's
|
||||
meant or a mistake, told the part, what it's against and what the geometry measured
|
||||
And an answer 0.7 sure or more is kept as a verdict, `by: "ask"`; a person's verdict on the same finding outranks
|
||||
it whatever their order (labels.rs, tested)
|
||||
Measured on room 106 (shot-window, -tv, -case, -in; 16 asked): sure and plausible on doubled faces (0.92-0.95),
|
||||
the floor clothes through each other (0.74-0.77), the floating sun hat (0.72), the hanging rail (0.88); unsure
|
||||
(0.52-0.68, not kept) on chair and table feet in carpet pile and a leg through a strap; and sure the draped map
|
||||
is a mistake (0.89), most likely led by the lint's own words ("in the air, touching nothing"), where a person's
|
||||
--fine is what settles it. Asked of the hat's clip with no context it said meant (0.59), with it mistake (0.72):
|
||||
the context moves the answer, for better where the geometry is right
|
||||
|
||||
Scenario: NT11. A motion critic of our own (@done 2026-11-27, raea-sys-motionfaults critic.rs)
|
||||
Given every motion verdict as an example: a fix that took a finding away (`fixed`), a look at the render
|
||||
(`--real`/`--fine`, `--by claude`), never a planted fault (it would learn the rules back)
|
||||
When `raea scene faults train` fits it: a logistic model over a finding's size against its check's scale and the
|
||||
words of what it is (its check, its joint's family, its key), the frames it lasts held at its prior for now
|
||||
Then a motion finding is said when a verdict called its key real at its size, or the verdicts' lines let it
|
||||
stand and the critic scores it 0.5 or more
|
||||
Measured (11-27): 50 examples on 22 keys, 37 real (29 from the ladder lab's fix, 9 rung thumbs and the knotted
|
||||
hand looked at) and 13 fine (the pinky's middle joint bent back 20-25°, both hands): the prior agreed with 37,
|
||||
the fitted critic with 49, and with 50 fitted each time without the key asked about. What it learns carries:
|
||||
the pinky's family word holds back small bends on joints never judged (tested). And it over-learns: the fine
|
||||
pinky bends pulled the 34° pinky in frame 1391's knotted hand under 0.5, so a verdict on the finding's own
|
||||
key at its size outranks it (tested); the frames weight had learned that long findings were fine only because
|
||||
the fine bends ran long, so it waits for far more verdicts
|
||||
|
||||
Results (the first verdicts both ways, 2026-11-27, each from a look at its ringed render): the draped map, chair
|
||||
and table feet 12 mm into the carpet, a chair leg over a bag strap, and the AC, curtain rod and sheers mounted on
|
||||
their walls are fine; the rail, cut off at its frame's edge, has none. With 9 vision-model rows and 2 fixes: 18,
|
||||
10 real and 8 fine, on 15 findings; the prior agreed with 13, the fitted judge with 17, and with 15 fitted each
|
||||
time without the finding asked about (held out; `train` reports it).
|
||||
The first fit, on 15 verdicts all real, had raised every weight toward "fault" (one-way verdicts carry no line), so
|
||||
verdicts all one way now teach only the words (model.rs, tested) and one already scored 0.9 its way stops teaching.
|
||||
The vision model called the draped map a mistake (0.89), led by the lint's "in the air, touching nothing"
|
||||
Then two more scenes (each call from a look at its render): halcyon's office (officelab office-counter: the desk
|
||||
kit's doubled faces real, two brochures in their rack fine) and five-to-a-corner's voxel kit (its 240 m ground plane
|
||||
"in the air" over a hidden plinth, fine). 22 verdicts on 18 findings from 2 projects, 11 real and 11 fine: the prior
|
||||
agreed with 16, the fitted judge with 21, and with 19 fitted each time without the finding asked about.
|
||||
Two scenes it couldn't judge: the motel's whole exterior block (motel.tsx block-wide) made no progress in 8 minutes,
|
||||
and a plain render of that view ran past 8 minutes too: the time is the block's own shapes being built
|
||||
(raea_core_shape, sampled), then the lint's rest test, not the judge; anchor-tenant's tvroom throws before its first frame
|
||||
Then six of gambit's interiors (drugstore, baker, grocer, butcher, bank, department store), each likely fault ringed
|
||||
on its render (`--ask N --dry`) and called from a look: 41 verdicts, 3 real (the grocer's till and coffee mill 30 mm
|
||||
over the counter, which show a dark slot under them; the drugstore's scale jammed into the till) and 38 fine (tills
|
||||
and cake cases 10 mm up, which read as seated at 3.4 m; a prop's own parts pressed into each other, like a barrel's
|
||||
lid, a sign's plate, a desk's top or meat on its tray; hanging lamps "in the air" on their rods; a dress form on its
|
||||
pole). The judge as it stood (22 verdicts, none from gambit) had called nearly all 41 faults, about 2 right: what
|
||||
it had learned from a motel didn't carry to a Berlin shop. Refitted on all 63 (14 real, 49 fine, 3 projects, 13
|
||||
shots), with each gambit shop left out and then judged: 34 of 41 right; every shot held out in turn, as `train`
|
||||
now reports it: 51 of 63 (the prior: 18). What it still gets wrong: floats by size (10 mm fine, 30 mm real, a 4 mm hat real;
|
||||
seven verdicts don't fix a line, and the word "till" learned "fine" from the tills' shared faces), and the
|
||||
drugstore's scale, whose seam is truly hidden (it enters the till's far face) though the jam shows. Tried in the
|
||||
replay and not kept, none beating the fit as it stands by more than a verdict: the gap alone for floats, sunk and
|
||||
clips; "a prop's own parts" from the words of both names; naming prefixes ("prop") dropped from the words.
|
||||
Motion on gambit's fp labs (takedown, sneak, crowd street, 11-27): 82-118 findings a shot. The four crowd walkers
|
||||
read cleanly (a wrist 14° past, knees 11-13°). The fp character's shins read 136-165° past their range, always
|
||||
as flex about 74° with a twist near 180°, alternating legs in step with its crouch walk, and each time its foot
|
||||
reads the opposite roll: a roll the solve puts on the shin and takes back at the foot. Rendered side and front,
|
||||
its knees bend forward and nothing shows. Not recorded as verdicts: a line or a critic example on limit:calf at
|
||||
that size would hide a knee broken backward on every other character. Fixed (legs.rs settled): a roll of 15° or
|
||||
more about a joint's own bone moves to its child when the two are then less past their ranges together; it moves
|
||||
no joint's place, and a roll nothing takes back stays (tested both ways). Only where the joint's other children
|
||||
sit on the bone's own line (a shin's twist joints): the first cut moved a hand's roll onto one finger, which moves
|
||||
the others and has no limits to show it, hid 77 of the crowd's wrists, and the fix-to-verdict path then kept every
|
||||
finding the change hid (44 shins and feet, 77 wrists) as a real fix. Those rows are removed, and a fix is now only
|
||||
read between runs of the same checks (motionfaults CHECKS, kept in motion.last). Limit findings: takedown 34 ->
|
||||
14, sneak 21 -> 6, the crowd's 79 unchanged, every hand finding kept; run twice, 0 fixes either time. The crowd's
|
||||
wrists 14° past (a 29° twist on 120 px walkers) are fine up to 15 (by claude): the critic's first fine examples
|
||||
off the pinky, 107 on 24 keys, 106 right with each key held out; the takedown's 126-138° wrists still stand. What's left can't be judged from these cameras:
|
||||
the takedown's knife wrist hidden behind the collar, the sentry's knees under his greatcoat as he falls.
|
||||
|
||||
Results (NT10, 2026-11-27: 107 ACCAD takes retargeted onto projects/sheet3d's flannel body, 12,472 frames):
|
||||
- Clean capture: 84 of 107 takes have no finding. Of the 23 flagged, the limits and jolts are mostly the retarget's
|
||||
own errors a viewer would see (a forearm twisted 168° in a frame, toes bent 50° back, a hand bent 74° sideways);
|
||||
the skates are feet dragged in crouches and a 6 s squat's slow drift, and 6 glides where an actor slides a foot
|
||||
(getting up from lying, a turn): arguable, the place verdicts would settle.
|
||||
- Planted, 2 of each kind in every take (1,051): through 214/214 (from 6 mm in), finger 214/214 (from 35°), jolt
|
||||
214/214 (from 20°), skate 103/103 (from 10 cm), limit 205/214 (every one past the 10° line; the 9 missed were
|
||||
8-10° past), buckle 89/92 (from 15°; 3 missed in long squatting stances, 18-22°).
|
||||
- First pass before the lines were set from capture: 105 of 107 takes flagged. The causes: a quaternion's sign
|
||||
flip read as a 360° jolt, stance from height alone (a running foot near the ground counted as standing), and any
|
||||
second knee bend in a stance called a buckle (a walk bends again before toe-off). Each is fixed and tested.
|
||||
|
||||
Results (NT7, the runs of 2026-11-27 on projects/halcyon-motel compositions/interiors.tsx, prior only):
|
||||
- Lint errors per room shot 30-31 (every shot alike); likely faults per shot after judging: in 5, bed 1, stand 0,
|
||||
case 3, tv 1, window 7, vanity 0, bath 0; office 2, bell 0, keys 0, clerk 2 (the office lints with 0 errors: its
|
||||
2 are visible doubled faces inside the counter and the desk kit, which the lint calls warnings).
|
||||
- Room 106: 60 distinct findings (31 of them mounted parts with a gap under them, none over 0.12) -> 12 judged a
|
||||
fault in some shot. Seen and plausibly real: floor clothes through each other (46 px), the vanity's and the
|
||||
suitcase's doubled faces, a chair leg 22 mm through a bag strap, a sun hat 4 mm over the table (3 px). Seen and
|
||||
likely fine, for verdicts to teach: the map draped over the dresser ("air"), chair and table feet 12 mm into the
|
||||
carpet ("seated").
|
||||
- NT8 on shot-in, 16 planted: the lint found 16 (after NT8a; 10 before it); judged faults 9/9 plain to see,
|
||||
6/6 seen under 2 px, 0/1 hidden (a 7 mm lamp lift whose spots sit inside its own base: 0.38).
|
||||
- The loop on live data: another session's edit took the magazine's 12 mm float away between runs; it was kept as
|
||||
fixed (real) in the two shots that show it, and train moved "floats:magazine" and the bed's words +0.05.
|
||||
The first rule also kept it for shots where it was hidden and for gaps that became mounts; both now ruled out.
|
||||
- Cost: a judged shot takes about 45 s on the room (stepping the shot and the lint; the judge itself is
|
||||
milliseconds); --seed relints once per planted fault (about 30 s each).
|
||||
@@ -28,8 +28,12 @@ mod tests;
|
||||
|
||||
pub type R<T> = Result<T, String>;
|
||||
|
||||
/// A flag's value (`--out x`): the first of `flags`, each value of a flag given more than once (`--real a --real b`).
|
||||
pub fn flag(args: &[String], name: &str) -> Option<String> {
|
||||
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned()
|
||||
flags(args, name).into_iter().next()
|
||||
}
|
||||
pub fn flags(args: &[String], name: &str) -> Vec<String> {
|
||||
args.iter().zip(args.iter().skip(1)).filter(|(k, _)| *k == name).map(|(_, v)| v.clone()).collect()
|
||||
}
|
||||
|
||||
/// The space's brand kit for a composition `w` px wide: the nearest brand/brand.css at or above the edit's folder (up
|
||||
|
||||
@@ -11,6 +11,8 @@ raea-core-scene = { path = "../../core/scene" }
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
raea-sys-contact = { path = "../../systems/contact" }
|
||||
raea-sys-stage = { path = "../../systems/stage" }
|
||||
# the lint's other faults judged as the render shows them (docs/notice.feature NT9)
|
||||
raea-sys-notice = { path = "../../systems/notice" }
|
||||
# each part held to its planned detail (MK21)
|
||||
raea-runtime-lod-plan = { path = "../lod-plan" }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,75 @@
|
||||
//! The scene lint's other faults judged at a render's end (docs/notice.feature NT9; RAEA_FAULTS_CHECK=0 skips it):
|
||||
//! parts floating, sunk, in the air, a prop lifted against a wall, faces fighting for the same depth. The first frame's
|
||||
//! parts are linted (raea-sys-contact) and each finding judged by raea-sys-notice as a viewer of this render would see
|
||||
//! it: through every frame's camera (up to CAMERAS, evenly over the render), by its size on screen, by the learned
|
||||
//! judge. Only the likely faults are said. Parts clipping each other are the clipping check's, which already follows
|
||||
//! them through every frame, so they're left out here.
|
||||
//!
|
||||
//! A render keeps the first two frames' parts and each frame's camera (one item a frame), nothing more.
|
||||
|
||||
use raea_core_facts::{Finding, Level};
|
||||
use raea_core_scene::Item;
|
||||
|
||||
/// The most frames whose cameras are asked.
|
||||
const CAMERAS: usize = 48;
|
||||
|
||||
pub struct Faults {
|
||||
w: u32,
|
||||
h: u32,
|
||||
first: Option<(i64, Vec<Item>)>,
|
||||
second: Option<Vec<Item>>,
|
||||
cams: Vec<Item>,
|
||||
}
|
||||
|
||||
impl Faults {
|
||||
pub fn new(w: u32, h: u32) -> Faults {
|
||||
Faults { w, h, first: None, second: None, cams: Vec::new() }
|
||||
}
|
||||
|
||||
pub fn push(&mut self, frame: i64, its: &[Item]) {
|
||||
if its.is_empty() {
|
||||
return;
|
||||
}
|
||||
match (&self.first, &self.second) {
|
||||
(None, _) => self.first = Some((frame, its.to_vec())),
|
||||
(Some(_), None) => self.second = Some(its.to_vec()),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(c) = its.iter().find(|i| i.kind == "camera") {
|
||||
self.cams.push(c.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn told(self, by: &str) -> Vec<Finding> {
|
||||
let Some((frame, first)) = self.first else { return Vec::new() };
|
||||
let t = std::time::Instant::now();
|
||||
let next = self.second.as_deref().unwrap_or(&first);
|
||||
let (found, _) = raea_sys_contact::lint_with(&first, next, false);
|
||||
let linted = t.elapsed();
|
||||
let step = self.cams.len().div_ceil(CAMERAS).max(1);
|
||||
let mut views = vec![first.clone()];
|
||||
views.extend(self.cams.iter().step_by(step).map(|c| vec![c.clone()]));
|
||||
let model = raea_sys_notice::Model::load();
|
||||
let judged = raea_sys_notice::judge(&found, &views, self.w, self.h, &model);
|
||||
let out: Vec<Finding> = judged
|
||||
.iter()
|
||||
.filter(|j| j.p >= raea_sys_notice::FAULT && j.fault.check != "clips")
|
||||
.map(|j| {
|
||||
let f = &j.fault;
|
||||
let mut x = Finding::new(&f.check, Level::Warn, format!("{} (likely a fault, {:.2}: seen on {} of {} frames asked, {:.1} px)", f.says, j.p, j.seen.shown, j.seen.frames, j.seen.px), by).frames(frame, frame + 1).about(f.part.clone(), None).measure("likely", f64::from(j.p), "", Some(f64::from(raea_sys_notice::FAULT)));
|
||||
if let Some(into) = &f.into {
|
||||
x = x.about(into.clone(), None);
|
||||
}
|
||||
x
|
||||
})
|
||||
.collect();
|
||||
for f in &out {
|
||||
eprintln!("raea: {}", f.line());
|
||||
}
|
||||
raea_core_facts::finding::said(&out);
|
||||
if std::env::var("RAEA_TIMES").is_ok() {
|
||||
eprintln!("raea times: the judged faults {:.0} ms, the lint {:.0} of it ({} findings, {} likely faults)", t.elapsed().as_secs_f64() * 1e3, linted.as_secs_f64() * 1e3, judged.len(), out.len());
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,10 @@
|
||||
//! the manifest's word on the parts (raea_sys_stage::Mounts) keep of them, and let go, so a long render never holds its
|
||||
//! frames' parts for its checks. raea-runtime-export hands each frame in as it's drawn, and a still's at its end.
|
||||
//! With them, each part held to its planned detail (raea-runtime-lod-plan; RAEA_LOD_CHECK=0 skips it): its own `lod`, else
|
||||
//! its name's on the plan above the composition (its plan.rs: `lod` on the brief's make objects, MK22).
|
||||
//! its name's on the plan above the composition (its plan.rs: `lod` on the brief's make objects, MK22). And the scene
|
||||
//! lint's other faults judged as this render shows them (faults.rs, raea-sys-notice; RAEA_FAULTS_CHECK=0 skips it).
|
||||
|
||||
mod faults;
|
||||
|
||||
use raea_core_facts::Finding;
|
||||
use raea_core_scene::Item;
|
||||
@@ -13,6 +16,7 @@ pub struct EndChecks {
|
||||
clip: Option<raea_sys_contact::Clipping>,
|
||||
stage: Option<raea_sys_stage::Staging>,
|
||||
lod: Option<raea_runtime_lod_plan::Lods>,
|
||||
faults: Option<faults::Faults>,
|
||||
mounts: raea_sys_stage::Mounts,
|
||||
any: bool,
|
||||
parts: usize,
|
||||
@@ -23,7 +27,8 @@ impl EndChecks {
|
||||
let on = |k: &str| std::env::var(k).as_deref() != Ok("0");
|
||||
let (clip, stage) = (on("RAEA_CLIP_CHECK").then(|| raea_sys_contact::Clipping::new(w, h, fps)), on("RAEA_STAGE_CHECK").then(|| raea_sys_stage::Staging::new(w, h, fps)));
|
||||
let lod = on("RAEA_LOD_CHECK").then(|| raea_runtime_lod_plan::Lods::new(w, h, fps, raea_runtime_lod_plan::plan::here(), false));
|
||||
EndChecks { clip, stage, lod, mounts: raea_sys_stage::Mounts::new(w, h), any: false, parts: 0 }
|
||||
let faults = on("RAEA_FAULTS_CHECK").then(|| faults::Faults::new(w, h));
|
||||
EndChecks { clip, stage, lod, faults, mounts: raea_sys_stage::Mounts::new(w, h), any: false, parts: 0 }
|
||||
}
|
||||
|
||||
/// The next frame (its number, `frame`): its parts, and its page where the manifest has it.
|
||||
@@ -38,6 +43,9 @@ impl EndChecks {
|
||||
if let Some(l) = &mut self.lod {
|
||||
l.push(frame, its);
|
||||
}
|
||||
if let Some(f) = &mut self.faults {
|
||||
f.push(frame, its);
|
||||
}
|
||||
self.mounts.push(frame, its);
|
||||
}
|
||||
|
||||
@@ -59,6 +67,9 @@ impl EndChecks {
|
||||
closer.iter().for_each(|f| eprintln!("raea: {}", f.line()));
|
||||
raea_core_facts::finding::said(&closer);
|
||||
found.extend(closer);
|
||||
// the lint's other faults (floating, sunk, lifted, fighting faces), judged as this render shows them
|
||||
found.extend(self.faults.map_or_else(Vec::new, |f| f.told(raea_sys_stage::BY)));
|
||||
mark("end checks: judged faults");
|
||||
// the clipping check's solids, kept for the process, aren't needed again by a render
|
||||
raea_sys_contact::forget();
|
||||
mark("end checks: done, their solids let go");
|
||||
|
||||
@@ -7,6 +7,7 @@ use serde_json::{Value, json};
|
||||
use crate::fit::{Mark, fit};
|
||||
use crate::prior::{coefficients, oddness, shape};
|
||||
use crate::rig::{Pose, Side, Skeleton};
|
||||
use crate::shape::Solid;
|
||||
use crate::soma::from_soma;
|
||||
use crate::turns::{from_turns, with_twists};
|
||||
|
||||
@@ -14,6 +15,21 @@ pub fn num(v: &Value, what: &str) -> Result<f32, String> {
|
||||
v.as_f64().map(|n| n as f32).ok_or_else(|| format!("character.take: {what} isn't a number"))
|
||||
}
|
||||
|
||||
/// A held thing's shape: a ball's radius, a box's half sizes, or a capsule's or cylinder's [half length, radius].
|
||||
pub fn solid(v: &Value) -> Result<Solid, String> {
|
||||
if !v["ball"].is_null() {
|
||||
return Ok(Solid::Ball { r: num(&v["ball"], "thing.ball")? });
|
||||
}
|
||||
if !v["box"].is_null() {
|
||||
return Ok(Solid::Box { half: vec3(&v["box"], "thing.box")? });
|
||||
}
|
||||
// a capsule or a cylinder: half its length along its own y, then its radius
|
||||
let rod = ["capsule", "cylinder"].into_iter().find(|k| !v[*k].is_null()).ok_or("character.take: the thing needs a shape: ball, box, capsule or cylinder")?;
|
||||
let a = v[rod].as_array().filter(|a| a.len() == 2).ok_or_else(|| format!("character.take: thing.{rod} isn't [half its length, radius]"))?;
|
||||
let (half, r) = (num(&a[0], rod)?, num(&a[1], rod)?);
|
||||
Ok(if rod == "capsule" { Solid::Capsule { half, r } } else { Solid::Cylinder { half, r } })
|
||||
}
|
||||
|
||||
pub fn vec3(v: &Value, what: &str) -> Result<Vec3, String> {
|
||||
let a = v.as_array().filter(|a| a.len() == 3).ok_or_else(|| format!("character.take: {what} isn't [x, y, z]"))?;
|
||||
Ok(Vec3::new(num(&a[0], what)?, num(&a[1], what)?, num(&a[2], what)?))
|
||||
|
||||
@@ -247,6 +247,13 @@ pub fn clamp_turn(skel: &Skeleton, i: usize, q: Quat) -> (Quat, f32) {
|
||||
(turn, q.angle_between(turn).to_degrees())
|
||||
}
|
||||
|
||||
/// How far one joint's turn is outside its limit, degrees (0 inside it, or for a joint with no limits).
|
||||
pub fn over(skel: &Skeleton, i: usize, q: Quat) -> f32 {
|
||||
let Some(ax) = axes(skel, i) else { return 0.0 };
|
||||
let (a, c) = (read(&ax, q), clamped(&ax, read(&ax, q)));
|
||||
(a.flex - c.flex).hypot(a.side - c.side).max((a.twist - c.twist).abs())
|
||||
}
|
||||
|
||||
/// Every joint of a pose outside its limit by more than `tolerance` degrees: its index and by how much, worst first.
|
||||
pub fn violations(skel: &Skeleton, p: &Pose, tolerance: f32) -> Vec<(usize, f32)> {
|
||||
let mut out: Vec<(usize, f32)> = (0..skel.joints.len())
|
||||
|
||||
@@ -23,7 +23,7 @@ use raea_core_scene::{Item, excused, gltf_tris, src_path, vec3};
|
||||
|
||||
// what each part rests on, and the parts that float, sink or clip (`raea scene lint|explain`)
|
||||
pub mod lint;
|
||||
pub use lint::lint;
|
||||
pub use lint::{lint, lint_with};
|
||||
// a model's box and a seat's facing (scene.bounds, scene.facing)
|
||||
mod assets;
|
||||
pub use assets::assets;
|
||||
|
||||
+37
-56
@@ -14,7 +14,7 @@ use std::collections::HashMap;
|
||||
use bevy::math::{Mat4, Vec3};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use raea_core_scene::{Item, Part, base_ident, face, feet, glows, label, parts_of, ray_tri, unparked, wall};
|
||||
use raea_core_scene::{Item, Part, base_ident, face, feet, glows, label, parts_of, unparked, wall};
|
||||
|
||||
use super::solid_of;
|
||||
|
||||
@@ -195,52 +195,6 @@ fn rest_of(parts: &[Part], grid: &Grid, insets: &[Option<usize>], i: usize) -> R
|
||||
Rest::Air { below: nearest_below }
|
||||
}
|
||||
|
||||
/// The closest other part within MOUNT of this one's top or sides: rays out from points on its box's faces, up and
|
||||
/// along ±x and ±z, against the parts whose boxes come within reach.
|
||||
fn touching(parts: &[Part], i: usize) -> Option<(usize, u32, f32)> {
|
||||
let p = &parts[i];
|
||||
let reach = CARCASS.max(2.0 * MOUNT);
|
||||
let near: Vec<usize> = (0..parts.len())
|
||||
.filter(|&j| j != i && !(parts[j].lo.cmpgt(p.hi + Vec3::splat(reach)).any() || p.lo.cmpgt(parts[j].hi + Vec3::splat(reach)).any()))
|
||||
.collect();
|
||||
if near.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// the points of the part nearest each face of its box, out along that face's normal
|
||||
let dirs = [Vec3::Y, Vec3::X, -Vec3::X, Vec3::Z, -Vec3::Z];
|
||||
let mut best: Option<(usize, u32, f32)> = None;
|
||||
for d in dirs {
|
||||
let extent = |q: Vec3| q.dot(d);
|
||||
let far = p.tris.iter().flatten().map(|q| extent(*q)).fold(f32::MIN, f32::max);
|
||||
let tol = 0.003f32.max(0.01 * (p.hi - p.lo).max_element());
|
||||
let mut pts: Vec<Vec3> = p.tris.iter().flatten().filter(|q| extent(**q) >= far - tol).copied().collect();
|
||||
pts.dedup_by(|a, b| (*a - *b).length() < 1e-5);
|
||||
let step = (pts.len() / 24).max(1);
|
||||
for o in pts.into_iter().step_by(step) {
|
||||
for &j in &near {
|
||||
for (k, t) in parts[j].tris.iter().enumerate() {
|
||||
// the ray starts a touch inside, so a face flush with it is found at ~0
|
||||
if let Some(s) = ray_tri(o - d * 0.0005, d, *t) {
|
||||
let gap = s - 0.0005;
|
||||
// close, or a door a reveal in front of the carcass that covers it (not a shelf off its wall)
|
||||
let ok = gap <= MOUNT || (gap <= CARCASS && !wall(&parts[j]) && covers(&parts[j], p, d));
|
||||
if ok && best.is_none_or(|(_, _, g)| gap.abs() < g.abs()) {
|
||||
best = Some((j, parts[j].node[k], gap));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Whether `back`'s box covers `front`'s across the two axes square to `d` (within a centimetre): a carcass behind its
|
||||
/// door, a ceiling over its lamp.
|
||||
fn covers(back: &Part, front: &Part, d: Vec3) -> bool {
|
||||
(0..3).filter(|&k| d[k].abs() < 0.5).all(|k| back.lo[k] <= front.lo[k] + 0.01 && back.hi[k] >= front.hi[k] - 0.01)
|
||||
}
|
||||
|
||||
fn named(parts: &[Part], j: usize, node: u32) -> String {
|
||||
let p = &parts[j];
|
||||
match p.nodes.get(node as usize).filter(|n| !n.is_empty() && p.nodes.len() > 1) {
|
||||
@@ -271,6 +225,12 @@ fn moving(now: &[Item], other: &[Item]) -> Vec<bool> {
|
||||
/// One frame's parts, each with what it rests on, and the faults: (findings as JSON, the error count).
|
||||
/// `now` is the frame's parts, `next` the next frame's (or the one before, at the end) to see what moves.
|
||||
pub fn lint(now: &[Item], next: &[Item]) -> (Vec<Value>, usize) {
|
||||
lint_with(now, next, true)
|
||||
}
|
||||
|
||||
/// The lint, with or without parts passing into each other (`clips`): without, for a render's end, whose clipping
|
||||
/// check has followed those through every frame already (the pair test is most of the lint's time).
|
||||
pub fn lint_with(now: &[Item], next: &[Item], clips: bool) -> (Vec<Value>, usize) {
|
||||
let moving = moving(now, next);
|
||||
let (parts, items, mut skipped) = parts_of(now, &moving);
|
||||
let (parts, items) = unparked(parts, items, &mut skipped);
|
||||
@@ -328,14 +288,23 @@ pub fn lint(now: &[Item], next: &[Item]) -> (Vec<Value>, usize) {
|
||||
// parent group moving it)
|
||||
let y = items[i].world.w_axis.y;
|
||||
match &r {
|
||||
Rest::On { under, node, gap, .. } => {
|
||||
Rest::On { under, node, gap, at, .. } => {
|
||||
v["on"] = json!(named(&parts, *under, *node));
|
||||
v["gap"] = json!((gap * 1e5).round() / 1e5);
|
||||
v["at"] = json!([at.x, at.y, at.z]);
|
||||
if level == "error" {
|
||||
v["fix"] = json!({"y": ((y - gap) * 1e5).round() / 1e5, "dy": (-gap * 1e5).round() / 1e5});
|
||||
}
|
||||
}
|
||||
Rest::Mounted { on, node, .. } => v["on"] = json!(named(&parts, *on, *node)),
|
||||
Rest::Mounted { on, node, below, .. } => {
|
||||
v["on"] = json!(named(&parts, *on, *node));
|
||||
// how far above what's under it: a table lamp lifted against a wall reads as mounted on the wall, and
|
||||
// only what the thing is can say whether it should hang there (raea-sys-notice judges it by name)
|
||||
if let Some((j, g)) = below {
|
||||
v["gap"] = json!((g * 1e5).round() / 1e5);
|
||||
v["under"] = json!(parts[*j].label);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out.push(v);
|
||||
@@ -352,9 +321,9 @@ pub fn lint(now: &[Item], next: &[Item]) -> (Vec<Value>, usize) {
|
||||
}
|
||||
// parts passing into each other, wherever (the clipping check's own test: deep for the smaller part's size, a
|
||||
// real share of it, not resting contact and not a foot seated in what's below)
|
||||
let solids: Vec<_> = items.iter().map(|it| solid_of(it).ok()).collect();
|
||||
for i in 0..parts.len() {
|
||||
for j in i + 1..parts.len() {
|
||||
let solids: Vec<_> = if clips { items.iter().map(|it| solid_of(it).ok()).collect() } else { Vec::new() };
|
||||
for i in 0..solids.len() {
|
||||
for j in i + 1..solids.len() {
|
||||
if parts[i].excused || parts[j].excused || parts[i].lo.cmpgt(parts[j].hi).any() || parts[j].lo.cmpgt(parts[i].hi).any() {
|
||||
continue;
|
||||
}
|
||||
@@ -379,7 +348,9 @@ pub fn lint(now: &[Item], next: &[Item]) -> (Vec<Value>, usize) {
|
||||
fix["dy"] = json!((-gap * 1e4).round() / 1e4);
|
||||
then = format!(" and {:+.3} m along y to rest on {}", -gap, named(&parts, under, node));
|
||||
}
|
||||
out.push(json!({"part": small, "into": big, "check": "clips", "level": "error", "depth": (h.depth * 1e4).round() / 1e4, "share": (h.share * 1e3).round() / 1e3, "fix": fix,
|
||||
// where the two surfaces meet, for where a viewer would see it (raea-sys-notice)
|
||||
let seam: Vec<[f32; 3]> = h.seam.iter().step_by((h.seam.len() / 16).max(1)).map(|p| p.to_array()).collect();
|
||||
out.push(json!({"part": small, "into": big, "check": "clips", "level": "error", "depth": (h.depth * 1e4).round() / 1e4, "share": (h.share * 1e3).round() / 1e3, "fix": fix, "seam": seam,
|
||||
"says": format!("{small} passes {} into {big} ({:.0}% of it inside): move it {by:+.3} m along world {axis_name}{then}", mm(h.depth), h.share * 100.0)}));
|
||||
}
|
||||
}
|
||||
@@ -401,7 +372,7 @@ pub fn lint(now: &[Item], next: &[Item]) -> (Vec<Value>, usize) {
|
||||
if level == "error" {
|
||||
errors += 1;
|
||||
}
|
||||
out.push(json!({"part": parts[i].label, "into": parts[j].label, "check": "zfight", "level": level, "faces": n, "area": (area * 1e6).round() / 1e6, "at": [at.x, at.y, at.z],
|
||||
out.push(json!({"part": parts[i].label, "into": parts[j].label, "check": "zfight", "level": level, "faces": n, "area": (area * 1e6).round() / 1e6, "at": [at.x, at.y, at.z], "spots": spots(&over.spots),
|
||||
"says": format!("{} and {} have faces in one plane over each other ({n} pair{}, {:.1} cm² shared, most at [{:.3}, {:.3}, {:.3}]): they flicker as the camera moves; lift one by a millimetre or cut the overlap", parts[i].label, parts[j].label, if n == 1 { "" } else { "s" }, area * 1e4, at.x, at.y, at.z)}));
|
||||
}
|
||||
// the same triangles in both (a slab built into two neighbouring chunks) draw alike whichever wins, unless
|
||||
@@ -411,14 +382,20 @@ pub fn lint(now: &[Item], next: &[Item]) -> (Vec<Value>, usize) {
|
||||
"says": format!("{} and {} both hold the same {n} face{} ({:.1} cm², most at [{:.3}, {:.3}, {:.3}]): nothing to see where they look alike; take them out of one", parts[i].label, parts[j].label, if n == 1 { "" } else { "s" }, area * 1e4, at.x, at.y, at.z)}));
|
||||
}
|
||||
}
|
||||
if let Some((n, area, at)) = raea_core_zfight::overlaps(&parts[i].tris, None) {
|
||||
out.push(json!({"part": parts[i].label, "check": "zfight", "level": "warning", "faces": n, "area": (area * 1e6).round() / 1e6, "at": [at.x, at.y, at.z],
|
||||
let inside = raea_core_zfight::sorted(&parts[i].tris, None);
|
||||
if let Some((n, area, at)) = inside.fight {
|
||||
out.push(json!({"part": parts[i].label, "check": "zfight", "level": "warning", "faces": n, "area": (area * 1e6).round() / 1e6, "at": [at.x, at.y, at.z], "spots": spots(&inside.spots),
|
||||
"says": format!("{} has faces doubled in one plane inside it ({n} pair{}, {:.1} cm² shared): they flicker where they show; delete the doubles (raea gen check -o)", parts[i].label, if n == 1 { "" } else { "s" }, area * 1e4)}));
|
||||
}
|
||||
}
|
||||
(out, errors)
|
||||
}
|
||||
|
||||
/// A fight's shared patches as [x, y, z, nx, ny, nz, area] rows.
|
||||
fn spots(s: &[(Vec3, Vec3, f32)]) -> Vec<[f32; 7]> {
|
||||
s.iter().map(|(p, n, a)| [p.x, p.y, p.z, n.x, n.y, n.z, *a]).collect()
|
||||
}
|
||||
|
||||
/// The surface a part would land on and how far it is (negative: sunk): what it rests on, or the nearest surface
|
||||
/// under it when it's in the air.
|
||||
fn landing(r: &Rest) -> Option<(usize, u32, f32)> {
|
||||
@@ -442,6 +419,10 @@ fn rest_after(parts: &[Part], insets: &[Option<usize>], i: usize, v: Vec3) -> Re
|
||||
rest_of(&moved, &grid, insets, i)
|
||||
}
|
||||
|
||||
#[path = "lint/touching.rs"]
|
||||
mod touching;
|
||||
use touching::touching;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lint/tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,87 @@
|
||||
//! What a part touches at its top or sides (a wall it's mounted on, the carcass behind a door): rays out from its box's
|
||||
//! faces against the parts near it.
|
||||
|
||||
use bevy::math::Vec3;
|
||||
use raea_core_scene::{Part, ray_tri, wall};
|
||||
|
||||
use super::{CARCASS, MOUNT};
|
||||
|
||||
/// The closest other part within MOUNT of this one's top or sides: rays out from points on its box's faces, up and
|
||||
/// along ±x and ±z, against the parts whose boxes come within reach.
|
||||
pub(super) fn touching(parts: &[Part], i: usize) -> Option<(usize, u32, f32)> {
|
||||
let p = &parts[i];
|
||||
let reach = CARCASS.max(2.0 * MOUNT);
|
||||
let near: Vec<usize> = (0..parts.len())
|
||||
.filter(|&j| j != i && !(parts[j].lo.cmpgt(p.hi + Vec3::splat(reach)).any() || p.lo.cmpgt(parts[j].hi + Vec3::splat(reach)).any()))
|
||||
.collect();
|
||||
if near.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// the points of the part nearest each face of its box, out along that face's normal
|
||||
let dirs = [Vec3::Y, Vec3::X, -Vec3::X, Vec3::Z, -Vec3::Z];
|
||||
let mut best: Option<(usize, u32, f32)> = None;
|
||||
for d in dirs {
|
||||
let extent = |q: Vec3| q.dot(d);
|
||||
let far = p.tris.iter().flatten().map(|q| extent(*q)).fold(f32::MIN, f32::max);
|
||||
let tol = 0.003f32.max(0.01 * (p.hi - p.lo).max_element());
|
||||
let mut pts: Vec<Vec3> = p.tris.iter().flatten().filter(|q| extent(**q) >= far - tol).copied().collect();
|
||||
pts.dedup_by(|a, b| (*a - *b).length() < 1e-5);
|
||||
let step = (pts.len() / 24).max(1);
|
||||
// the rays run along an axis: a triangle (or a part) whose box doesn't straddle the ray's line, or lies past
|
||||
// its reach, can't be met in reach, so it's passed over before the full test (the same answer; on room 106 the
|
||||
// full test of every triangle was nearly all of a lint's 30 s)
|
||||
let a = (0..3).find(|&k| d[k] != 0.0).unwrap();
|
||||
let (b, c) = ((a + 1) % 3, (a + 2) % 3);
|
||||
let span = |o: Vec3| if d[a] > 0.0 { (o[a] - 0.001, o[a] + reach + 0.001) } else { (o[a] - reach - 0.001, o[a] + 0.001) };
|
||||
let meets = |o: Vec3, lo: Vec3, hi: Vec3| {
|
||||
let (from, to) = span(o);
|
||||
lo[b] <= o[b] + 1e-5 && hi[b] >= o[b] - 1e-5 && lo[c] <= o[c] + 1e-5 && hi[c] >= o[c] - 1e-5 && lo[a] <= to && hi[a] >= from
|
||||
};
|
||||
let pts: Vec<Vec3> = pts.into_iter().step_by(step).collect();
|
||||
// and the triangles any of this side's rays could meet, found once: those whose box meets the box the rays
|
||||
// sweep (the points' own, out by the reach along the axis)
|
||||
let (mut lo, mut hi) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
|
||||
for o in &pts {
|
||||
(lo, hi) = (lo.min(*o), hi.max(*o));
|
||||
}
|
||||
lo[a] -= reach + 0.001;
|
||||
hi[a] += reach + 0.001;
|
||||
let boxes = |l: Vec3, h: Vec3| (l - Vec3::splat(1e-5)).cmple(hi).all() && (lo - Vec3::splat(1e-5)).cmple(h).all();
|
||||
let cands: Vec<(usize, Vec<usize>)> = near
|
||||
.iter()
|
||||
.filter(|&&j| boxes(parts[j].lo, parts[j].hi))
|
||||
.map(|&j| (j, parts[j].tris.iter().enumerate().filter(|(_, t)| boxes(t[0].min(t[1]).min(t[2]), t[0].max(t[1]).max(t[2]))).map(|(k, _)| k).collect()))
|
||||
.collect();
|
||||
for &o in &pts {
|
||||
for (j, ks) in &cands {
|
||||
let j = *j;
|
||||
if !meets(o, parts[j].lo, parts[j].hi) {
|
||||
continue;
|
||||
}
|
||||
for &k in ks {
|
||||
let t = &parts[j].tris[k];
|
||||
if !meets(o, t[0].min(t[1]).min(t[2]), t[0].max(t[1]).max(t[2])) {
|
||||
continue;
|
||||
}
|
||||
// the ray starts a touch inside, so a face flush with it is found at ~0
|
||||
if let Some(s) = ray_tri(o - d * 0.0005, d, *t) {
|
||||
let gap = s - 0.0005;
|
||||
// close, or a door a reveal in front of the carcass that covers it (not a shelf off its wall)
|
||||
let ok = gap <= MOUNT || (gap <= CARCASS && !wall(&parts[j]) && covers(&parts[j], p, d));
|
||||
if ok && best.is_none_or(|(_, _, g)| gap.abs() < g.abs()) {
|
||||
best = Some((j, parts[j].node[k], gap));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Whether `back`'s box covers `front`'s across the two axes square to `d` (within a centimetre): a carcass behind its
|
||||
/// door, a ceiling over its lamp.
|
||||
fn covers(back: &Part, front: &Part, d: Vec3) -> bool {
|
||||
(0..3).filter(|&k| d[k].abs() < 0.5).all(|k| back.lo[k] <= front.lo[k] + 0.01 && back.hi[k] >= front.hi[k] - 0.01)
|
||||
}
|
||||
|
||||
@@ -3,31 +3,18 @@
|
||||
//! grab's, the release's); the answer is the pose to draw and where the thing is.
|
||||
|
||||
use glam::Quat;
|
||||
use raea_sys_body::json::{num, posed, quat, vec3};
|
||||
use raea_sys_body::json::{num, posed, quat, solid, vec3};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::trunk::stand_for;
|
||||
use crate::hand::{Grip, Hold, HoldOptions, find_holds};
|
||||
use raea_sys_body::rig::{Pose, Side, Skeleton};
|
||||
use raea_sys_body::shape::{Solid, Thing};
|
||||
use raea_sys_body::shape::Thing;
|
||||
use crate::take::{Key, Release, Take, perform};
|
||||
|
||||
pub const TAKE_ARGS: &str = "{ joints: { name: string; parent: number; head: [number, number, number]; tail: [number, number, number] }[]; t: number; base: { t: number; root: [number, number, number]; turns: [number, number, number, number][] }[]; thing: { ball?: number; box?: [number, number, number]; capsule?: [number, number]; cylinder?: [number, number]; at: [number, number, number]; turn?: [number, number, number, number] }; start: number; grab?: number; carried?: number; carry?: [number, number, number]; hand?: \"L\" | \"R\"; lower?: number; holds?: { side: \"L\" | \"R\"; at: [number, number, number]; normal: [number, number, number]; along?: [number, number, number]; shape?: number[] }[]; path?: { t: number; carry: [number, number, number]; tilt?: [number, number, number, number] }[]; weight?: number; pass?: number; slide?: { t: number; at: [number, number, number]; turn?: [number, number, number, number] }[]; leave?: number; avoid?: { ball?: number; box?: [number, number, number]; capsule?: [number, number]; cylinder?: [number, number]; at: [number, number, number]; turn?: [number, number, number, number] }[]; put?: { at: number; down: number; place: [number, number, number] }; throw?: { at: number; velocity: [number, number, number]; floor?: number } }";
|
||||
pub const TAKE_ANSWER: &str = "{ pose: { root: [number, number, number]; turns: [number, number, number, number][] }; thing: { at: [number, number, number]; turn: [number, number, number, number] }; phase: \"Before\" | \"Reach\" | \"Lift\" | \"Carry\" | \"Release\" | \"After\"; hands: 1 | 2; miss: number; moved: number; limited: boolean; stand: { at: [number, number, number]; yaw: number }; reach: { ok: boolean; move: number } }";
|
||||
|
||||
fn solid(v: &Value) -> Result<Solid, String> {
|
||||
if !v["ball"].is_null() {
|
||||
return Ok(Solid::Ball { r: num(&v["ball"], "thing.ball")? });
|
||||
}
|
||||
if !v["box"].is_null() {
|
||||
return Ok(Solid::Box { half: vec3(&v["box"], "thing.box")? });
|
||||
}
|
||||
// a capsule or a cylinder: half its length along its own y, then its radius
|
||||
let rod = ["capsule", "cylinder"].into_iter().find(|k| !v[*k].is_null()).ok_or("character.take: the thing needs a shape: ball, box, capsule or cylinder")?;
|
||||
let a = v[rod].as_array().filter(|a| a.len() == 2).ok_or_else(|| format!("character.take: thing.{rod} isn't [half its length, radius]"))?;
|
||||
let (half, r) = (num(&a[0], rod)?, num(&a[1], rod)?);
|
||||
Ok(if rod == "capsule" { Solid::Capsule { half, r } } else { Solid::Cylinder { half, r } })
|
||||
}
|
||||
|
||||
pub fn take_json(v: &Value) -> Result<Value, String> {
|
||||
let skel = Skeleton::from_value(v)?;
|
||||
|
||||
@@ -13,12 +13,8 @@ raea-sys-atlas = { path = "../atlas" }
|
||||
parry3d = "0.31"
|
||||
rayon = "1"
|
||||
serde_json = "1"
|
||||
# the paths the light is traced along (BK3)
|
||||
raea-sys-lighttrace = { path = "../lighttrace" }
|
||||
# a model read on its own second UVs (own.rs): its meshes, and its base colour textures decoded
|
||||
gltf = { version = "1.4", default-features = false, features = ["utils", "names"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# the panorama the atelier's run reads (own/tests.rs)
|
||||
image = { version = "0.25", default-features = false, features = ["hdr"] }
|
||||
# the process's one shared GPU device, and wgpu's ray queries on it (BK3)
|
||||
raea-gpu-device = { path = "../../gpu/device" }
|
||||
wgpu = "=30.0.1"
|
||||
bytemuck = "1"
|
||||
pollster = "0.4"
|
||||
@@ -5,7 +5,6 @@
|
||||
//! progress). Next: a clean map (BK4), and the bake in a composition (BK5).
|
||||
|
||||
// each texel's ray origin and the texels inside other geometry (BK2)
|
||||
pub mod own;
|
||||
pub mod texels;
|
||||
#[cfg(test)]
|
||||
mod trace_tests;
|
||||
// the light that bounces, traced on the GPU (BK3)
|
||||
pub mod trace;
|
||||
@@ -1,169 +0,0 @@
|
||||
//! A model traced on its own second UVs, a map a mesh (docs/bake.feature BK3): what lightbake.py lays out, so raea's
|
||||
//! light is compared with Cycles' texel for texel. Every mesh of the .glb in world space with its materials (base
|
||||
//! colour, its texture, less what's metal), and a mesh's texels at a side: those whose centre a triangle covers.
|
||||
|
||||
use gltf::mesh::util::ReadIndices;
|
||||
use parry3d::glamx::{Mat4, Vec2, Vec3};
|
||||
use std::collections::HashMap;
|
||||
use std::ops::Range;
|
||||
|
||||
use parry3d::shape::TriMesh;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::texels::starts;
|
||||
use raea_sys_lighttrace::{Image, Surface};
|
||||
|
||||
pub struct Mesh {
|
||||
pub name: String,
|
||||
/// its triangles in Model::triangles
|
||||
pub triangles: Range<usize>,
|
||||
}
|
||||
|
||||
/// A .glb's meshes in the world, as World takes them, with each vertex's second UV.
|
||||
#[derive(Default)]
|
||||
pub struct Model {
|
||||
pub positions: Vec<[f32; 3]>,
|
||||
pub normals: Vec<[f32; 3]>,
|
||||
pub uvs: Vec<[f32; 2]>,
|
||||
pub second: Vec<[f32; 2]>,
|
||||
pub triangles: Vec<[u32; 3]>,
|
||||
pub surfaces: Vec<Surface>,
|
||||
pub textures: Vec<Image>,
|
||||
pub meshes: Vec<Mesh>,
|
||||
}
|
||||
|
||||
/// A texel of a mesh's map whose centre a triangle covers.
|
||||
pub struct At {
|
||||
pub x: u32,
|
||||
pub y: u32,
|
||||
/// its point off the surface, the sides of its footprint and its open starts (texels::starts)
|
||||
pub origin: [f32; 3],
|
||||
pub sides: [[f32; 3]; 2],
|
||||
pub open: u32,
|
||||
/// the shading normal there (the vertices', interpolated), on the plane's side
|
||||
pub normal: [f32; 3],
|
||||
}
|
||||
|
||||
/// The model, its textures no longer a side than `most` (a bounce blurs the rest away).
|
||||
pub fn read(glb: &[u8], most: u32) -> Result<Model, String> {
|
||||
let g = gltf::Gltf::from_slice(glb).map_err(|e| e.to_string())?;
|
||||
let blob = g.blob.clone().ok_or("a model without its binary: only a .glb is read")?;
|
||||
let mut m = Model::default();
|
||||
let mut images = HashMap::new();
|
||||
let mut stack: Vec<(gltf::Node, Mat4)> = match g.default_scene().or(g.scenes().next()) {
|
||||
Some(s) => s.nodes().map(|n| (n, Mat4::IDENTITY)).collect(),
|
||||
None => return Err("a model without a scene".into()),
|
||||
};
|
||||
while let Some((node, up)) = stack.pop() {
|
||||
let world = up * Mat4::from_cols_array_2d(&node.transform().matrix());
|
||||
stack.extend(node.children().map(|c| (c, world)));
|
||||
let Some(mesh) = node.mesh() else { continue };
|
||||
let first = m.triangles.len();
|
||||
for p in mesh.primitives() {
|
||||
if p.mode() != gltf::mesh::Mode::Triangles {
|
||||
continue;
|
||||
}
|
||||
primitive(&mut m, &p, world, &blob, &mut images, most)?;
|
||||
}
|
||||
m.meshes.push(Mesh { name: mesh.name().unwrap_or_default().to_string(), triangles: first..m.triangles.len() });
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
fn primitive(m: &mut Model, p: &gltf::Primitive, world: Mat4, blob: &[u8], images: &mut HashMap<usize, u32>, most: u32) -> Result<(), String> {
|
||||
let r = p.reader(|_| Some(blob));
|
||||
let base = m.positions.len() as u32;
|
||||
let turn = world.inverse().transpose();
|
||||
m.positions.extend(r.read_positions().ok_or("a mesh without positions")?.map(|v| world.transform_point3(Vec3::from(v)).to_array()));
|
||||
let n = m.positions.len() - base as usize;
|
||||
match r.read_normals() {
|
||||
Some(v) => m.normals.extend(v.map(|v| turn.transform_vector3(Vec3::from(v)).normalize_or_zero().to_array())),
|
||||
None => m.normals.extend(vec![[0.0; 3]; n]),
|
||||
}
|
||||
let uv = |set: u32| r.read_tex_coords(set).map_or(vec![[0.0; 2]; n], |u| u.into_f32().collect());
|
||||
let (first, second) = (uv(0), uv(1));
|
||||
m.uvs.extend(first);
|
||||
m.second.extend(second);
|
||||
let index: Vec<u32> = match r.read_indices() {
|
||||
Some(ReadIndices::U8(i)) => i.map(u32::from).collect(),
|
||||
Some(ReadIndices::U16(i)) => i.map(u32::from).collect(),
|
||||
Some(ReadIndices::U32(i)) => i.collect(),
|
||||
None => (0..n as u32).collect(),
|
||||
};
|
||||
let pbr = p.material().pbr_metallic_roughness();
|
||||
let [cr, cg, cb, _] = pbr.base_color_factor();
|
||||
let texture = match pbr.base_color_texture() {
|
||||
Some(t) => Some(texture(m, &t.texture().source(), blob, images, most)?),
|
||||
None => None,
|
||||
};
|
||||
let e = p.material().emissive_factor();
|
||||
let surface = Surface { albedo: [cr, cg, cb], emission: e, metallic: pbr.metallic_factor(), roughness: pbr.roughness_factor(), f0: 0.04, texture };
|
||||
m.triangles.extend(index.chunks_exact(3).map(|t| [base + t[0], base + t[1], base + t[2]]));
|
||||
m.surfaces.resize(m.triangles.len(), surface);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn texture(m: &mut Model, image: &gltf::Image, blob: &[u8], images: &mut HashMap<usize, u32>, most: u32) -> Result<u32, String> {
|
||||
if let Some(k) = images.get(&image.index()) {
|
||||
return Ok(*k);
|
||||
}
|
||||
let gltf::image::Source::View { view, .. } = image.source() else { return Err("a texture outside the .glb".into()) };
|
||||
let bytes = &blob[view.offset()..view.offset() + view.length()];
|
||||
let full = image::load_from_memory(bytes).map_err(|e| format!("a texture: {e}"))?;
|
||||
let small = if full.width().max(full.height()) > most { full.thumbnail(most, most) } else { full }.to_rgba8();
|
||||
let rgba = small.pixels().map(|p| u32::from_le_bytes(p.0)).collect();
|
||||
m.textures.push(Image { width: small.width(), height: small.height(), rgba });
|
||||
let k = m.textures.len() as u32 - 1;
|
||||
images.insert(image.index(), k);
|
||||
Ok(k)
|
||||
}
|
||||
|
||||
/// A mesh's texels on its second UVs at `side` by `side`, each once (the first triangle over its centre); `offset` as
|
||||
/// Texels' own.
|
||||
pub fn texels(m: &Model, mesh: &Mesh, world: &TriMesh, side: u32, offset: f32, whole: bool) -> Vec<At> {
|
||||
let mut taken = vec![false; (side * side) as usize];
|
||||
let mut out = vec![];
|
||||
for tri in &m.triangles[mesh.triangles.clone()] {
|
||||
let uv = tri.map(|v| m.second[v as usize].map(|c| c * side as f32));
|
||||
let [pos, nor] = [&m.positions, &m.normals].map(|list| tri.map(|v| Vec3::from(list[v as usize])));
|
||||
let cross = |a: [f32; 2], b: [f32; 2], c: [f32; 2]| (Vec2::from(b) - Vec2::from(a)).perp_dot(Vec2::from(c) - Vec2::from(a));
|
||||
let area = cross(uv[0], uv[1], uv[2]);
|
||||
let plane = (pos[1] - pos[0]).cross(pos[2] - pos[0]);
|
||||
if area.abs() < 1e-9 || plane.length_squared() < 1e-24 {
|
||||
continue;
|
||||
}
|
||||
// a texel's sides on this triangle, metres
|
||||
let (e1, e2) = (Vec2::from(uv[1]) - Vec2::from(uv[0]), Vec2::from(uv[2]) - Vec2::from(uv[0]));
|
||||
let sides = [((pos[1] - pos[0]) * e2.y - (pos[2] - pos[0]) * e1.y) / area, ((pos[2] - pos[0]) * e1.x - (pos[1] - pos[0]) * e2.x) / area];
|
||||
let span = |k: usize| {
|
||||
let (lo, hi) = uv.iter().fold((f32::MAX, f32::MIN), |(l, h), q| (l.min(q[k]), h.max(q[k])));
|
||||
((lo - 0.5).ceil().max(0.0) as u32, ((hi - 0.5).floor() as i64).clamp(-1, side as i64 - 1))
|
||||
};
|
||||
let ((x0, x1), (y0, y1)) = (span(0), span(1));
|
||||
for y in y0 as i64..=y1 {
|
||||
for x in x0 as i64..=x1 {
|
||||
let c = [x as f32 + 0.5, y as f32 + 0.5];
|
||||
let w = [cross(uv[1], uv[2], c) / area, cross(uv[2], uv[0], c) / area, cross(uv[0], uv[1], c) / area];
|
||||
let at = (y as u32 * side + x as u32) as usize;
|
||||
if w.iter().any(|&v| v < 0.0) || taken[at] {
|
||||
continue;
|
||||
}
|
||||
taken[at] = true;
|
||||
let p = pos[0] * w[0] + pos[1] * w[1] + pos[2] * w[2];
|
||||
let shade = (nor[0] * w[0] + nor[1] * w[1] + nor[2] * w[2]).normalize_or_zero();
|
||||
let mut n = plane.normalize();
|
||||
if n.dot(shade) < 0.0 {
|
||||
n = -n;
|
||||
}
|
||||
out.push((At { x: x as u32, y: y as u32, origin: p.to_array(), sides: sides.map(|s| s.to_array()), open: 0, normal: if shade == Vec3::ZERO { n } else { shade }.to_array() }, n, pos));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.into_par_iter().enumerate().map(|(k, (a, n, pos))| {
|
||||
let (origin, open) = starts(world, pos, Vec3::from(a.origin), n, a.sides.map(Vec3::from), offset, k as u32, whole);
|
||||
At { origin, open, ..a }
|
||||
}).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,148 +0,0 @@
|
||||
use super::*;
|
||||
use crate::texels::tests::{cuboid, glb};
|
||||
use raea_sys_lighttrace::{Settings, Sky, Starts, Sun, World, trace};
|
||||
|
||||
#[test]
|
||||
fn a_model_reads_in_the_world_with_its_materials() {
|
||||
let m = read(&glb(&[(cuboid([0.0; 3], [1.0; 3]), [0.0, 2.0, 0.0])]), 64).unwrap();
|
||||
assert_eq!((m.meshes.len(), m.triangles.len(), m.surfaces.len()), (1, 12, 12));
|
||||
assert!(m.positions.iter().all(|p| (2.0..=3.0).contains(&p[1])), "the node's translation");
|
||||
// glTF's metallic and roughness are 1 when a material doesn't say; the rest under it has the dielectric's F0
|
||||
assert_eq!(m.surfaces[0], Surface { albedo: [1.0; 3], metallic: 1.0, roughness: 1.0, f0: 0.04, ..Surface::default() });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn texels_lie_where_the_second_uvs_put_them() {
|
||||
// a 2 m by 1 m wall standing at z = 3, facing +Z, over the left half of its map
|
||||
let quad = [([0.0f32, 0.0, 3.0], [0.0f32, 1.0f32]), ([2.0, 0.0, 3.0], [0.5, 1.0]), ([2.0, 1.0, 3.0], [0.5, 0.5]), ([0.0, 1.0, 3.0], [0.0, 0.5])];
|
||||
let m = Model {
|
||||
positions: quad.iter().map(|q| q.0).collect(),
|
||||
normals: vec![[0.0, 0.0, 1.0]; 4],
|
||||
uvs: vec![[0.0; 2]; 4],
|
||||
second: quad.iter().map(|q| q.1).collect(),
|
||||
triangles: vec![[0, 1, 2], [0, 2, 3]],
|
||||
surfaces: vec![Surface::default(); 2],
|
||||
meshes: vec![Mesh { name: "wall".into(), triangles: 0..2 }],
|
||||
..Model::default()
|
||||
};
|
||||
let world = parry3d::shape::TriMesh::new(m.positions.iter().map(|p| Vec3::from(*p)).collect(), m.triangles.clone()).unwrap();
|
||||
let t = texels(&m, &m.meshes[0], &world, 16, 1e-4, false);
|
||||
assert_eq!(t.len(), 8 * 8, "a quarter of 16 x 16, each once");
|
||||
for a in &t {
|
||||
let want = [(a.x as f32 + 0.5) / 8.0 * 2.0, 1.0 - (a.y as f32 + 0.5 - 8.0) / 8.0];
|
||||
assert!((a.origin[0] - want[0]).abs() < 1e-2 && (a.origin[1] - want[1]).abs() < 1e-2 && (a.origin[2] - 3.0001).abs() < 1e-5, "{},{} at {:?}", a.x, a.y, a.origin);
|
||||
assert_eq!(a.normal, [0.0, 0.0, 1.0]);
|
||||
assert_eq!(a.sides, [[0.25, 0.0, 0.0], [0.0, -0.125, 0.0]], "a texel's sides");
|
||||
}
|
||||
}
|
||||
|
||||
fn number(name: &str, d: f32) -> f32 {
|
||||
std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(d)
|
||||
}
|
||||
|
||||
/// lightbake.py's smooth: a 3 x 3 mean over the covered texels, `passes` times.
|
||||
fn smooth(side: usize, map: &mut Vec<Option<[f32; 3]>>, passes: usize) {
|
||||
for _ in 0..passes {
|
||||
let from = map.clone();
|
||||
for (i, out) in map.iter_mut().enumerate().filter(|(_, v)| v.is_some()) {
|
||||
let (x, y) = ((i % side) as i32, (i / side) as i32);
|
||||
let near: Vec<[f32; 3]> = (-1..=1).flat_map(|dy| (-1..=1).map(move |dx| (x + dx, y + dy))).filter(|&(a, b)| a >= 0 && b >= 0 && a < side as i32 && b < side as i32).filter_map(|(a, b)| from[b as usize * side + a as usize]).collect();
|
||||
*out = Some(std::array::from_fn(|k| near.iter().map(|c| c[k]).sum::<f32>() / near.len() as f32));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The atelier's run (docs/bake.feature BK3): a model lightbake.py baked, traced on its own maps under the light its
|
||||
/// .blend held, and each map against Cycles' (compare.rs's map_stops: the mean distance in stops and the signed one,
|
||||
/// over the texels both cover, Cycles' clipped ones out). RAEA_BAKE_DIR holds set.glb, set.lightmaps.json and
|
||||
/// lightmaps/, RAEA_BAKE_SKY the panorama; _RUNS ("512x4": samples x bounces, each in turn), _STRENGTH, _ROTATION, _SMOOTH, _SUN ("x,y,z,r,g,b")
|
||||
/// _ONLY (mesh names), _OFFSET (metres), _WHOLE (a texel's buried part counts, as in Cycles), _LAMBERT (no glossy layers, for a diffuse-only reference), _DUMP (a folder: each map's luminances, raea's and Cycles', and the texel's place, as f32 threes)
|
||||
/// and _OUT (each run's table, OUT-RUN.json).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn against_cycles() {
|
||||
let dir = std::path::PathBuf::from(std::env::var("RAEA_BAKE_DIR").expect("RAEA_BAKE_DIR"));
|
||||
let t0 = std::time::Instant::now();
|
||||
let mut m = read(&std::fs::read(dir.join("set.glb")).unwrap(), 512).unwrap();
|
||||
if std::env::var("RAEA_BAKE_LAMBERT").is_ok() {
|
||||
m.surfaces.iter_mut().for_each(|s| *s = Surface { albedo: s.albedo.map(|c| c * (1.0 - s.metallic)), metallic: 0.0, f0: 0.0, ..*s });
|
||||
}
|
||||
let listed: serde_json::Value = serde_json::from_slice(&std::fs::read(dir.join("set.lightmaps.json")).unwrap()).unwrap();
|
||||
let far = m.positions.iter().flatten().fold(0.0f32, |a, v| a.max(v.abs()));
|
||||
let offset = number("RAEA_BAKE_OFFSET", crate::texels::offset(far));
|
||||
let hdr = image::open(std::env::var("RAEA_BAKE_SKY").expect("RAEA_BAKE_SKY")).unwrap().to_rgb32f();
|
||||
let sky = Sky { width: hdr.width(), height: hdr.height(), rgb: hdr.pixels().map(|p| p.0).collect(), strength: number("RAEA_BAKE_STRENGTH", 1.0), rotation: number("RAEA_BAKE_ROTATION", 0.0) };
|
||||
let sun = std::env::var("RAEA_BAKE_SUN").ok().map(|s| {
|
||||
let v: Vec<f32> = s.split(',').map(|x| x.parse().unwrap()).collect();
|
||||
Sun { dir: [v[0], v[1], v[2]], irradiance: [v[3], v[4], v[5]], half_angle: 0.00459 }
|
||||
});
|
||||
let world = parry3d::shape::TriMesh::new(m.positions.iter().map(|p| Vec3::from(*p)).collect(), m.triangles.clone()).unwrap();
|
||||
let mut maps = vec![];
|
||||
for l in listed["meshes"].as_array().unwrap() {
|
||||
let name = l["mesh"].as_str().unwrap();
|
||||
if std::env::var("RAEA_BAKE_ONLY").is_ok_and(|only| !only.split(',').any(|o| o == name)) {
|
||||
continue;
|
||||
}
|
||||
let mesh = m.meshes.iter().find(|x| x.name == name).unwrap_or_else(|| panic!("no mesh {name}"));
|
||||
let side = l["size"].as_u64().unwrap() as u32;
|
||||
maps.push((name.to_string(), mesh, side, l["lightmap_exposure"].as_f64().unwrap() as f32 / 683.0, texels(&m, mesh, &world, side, offset, std::env::var("RAEA_BAKE_WHOLE").is_ok())));
|
||||
}
|
||||
let origin: Vec<[f32; 3]> = maps.iter().flat_map(|x| x.4.iter().map(|a| a.origin)).collect();
|
||||
let sides: Vec<[[f32; 3]; 2]> = maps.iter().flat_map(|x| x.4.iter().map(|a| a.sides)).collect();
|
||||
let open: Vec<u32> = maps.iter().flat_map(|x| x.4.iter().map(|a| a.open)).collect();
|
||||
let normal: Vec<[f32; 3]> = maps.iter().flat_map(|x| x.4.iter().map(|a| a.normal)).collect();
|
||||
println!("{} meshes, {} triangles, {} texels, {} inside, {} textures; read and laid in {:.1} s", m.meshes.len(), m.triangles.len(), origin.len(), open.iter().filter(|m| **m == 0).count(), m.textures.len(), t0.elapsed().as_secs_f64());
|
||||
let runs = std::env::var("RAEA_BAKE_RUNS").unwrap_or("512x4".into());
|
||||
let w = World { positions: &m.positions, triangles: &m.triangles, surfaces: &m.surfaces, uvs: &m.uvs, textures: &m.textures };
|
||||
for run in runs.split(',') {
|
||||
let [samples, bounces] = run.split('x').collect::<Vec<_>>().try_into().expect("SAMPLESxBOUNCES");
|
||||
let s = Settings { samples: samples.parse().unwrap(), bounces: bounces.parse().unwrap(), per_pass: 8, sky: sky.clone(), sun };
|
||||
let t1 = std::time::Instant::now();
|
||||
let light = trace(&w, &Starts { origin: &origin, normal: &normal, sides: &sides, open: &open, offset }, &s, &mut |_, _| {}).unwrap();
|
||||
let seconds = t1.elapsed().as_secs_f64();
|
||||
println!("{} values that aren't finite", light.iter().flatten().filter(|v| !v.is_finite()).count());
|
||||
println!("{run}: traced {} samples, {} bounces in {seconds:.1} s", s.samples, s.bounces);
|
||||
let passes = number("RAEA_BAKE_SMOOTH", 2.0) as usize;
|
||||
let (mut first, mut rows) = (0, vec![]);
|
||||
let (mut abs, mut signed, mut n, mut zeros) = (0.0f64, 0.0f64, 0usize, 0usize);
|
||||
for (name, mesh, side, scale, at) in &maps {
|
||||
let side = *side as usize;
|
||||
let mut mine = vec![None; side * side];
|
||||
for (k, a) in at.iter().enumerate() {
|
||||
if open[first + k] != 0 {
|
||||
mine[a.y as usize * side + a.x as usize] = Some(light[first + k]);
|
||||
}
|
||||
}
|
||||
first += at.len();
|
||||
smooth(side, &mut mine, passes);
|
||||
let file = listed["meshes"].as_array().unwrap().iter().find(|l| l["mesh"] == name.as_str()).unwrap()["map"].as_str().unwrap().rsplit('/').next().unwrap().to_string();
|
||||
let theirs = image::open(dir.join("lightmaps").join(file)).unwrap().to_rgb16();
|
||||
let lum = |c: [f32; 3]| 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
|
||||
let (mut a, mut b, mut k) = (0.0f64, 0.0f64, 0usize);
|
||||
let mut pairs: Vec<f32> = vec![];
|
||||
for (i, v) in mine.iter().enumerate() {
|
||||
let q = theirs.get_pixel((i % side) as u32, (i / side) as u32).0;
|
||||
let (Some(v), false) = (v, q.contains(&u16::MAX)) else { continue };
|
||||
let (x, y) = (lum(*v), lum(q.map(|c| c as f32 / 65535.0 * scale)));
|
||||
pairs.extend([x, y, i as f32]);
|
||||
if x <= 0.0 || y <= 0.0 {
|
||||
zeros += 1;
|
||||
continue;
|
||||
}
|
||||
let st = (x / y).log2() as f64;
|
||||
(a, b, k) = (a + st.abs(), b + st, k + 1);
|
||||
}
|
||||
if let Ok(d) = std::env::var("RAEA_BAKE_DUMP") {
|
||||
std::fs::write(format!("{d}/{run}-{name}.f32"), pairs.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>()).unwrap();
|
||||
}
|
||||
let s0 = m.surfaces[mesh.triangles.start];
|
||||
(abs, signed, n) = (abs + a, signed + b, n + k);
|
||||
rows.push(serde_json::json!({ "mesh": name, "side": side, "texels": k, "mean_stops": a / k.max(1) as f64, "bias_stops": b / k.max(1) as f64, "textured": s0.texture.is_some(), "albedo": s0.albedo }));
|
||||
}
|
||||
let over = rows.iter().filter(|r| r["texels"].as_u64().unwrap() > 0 && r["mean_stops"].as_f64().unwrap() > 1.0 / 3.0).count();
|
||||
println!("{n} texels compared ({zeros} left out, one side exactly 0): mean {:.3} stops, bias {:+.3}; {over} of {} meshes over 1/3 stop", abs / n as f64, signed / n as f64, rows.len());
|
||||
if let Ok(out) = std::env::var("RAEA_BAKE_OUT") {
|
||||
std::fs::write(format!("{out}-{run}.json"), serde_json::json!({ "samples": s.samples, "bounces": s.bounces, "trace_seconds": seconds, "mean_stops": abs / n as f64, "bias_stops": signed / n as f64, "meshes": rows }).to_string()).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,6 @@ use rayon::prelude::*;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use raea_sys_atlas::rays::{hemi, sample};
|
||||
use raea_sys_lighttrace::CENTRE;
|
||||
pub use raea_sys_atlas::{Layout, Texel};
|
||||
|
||||
/// Rays each texel casts for the inside test: cosine-weighted, the atlas's rotated R2 sequence per texel.
|
||||
@@ -24,11 +23,9 @@ pub struct Texels {
|
||||
pub layout: Layout,
|
||||
/// each texel's ray origin: its surface point, four offsets in from its triangle's edges, moved `offset` along its normal
|
||||
pub origin: Vec<[f32; 3]>,
|
||||
/// the two sides of each texel's footprint, and which of the points over it are open (0 inside other geometry: their
|
||||
/// rays meet back faces, left for BK4 to fill), as raea_sys_lighttrace::Starts takes them
|
||||
pub sides: Vec<[[f32; 3]; 2]>,
|
||||
pub open: Vec<u32>,
|
||||
/// metres off the surface: `offset` of the model's size or of its farthest coordinate
|
||||
/// the texels inside other geometry (their rays meet back faces), left for BK4 to fill
|
||||
pub inside: Vec<bool>,
|
||||
/// metres off the surface: 1e-5 of the model's size or of its farthest coordinate, at least 10 microns
|
||||
pub offset: f32,
|
||||
/// the model's triangles in world space, for the trace (BK3)
|
||||
pub mesh: TriMesh,
|
||||
@@ -40,19 +37,6 @@ pub fn request(texels: f32, max_side: u32) -> Value {
|
||||
json!({ "env": { "density": texels, "max_side": max_side } })
|
||||
}
|
||||
|
||||
impl Texels {
|
||||
/// Which texels are inside other geometry, in the layout's order.
|
||||
pub fn inside(&self) -> Vec<bool> {
|
||||
self.open.iter().map(|&m| m == 0).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// How far off a surface a ray starts in a model of this size, metres: three times what its floats round to
|
||||
/// (a_surface_never_meets_itself), and well under the gaps things are stacked with (0.2 mm in a 15 m room).
|
||||
pub fn offset(size: f32) -> f32 {
|
||||
(1e-6 * size).max(1e-6)
|
||||
}
|
||||
|
||||
/// Every texel of the model's atlas in the world: its origin and whether it's inside other geometry.
|
||||
pub fn texels(glb: &[u8], req: &Value) -> Result<Texels, String> {
|
||||
let (layout, mesh) = raea_sys_atlas::laid(glb, req)?;
|
||||
@@ -60,24 +44,20 @@ pub fn texels(glb: &[u8], req: &Value) -> Result<Texels, String> {
|
||||
for &v in mesh.vertices() {
|
||||
(lo, hi, far) = (lo.min(v), hi.max(v), far.max(v.abs().max_element()));
|
||||
}
|
||||
let offset = offset((hi - lo).length().max(far));
|
||||
// a texel of the atlas is a square of its density; its turn on the surface doesn't matter to its footprint
|
||||
let sides: Vec<[[f32; 3]; 2]> = layout.texels.iter().map(|t| {
|
||||
let n = Vec3::from(t.n);
|
||||
let u = n.any_orthonormal_vector() / layout.density;
|
||||
[u.to_array(), n.cross(u).to_array()]
|
||||
}).collect();
|
||||
let (origin, open) = layout.texels.par_iter().zip(&sides).enumerate().map(|(i, (t, s))| {
|
||||
let offset = (1e-5 * (hi - lo).length().max(far)).max(1e-5);
|
||||
let half = 0.5 / layout.density;
|
||||
let origin: Vec<[f32; 3]> = layout.texels.iter().map(|t| {
|
||||
let tri = mesh.indices()[t.tri as usize].map(|v| mesh.vertices()[v as usize]);
|
||||
starts(&mesh, tri, Vec3::from(t.p), Vec3::from(t.n), s.map(Vec3::from), offset, i as u32, false)
|
||||
}).unzip();
|
||||
Ok(Texels { layout, origin, sides, open, offset, mesh })
|
||||
(off_edges(tri, Vec3::from(t.p), 4.0 * offset, half) + Vec3::from(t.n) * offset).to_array()
|
||||
}).collect();
|
||||
let inside = layout.texels.par_iter().zip(&origin).enumerate().map(|(i, (t, &o))| inside(&mesh, Vec3::from(o), Vec3::from(t.n), i as u32)).collect();
|
||||
Ok(Texels { layout, origin, inside, offset, mesh })
|
||||
}
|
||||
|
||||
/// Whether a texel is inside other geometry: of its rays that meet anything, at least half meet a back face and more
|
||||
/// meet back faces than front ones. A foot inside a closed floor slab meets back faces every way; one under a floor
|
||||
/// that is a single plane meets its underside upwards and nothing downwards, and is inside too.
|
||||
pub(crate) fn inside(mesh: &TriMesh, o: Vec3, n: Vec3, seed: u32) -> bool {
|
||||
fn inside(mesh: &TriMesh, o: Vec3, n: Vec3, seed: u32) -> bool {
|
||||
let (mut back, mut front) = (0, 0);
|
||||
for j in 0..RAYS {
|
||||
let d = hemi(n, sample(seed, j));
|
||||
@@ -89,34 +69,11 @@ pub(crate) fn inside(mesh: &TriMesh, o: Vec3, n: Vec3, seed: u32) -> bool {
|
||||
back * 2 >= RAYS && back > front
|
||||
}
|
||||
|
||||
/// Where a texel's samples start: its point off the surface, and which of the 4 x 4 points of its footprint are open
|
||||
/// (on its triangle, clear of its edges, not inside other geometry). A texel half buried keeps only its open half:
|
||||
/// what it's averaged over is what can be seen (`whole` takes the buried part too, as Cycles does: for comparing). A
|
||||
/// corner and the centre that agree stand for the rest.
|
||||
pub(crate) fn starts(mesh: &TriMesh, tri: [Vec3; 3], p: Vec3, n: Vec3, [u, v]: [Vec3; 2], offset: f32, seed: u32, whole: bool) -> ([f32; 3], u32) {
|
||||
let gap = 4.0 * offset;
|
||||
let centre = off_edges(tri, p, gap, 0.5 * u.length().max(v.length())) + n * offset;
|
||||
let at = |c: u32| p + u * ((c % 4) as f32 / 4.0 - 0.375) + v * ((c / 4) as f32 / 4.0 - 0.375);
|
||||
let cells: Vec<u32> = (0..16).filter(|&c| off_edges(tri, at(c), gap, f32::MAX).distance(at(c)) < 0.5 * offset).collect();
|
||||
if whole && !cells.is_empty() {
|
||||
return ((p + n * offset).to_array(), cells.iter().fold(0, |m, c| m | 1 << c));
|
||||
}
|
||||
let hid = inside(mesh, centre, n, seed);
|
||||
let buried = |c: u32| inside(mesh, at(c) + n * offset, n, seed ^ (c + 1).wrapping_mul(0x9e37_79b9));
|
||||
if cells.is_empty() {
|
||||
return (centre.to_array(), if hid { 0 } else { CENTRE });
|
||||
}
|
||||
let corners: Vec<u32> = cells.iter().copied().filter(|c| [0, 3, 12, 15].contains(c)).collect();
|
||||
let mixed = corners.iter().any(|&c| buried(c) != hid) || (corners.is_empty() && cells.len() < 16);
|
||||
let open = if !mixed { if hid { 0 } else { cells.iter().fold(0, |m, c| m | 1 << c) } } else { cells.iter().filter(|&&c| !buried(c)).fold(0, |m, c| m | 1 << c) };
|
||||
if open == 0 { (centre.to_array(), if hid { 0 } else { CENTRE }) } else { ((p + n * offset).to_array(), open) }
|
||||
}
|
||||
|
||||
/// p moved along its triangle until it's `gap` from each edge, or by `most` (half a texel: its own footprint; a needle
|
||||
/// narrower than the gap would send it to its far end). A chart's
|
||||
/// edge band takes its texels from the edge itself, and a point on the edge of a floor is in the plane of the wall
|
||||
/// standing on it: its rays started in that wall and half of them left the room.
|
||||
pub(crate) fn off_edges([a, b, c]: [Vec3; 3], p: Vec3, gap: f32, most: f32) -> Vec3 {
|
||||
fn off_edges([a, b, c]: [Vec3; 3], p: Vec3, gap: f32, most: f32) -> Vec3 {
|
||||
let n = (b - a).cross(c - a);
|
||||
let area = n.length_squared().max(f32::MIN_POSITIVE);
|
||||
// barycentric weights, each raised to what stands `gap` from the edge opposite its corner (its height: area / edge)
|
||||
|
||||
@@ -100,7 +100,7 @@ fn a_point_on_an_edge_is_moved_off_it_and_never_far() {
|
||||
fn texels_inside_the_slab_are_marked_and_those_in_the_open_are_not() {
|
||||
let t = texels(&set(), &request(16.0, 1024)).unwrap();
|
||||
let (mut sunk, mut open, mut under) = (0, 0, 0);
|
||||
for (x, &inside) in t.layout.texels.iter().zip(&t.inside()) {
|
||||
for (x, &inside) in t.layout.texels.iter().zip(&t.inside) {
|
||||
let [px, py, pz] = x.p;
|
||||
if (-0.18..-0.02).contains(&py) && px.abs() < 0.26 && pz.abs() < 0.26 {
|
||||
// the block's sides within the slab's thickness, away from its faces
|
||||
@@ -123,7 +123,7 @@ fn texels_inside_the_slab_are_marked_and_those_in_the_open_are_not() {
|
||||
#[test]
|
||||
fn the_same_model_gives_the_same_texels() {
|
||||
let (a, b) = (texels(&set(), &request(16.0, 1024)).unwrap(), texels(&set(), &request(16.0, 1024)).unwrap());
|
||||
assert!(a.layout == b.layout && a.origin == b.origin && a.open == b.open);
|
||||
assert!(a.layout == b.layout && a.origin == b.origin && a.inside == b.inside);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -143,11 +143,11 @@ fn measured() {
|
||||
let layout = raea_sys_atlas::layout(&glb, &request(64.0, 4096)).unwrap();
|
||||
let t1 = std::time::Instant::now();
|
||||
let t = texels(&glb, &request(64.0, 4096)).unwrap();
|
||||
let inside = t.inside().iter().filter(|&&i| i).count();
|
||||
let inside = t.inside.iter().filter(|&&i| i).count();
|
||||
if let Ok(out) = std::env::var("RAEA_BAKE_OUT") {
|
||||
// the atlas: grey where a texel is in the open, red where it's inside, black where there's none (a PPM)
|
||||
let mut img = vec![0u8; (layout.w * layout.h * 3) as usize];
|
||||
for (x, &i) in t.layout.texels.iter().zip(&t.inside()) {
|
||||
for (x, &i) in t.layout.texels.iter().zip(&t.inside) {
|
||||
let k = 3 * (x.y as usize * layout.w as usize + x.x as usize);
|
||||
img[k..k + 3].copy_from_slice(if i { &[230, 40, 30] } else { &[150, 150, 150] });
|
||||
}
|
||||
|
||||
@@ -4,86 +4,32 @@
|
||||
//! systems/rt's from a Bevy render world; the kernel's WGSL (wgsl/diffuse.wgsl) is a module rt can include as it is.
|
||||
//! A device without ray queries is refused with the reason, and the composition renders unbaked.
|
||||
|
||||
pub mod glossy;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
/// What a triangle sends on: its base colour (times its texture's, when it has one) and the light it gives off, linear RGB;
|
||||
/// how much of it is a metal, how rough its glossy layers are, and the F0 of the dielectric layer over the rest (0: none,
|
||||
/// and with no metal either it's Lambert).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
/// What a triangle sends on: the share of light it reflects (diffuse) and the light it gives off, linear RGB.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Surface {
|
||||
pub albedo: [f32; 3],
|
||||
pub emission: [f32; 3],
|
||||
pub metallic: f32,
|
||||
pub roughness: f32,
|
||||
pub f0: f32,
|
||||
/// its texture's place in `World::textures`
|
||||
pub texture: Option<u32>,
|
||||
}
|
||||
|
||||
/// A colour texture: sRGB, 8 bits a channel (red in the low byte), top row first.
|
||||
pub struct Image {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub rgba: Vec<u32>,
|
||||
}
|
||||
|
||||
/// The world a bake traces: triangles in world space, each with its surface; a UV a vertex (or none at all).
|
||||
/// The world a bake traces: triangles in world space, each with its surface.
|
||||
pub struct World<'a> {
|
||||
pub positions: &'a [[f32; 3]],
|
||||
pub triangles: &'a [[u32; 3]],
|
||||
pub surfaces: &'a [Surface],
|
||||
pub uvs: &'a [[f32; 2]],
|
||||
pub textures: &'a [Image],
|
||||
}
|
||||
|
||||
/// The sky: a panorama (its middle straight ahead, -Z) at its strength, turned counter-clockwise from above.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Sky {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// linear RGB, top row first
|
||||
pub rgb: Vec<[f32; 3]>,
|
||||
pub strength: f32,
|
||||
pub rotation: f32,
|
||||
}
|
||||
|
||||
impl Sky {
|
||||
/// One light from everywhere.
|
||||
pub fn even(rgb: [f32; 3]) -> Sky {
|
||||
Sky { width: 1, height: 1, rgb: vec![rgb], strength: 1.0, rotation: 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// The sun: out at the texel (it stays live), in at every bounce after.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Sun {
|
||||
/// toward it
|
||||
pub dir: [f32; 3],
|
||||
/// its irradiance on a surface facing it, linear RGB, in the sky's units
|
||||
pub irradiance: [f32; 3],
|
||||
/// half its disk's angle, radians
|
||||
pub half_angle: f32,
|
||||
}
|
||||
|
||||
/// A texel that starts only at its point (`Starts::open`).
|
||||
pub const CENTRE: u32 = 1 << 16;
|
||||
|
||||
/// What's traced from: each texel's point (BK2, already off its surface) and normal; the two sides of its footprint,
|
||||
/// and which of the 4 x 4 points over it are open (a bit each, row by row; `CENTRE` alone for its point only, 0 when it's
|
||||
/// inside other geometry and left at zero for BK4 to fill); and the offset each bounce leaves its surface by.
|
||||
/// What's traced from: each texel's origin (BK2, already off its surface), its normal, and whether it's inside other
|
||||
/// geometry (left at zero for BK4 to fill), and the offset each bounce leaves its surface by.
|
||||
pub struct Starts<'a> {
|
||||
pub origin: &'a [[f32; 3]],
|
||||
pub normal: &'a [[f32; 3]],
|
||||
pub sides: &'a [[[f32; 3]; 2]],
|
||||
pub open: &'a [u32],
|
||||
pub inside: &'a [bool],
|
||||
pub offset: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Settings {
|
||||
/// samples a texel
|
||||
pub samples: u32,
|
||||
@@ -91,13 +37,13 @@ pub struct Settings {
|
||||
pub bounces: u32,
|
||||
/// samples a texel in each pass: a pass short enough that the machine stays responsive
|
||||
pub per_pass: u32,
|
||||
pub sky: Sky,
|
||||
pub sun: Option<Sun>,
|
||||
/// the sky's light, linear RGB (the composition's <Environment> comes in BK3's next step)
|
||||
pub sky: [f32; 3],
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self { samples: 512, bounces: 4, per_pass: 16, sky: Sky::even([1.0; 3]), sun: None }
|
||||
Self { samples: 512, bounces: 4, per_pass: 16, sky: [1.0; 3] }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,15 +53,8 @@ const CHUNK: u32 = 1 << 18;
|
||||
/// The light reaching each texel (the mean its cosine-weighted rays bring back), in `from`'s order; inside texels 0.
|
||||
pub fn trace(world: &World, from: &Starts, s: &Settings, progress: &mut dyn FnMut(u32, u32)) -> Result<Vec<[f32; 3]>, String> {
|
||||
let n = from.origin.len();
|
||||
if from.normal.len() != n || from.open.len() != n || from.sides.len() != n || world.surfaces.len() != world.triangles.len() {
|
||||
return Err("trace: the texels' origins, normals, sides and open starts, and the triangles' surfaces, must match".into());
|
||||
}
|
||||
if s.sky.rgb.is_empty() || s.sky.rgb.len() != (s.sky.width * s.sky.height) as usize {
|
||||
return Err("trace: the sky's picture doesn't match its size".into());
|
||||
}
|
||||
let textured = world.surfaces.iter().any(|s| s.texture.is_some());
|
||||
if (textured && world.uvs.len() != world.positions.len()) || world.surfaces.iter().any(|s| s.texture.is_some_and(|t| t as usize >= world.textures.len())) {
|
||||
return Err("trace: a textured surface needs its texture and a UV on every vertex".into());
|
||||
if from.normal.len() != n || from.inside.len() != n || world.surfaces.len() != world.triangles.len() {
|
||||
return Err("trace: the texels' origins, normals and inside marks, and the triangles' surfaces, must match".into());
|
||||
}
|
||||
if n == 0 || world.triangles.is_empty() {
|
||||
return Ok(vec![[0.0; 3]; n]);
|
||||
@@ -140,27 +79,9 @@ fn dispatch(device: &wgpu::Device, queue: &wgpu::Queue, world: &World, from: &St
|
||||
let n = from.origin.len();
|
||||
let tlas = accel(device, queue, world);
|
||||
let vec4 = |v: [f32; 3], w: f32| [v[0], v[1], v[2], w];
|
||||
let mut uvs = world.uvs.to_vec();
|
||||
uvs.resize(world.positions.len(), [0.0; 2]);
|
||||
let positions: Vec<[f32; 4]> = world.positions.iter().zip(&uvs).map(|(p, uv)| vec4(*p, uv[0])).collect();
|
||||
let vs: Vec<f32> = uvs.iter().map(|uv| uv[1]).collect();
|
||||
let firsts: Vec<u32> = world.textures.iter().scan(0u32, |at, t| Some(std::mem::replace(at, *at + t.rgba.len() as u32))).collect();
|
||||
let surfaces: Vec<[u32; 16]> = world.surfaces.iter().map(|s| {
|
||||
let tex = s.texture.map_or([0; 4], |k| [1, firsts[k as usize], world.textures[k as usize].width, world.textures[k as usize].height]);
|
||||
let mut row = [0u32; 16];
|
||||
for k in 0..3 {
|
||||
(row[k], row[4 + k]) = (s.albedo[k].to_bits(), s.emission[k].to_bits());
|
||||
}
|
||||
row[8..12].copy_from_slice(&tex);
|
||||
row[12..15].copy_from_slice(&[s.metallic, s.roughness, s.f0].map(f32::to_bits));
|
||||
row
|
||||
}).collect();
|
||||
let mut images: Vec<u32> = world.textures.iter().flat_map(|t| t.rgba.iter().copied()).collect();
|
||||
if images.is_empty() {
|
||||
images.push(0);
|
||||
}
|
||||
let sky: Vec<[f32; 4]> = s.sky.rgb.iter().map(|c| vec4(c.map(|x| x * s.sky.strength), 0.0)).chain(glossy::table()).collect();
|
||||
let texels: Vec<[f32; 4]> = (0..n).flat_map(|i| [vec4(from.origin[i], f32::from_bits(from.open[i])), vec4(from.normal[i], 0.0), vec4(from.sides[i][0], 0.0), vec4(from.sides[i][1], 0.0)]).collect();
|
||||
let positions: Vec<[f32; 4]> = world.positions.iter().map(|p| vec4(*p, 1.0)).collect();
|
||||
let surfaces: Vec<[f32; 4]> = world.surfaces.iter().flat_map(|s| [vec4(s.albedo, 0.0), vec4(s.emission, 0.0)]).collect();
|
||||
let texels: Vec<[f32; 4]> = (0..n).flat_map(|i| [vec4(from.origin[i], from.inside[i] as u32 as f32), vec4(from.normal[i], 0.0)]).collect();
|
||||
let storage = |label: &str, bytes: &[u8], usage: wgpu::BufferUsages| device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents: bytes, usage: wgpu::BufferUsages::STORAGE | usage });
|
||||
let index: Vec<u32> = world.triangles.iter().flatten().copied().collect();
|
||||
let bufs = [
|
||||
@@ -170,34 +91,24 @@ fn dispatch(device: &wgpu::Device, queue: &wgpu::Queue, world: &World, from: &St
|
||||
storage("lightbake texels", bytemuck::cast_slice(&texels), wgpu::BufferUsages::empty()),
|
||||
storage("lightbake accum", &vec![0u8; n * 16], wgpu::BufferUsages::COPY_SRC),
|
||||
];
|
||||
let more = [
|
||||
storage("lightbake vs", bytemuck::cast_slice(&vs), wgpu::BufferUsages::empty()),
|
||||
storage("lightbake textures", bytemuck::cast_slice(&images), wgpu::BufferUsages::empty()),
|
||||
storage("lightbake sky", bytemuck::cast_slice(&sky), wgpu::BufferUsages::empty()),
|
||||
];
|
||||
let params = device.create_buffer(&wgpu::BufferDescriptor { label: Some("lightbake params"), size: 80, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
|
||||
let src = format!("enable wgpu_ray_query;\n{}\n{}\n{}", include_str!("wgsl/diffuse.wgsl"), include_str!("wgsl/glossy.wgsl"), include_str!("wgsl/trace.wgsl"));
|
||||
let params = device.create_buffer(&wgpu::BufferDescriptor { label: Some("lightbake params"), size: 48, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
|
||||
let src = format!("enable wgpu_ray_query;\n{}\n{}", include_str!("wgsl/diffuse.wgsl"), include_str!("wgsl/trace.wgsl"));
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("lightbake trace"), source: wgpu::ShaderSource::Wgsl(src.into()) });
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("lightbake trace"), layout: None, module: &module, entry_point: Some("main"), compilation_options: Default::default(), cache: None });
|
||||
let mut entries = vec![wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::AccelerationStructure(&tlas) }];
|
||||
let all = bufs.iter().chain(std::iter::once(¶ms)).chain(&more);
|
||||
entries.extend(all.enumerate().map(|(k, b)| wgpu::BindGroupEntry { binding: k as u32 + 1, resource: b.as_entire_binding() }));
|
||||
entries.extend(bufs.iter().enumerate().map(|(k, b)| wgpu::BindGroupEntry { binding: k as u32 + 1, resource: b.as_entire_binding() }));
|
||||
entries.push(wgpu::BindGroupEntry { binding: 6, resource: params.as_entire_binding() });
|
||||
let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("lightbake trace"), layout: &pipeline.get_bind_group_layout(0), entries: &entries });
|
||||
let passes = s.samples.div_ceil(s.per_pass.max(1));
|
||||
for pass in 0..passes {
|
||||
let per = s.per_pass.max(1).min(s.samples - pass * s.per_pass.max(1));
|
||||
for first in (0..n as u32).step_by(CHUNK as usize) {
|
||||
let mut p = [0u32; 20];
|
||||
if let Some(sun) = &s.sun {
|
||||
let l = sun.dir.iter().map(|x| x * x).sum::<f32>().sqrt();
|
||||
for k in 0..3 {
|
||||
(p[k], p[4 + k]) = ((sun.dir[k] / l).to_bits(), sun.irradiance[k].to_bits());
|
||||
}
|
||||
p[3] = sun.half_angle.cos().to_bits();
|
||||
let mut p = [0u32; 12];
|
||||
for (k, v) in s.sky.iter().enumerate() {
|
||||
p[k] = v.to_bits();
|
||||
}
|
||||
let end = (first + CHUNK).min(n as u32);
|
||||
(p[8], p[9], p[10], p[11], p[12], p[13]) = (end, pass * s.per_pass.max(1), per, s.bounces, from.offset.to_bits(), first);
|
||||
(p[14], p[15], p[16]) = (s.sky.width, s.sky.height, s.sky.rotation.to_bits());
|
||||
(p[4], p[5], p[6], p[7], p[8], p[9]) = (end, pass, per, s.bounces, from.offset.to_bits(), first);
|
||||
queue.write_buffer(¶ms, 0, bytemuck::cast_slice(&p));
|
||||
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("lightbake pass") });
|
||||
{
|
||||
@@ -213,11 +124,6 @@ fn dispatch(device: &wgpu::Device, queue: &wgpu::Queue, world: &World, from: &St
|
||||
}
|
||||
let acc = read(device, queue, &bufs[4], n * 16)?;
|
||||
let acc: &[[f32; 4]] = bytemuck::cast_slice(&acc);
|
||||
// a pass the GPU dropped, or light that isn't a number, is an error here: never kept as a dark or a broken map
|
||||
let wrong = acc.iter().zip(from.open).filter(|(a, open)| a[3] != if **open == 0 { 0.0 } else { s.samples as f32 } || !a.iter().all(|c| c.is_finite())).count();
|
||||
if wrong > 0 {
|
||||
return Err(format!("the light bake's trace came back wrong on {wrong} of {n} texels (not {} samples each, or light that isn't finite)", s.samples));
|
||||
}
|
||||
Ok(acc.iter().map(|a| if a[3] > 0.0 { [a[0] / a[3], a[1] / a[3], a[2] / a[3]] } else { [0.0; 3] }).collect())
|
||||
}
|
||||
|
||||
@@ -256,3 +162,6 @@ fn read(device: &wgpu::Device, queue: &wgpu::Queue, buf: &wgpu::Buffer, size: us
|
||||
let bytes = back.slice(..).get_mapped_range().map_err(|e| format!("the light bake's readback: {e}"))?.to_vec();
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,107 @@
|
||||
use super::*;
|
||||
use crate::texels::tests::{cuboid, glb, set};
|
||||
use crate::texels::{request, texels};
|
||||
|
||||
fn world(mesh: &parry3d::shape::TriMesh, surfaces: &[Surface]) -> (Vec<[f32; 3]>, Vec<[u32; 3]>, Vec<Surface>) {
|
||||
(mesh.vertices().iter().map(|v| v.to_array()).collect(), mesh.indices().to_vec(), surfaces.to_vec())
|
||||
}
|
||||
|
||||
/// The light on t's texels, each triangle's surface given by its centroid.
|
||||
fn run(t: &crate::texels::Texels, surface: impl Fn([f32; 3]) -> Surface, s: &Settings) -> Vec<[f32; 3]> {
|
||||
let v = t.mesh.vertices();
|
||||
let surfaces: Vec<Surface> = t.mesh.indices().iter().map(|i| surface(std::array::from_fn(|k| i.iter().map(|&j| v[j as usize][k]).sum::<f32>() / 3.0))).collect();
|
||||
let (p, i, s2) = world(&t.mesh, &surfaces);
|
||||
let normal: Vec<[f32; 3]> = t.layout.texels.iter().map(|x| x.n).collect();
|
||||
let starts = Starts { origin: &t.origin, normal: &normal, inside: &t.inside, offset: t.offset };
|
||||
trace(&World { positions: &p, triangles: &i, surfaces: &s2 }, &starts, s, &mut |_, _| {}).unwrap()
|
||||
}
|
||||
|
||||
/// A white set under a white sky: whatever bounces, every texel's light is the sky's (a white furnace). The block sunk
|
||||
/// in the slab and the box set by its node make real concave corners; paths there bounce until they find the sky.
|
||||
#[test]
|
||||
fn a_white_furnace_is_the_sky_at_every_texel() {
|
||||
let t = texels(&set(), &request(8.0, 1024)).unwrap();
|
||||
let s = Settings { samples: 64, bounces: 64, per_pass: 16, sky: [1.0; 3] };
|
||||
let light = run(&t, |_| Surface { albedo: [1.0; 3], emission: [0.0; 3] }, &s);
|
||||
let open: Vec<[f32; 3]> = light.iter().zip(&t.inside).filter(|(_, i)| !**i).map(|(l, _)| *l).collect();
|
||||
let off = open.iter().filter(|l| l.iter().any(|c| (c - 1.0).abs() > 0.01)).count();
|
||||
println!("furnace: {off} of {} off by more than 1%", open.len());
|
||||
let worst = open.iter().flatten().fold(0.0f32, |m, c| m.max((c - 1.0).abs()));
|
||||
println!("furnace: worst {worst}, mean {}", open.iter().map(|l| l[0]).sum::<f32>() / open.len() as f32);
|
||||
assert!(open.len() > 500 && off == 0, "{off} of {} texels more than 1% off the sky, worst {worst}", open.len());
|
||||
}
|
||||
|
||||
/// A black wall 40 m long and 2 m high on a black floor under a white sky: the floor's light at a distance d from its
|
||||
/// foot is what the sky leaves, 1/2 (1 + d / sqrt(d^2 + h^2)) (an endless wall's form factor), which only cosine-weighted
|
||||
/// rays give.
|
||||
#[test]
|
||||
fn a_walls_shadow_on_the_floor_is_its_form_factor() {
|
||||
let set = glb(&[(cuboid([0.0, -0.1, -20.0], [6.0, 0.0, 20.0]), [0.0; 3]), (cuboid([-0.2, -0.1, -20.0], [0.0, 2.0, 20.0]), [0.0; 3])]);
|
||||
let t = texels(&set, &request(4.0, 1024)).unwrap();
|
||||
let light = run(&t, |_| Surface { albedo: [0.0; 3], emission: [0.0; 3] }, &Settings { samples: 512, ..Settings::default() });
|
||||
for d in [0.5f32, 1.0, 2.0, 4.0] {
|
||||
let v: Vec<(f32, f32)> = t.layout.texels.iter().zip(&light).filter(|(x, _)| x.p[1].abs() < 1e-3 && x.n[1] > 0.9 && x.p[2].abs() < 4.0 && (x.p[0] - d).abs() < 0.13).map(|(x, l)| (0.5 * (1.0 + x.p[0] / (x.p[0] * x.p[0] + 4.0).sqrt()), l[0])).collect();
|
||||
let (want, got) = v.iter().fold((0.0, 0.0), |(a, b), (w, g)| (a + w / v.len() as f32, b + g / v.len() as f32));
|
||||
println!("wall: d {d} m: {got:.4} for {want:.4} over {} texels", v.len());
|
||||
assert!(v.len() > 20 && (got - want).abs() < 0.01, "{d} m from the wall the floor gets {got}, not {want}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A closed box glowing 1 all round with an albedo of a half: every point inside gets 1 + 1/2 + 1/4 ... = 2.
|
||||
#[test]
|
||||
fn a_glowing_box_adds_up_its_bounces() {
|
||||
let inward = cuboid([-1.0; 3], [1.0; 3]).into_iter().map(|[a, b, c]| [a, c, b]).collect();
|
||||
let t = texels(&glb(&[(inward, [0.0; 3])]), &request(8.0, 1024)).unwrap();
|
||||
let light = run(&t, |_| Surface { albedo: [0.5; 3], emission: [1.0; 3] }, &Settings { samples: 64, bounces: 64, per_pass: 16, sky: [0.0; 3] });
|
||||
let mean = light.iter().zip(&t.inside).filter(|(_, i)| !**i).map(|(l, _)| l[0]).sum::<f32>() / t.inside.iter().filter(|i| !**i).count() as f32;
|
||||
println!("box: {mean:.4} for 2, {} of {} texels marked inside", t.inside.iter().filter(|i| **i).count(), t.inside.len());
|
||||
assert!((mean - 2.0).abs() < 0.01, "the glowing box's light is {mean}, not 2");
|
||||
}
|
||||
|
||||
/// A white floor beside a red wall: the floor near the wall gets redder than the floor far from it.
|
||||
#[test]
|
||||
fn a_red_wall_bleeds_onto_the_floor() {
|
||||
let floor = cuboid([-1.0, -0.1, -2.0], [1.0, 0.0, 2.0]);
|
||||
let wall = cuboid([-1.0, 0.0, -2.0], [-0.9, 2.0, 2.0]);
|
||||
let t = texels(&glb(&[(floor, [0.0; 3]), (wall, [0.0; 3])]), &request(16.0, 1024)).unwrap();
|
||||
let red = |c: [f32; 3]| Surface { albedo: if c[1] > 0.5 { [0.9, 0.0, 0.0] } else { [0.9; 3] }, emission: [0.0; 3] };
|
||||
let light = run(&t, red, &Settings { samples: 128, bounces: 4, per_pass: 32, sky: [1.0; 3] });
|
||||
// floor top texels near the wall (x -0.9..-0.7) and far (x > 0.6)
|
||||
let mean = |near: bool| {
|
||||
let v: Vec<f32> = t.layout.texels.iter().zip(&light).zip(&t.inside).filter(|((x, _), i)| !**i && x.p[1].abs() < 1e-3 && x.n[1] > 0.9 && if near { x.p[0] < -0.7 } else { x.p[0] > 0.6 }).map(|((_, l), _)| l[1] / l[0]).collect();
|
||||
v.iter().sum::<f32>() / v.len() as f32
|
||||
};
|
||||
let (near, far) = (mean(true), mean(false));
|
||||
assert!(near < far * 0.97, "green over red near the red wall {near}, far from it {far}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_bake_gives_the_same_bytes() {
|
||||
let t = texels(&set(), &request(8.0, 1024)).unwrap();
|
||||
let s = Settings { samples: 16, per_pass: 8, ..Settings::default() };
|
||||
let surf = |c: [f32; 3]| Surface { albedo: [0.5 + 0.1 * c[0].abs().fract(); 3], emission: [0.0; 3] };
|
||||
let (a, b) = (run(&t, surf, &s), run(&t, surf, &s));
|
||||
assert!(a.iter().any(|l| l[0] > 0.1), "no light at all");
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mismatched_inputs_are_refused() {
|
||||
let starts = Starts { origin: &[[0.0; 3]], normal: &[], inside: &[], offset: 1e-4 };
|
||||
assert!(trace(&World { positions: &[], triangles: &[], surfaces: &[] }, &starts, &Settings::default(), &mut |_, _| {}).is_err());
|
||||
}
|
||||
|
||||
/// The measured run (docs/bake.feature BK3): RAEA_BAKE_GLB at 64 texels a metre, every surface 0.7 grey under a white
|
||||
/// sky, RAEA_BAKE_SAMPLES (default 512) a texel: the trace's time alone.
|
||||
/// `cargo test -p raea-sys-lightbake trace::tests::measured -- --ignored --nocapture`
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn measured() {
|
||||
let glb = std::fs::read(std::env::var("RAEA_BAKE_GLB").expect("RAEA_BAKE_GLB: a .glb")).unwrap();
|
||||
let samples = std::env::var("RAEA_BAKE_SAMPLES").ok().and_then(|v| v.parse().ok()).unwrap_or(512);
|
||||
let t = texels(&glb, &request(64.0, 4096)).unwrap();
|
||||
let t0 = std::time::Instant::now();
|
||||
let light = run(&t, |_| Surface { albedo: [0.7; 3], emission: [0.0; 3] }, &Settings { samples, ..Settings::default() });
|
||||
let lit = light.iter().zip(&t.inside).filter(|(_, i)| !**i).map(|(l, _)| l[0]).collect::<Vec<_>>();
|
||||
println!("{} texels, {} triangles, {samples} samples, 4 bounces: {:.2} s, mean light {:.3}", light.len(), t.mesh.indices().len(), t0.elapsed().as_secs_f64(), lit.iter().sum::<f32>() / lit.len() as f32);
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
use raea_sys_lighttrace::*;
|
||||
use crate::texels::tests::{cuboid, glb, set};
|
||||
use crate::texels::{request, starts, texels};
|
||||
use parry3d::glamx::Vec3;
|
||||
|
||||
fn world(mesh: &parry3d::shape::TriMesh, surfaces: &[Surface]) -> (Vec<[f32; 3]>, Vec<[u32; 3]>, Vec<Surface>) {
|
||||
(mesh.vertices().iter().map(|v| v.to_array()).collect(), mesh.indices().to_vec(), surfaces.to_vec())
|
||||
}
|
||||
|
||||
/// The light on t's texels, each triangle's surface given by its centroid.
|
||||
fn run(t: &crate::texels::Texels, surface: impl Fn([f32; 3]) -> Surface, s: &Settings) -> Vec<[f32; 3]> {
|
||||
let v = t.mesh.vertices();
|
||||
let surfaces: Vec<Surface> = t.mesh.indices().iter().map(|i| surface(std::array::from_fn(|k| i.iter().map(|&j| v[j as usize][k]).sum::<f32>() / 3.0))).collect();
|
||||
let (p, i, s2) = world(&t.mesh, &surfaces);
|
||||
let normal: Vec<[f32; 3]> = t.layout.texels.iter().map(|x| x.n).collect();
|
||||
let starts = Starts { origin: &t.origin, normal: &normal, sides: &t.sides, open: &t.open, offset: t.offset };
|
||||
trace(&World { positions: &p, triangles: &i, surfaces: &s2, uvs: &[], textures: &[] }, &starts, s, &mut |_, _| {}).unwrap()
|
||||
}
|
||||
|
||||
/// A white set under a white sky: whatever bounces, every texel's light is the sky's (a white furnace). The block sunk
|
||||
/// in the slab and the box set by its node make real concave corners; paths there bounce until they find the sky.
|
||||
#[test]
|
||||
fn a_white_furnace_is_the_sky_at_every_texel() {
|
||||
let t = texels(&set(), &request(8.0, 1024)).unwrap();
|
||||
let s = Settings { samples: 64, bounces: 64, per_pass: 16, sky: Sky::even([1.0; 3]), ..Settings::default() };
|
||||
let light = run(&t, |_| Surface { albedo: [1.0; 3], ..Surface::default() }, &s);
|
||||
let open: Vec<[f32; 3]> = light.iter().zip(&t.inside()).filter(|(_, i)| !**i).map(|(l, _)| *l).collect();
|
||||
let off = open.iter().filter(|l| l.iter().any(|c| (c - 1.0).abs() > 0.01)).count();
|
||||
println!("furnace: {off} of {} off by more than 1%", open.len());
|
||||
let worst = open.iter().flatten().fold(0.0f32, |m, c| m.max((c - 1.0).abs()));
|
||||
println!("furnace: worst {worst}, mean {}", open.iter().map(|l| l[0]).sum::<f32>() / open.len() as f32);
|
||||
assert!(open.len() > 500 && off == 0, "{off} of {} texels more than 1% off the sky, worst {worst}", open.len());
|
||||
}
|
||||
|
||||
/// A black wall 40 m long and 2 m high on a black floor under a white sky: the floor's light at a distance d from its
|
||||
/// foot is what the sky leaves, 1/2 (1 + d / sqrt(d^2 + h^2)) (an endless wall's form factor), which only cosine-weighted
|
||||
/// rays give.
|
||||
#[test]
|
||||
fn a_walls_shadow_on_the_floor_is_its_form_factor() {
|
||||
let set = glb(&[(cuboid([0.0, -0.1, -20.0], [6.0, 0.0, 20.0]), [0.0; 3]), (cuboid([-0.2, -0.1, -20.0], [0.0, 2.0, 20.0]), [0.0; 3])]);
|
||||
let t = texels(&set, &request(4.0, 1024)).unwrap();
|
||||
let light = run(&t, |_| Surface { albedo: [0.0; 3], ..Surface::default() }, &Settings { samples: 512, ..Settings::default() });
|
||||
for d in [0.5f32, 1.0, 2.0, 4.0] {
|
||||
let v: Vec<(f32, f32)> = t.layout.texels.iter().zip(&light).filter(|(x, _)| x.p[1].abs() < 1e-3 && x.n[1] > 0.9 && x.p[2].abs() < 4.0 && (x.p[0] - d).abs() < 0.13).map(|(x, l)| (0.5 * (1.0 + x.p[0] / (x.p[0] * x.p[0] + 4.0).sqrt()), l[0])).collect();
|
||||
let (want, got) = v.iter().fold((0.0, 0.0), |(a, b), (w, g)| (a + w / v.len() as f32, b + g / v.len() as f32));
|
||||
println!("wall: d {d} m: {got:.4} for {want:.4} over {} texels", v.len());
|
||||
assert!(v.len() > 20 && (got - want).abs() < 0.01, "{d} m from the wall the floor gets {got}, not {want}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A closed box glowing 1 all round with an albedo of a half: every point inside gets 1 + 1/2 + 1/4 ... = 2.
|
||||
#[test]
|
||||
fn a_glowing_box_adds_up_its_bounces() {
|
||||
let inward = cuboid([-1.0; 3], [1.0; 3]).into_iter().map(|[a, b, c]| [a, c, b]).collect();
|
||||
let t = texels(&glb(&[(inward, [0.0; 3])]), &request(8.0, 1024)).unwrap();
|
||||
let light = run(&t, |_| Surface { albedo: [0.5; 3], emission: [1.0; 3], ..Surface::default() }, &Settings { samples: 64, bounces: 64, per_pass: 16, sky: Sky::even([0.0; 3]), ..Settings::default() });
|
||||
let mean = light.iter().zip(&t.inside()).filter(|(_, i)| !**i).map(|(l, _)| l[0]).sum::<f32>() / t.inside().iter().filter(|i| !**i).count() as f32;
|
||||
println!("box: {mean:.4} for 2, {} of {} texels marked inside", t.inside().iter().filter(|i| **i).count(), t.inside().len());
|
||||
assert!((mean - 2.0).abs() < 0.01, "the glowing box's light is {mean}, not 2");
|
||||
}
|
||||
|
||||
/// A white floor beside a red wall: the floor near the wall gets redder than the floor far from it.
|
||||
#[test]
|
||||
fn a_red_wall_bleeds_onto_the_floor() {
|
||||
let floor = cuboid([-1.0, -0.1, -2.0], [1.0, 0.0, 2.0]);
|
||||
let wall = cuboid([-1.0, 0.0, -2.0], [-0.9, 2.0, 2.0]);
|
||||
let t = texels(&glb(&[(floor, [0.0; 3]), (wall, [0.0; 3])]), &request(16.0, 1024)).unwrap();
|
||||
let red = |c: [f32; 3]| Surface { albedo: if c[1] > 0.5 { [0.9, 0.0, 0.0] } else { [0.9; 3] }, ..Surface::default() };
|
||||
let light = run(&t, red, &Settings { samples: 128, bounces: 4, per_pass: 32, sky: Sky::even([1.0; 3]), ..Settings::default() });
|
||||
// floor top texels near the wall (x -0.9..-0.7) and far (x > 0.6)
|
||||
let mean = |near: bool| {
|
||||
let v: Vec<f32> = t.layout.texels.iter().zip(&light).zip(&t.inside()).filter(|((x, _), i)| !**i && x.p[1].abs() < 1e-3 && x.n[1] > 0.9 && if near { x.p[0] < -0.7 } else { x.p[0] > 0.6 }).map(|((_, l), _)| l[1] / l[0]).collect();
|
||||
v.iter().sum::<f32>() / v.len() as f32
|
||||
};
|
||||
let (near, far) = (mean(true), mean(false));
|
||||
assert!(near < far * 0.97, "green over red near the red wall {near}, far from it {far}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_bake_gives_the_same_bytes() {
|
||||
let t = texels(&set(), &request(8.0, 1024)).unwrap();
|
||||
let s = Settings { samples: 16, per_pass: 8, ..Settings::default() };
|
||||
let surf = |c: [f32; 3]| Surface { albedo: [0.5 + 0.1 * c[0].abs().fract(); 3], ..Surface::default() };
|
||||
let (a, b) = (run(&t, surf, &s), run(&t, surf, &s));
|
||||
assert!(a.iter().any(|l| l[0] > 0.1), "no light at all");
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mismatched_inputs_are_refused() {
|
||||
let starts = Starts { origin: &[[0.0; 3]], normal: &[], sides: &[], open: &[], offset: 1e-4 };
|
||||
assert!(trace(&World { positions: &[], triangles: &[], surfaces: &[], uvs: &[], textures: &[] }, &starts, &Settings::default(), &mut |_, _| {}).is_err());
|
||||
}
|
||||
|
||||
/// A floor, and something on it: the light on a texel 0.4 m a side whose centre is 0.1 m under its edge at x = 0, by
|
||||
/// its starts, and which of them are open.
|
||||
fn half_covered(on_it: &[crate::texels::tests::Tri], samples_at_centre: bool) -> (f32, u32) {
|
||||
let floor = [[-40.0, 0.0, -40.0], [-40.0, 0.0, 80.0], [80.0, 0.0, -40.0]];
|
||||
let mesh = parry3d::shape::TriMesh::new(std::iter::once(floor).chain(on_it.iter().copied()).flatten().map(Vec3::from).collect(), (0..on_it.len() as u32 + 1).map(|k| [3 * k, 3 * k + 1, 3 * k + 2]).collect()).unwrap();
|
||||
let sides = [[0.4, 0.0, 0.0], [0.0, 0.0, 0.4]];
|
||||
let (origin, open) = starts(&mesh, floor.map(Vec3::from), Vec3::new(0.1, 0.0, 0.0), Vec3::Y, sides.map(Vec3::from), 1e-4, 7, false);
|
||||
let (p, i, s) = world(&mesh, &vec![Surface::default(); mesh.indices().len()]);
|
||||
let st = Starts { origin: &[origin], normal: &[[0.0, 1.0, 0.0]], sides: &[sides], open: &[if samples_at_centre { CENTRE } else { open }], offset: 1e-4 };
|
||||
let l = trace(&World { positions: &p, triangles: &i, surfaces: &s, uvs: &[], textures: &[] }, &st, &Settings { samples: 4096, ..Settings::default() }, &mut |_, _| {}).unwrap();
|
||||
(l[0][0], open)
|
||||
}
|
||||
|
||||
/// A texel with a sheet 0.2 mm over three quarters of it (a stack's ledge): a quarter of the sky, as Cycles' jittered
|
||||
/// samples see, where its centre alone sees nothing.
|
||||
#[test]
|
||||
fn a_texel_under_a_sheets_edge_sees_the_part_that_is_open() {
|
||||
let sheet = cuboid([0.0, 0.0002, -10.0], [10.0, 0.0052, 10.0]);
|
||||
let (centre, _) = half_covered(&sheet, true);
|
||||
let (over, open) = half_covered(&sheet, false);
|
||||
println!("ledge: centre {centre:.4}, over the texel {over:.4} for 0.249, open {open:#x}");
|
||||
assert!(centre < 0.01 && (over - 0.249).abs() < 0.01 && open == 0xffff, "{centre} {over} {open:#x}");
|
||||
}
|
||||
|
||||
/// A texel three quarters inside a block sunk in the floor: only its open quarter counts, not that quarter averaged with
|
||||
/// the dark inside.
|
||||
#[test]
|
||||
fn a_texel_half_buried_is_lit_by_its_open_part() {
|
||||
let block = cuboid([0.0, -1.0, -10.0], [10.0, 1.0, 10.0]);
|
||||
let (over, open) = half_covered(&block, false);
|
||||
println!("block: {over:.4} over its open part, open {open:#x}");
|
||||
assert!(open == 0x1111 && (0.48..0.58).contains(&over), "{over} {open:#x}");
|
||||
}
|
||||
|
||||
/// A 40 m floor lit by the sun at 45 degrees and nothing else: a point 0.1 m over it looking down gets the sunlit
|
||||
/// floor's light, albedo x irradiance x cos 45 / pi; a point on the floor gets nothing, its own sun being live.
|
||||
#[test]
|
||||
fn the_sun_lights_what_it_bounces_to_and_not_the_texel_itself() {
|
||||
let p = [[-20.0, 0.0, -20.0], [20.0, 0.0, -20.0], [20.0, 0.0, 20.0], [-20.0, 0.0, 20.0]];
|
||||
let surfaces = [Surface { albedo: [0.5; 3], ..Surface::default() }; 2];
|
||||
let world = World { positions: &p, triangles: &[[0, 2, 1], [0, 3, 2]], surfaces: &surfaces, uvs: &[], textures: &[] };
|
||||
let starts = Starts { origin: &[[0.0, 0.1, 0.0], [8.0, 1e-4, 0.0]], normal: &[[0.0, -1.0, 0.0], [0.0, 1.0, 0.0]], sides: &[[[0.0; 3]; 2]; 2], open: &[CENTRE; 2], offset: 1e-4 };
|
||||
let sun = Sun { dir: [1.0, 1.0, 0.0], irradiance: [std::f32::consts::PI, 0.0, 0.0], half_angle: 0.0046 };
|
||||
let s = Settings { samples: 4096, per_pass: 64, bounces: 1, sky: Sky::even([0.0; 3]), sun: Some(sun), ..Settings::default() };
|
||||
let l = trace(&world, &starts, &s, &mut |_, _| {}).unwrap();
|
||||
println!("sun: over the floor {:?} for 0.3536, on it {:?} for 0", l[0], l[1]);
|
||||
assert!((l[0][0] - 0.3536).abs() < 0.005 && l[0][1] == 0.0 && l[1] == [0.0; 3], "{l:?}");
|
||||
}
|
||||
|
||||
/// A sky lit only in its left-to-right middle half (straight ahead, -Z): a wall facing -Z gets the light, one facing +Z
|
||||
/// none; turned a quarter counter-clockwise from above the light comes from -X.
|
||||
#[test]
|
||||
fn the_panorama_faces_ahead_and_turns_counter_clockwise() {
|
||||
let set = glb(&[(cuboid([-0.5, 0.0, -0.5], [0.5, 1.0, 0.5]), [0.0; 3])]);
|
||||
let t = texels(&set, &request(8.0, 512)).unwrap();
|
||||
let sky = |rotation| Sky { width: 64, height: 1, rgb: (0..64).map(|x| if (16..48).contains(&x) { [1.0; 3] } else { [0.0; 3] }).collect(), strength: 1.0, rotation };
|
||||
let faces = |rotation: f32| {
|
||||
let light = run(&t, |_| Surface::default(), &Settings { samples: 256, sky: sky(rotation), ..Settings::default() });
|
||||
[[0.0, 0.0, -1.0], [0.0, 0.0, 1.0], [-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]].map(|n: [f32; 3]| {
|
||||
let v: Vec<f32> = t.layout.texels.iter().zip(&light).filter(|(x, _)| (0..3).all(|k| (x.n[k] - n[k]).abs() < 0.1)).map(|(_, l)| l[0]).collect();
|
||||
v.iter().sum::<f32>() / v.len() as f32
|
||||
})
|
||||
};
|
||||
let (ahead, turned) = (faces(0.0), faces(std::f32::consts::FRAC_PI_2));
|
||||
println!("sky: -Z +Z -X +X {ahead:?}, turned {turned:?}");
|
||||
assert!(ahead[0] > 0.97 && ahead[1] < 0.03 && (ahead[2] - 0.5).abs() < 0.03, "{ahead:?}");
|
||||
assert!(turned[2] > 0.97 && turned[3] < 0.03 && (turned[0] - 0.5).abs() < 0.03, "{turned:?}");
|
||||
}
|
||||
|
||||
/// Points looking straight up under an even sky, 134 million rays: one in 2^24 goes exactly up, where the panorama's
|
||||
/// longitude is atan2(0, 0), which Metal gave as NaN (a whole texel lost on the atelier at 1024 samples).
|
||||
#[test]
|
||||
fn a_ray_straight_up_sees_the_sky() {
|
||||
let p = [[0.0, -5.0, 0.0], [1.0, -5.0, 0.0], [0.0, -5.0, 1.0]];
|
||||
let world = World { positions: &p, triangles: &[[0, 1, 2]], surfaces: &[Surface::default()], uvs: &[], textures: &[] };
|
||||
let n = 16384;
|
||||
let (origin, normal, sides, open) = (vec![[0.0; 3]; n], vec![[0.0, 1.0, 0.0]; n], vec![[[0.0; 3]; 2]; n], vec![CENTRE; n]);
|
||||
let l = trace(&world, &Starts { origin: &origin, normal: &normal, sides: &sides, open: &open, offset: 1e-4 }, &Settings { samples: 8192, per_pass: 128, ..Settings::default() }, &mut |_, _| {}).unwrap();
|
||||
assert_eq!(l.iter().flatten().filter(|v| !v.is_finite()).count(), 0, "values that aren't finite");
|
||||
assert!(l.iter().all(|c| (c[0] - 1.0).abs() < 1e-3), "not the sky: {:?}", l.iter().find(|c| (c[0] - 1.0).abs() >= 1e-3));
|
||||
}
|
||||
|
||||
/// A floor textured red on its left half and green on its right (sRGB 188 is 0.5 linear): the underside of a plate
|
||||
/// over each half sees that half's colour.
|
||||
#[test]
|
||||
fn a_textured_floor_bounces_its_texture() {
|
||||
let (mut p, mut tri, mut uv) = (vec![], vec![], vec![]);
|
||||
for (x, z) in [(-20.0f32, -20.0f32), (20.0, -20.0), (20.0, 20.0), (-20.0, 20.0)] {
|
||||
p.push([x, 0.0, z]);
|
||||
uv.push([(x + 20.0) / 40.0, (z + 20.0) / 40.0]);
|
||||
}
|
||||
tri.extend([[0u32, 2, 1], [0, 3, 2]]);
|
||||
let image = Image { width: 2, height: 1, rgba: vec![0xff00_00bc, 0xff00_bc00] };
|
||||
let surfaces = vec![Surface { albedo: [1.0; 3], texture: Some(0), ..Surface::default() }; 2];
|
||||
let origin: Vec<[f32; 3]> = [-10.0, 10.0].into_iter().map(|x| [x, 0.1, 0.0]).collect();
|
||||
let starts = Starts { origin: &origin, normal: &[[0.0, -1.0, 0.0]; 2], sides: &[[[0.0; 3]; 2]; 2], open: &[CENTRE; 2], offset: 1e-4 };
|
||||
let s = Settings { samples: 4096, per_pass: 64, bounces: 2, ..Settings::default() };
|
||||
let l = trace(&World { positions: &p, triangles: &tri, surfaces: &surfaces, uvs: &uv, textures: &[image] }, &starts, &s, &mut |_, _| {}).unwrap();
|
||||
println!("textured: {l:?}");
|
||||
assert!((l[0][0] - 0.5029).abs() < 0.01 && l[0][1] < 0.01 && (l[1][1] - 0.5029).abs() < 0.01 && l[1][0] < 0.01, "{l:?}");
|
||||
let bad = trace(&World { positions: &p, triangles: &tri, surfaces: &surfaces, uvs: &[], textures: &[] }, &starts, &s, &mut |_, _| {});
|
||||
assert!(bad.is_err());
|
||||
}
|
||||
|
||||
/// The measured run (docs/bake.feature BK3): RAEA_BAKE_GLB at 64 texels a metre, every surface 0.7 grey under a white
|
||||
/// sky, RAEA_BAKE_SAMPLES (default 512) a texel: the trace's time alone.
|
||||
/// `cargo test -p raea-sys-lightbake trace_tests::measured -- --ignored --nocapture`
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn measured() {
|
||||
let glb = std::fs::read(std::env::var("RAEA_BAKE_GLB").expect("RAEA_BAKE_GLB: a .glb")).unwrap();
|
||||
let samples = std::env::var("RAEA_BAKE_SAMPLES").ok().and_then(|v| v.parse().ok()).unwrap_or(512);
|
||||
let t = texels(&glb, &request(64.0, 4096)).unwrap();
|
||||
let t0 = std::time::Instant::now();
|
||||
let light = run(&t, |_| Surface { albedo: [0.7; 3], ..Surface::default() }, &Settings { samples, ..Settings::default() });
|
||||
let lit = light.iter().zip(&t.inside()).filter(|(_, i)| !**i).map(|(l, _)| l[0]).collect::<Vec<_>>();
|
||||
println!("{} texels, {} triangles, {samples} samples, 4 bounces: {:.2} s, mean light {:.3}", light.len(), t.mesh.indices().len(), t0.elapsed().as_secs_f64(), lit.iter().sum::<f32>() / lit.len() as f32);
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,93 @@
|
||||
// The light that bounces, per texel (docs/bake.feature BK3): paths from the texel's origin through the model's own
|
||||
// triangles (one BLAS, one TLAS) by wgpu's ray queries. What a texel keeps is the mean light its cosine-weighted rays
|
||||
// bring back, so the lightmap times a surface's albedo is the light it sends on. At each hit the surface's emission
|
||||
// is added and the path goes on weighted by its albedo (Lambert, diffuse.wgsl); a miss sees the sky; after the
|
||||
// second bounce Russian roulette ends paths by their weight, unbiased. Passes add to `accum` (rgb, samples).
|
||||
|
||||
struct Params {
|
||||
sky: vec4<f32>,
|
||||
count: u32,
|
||||
pass_index: u32,
|
||||
per_pass: u32,
|
||||
bounces: u32,
|
||||
offset: f32,
|
||||
// the first texel of this dispatch (a bake's texels go in chunks)
|
||||
first: u32,
|
||||
_pad1: f32,
|
||||
_pad2: f32,
|
||||
}
|
||||
|
||||
struct Surface {
|
||||
albedo: vec4<f32>,
|
||||
emission: vec4<f32>,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var tlas: acceleration_structure;
|
||||
@group(0) @binding(1) var<storage, read> positions: array<vec4<f32>>;
|
||||
@group(0) @binding(2) var<storage, read> indices: array<u32>;
|
||||
@group(0) @binding(3) var<storage, read> surfaces: array<Surface>;
|
||||
// per texel: origin (w: 1 when inside other geometry) and normal
|
||||
@group(0) @binding(4) var<storage, read> texels: array<vec4<f32>>;
|
||||
@group(0) @binding(5) var<storage, read_write> accum: array<vec4<f32>>;
|
||||
@group(0) @binding(6) var<uniform> params: Params;
|
||||
|
||||
// The nearest hit. Its own function: a ray_query declared in a loop is zeroed again each turn, which naga writes for
|
||||
// Metal as an assignment Metal's intersection_query deletes.
|
||||
fn nearest(o: vec3<f32>, d: vec3<f32>) -> RayIntersection {
|
||||
var rq: ray_query;
|
||||
rayQueryInitialize(&rq, tlas, RayDesc(0u, 0xffu, 0.0, 1.0e30, o, d));
|
||||
while (rayQueryProceed(&rq)) {}
|
||||
return rayQueryGetCommittedIntersection(&rq);
|
||||
}
|
||||
|
||||
@compute @workgroup_size(64)
|
||||
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
let i = params.first + gid.x;
|
||||
if (i >= params.count) {
|
||||
return;
|
||||
}
|
||||
let at = texels[2u * i];
|
||||
if (at.w > 0.5) {
|
||||
return;
|
||||
}
|
||||
let n0 = texels[2u * i + 1u].xyz;
|
||||
var sum = vec3<f32>(0.0);
|
||||
for (var s = 0u; s < params.per_pass; s = s + 1u) {
|
||||
var rng = raea_hash(i * 0x9e3779b9u ^ raea_hash(params.pass_index * params.per_pass + s));
|
||||
var o = at.xyz;
|
||||
var n = n0;
|
||||
var weight = vec3<f32>(1.0);
|
||||
var light = vec3<f32>(0.0);
|
||||
for (var b = 0u; b < params.bounces; b = b + 1u) {
|
||||
let d = raea_diffuse_sample(n, vec2<f32>(raea_rand(&rng), raea_rand(&rng)));
|
||||
let hit = nearest(o, d);
|
||||
if (hit.kind == RAY_QUERY_INTERSECTION_NONE) {
|
||||
light = light + weight * params.sky.rgb;
|
||||
break;
|
||||
}
|
||||
let p = hit.primitive_index;
|
||||
let srf = surfaces[p];
|
||||
light = light + weight * srf.emission.rgb;
|
||||
let a = positions[indices[3u * p]].xyz;
|
||||
let bb = positions[indices[3u * p + 1u]].xyz;
|
||||
let c = positions[indices[3u * p + 2u]].xyz;
|
||||
var ng = normalize(cross(bb - a, c - a));
|
||||
if (dot(ng, d) > 0.0) {
|
||||
ng = -ng;
|
||||
}
|
||||
let w = hit.barycentrics;
|
||||
o = a * (1.0 - w.x - w.y) + bb * w.x + c * w.y + ng * params.offset;
|
||||
n = ng;
|
||||
weight = weight * srf.albedo.rgb;
|
||||
if (b >= 2u) {
|
||||
let q = max(weight.r, max(weight.g, weight.b));
|
||||
if (raea_rand(&rng) >= q) {
|
||||
break;
|
||||
}
|
||||
weight = weight / q;
|
||||
}
|
||||
}
|
||||
sum = sum + light;
|
||||
}
|
||||
accum[i] = accum[i] + vec4<f32>(sum, f32(params.per_pass));
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
[package]
|
||||
name = "raea-sys-lighttrace"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "Light paths traced on the GPU: what a triangle bounces, the sky, the sun and emission, by wgpu's ray queries (docs/bake.feature BK3)"
|
||||
|
||||
[dependencies]
|
||||
# the process's one shared GPU device, and wgpu's ray queries on it
|
||||
raea-gpu-device = { path = "../../gpu/device" }
|
||||
wgpu = "=30.0.1"
|
||||
bytemuck = "1"
|
||||
pollster = "0.4"
|
||||
@@ -1,120 +0,0 @@
|
||||
//! The GGX the kernel's glossy bounces use (docs/bake.feature BK3), on the CPU: the directional albedo a rough metal or
|
||||
//! dielectric layer keeps, tabled, so the kernel can give back what a single scatter loses and keep what's under a
|
||||
//! dielectric's layer. The functions are Cycles' (github.com/blender/cycles, BSD-3-Clause, see NOTICE:
|
||||
//! kernel/closure/bsdf_microfacet.h, bsdf_util.h, kernel/sample/mapping.h), written here in Rust and in wgsl/glossy.wgsl until
|
||||
//! tools/cycles-port is on main, and held to its own output below.
|
||||
|
||||
use std::f32::consts::PI;
|
||||
|
||||
/// Rows and columns of the table: roughness, then the cosine to the viewer.
|
||||
pub const STEPS: usize = 32;
|
||||
|
||||
pub fn lambda(a2: f32, c: f32) -> f32 {
|
||||
0.5 * ((1.0 + a2 * (1.0 / (c * c) - 1.0).max(0.0)).sqrt() - 1.0)
|
||||
}
|
||||
|
||||
/// Cycles' bsdf_G: the combined masking and shadowing of the two directions.
|
||||
pub fn g2(a2: f32, ci: f32, co: f32) -> f32 {
|
||||
1.0 / (1.0 + lambda(a2, ci) + lambda(a2, co))
|
||||
}
|
||||
|
||||
pub fn d(a2: f32, c: f32) -> f32 {
|
||||
let c2 = (c * c).min(1.0);
|
||||
a2 / (PI * (1.0 - c2 + a2 * c2).powi(2))
|
||||
}
|
||||
|
||||
/// A microfacet normal from the ones visible from `wi` (Heitz 2018, as Cycles samples it), in the shading frame.
|
||||
pub fn vndf(wi: [f32; 3], [ax, ay]: [f32; 2], r: [f32; 2]) -> [f32; 3] {
|
||||
let n = |v: [f32; 3]| {
|
||||
let l = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
|
||||
[v[0] / l, v[1] / l, v[2] / l]
|
||||
};
|
||||
let w = n([ax * wi[0], ay * wi[1], wi[2]]);
|
||||
let l2 = w[0] * w[0] + w[1] * w[1];
|
||||
let t1 = if l2 > 1e-7 { [-w[1] / l2.sqrt(), w[0] / l2.sqrt(), 0.0] } else { [1.0, 0.0, 0.0] };
|
||||
let t2 = [w[1] * t1[2] - w[2] * t1[1], w[2] * t1[0] - w[0] * t1[2], w[0] * t1[1] - w[1] * t1[0]];
|
||||
let (a1, b1) = (2.0 * r[0] - 1.0, 2.0 * r[1] - 1.0);
|
||||
let (rad, phi) = if a1 == 0.0 && b1 == 0.0 { (0.0, 0.0) } else if a1 * a1 > b1 * b1 { (a1, PI / 4.0 * (b1 / a1)) } else { (b1, PI / 2.0 - PI / 4.0 * (a1 / b1)) };
|
||||
let x = rad * phi.cos();
|
||||
let s = 0.5 * (1.0 + w[2]);
|
||||
let y = (1.0 - x * x).max(0.0).sqrt() * (1.0 - s) + rad * phi.sin() * s;
|
||||
let z = (1.0 - x * x - y * y).max(0.0).sqrt();
|
||||
let h: [f32; 3] = std::array::from_fn(|k| x * t1[k] + y * t2[k] + z * w[k]);
|
||||
n([ax * h[0], ay * h[1], h[2].max(0.0)])
|
||||
}
|
||||
|
||||
/// Where a dielectric of IOR 1.5 stands between its F0 (0.04) and 1 (Cycles' fresnel_dielectric_cos).
|
||||
pub fn dielectric(c: f32) -> f32 {
|
||||
let g = (1.25 + c * c).sqrt();
|
||||
let (a, b) = ((g - c) / (g + c), (c * (g + c) - 1.0) / (c * (g - c) + 1.0));
|
||||
((0.5 * a * a * (1.0 + b * b) - 0.04) / 0.96).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// The table, a row a roughness (0 to 1) and a column the square root of the cosine to the viewer (0 to 1): a white lobe's albedo (single scatter), the part of
|
||||
/// it Schlick's (1 - c)^5 weighs, the part `dielectric` weighs, and the row's mean albedo over the cosines.
|
||||
pub fn table() -> Vec<[f32; 4]> {
|
||||
const N: u32 = 1024;
|
||||
let mut out = vec![[0.0f32; 4]; STEPS * STEPS];
|
||||
for (i, row) in out.chunks_mut(STEPS).enumerate() {
|
||||
let a = (i as f32 / (STEPS - 1) as f32).powi(2).max(1e-3);
|
||||
for (j, cell) in row.iter_mut().enumerate() {
|
||||
let mu = (j as f32 / (STEPS - 1) as f32).powi(2).max(1e-4);
|
||||
let wo = [(1.0 - mu * mu).sqrt(), 0.0, mu];
|
||||
for k in 0..N {
|
||||
let h = vndf(wo, [a, a], [(k as f32 + 0.5) / N as f32, k.reverse_bits() as f32 / 4294967296.0]);
|
||||
let c = wo[0] * h[0] + wo[1] * h[1] + wo[2] * h[2];
|
||||
let z = 2.0 * c * h[2] - wo[2];
|
||||
if z > 0.0 {
|
||||
let g = g2(a * a, z, mu) * (1.0 + lambda(a * a, mu)) / N as f32;
|
||||
for (sum, f) in cell.iter_mut().zip([1.0, (1.0 - c).clamp(0.0, 1.0).powi(5), dielectric(c)]) {
|
||||
*sum += f * g;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// the mean of E over the cosines, 2 mu dmu with mu = y^2, a trapezoid between the nodes
|
||||
let y = |j: usize| j as f32 / (STEPS - 1) as f32;
|
||||
let at = |j: usize| 4.0 * row[j][0] * y(j).powi(3);
|
||||
let mean = (1..STEPS).map(|j| (at(j - 1) + at(j)) / 2.0 / (STEPS - 1) as f32).sum::<f32>();
|
||||
row.iter_mut().for_each(|c| c[3] = mean);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Cases of tools/cycles-port's oracle (Cycles 6ea3d9bcd81a, built as C++): the two alphas, a cosine, wi, the disk's two
|
||||
/// numbers; then D, G (with wi.z), lambda and the sampled normal.
|
||||
#[test]
|
||||
fn the_ggx_is_cycles() {
|
||||
#[rustfmt::skip]
|
||||
let cases: [([f32; 2], f32, [f32; 3], [f32; 2], [f32; 3], [f32; 3]); 3] = [
|
||||
([0.030198643, 0.0263823215], 0.547724247, [0.16266492, -0.762519956, 0.626181662], [0.495889366, 0.548348844], [0.000591959222, 0.999115765, 0.000531673431], [-0.000647504407, 0.00159752904, 0.999998569]),
|
||||
([0.982707202, 0.182275727], 0.108885549, [-0.725084424, 0.324529201, 0.607398808], [0.56473726, 0.590222061], [0.307646185, 0.187696591, 4.01351929], [-0.52829963, -0.00960596558, 0.849003613]),
|
||||
([0.342305034, 0.509727001], 0.47010687, [-0.767907083, -0.492557466, 0.409519047], [0.999985695, 0.494606256], [0.0575702898, 0.817566216, 0.0943524837], [0.531567872, -0.846983373, 0.0074105612]),
|
||||
];
|
||||
for (a, c, wi, r, want, normal) in cases {
|
||||
let a2 = a[0] * a[0];
|
||||
for (got, want) in [d(a2, c), g2(a2, c, wi[2]), lambda(a2, c)].into_iter().zip(want) {
|
||||
assert!((got - want).abs() <= (2e-5 * want.abs()).max(2e-6), "{got} for {want}");
|
||||
}
|
||||
let h = vndf(wi, a, r);
|
||||
assert!(h.iter().zip(normal).all(|(g, w)| (g - w).abs() < 1e-4), "{h:?} for {normal:?}");
|
||||
}
|
||||
// the dielectric at eta 1.5 the kernel fixes, by its own closed forms: F0 at normal incidence and 1 at grazing
|
||||
assert!(dielectric(1.0).abs() < 1e-5 && (dielectric(0.0) - 1.0).abs() < 1e-5);
|
||||
}
|
||||
|
||||
/// A white lobe keeps all its light when it's smooth, loses some when rough, and its parts stay inside it.
|
||||
#[test]
|
||||
fn the_table_is_a_lobes_albedo() {
|
||||
let t = table();
|
||||
assert!((t[STEPS - 1][0] - 1.0).abs() < 0.01, "smooth, face on: {}", t[STEPS - 1][0]);
|
||||
// at alpha 1, seen face on, D is 1/pi and G 2z/(1 + z): the albedo is 1 - ln 2
|
||||
let rough = t[STEPS * STEPS - 1][0];
|
||||
assert!((rough - (1.0 - std::f32::consts::LN_2)).abs() < 2e-3, "rough, face on: {rough}");
|
||||
assert!(t.iter().all(|c| c[0] <= 1.002 && c[1] <= c[0] && c[2] <= c[0] && c[3] > 0.0 && c[3] <= 1.002));
|
||||
}
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
use crate::glossy::{STEPS, d, dielectric, g2, table};
|
||||
use crate::*;
|
||||
|
||||
// (a floor of 20 km puts its rays' starts within its own rounding at this offset, and they meet it)
|
||||
const FLOOR: f32 = 400.0;
|
||||
|
||||
fn surface(base: f32, metallic: f32, roughness: f32, f0: f32) -> Surface {
|
||||
Surface { albedo: [base; 3], metallic, roughness, f0, ..Surface::default() }
|
||||
}
|
||||
|
||||
/// The light on a point half a metre over a wide floor, facing it, with a panel glowing 1 over it or not.
|
||||
fn over_a_floor(floor: Surface, panel: bool, s: &Settings) -> f32 {
|
||||
let mut p = vec![[-FLOOR, 0.0, -FLOOR], [-FLOOR, 0.0, 3.0 * FLOOR], [3.0 * FLOOR, 0.0, -FLOOR]];
|
||||
let mut t = vec![[0, 1, 2]];
|
||||
let mut surfaces = vec![floor];
|
||||
if panel {
|
||||
p.extend(PANEL);
|
||||
t.extend([[3, 4, 5], [3, 5, 6]]);
|
||||
surfaces.extend([Surface { emission: [1.0; 3], ..Surface::default() }; 2]);
|
||||
}
|
||||
let st = Starts { origin: &[[0.0, 0.5, 0.0]; 64], normal: &[[0.0, -1.0, 0.0]; 64], sides: &[[[0.0; 3]; 2]; 64], open: &[CENTRE; 64], offset: 1e-4 };
|
||||
let l = trace(&World { positions: &p, triangles: &t, surfaces: &surfaces, uvs: &[], textures: &[] }, &st, s, &mut |_, _| {}).unwrap();
|
||||
l.iter().map(|l| l[0]).sum::<f32>() / 64.0
|
||||
}
|
||||
|
||||
const PANEL: [[f32; 3]; 4] = [[2.0, 4.0, -2.0], [6.0, 4.0, -2.0], [6.0, 4.0, 2.0], [2.0, 4.0, 2.0]];
|
||||
const KINDS: [(&str, f32, f32, f32, f32); 5] = [("rough metal", 0.8, 1.0, 0.9, 0.0), ("smooth metal", 0.8, 1.0, 0.1, 0.0), ("plastic", 0.5, 0.0, 0.3, 0.04), ("half metal", 0.6, 0.5, 0.6, 0.04), ("chalk", 0.5, 0.0, 1.0, 0.0)];
|
||||
|
||||
/// What the kernel should send from wi to wo (its z the normal), the cosine included, after a turn of density `likely`.
|
||||
fn sent(t: &[[f32; 4]], (_, base, metallic, rough, f0): (&str, f32, f32, f32, f32), likely: f32, wo: [f32; 3], wi: [f32; 3]) -> f32 {
|
||||
let mu = wo[2];
|
||||
if wi[2] <= 0.0 || mu <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
if metallic == 0.0 && f0 == 0.0 {
|
||||
return base * wi[2] / std::f32::consts::PI;
|
||||
}
|
||||
let a = (rough * rough).max(0.5 * (1.0 - likely).max(0.0).sqrt());
|
||||
let at = [mu.sqrt(), a.sqrt()].map(|x| x.min(1.0) * (STEPS - 1) as f32);
|
||||
let [j, i] = at.map(|x| (x as usize).min(STEPS - 2));
|
||||
let (f, g) = (at[0] - j as f32, at[1] - i as f32);
|
||||
let cell = |k: usize| (t[i * STEPS + j][k] * (1.0 - f) + t[i * STEPS + j + 1][k] * f) * (1.0 - g) + (t[(i + 1) * STEPS + j][k] * (1.0 - f) + t[(i + 1) * STEPS + j + 1][k] * f) * g;
|
||||
let mix = |a: f32, b: f32, s: f32| a + (b - a) * s;
|
||||
let kept = |fss: f32| 1.0 + fss * cell(3) / (1.0 - fss * (1.0 - cell(3))) * (1.0 - cell(0)) / cell(0);
|
||||
let h: [f32; 3] = std::array::from_fn(|k| wo[k] + wi[k]);
|
||||
let l = h.iter().map(|x| x * x).sum::<f32>().sqrt();
|
||||
let c = (0..3).map(|k| wo[k] * h[k] / l).sum::<f32>();
|
||||
let coat = if f0 > 0.0 { (1.0 - metallic) * kept(mix(f0, 1.0, (0.0894977 - 0.04) / 0.96)) } else { 0.0 };
|
||||
let diffuse = base * (1.0 - metallic - coat * (f0 * cell(0) + (1.0 - f0) * cell(2))).max(0.0);
|
||||
let fresnel = metallic * kept(mix(base, 1.0, 1.0 / 21.0)) * mix(base, 1.0, (1.0 - c).clamp(0.0, 1.0).powi(5)) + coat * mix(f0, 1.0, dielectric(c));
|
||||
diffuse * wi[2] / std::f32::consts::PI + fresnel * d(a * a, h[2] / l) * g2(a * a, mu, wi[2]) / (4.0 * mu)
|
||||
}
|
||||
|
||||
/// The mean over the point's own rays of `at` (the ray from the floor up to the point, its cosine over pi, where it hit).
|
||||
fn over_rays(at: impl Fn([f32; 3], f32, [f32; 3], u32) -> f32) -> f32 {
|
||||
const N: u32 = 1 << 20;
|
||||
let total: f64 = (0..N).map(|k| {
|
||||
let (u, v) = ((k as f32 + 0.5) / N as f32, k.reverse_bits() as f32 / 4294967296.0);
|
||||
let (r, phi, z) = (u.sqrt(), std::f32::consts::TAU * v, (1.0 - u).sqrt().max(1e-3));
|
||||
let wo = [r * phi.cos(), r * phi.sin(), z];
|
||||
at(wo, z / std::f32::consts::PI, [-wo[0] * 0.5 / z, -wo[1] * 0.5 / z, 0.0], k) as f64
|
||||
}).sum();
|
||||
(total / N as f64) as f32
|
||||
}
|
||||
|
||||
/// Whatever the surface, white ones send on all they get: a point over one sees the sky's 1.
|
||||
#[test]
|
||||
fn white_glossy_surfaces_send_on_all_their_light() {
|
||||
let s = Settings { samples: 4096, per_pass: 64, bounces: 4, ..Settings::default() };
|
||||
let mut off = 0;
|
||||
for (name, metallic, f0) in [("metal", 1.0, 0.0), ("dielectric", 0.0, 0.04), ("half", 0.5, 0.04)] {
|
||||
for rough in [0.1, 0.5, 0.75, 1.0] {
|
||||
let l = over_a_floor(surface(1.0, metallic, rough, f0), false, &s);
|
||||
println!("{name} of roughness {rough}: {l:.4} for 1");
|
||||
off += ((l - 1.0).abs() >= 0.01) as u32;
|
||||
}
|
||||
}
|
||||
assert_eq!(off, 0, "white surfaces off by 1% or more");
|
||||
}
|
||||
|
||||
/// The sun off a floor, against the same light summed on the CPU with the functions held to Cycles' (glossy.rs).
|
||||
#[test]
|
||||
fn the_suns_glint_is_the_lobes_own() {
|
||||
let t = table();
|
||||
let toward = [0.6f32, 0.8, 0.0];
|
||||
let sun = Sun { dir: toward, irradiance: [1.0; 3], half_angle: 1e-3 };
|
||||
let s = Settings { samples: 16384, per_pass: 64, bounces: 1, sky: Sky::even([0.0; 3]), sun: Some(sun) };
|
||||
for kind in KINDS {
|
||||
let got = over_a_floor(surface(kind.1, kind.2, kind.3, kind.4), false, &s);
|
||||
// the floor's frame here: x, z of the world, then up
|
||||
let want = over_rays(|wo, likely, _, _| sent(&t, kind, likely, wo, [toward[0], toward[2], toward[1]]));
|
||||
println!("sun, {}: {got:.5} for {want:.5}", kind.0);
|
||||
assert!((got / want - 1.0).abs() < 0.01, "{}: {got} for {want}", kind.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A glowing panel found by the paths' own turns, against the same light summed over the panel.
|
||||
#[test]
|
||||
fn a_panels_reflection_is_found_by_its_turns() {
|
||||
let t = table();
|
||||
let s = Settings { samples: 16384, per_pass: 64, bounces: 2, sky: Sky::even([0.0; 3]), sun: None };
|
||||
let mut off = 0;
|
||||
for kind in KINDS {
|
||||
let got = over_a_floor(surface(kind.1, kind.2, kind.3, kind.4), true, &s);
|
||||
let want = over_rays(|wo, likely, p, k| {
|
||||
let [u, v] = [0.754_877_666_246_693, 0.569_840_290_998_053].map(|g: f64| (k as f64 * g).fract() as f32);
|
||||
let to = [PANEL[0][0] + 4.0 * u - p[0], PANEL[0][2] + 4.0 * v - p[1], PANEL[0][1]];
|
||||
let r2 = to.iter().map(|x| x * x).sum::<f32>();
|
||||
let wi = to.map(|x| x / r2.sqrt());
|
||||
sent(&t, kind, likely, wo, wi) * wi[2] * 16.0 / r2
|
||||
});
|
||||
println!("panel, {}: {got:.5} for {want:.5}", kind.0);
|
||||
off += ((got / want - 1.0).abs() >= 0.015) as u32;
|
||||
}
|
||||
assert_eq!(off, 0, "kinds off by 1.5% or more");
|
||||
}
|
||||
|
||||
/// The share of rays that meet the plane they leave, off a tilted triangle `far` m from the origin, at an offset of `rel`
|
||||
/// of that: from the texels themselves, and from where a bounce lands (a point over it, the plane half grey).
|
||||
fn meets_itself(far: f32, rel: f32) -> [f32; 2] {
|
||||
let [u, v] = [[0.64f32, 0.48, 0.6], [-0.6, 0.8, 0.0]];
|
||||
let n = [-0.48f32, -0.36, 0.8];
|
||||
let at = |a: f32, b: f32, h: f32| -> [f32; 3] { std::array::from_fn(|k| [0.6, 0.64, 0.48][k] * far + (u[k] * a + v[k] * b + n[k] * h) * far) };
|
||||
let p = [at(-0.4, -0.4, 0.0), at(1.0, -0.4, 0.0), at(-0.4, 1.0, 0.0)];
|
||||
let hash = |k: u32| (k.wrapping_mul(0x9e37_79b9) >> 8) as f32 / 16777216.0;
|
||||
let origin: Vec<[f32; 3]> = (0..4096).map(|k| at(0.3 * hash(k) - 0.2, 0.3 * hash(k + 7919) - 0.2, rel)).collect();
|
||||
let over: Vec<[f32; 3]> = (0..4096).map(|k| at(0.1 * hash(k) - 0.1, 0.1 * hash(k + 7919) - 0.1, 1e-3)).collect();
|
||||
let run = |from: &[[f32; 3]], normal: [f32; 3], albedo: f32, bounces: u32| {
|
||||
let m = from.len();
|
||||
let st = Starts { origin: from, normal: &vec![normal; m], sides: &vec![[[0.0; 3]; 2]; m], open: &vec![CENTRE; m], offset: rel * far };
|
||||
let l = trace(&World { positions: &p, triangles: &[[0, 1, 2]], surfaces: &[Surface { albedo: [albedo; 3], ..Surface::default() }], uvs: &[], textures: &[] }, &st, &Settings { samples: 256, bounces, ..Settings::default() }, &mut |_, _| {}).unwrap();
|
||||
l.iter().map(|l| l[0]).sum::<f32>() / m as f32
|
||||
};
|
||||
let direct = 1.0 - run(&origin, n, 0.0, 1);
|
||||
// half grey once: 0.5 of the sky; every further meeting halves it
|
||||
let bounced = 1.0 - run(&over, n.map(|c| -c), 0.5, 3) / 0.5;
|
||||
[direct, bounced]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_surface_never_meets_itself() {
|
||||
let mut off = 0;
|
||||
for far in [1.0, 15.0, 300.0, 5000.0] {
|
||||
for rel in [1e-5, 1e-6, 3e-7, 1e-7] {
|
||||
let [direct, bounced] = meets_itself(far, rel);
|
||||
println!("{far} m, offset {rel:e} of it: {direct:.5} of the texels' rays, {bounced:.5} of the bounces'");
|
||||
off += (rel >= 1e-6 && (direct.abs() > 1e-3 || bounced.abs() > 5e-3)) as u32;
|
||||
}
|
||||
}
|
||||
assert_eq!(off, 0);
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
// The glossy layers of a surface (docs/bake.feature BK3), after Cycles' Principled: a metal (GGX, F82 with a white edge
|
||||
// tint, which is Schlick) and a dielectric layer of IOR 1.5 over Lambert. The GGX, its sampling and the Fresnels are
|
||||
// Cycles' (github.com/blender/cycles 6ea3d9bcd81a, kernel/closure/bsdf_microfacet.h, bsdf_util.h and
|
||||
// kernel/sample/mapping.h, BSD-3-Clause: see NOTICE), written here until tools/cycles-port is on main. What a single
|
||||
// scatter loses is given back from glossy.rs's table. It needs raea_layers_at(i), that table's cells, STEPS by STEPS:
|
||||
// by roughness and the cosine's square root: the albedo of a white lobe
|
||||
// (E), its Schlick part, its dielectric part, and E's mean over the cosines.
|
||||
|
||||
const RAEA_STEPS: i32 = 32;
|
||||
|
||||
fn raea_ggx_lambda(a2: f32, c: f32) -> f32 {
|
||||
return 0.5 * (sqrt(1.0 + a2 * max(1.0 / (c * c) - 1.0, 0.0)) - 1.0);
|
||||
}
|
||||
|
||||
fn raea_ggx_d(a2: f32, c: f32) -> f32 {
|
||||
let c2 = min(c * c, 1.0);
|
||||
let q = 1.0 - c2 + a2 * c2;
|
||||
return a2 / (3.141592654 * q * q);
|
||||
}
|
||||
|
||||
// A microfacet normal from the ones visible from w (Heitz 2018), in the shading frame (z the normal).
|
||||
fn raea_ggx_sample(w: vec3<f32>, a: f32, r: vec2<f32>) -> vec3<f32> {
|
||||
let v = normalize(vec3<f32>(a * w.x, a * w.y, w.z));
|
||||
let l2 = v.x * v.x + v.y * v.y;
|
||||
var t1 = vec3<f32>(1.0, 0.0, 0.0);
|
||||
if (l2 > 1e-7) {
|
||||
t1 = vec3<f32>(-v.y, v.x, 0.0) * inverseSqrt(l2);
|
||||
}
|
||||
let p = 2.0 * r - 1.0;
|
||||
var rad = 0.0;
|
||||
var phi = 0.0;
|
||||
if (p.x * p.x > p.y * p.y) {
|
||||
rad = p.x;
|
||||
phi = 0.785398163 * (p.y / p.x);
|
||||
} else if (p.y != 0.0) {
|
||||
rad = p.y;
|
||||
phi = 1.570796327 - 0.785398163 * (p.x / p.y);
|
||||
}
|
||||
let x = rad * cos(phi);
|
||||
let y = mix(sqrt(max(1.0 - x * x, 0.0)), rad * sin(phi), 0.5 * (1.0 + v.z));
|
||||
let h = x * t1 + y * cross(v, t1) + sqrt(max(1.0 - x * x - y * y, 0.0)) * v;
|
||||
return normalize(vec3<f32>(a * h.x, a * h.y, max(0.0, h.z)));
|
||||
}
|
||||
|
||||
// Where a dielectric of IOR 1.5 stands between its F0 and 1 at this cosine (Cycles' generalized Schlick, exponent < 0).
|
||||
fn raea_dielectric(cosine: f32) -> f32 {
|
||||
let c = abs(cosine);
|
||||
let g = sqrt(1.25 + c * c);
|
||||
let a = (g - c) / (g + c);
|
||||
let b = (c * (g + c) - 1.0) / (c * (g - c) + 1.0);
|
||||
return clamp((0.5 * a * a * (1.0 + b * b) - 0.04) / 0.96, 0.0, 1.0);
|
||||
}
|
||||
|
||||
fn raea_layer(rough: f32, mu: f32) -> vec4<f32> {
|
||||
let at = clamp(vec2<f32>(sqrt(mu), rough), vec2<f32>(0.0), vec2<f32>(1.0)) * f32(RAEA_STEPS - 1);
|
||||
let i = min(vec2<i32>(at), vec2<i32>(RAEA_STEPS - 2));
|
||||
let f = at - vec2<f32>(i);
|
||||
let k = i.y * RAEA_STEPS + i.x;
|
||||
return mix(mix(raea_layers_at(k), raea_layers_at(k + 1), f.x), mix(raea_layers_at(k + RAEA_STEPS), raea_layers_at(k + RAEA_STEPS + 1), f.x), f.y);
|
||||
}
|
||||
|
||||
// A surface seen from one direction: its lobes' weights, and how often the glossy ones are sampled.
|
||||
struct Lobes {
|
||||
diffuse: vec3<f32>,
|
||||
metal: vec3<f32>,
|
||||
base: vec3<f32>,
|
||||
f0: f32,
|
||||
coat: f32,
|
||||
a: f32,
|
||||
p: f32,
|
||||
}
|
||||
|
||||
// What the compensation multiplies a single scatter by (1 + Cycles' Fms times what's missing of the lobe).
|
||||
fn raea_kept(fss: vec3<f32>, t: vec4<f32>) -> vec3<f32> {
|
||||
return 1.0 + fss * t.w / (1.0 - fss * (1.0 - t.w)) * (1.0 - t.x) / t.x;
|
||||
}
|
||||
|
||||
// `gloss`: metallic, roughness, the dielectric's F0 (0: no such layer). `a_least`: the least alpha (filter glossy).
|
||||
fn raea_lobes(base: vec3<f32>, gloss: vec3<f32>, a_least: f32, mu: f32) -> Lobes {
|
||||
var l: Lobes;
|
||||
l.base = base;
|
||||
l.diffuse = base * (1.0 - gloss.x);
|
||||
if (gloss.x <= 0.0 && gloss.z <= 0.0) {
|
||||
return l;
|
||||
}
|
||||
l.a = max(max(gloss.y * gloss.y, a_least), 0.002);
|
||||
l.f0 = gloss.z;
|
||||
let t = raea_layer(sqrt(l.a), mu);
|
||||
l.metal = gloss.x * raea_kept(mix(base, vec3<f32>(1.0), 1.0 / 21.0), t);
|
||||
var seen = l.metal * (base * t.x + (1.0 - base) * t.y);
|
||||
if (gloss.z > 0.0) {
|
||||
// 0.05156: Cycles' average dielectric Fresnel at 1.5 (fresnel_dielectric_Fss) between F0 and 1
|
||||
l.coat = (1.0 - gloss.x) * raea_kept(vec3<f32>(mix(gloss.z, 1.0, 0.05156)), t).x;
|
||||
let c = l.coat * (gloss.z * t.x + (1.0 - gloss.z) * t.z);
|
||||
l.diffuse = base * max(1.0 - gloss.x - c, 0.0);
|
||||
seen = seen + c;
|
||||
}
|
||||
let g = dot(seen, vec3<f32>(1.0));
|
||||
l.p = g / max(g + dot(l.diffuse, vec3<f32>(1.0)), 1e-6);
|
||||
return l;
|
||||
}
|
||||
|
||||
// The light sent from wi to wo, cosine included, and (w) the density with which raea_lobes_sample picks wi.
|
||||
fn raea_lobes_eval(l: Lobes, wo: vec3<f32>, wi: vec3<f32>) -> vec4<f32> {
|
||||
if (wi.z <= 0.0) {
|
||||
return vec4<f32>(0.0);
|
||||
}
|
||||
let d = wi.z / 3.141592654;
|
||||
if (l.p <= 0.0) {
|
||||
return vec4<f32>(l.diffuse * d, d);
|
||||
}
|
||||
let h = normalize(wo + wi);
|
||||
let c = dot(wo, h);
|
||||
let a2 = l.a * l.a;
|
||||
let lo = raea_ggx_lambda(a2, wo.z);
|
||||
let one = raea_ggx_d(a2, h.z) / (4.0 * wo.z);
|
||||
let s5 = pow(clamp(1.0 - c, 0.0, 1.0), 5.0);
|
||||
let f = l.metal * mix(l.base, vec3<f32>(1.0), s5) + l.coat * mix(l.f0, 1.0, raea_dielectric(c));
|
||||
return vec4<f32>(l.diffuse * d + f * (one / (1.0 + lo + raea_ggx_lambda(a2, wi.z))), l.p * one / (1.0 + lo) + (1.0 - l.p) * d);
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
// The light that bounces, per texel (docs/bake.feature BK3): paths from the texel's origin through the model's own
|
||||
// triangles (one BLAS, one TLAS) by wgpu's ray queries. What a texel keeps is the mean light its cosine-weighted rays
|
||||
// bring back, so the lightmap times a surface's albedo is the light it sends on. At each hit the surface's emission
|
||||
// is added and the path goes on by its BSDF (Lambert, diffuse.wgsl, under the glossy layers of glossy.wgsl); a miss sees
|
||||
// the sky; after the second bounce Russian roulette ends paths by their weight, unbiased. As Cycles does by default
|
||||
// (filter glossy 1), a lobe is no sharper than its path's least likely turn: a caustic is blurred, not a firefly. Passes add to `accum` (rgb, samples).
|
||||
|
||||
struct Params {
|
||||
// toward the sun (w: the cosine of its half angle) and its irradiance facing it, all zero when there's none
|
||||
sun_dir: vec4<f32>,
|
||||
sun: vec4<f32>,
|
||||
count: u32,
|
||||
// the first sample of this pass (the random numbers are a sample's own)
|
||||
base: u32,
|
||||
per_pass: u32,
|
||||
bounces: u32,
|
||||
offset: f32,
|
||||
// the first texel of this dispatch (a bake's texels go in chunks)
|
||||
first: u32,
|
||||
sky_w: u32,
|
||||
sky_h: u32,
|
||||
rotation: f32,
|
||||
_pad0: f32,
|
||||
_pad1: f32,
|
||||
_pad2: f32,
|
||||
}
|
||||
|
||||
// tex: 1 when textured, then the texture's first word, width and height; gloss: metallic, roughness, the dielectric's F0
|
||||
struct Surface {
|
||||
albedo: vec4<f32>,
|
||||
emission: vec4<f32>,
|
||||
tex: vec4<u32>,
|
||||
gloss: vec4<f32>,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var tlas: acceleration_structure;
|
||||
// each vertex's place, and its u in w
|
||||
@group(0) @binding(1) var<storage, read> positions: array<vec4<f32>>;
|
||||
@group(0) @binding(2) var<storage, read> indices: array<u32>;
|
||||
@group(0) @binding(3) var<storage, read> surfaces: array<Surface>;
|
||||
// per texel: its point off the surface (w: which starts are open, see `start`), the hemisphere's normal, and its
|
||||
// footprint's two sides
|
||||
@group(0) @binding(4) var<storage, read> texels: array<vec4<f32>>;
|
||||
@group(0) @binding(5) var<storage, read_write> accum: array<vec4<f32>>;
|
||||
@group(0) @binding(6) var<uniform> params: Params;
|
||||
// each vertex's v
|
||||
@group(0) @binding(7) var<storage, read> vs: array<f32>;
|
||||
// the textures one after another, sRGB, 8 bits a channel
|
||||
@group(0) @binding(8) var<storage, read> images: array<u32>;
|
||||
// the panorama, top row first, its light already at its strength; then glossy.rs's table
|
||||
@group(0) @binding(9) var<storage, read> sky: array<vec4<f32>>;
|
||||
|
||||
fn raea_layers_at(k: i32) -> vec4<f32> {
|
||||
return sky[params.sky_w * params.sky_h + u32(k)];
|
||||
}
|
||||
|
||||
// The nearest hit. Its own function: a ray_query declared in a loop is zeroed again each turn, which naga writes for
|
||||
// Metal as an assignment Metal's intersection_query deletes.
|
||||
fn nearest(o: vec3<f32>, d: vec3<f32>) -> RayIntersection {
|
||||
var rq: ray_query;
|
||||
rayQueryInitialize(&rq, tlas, RayDesc(0u, 0xffu, 0.0, 1.0e30, o, d));
|
||||
while (rayQueryProceed(&rq)) {}
|
||||
return rayQueryGetCommittedIntersection(&rq);
|
||||
}
|
||||
|
||||
fn blocked(o: vec3<f32>, d: vec3<f32>) -> bool {
|
||||
var rq: ray_query;
|
||||
rayQueryInitialize(&rq, tlas, RayDesc(RAY_FLAG_TERMINATE_ON_FIRST_HIT, 0xffu, 0.0, 1.0e30, o, d));
|
||||
while (rayQueryProceed(&rq)) {}
|
||||
return rayQueryGetCommittedIntersection(&rq).kind != RAY_QUERY_INTERSECTION_NONE;
|
||||
}
|
||||
|
||||
// The panorama as raea draws it (systems/environment): its middle straight ahead (-Z), its right half to +X, turned
|
||||
// counter-clockwise from above by `rotation`; bilinear, wrapping round.
|
||||
fn sky_at(d: vec3<f32>) -> vec3<f32> {
|
||||
let size = vec2<f32>(f32(params.sky_w), f32(params.sky_h));
|
||||
// straight up or down has no longitude, and atan2(0, 0) may be NaN: any will do
|
||||
var lon = 0.0;
|
||||
if (d.x != 0.0 || d.z != 0.0) {
|
||||
lon = atan2(d.x, -d.z);
|
||||
}
|
||||
let u = fract(0.5 + (lon + params.rotation) / 6.283185307);
|
||||
let v = acos(clamp(d.y, -1.0, 1.0)) / 3.141592654;
|
||||
let at = vec2<f32>(u, v) * size - 0.5;
|
||||
let f = fract(at);
|
||||
let i = vec2<i32>(floor(at));
|
||||
let w = i32(params.sky_w);
|
||||
let x0 = u32((i.x + w) % w);
|
||||
let x1 = u32((i.x + 1 + w) % w);
|
||||
let y0 = u32(clamp(i.y, 0, i32(params.sky_h) - 1)) * params.sky_w;
|
||||
let y1 = u32(clamp(i.y + 1, 0, i32(params.sky_h) - 1)) * params.sky_w;
|
||||
return mix(mix(sky[y0 + x0].rgb, sky[y0 + x1].rgb, f.x), mix(sky[y1 + x0].rgb, sky[y1 + x1].rgb, f.x), f.y);
|
||||
}
|
||||
|
||||
// A texture's colour at uv, linear, its nearest texel, repeating.
|
||||
fn image_at(tex: vec4<u32>, uv: vec2<f32>) -> vec3<f32> {
|
||||
let q = fract(uv);
|
||||
let x = min(u32(q.x * f32(tex.z)), tex.z - 1u);
|
||||
let y = min(u32(q.y * f32(tex.w)), tex.w - 1u);
|
||||
let c = unpack4x8unorm(images[tex.y + y * tex.z + x]).rgb;
|
||||
return select(pow((c + 0.055) / 1.055, vec3<f32>(2.4)), c / 12.92, c <= vec3<f32>(0.04045));
|
||||
}
|
||||
|
||||
// Where a sample starts: one of the texel's 4 x 4 points, the open ones in turn (Cycles jitters its samples over the
|
||||
// texel too: a ledge narrower than a texel is half of it, not all or nothing). Bit 16 alone is the centre.
|
||||
fn start(i: u32, at: vec3<f32>, open: u32, turn: u32) -> vec3<f32> {
|
||||
var left = open & 0xffffu;
|
||||
if (left == 0u) {
|
||||
return at;
|
||||
}
|
||||
for (var k = turn % countOneBits(left); k > 0u; k = k - 1u) {
|
||||
left = left & (left - 1u);
|
||||
}
|
||||
let c = firstTrailingBit(left);
|
||||
let q = (vec2<f32>(f32(c % 4u), f32(c / 4u)) + 0.5) / 4.0 - 0.5;
|
||||
return at + texels[4u * i + 2u].xyz * q.x + texels[4u * i + 3u].xyz * q.y;
|
||||
}
|
||||
|
||||
@compute @workgroup_size(64)
|
||||
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
let i = params.first + gid.x;
|
||||
if (i >= params.count) {
|
||||
return;
|
||||
}
|
||||
let at = texels[4u * i];
|
||||
let open = bitcast<u32>(at.w);
|
||||
if (open == 0u) {
|
||||
return;
|
||||
}
|
||||
let n0 = texels[4u * i + 1u].xyz;
|
||||
var sum = vec3<f32>(0.0);
|
||||
for (var s = 0u; s < params.per_pass; s = s + 1u) {
|
||||
var rng = raea_hash(i * 0x9e3779b9u ^ raea_hash(params.base + s));
|
||||
var o = start(i, at.xyz, open, params.base + s + raea_hash(i));
|
||||
var n = n0;
|
||||
var weight = vec3<f32>(1.0);
|
||||
var light = vec3<f32>(0.0);
|
||||
var d = raea_diffuse_sample(n, vec2<f32>(raea_rand(&rng), raea_rand(&rng)));
|
||||
var likely = dot(n, d) / 3.141592654;
|
||||
for (var b = 0u; b < params.bounces; b = b + 1u) {
|
||||
let hit = nearest(o, d);
|
||||
if (hit.kind == RAY_QUERY_INTERSECTION_NONE) {
|
||||
light = light + weight * sky_at(d);
|
||||
break;
|
||||
}
|
||||
let p = hit.primitive_index;
|
||||
let srf = surfaces[p];
|
||||
light = light + weight * srf.emission.rgb;
|
||||
let a = positions[indices[3u * p]].xyz;
|
||||
let bb = positions[indices[3u * p + 1u]].xyz;
|
||||
let c = positions[indices[3u * p + 2u]].xyz;
|
||||
var ng = normalize(cross(bb - a, c - a));
|
||||
if (dot(ng, d) > 0.0) {
|
||||
ng = -ng;
|
||||
}
|
||||
let w = hit.barycentrics;
|
||||
o = a * (1.0 - w.x - w.y) + bb * w.x + c * w.y + ng * params.offset;
|
||||
n = ng;
|
||||
var albedo = srf.albedo.rgb;
|
||||
if (srf.tex.x == 1u) {
|
||||
let i0 = indices[3u * p];
|
||||
let i1 = indices[3u * p + 1u];
|
||||
let i2 = indices[3u * p + 2u];
|
||||
let k = 1.0 - w.x - w.y;
|
||||
albedo = albedo * image_at(srf.tex, vec2<f32>(positions[i0].w * k + positions[i1].w * w.x + positions[i2].w * w.y, vs[i0] * k + vs[i1] * w.x + vs[i2] * w.y));
|
||||
}
|
||||
let x = normalize(cross(n, select(vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(1.0, 0.0, 0.0), abs(n.x) < 0.9)));
|
||||
let frame = mat3x3<f32>(x, cross(n, x), n);
|
||||
var wo = -d * frame;
|
||||
wo.z = max(wo.z, 1e-4);
|
||||
let lobes = raea_lobes(albedo, srf.gloss.xyz, 0.5 * sqrt(max(0.0, 1.0 - likely)), wo.z);
|
||||
// the sun at the hit (never at the texel: its direct light stays live), from a point of its disk
|
||||
let toward = params.sun_dir.xyz;
|
||||
let facing = dot(n, toward);
|
||||
if (params.sun_dir.w > 0.0 && facing > 0.0) {
|
||||
let z = 1.0 - raea_rand(&rng) * (1.0 - params.sun_dir.w);
|
||||
let phi = 6.283185307 * raea_rand(&rng);
|
||||
let r = sqrt(max(0.0, 1.0 - z * z));
|
||||
let sa = select(vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(1.0, 0.0, 0.0), abs(toward.x) < 0.9);
|
||||
let st = normalize(cross(toward, sa));
|
||||
let sd = normalize(st * (r * cos(phi)) + cross(toward, st) * (r * sin(phi)) + toward * z);
|
||||
if (!blocked(o, sd)) {
|
||||
light = light + weight * params.sun.rgb * raea_lobes_eval(lobes, wo, sd * frame).rgb;
|
||||
}
|
||||
}
|
||||
let u = vec2<f32>(raea_rand(&rng), raea_rand(&rng));
|
||||
if (lobes.p <= 0.0) {
|
||||
d = raea_diffuse_sample(n, u);
|
||||
weight = weight * lobes.diffuse;
|
||||
likely = min(likely, dot(n, d) / 3.141592654);
|
||||
} else {
|
||||
if (raea_rand(&rng) < lobes.p) {
|
||||
d = reflect(-wo, raea_ggx_sample(wo, lobes.a, u));
|
||||
} else {
|
||||
d = raea_diffuse_sample(vec3<f32>(0.0, 0.0, 1.0), u);
|
||||
}
|
||||
let f = raea_lobes_eval(lobes, wo, d);
|
||||
if (f.w <= 0.0) {
|
||||
break;
|
||||
}
|
||||
weight = weight * f.rgb / f.w;
|
||||
likely = min(likely, f.w);
|
||||
d = normalize(frame * d);
|
||||
}
|
||||
if (b >= 2u) {
|
||||
let q = min(max(weight.r, max(weight.g, weight.b)), 1.0);
|
||||
if (raea_rand(&rng) >= q) {
|
||||
break;
|
||||
}
|
||||
weight = weight / q;
|
||||
}
|
||||
}
|
||||
sum = sum + light;
|
||||
}
|
||||
accum[i] = accum[i] + vec4<f32>(sum, f32(params.per_pass));
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "raea-sys-motionfaults"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "A clip's faults that only show in motion (docs/notice.feature NT10, NT11): knees buckling while the foot stands, feet skating, joints past their range, fingers twisted or bent back, jolts, and fingers through what the hand holds"
|
||||
|
||||
[dependencies]
|
||||
raea-core-ease = { path = "../../core/ease" }
|
||||
raea-sys-body = { path = "../body" }
|
||||
glam = "0.33"
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,55 @@
|
||||
//! A clip as JSON: the skeleton (`joints`, as skeleton.json and `character.take` have them), `fps`, and `frames`, each
|
||||
//! `{ root, turns }` as a pose is everywhere in raea/character. A clip that holds something says the thing's shape
|
||||
//! once (`thing`: ball, box, capsule or cylinder, as `character.take` takes it) and where it is on each frame
|
||||
//! (`frames[i].thing: { at, turn }`, what `character.take` answers), in the frame the body is posed in.
|
||||
|
||||
use glam::Quat;
|
||||
use raea_sys_body::json::{quat, solid, vec3};
|
||||
use raea_sys_body::rig::{Pose, Posed, Skeleton};
|
||||
use raea_sys_body::shape::Thing;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::Held;
|
||||
|
||||
pub struct Clip {
|
||||
pub skel: Skeleton,
|
||||
pub fps: f32,
|
||||
pub poses: Vec<Pose>,
|
||||
pub held: Option<Held>,
|
||||
}
|
||||
|
||||
|
||||
impl Clip {
|
||||
/// Every frame posed: each joint's place and turn, in the clip's frame.
|
||||
pub fn world(&self) -> Vec<Posed> {
|
||||
self.poses.iter().map(|p| self.skel.fk(p)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A clip read from its JSON.
|
||||
pub fn clip_of(v: &Value) -> Result<Clip, String> {
|
||||
let skel = Skeleton::from_value(v)?;
|
||||
let fps = v["fps"].as_f64().unwrap_or(30.0) as f32;
|
||||
let frames = v["frames"].as_array().ok_or("the clip has no frames")?;
|
||||
let shape = if v["thing"].is_null() { None } else { Some(solid(&v["thing"])?) };
|
||||
let (mut poses, mut held) = (Vec::with_capacity(frames.len()), Vec::with_capacity(frames.len()));
|
||||
for (k, f) in frames.iter().enumerate() {
|
||||
let mut p = skel.rest();
|
||||
p.root = vec3(&f["root"], &format!("frame {k}'s root"))?;
|
||||
for (slot, t) in p.turns.iter_mut().zip(f["turns"].as_array().ok_or_else(|| format!("frame {k} has no turns"))?) {
|
||||
*slot = quat(t, &format!("frame {k}'s turn"))?;
|
||||
}
|
||||
poses.push(p);
|
||||
held.push(match (shape, f.get("thing").filter(|t| !t.is_null())) {
|
||||
(Some(solid), Some(t)) => {
|
||||
let turn = if t["turn"].is_null() { Quat::IDENTITY } else { quat(&t["turn"], "a thing's turn")? };
|
||||
Some(Thing { solid, at: vec3(&t["at"], "a thing's at")?, turn })
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
}
|
||||
if poses.len() < 3 {
|
||||
return Err("a clip needs three frames or more to say how it moves".into());
|
||||
}
|
||||
Ok(Clip { skel, fps, poses, held: shape.map(|_| held) })
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
//! The motion critic: a logistic model over a finding's size and length and the words of what it is (its check, its
|
||||
//! joint's family, its key), the chance a person would call it wrong. The checks find; the critic says which findings
|
||||
//! matter. It learns only from real verdicts, never from planted faults (it would learn the rules back): a fix that
|
||||
//! took a finding away, or a look at the render (`--real`, `--fine`). Unlike a key's line (verdicts.rs), a word it
|
||||
//! learns carries to its neighbours: a pinky called fine bent back says something about the ring finger.
|
||||
//! Its examples are kept beside its model (raea's models folder, notice/motion.labels.jsonl); `raea scene faults
|
||||
//! train` fits it.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Fault;
|
||||
|
||||
pub const N: usize = 3;
|
||||
/// bias, size over the check's scale (at most 5), ln(1 + frames it lasts)
|
||||
pub const NAMES: [&str; N] = ["bias", "size", "frames"];
|
||||
/// Before any verdict, what the checks flag is a fault, the more so the bigger (a finding at its check's scale, 0.88).
|
||||
pub const PRIOR: [f32; N] = [1.0, 1.0, 0.0];
|
||||
/// A finding scored this or more is said.
|
||||
pub const SAY: f32 = 0.5;
|
||||
/// A verdict already scored this sure its way stops teaching.
|
||||
const MARGIN: f32 = 0.9;
|
||||
|
||||
/// The size a check's findings are read against: one unit is a clear fault of that kind.
|
||||
fn scale(check: &str) -> f32 {
|
||||
match check {
|
||||
"skate" => 0.05,
|
||||
"grip" | "through" => 0.03,
|
||||
"jolt" => 25.0,
|
||||
"buckle" => 12.0,
|
||||
_ => 10.0, // finger, limit: degrees past the range
|
||||
}
|
||||
}
|
||||
|
||||
/// A joint's family: its name without its segment number and side (pinky_02_r -> pinky, calf_l -> calf).
|
||||
fn family(joint: &str) -> String {
|
||||
let base = joint.trim_end_matches("_l").trim_end_matches("_r");
|
||||
base.split('_').next().unwrap_or(base).to_lowercase()
|
||||
}
|
||||
|
||||
/// A finding's features and words, from its check, joint, size and the frames it lasts.
|
||||
pub fn features_of(check: &str, joint: &str, value: f32, frames: usize) -> (Vec<f32>, Vec<String>) {
|
||||
let role = raea_sys_body::rig::role_name(joint);
|
||||
// a bone through a surface has no size of its own (its value is 0): it's a clear one, a unit
|
||||
let size = if check == "through" { 1.0 } else { (value.max(0.0) / scale(check)).min(5.0) };
|
||||
let x = vec![1.0, size, (1.0 + frames as f32).ln()];
|
||||
let toks = vec![format!("check:{check}"), format!("{check}:{}", family(&role)), format!("{check}:{role}")];
|
||||
(x, toks)
|
||||
}
|
||||
|
||||
pub fn features(f: &Fault) -> (Vec<f32>, Vec<String>) {
|
||||
features_of(f.check, &f.joint, f.value, f.to.saturating_sub(f.from) + 1)
|
||||
}
|
||||
|
||||
/// A verdict as an example row.
|
||||
pub fn row_of(check: &str, joint: &str, value: f32, frames: usize, real: bool, by: &str) -> Value {
|
||||
let (x, toks) = features_of(check, joint, value, frames);
|
||||
json!({"key": toks[2], "label": if real { 1 } else { 0 }, "by": by, "x": x, "toks": toks})
|
||||
}
|
||||
|
||||
pub fn row(f: &Fault, real: bool, by: &str) -> Value {
|
||||
row_of(f.check, &f.joint, f.value, f.to.saturating_sub(f.from) + 1, real, by)
|
||||
}
|
||||
|
||||
/// The critic's model and its examples: beside the motion verdicts (`verdicts`, notice/motion.json).
|
||||
pub fn paths(verdicts: &std::path::Path) -> (std::path::PathBuf, std::path::PathBuf) {
|
||||
(verdicts.with_file_name("motion-critic.json"), verdicts.with_file_name("motion.labels.jsonl"))
|
||||
}
|
||||
|
||||
/// Rows appended to the examples file.
|
||||
pub fn append(file: &std::path::Path, rows: &[Value]) -> Result<(), String> {
|
||||
use std::io::Write;
|
||||
if rows.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(d) = file.parent() {
|
||||
std::fs::create_dir_all(d).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let mut f = std::fs::OpenOptions::new().create(true).append(true).open(file).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
for r in rows {
|
||||
writeln!(f, "{r}").map_err(|e| e.to_string())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Critic {
|
||||
pub w: [f32; N],
|
||||
pub tokens: BTreeMap<String, f32>,
|
||||
pub labels: usize,
|
||||
}
|
||||
|
||||
use raea_core_ease::sigmoid;
|
||||
|
||||
impl Critic {
|
||||
pub fn prior() -> Critic {
|
||||
Critic { w: PRIOR, tokens: BTreeMap::new(), labels: 0 }
|
||||
}
|
||||
|
||||
pub fn score_x(&self, x: &[f32], toks: &[String]) -> f32 {
|
||||
let z: f32 = self.w.iter().zip(x).map(|(w, x)| w * x).sum::<f32>() + toks.iter().map(|t| self.tokens.get(t).copied().unwrap_or(0.0)).sum::<f32>();
|
||||
sigmoid(z)
|
||||
}
|
||||
|
||||
pub fn score(&self, f: &Fault) -> f32 {
|
||||
let (x, t) = features(f);
|
||||
self.score_x(&x, &t)
|
||||
}
|
||||
|
||||
/// Fitted to examples (features, words, 1 real / 0 fine): each weight held toward its prior, each word's toward
|
||||
/// nothing. Examples all one way teach only the words (they say what's wrong, not where the line is), and one
|
||||
/// already MARGIN sure its way stops teaching, as the scene judge does (raea-sys-notice model.rs).
|
||||
pub fn fit(ex: &[(Vec<f32>, Vec<String>, f32)]) -> Critic {
|
||||
let mut m = Critic::prior();
|
||||
m.labels = ex.len();
|
||||
if ex.is_empty() {
|
||||
return m;
|
||||
}
|
||||
let (hold_w, hold_t, rate, n) = (0.5f32, 0.3f32, 0.3f32, ex.len() as f32);
|
||||
for (_, toks, _) in ex {
|
||||
for t in toks {
|
||||
m.tokens.entry(t.clone()).or_insert(0.0);
|
||||
}
|
||||
}
|
||||
let both = ex.iter().any(|e| e.2 >= 0.5) && ex.iter().any(|e| e.2 < 0.5);
|
||||
for _ in 0..3000 {
|
||||
let mut gw = [0f32; N];
|
||||
let mut gt: BTreeMap<&str, f32> = BTreeMap::new();
|
||||
for (x, toks, y) in ex {
|
||||
let p = m.score_x(x, toks);
|
||||
if (*y >= 0.5 && p >= MARGIN) || (*y < 0.5 && p <= 1.0 - MARGIN) {
|
||||
continue;
|
||||
}
|
||||
let e = p - y;
|
||||
for k in 0..N {
|
||||
gw[k] += e * x[k];
|
||||
}
|
||||
for t in toks {
|
||||
*gt.entry(t).or_insert(0.0) += e;
|
||||
}
|
||||
}
|
||||
if both {
|
||||
// the frames a finding lasts stays at its prior until there's far more than a few dozen verdicts: on
|
||||
// the first 50 (11-27) it learned that long ones were fine only because the pinky's fine bends ran long
|
||||
for k in 0..N - 1 {
|
||||
m.w[k] -= rate * (gw[k] / n + hold_w * (m.w[k] - PRIOR[k]) / n);
|
||||
}
|
||||
}
|
||||
for (t, g) in gt {
|
||||
let w = m.tokens.get_mut(t).unwrap();
|
||||
*w -= rate * (g / n + hold_t * *w / n);
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
pub fn to_json(&self) -> Value {
|
||||
json!({"weights": NAMES.iter().zip(self.w).map(|(n, w)| (n.to_string(), json!(w))).collect::<serde_json::Map<_, _>>(),
|
||||
"tokens": self.tokens.iter().filter(|(_, w)| w.abs() >= 1e-3).map(|(k, w)| (k.clone(), json!(w))).collect::<serde_json::Map<_, _>>(),
|
||||
"labels": self.labels})
|
||||
}
|
||||
|
||||
pub fn of_json(v: &Value) -> Critic {
|
||||
let mut w = PRIOR;
|
||||
for (k, n) in NAMES.iter().enumerate() {
|
||||
if let Some(x) = v["weights"][n].as_f64() {
|
||||
w[k] = x as f32;
|
||||
}
|
||||
}
|
||||
let tokens = v["tokens"].as_object().into_iter().flatten().filter_map(|(k, x)| Some((k.clone(), x.as_f64()? as f32))).collect();
|
||||
Critic { w, tokens, labels: v["labels"].as_u64().unwrap_or(0) as usize }
|
||||
}
|
||||
|
||||
pub fn load(path: &std::path::Path) -> Critic {
|
||||
crate::read_json(path).map_or_else(Critic::prior, |v| Critic::of_json(&v))
|
||||
}
|
||||
}
|
||||
|
||||
/// Example rows read back (a later row on the same finding, by key and size, replaces an earlier one).
|
||||
pub fn examples(rows: &str) -> Vec<(Vec<f32>, Vec<String>, f32)> {
|
||||
let mut by: BTreeMap<String, (Vec<f32>, Vec<String>, f32)> = BTreeMap::new();
|
||||
for v in rows.lines().filter_map(|l| serde_json::from_str::<Value>(l).ok()) {
|
||||
let x: Vec<f32> = serde_json::from_value(v["x"].clone()).unwrap_or_default();
|
||||
let toks: Vec<String> = v["toks"].as_array().into_iter().flatten().filter_map(|t| t.as_str().map(String::from)).collect();
|
||||
if x.len() != N {
|
||||
continue;
|
||||
}
|
||||
let id = format!("{}|{:.3}|{:.3}", v["key"].as_str().unwrap_or(""), x[1], x[2]);
|
||||
by.insert(id, (x, toks, v["label"].as_f64().unwrap_or(0.0) as f32));
|
||||
}
|
||||
by.into_values().collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn f(check: &'static str, joint: &str, value: f32) -> Fault {
|
||||
Fault { check, joint: joint.into(), from: 10, to: 12, peak: 10, value, unit: "", says: String::new() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn untrained_it_says_what_the_checks_flag() {
|
||||
assert!(Critic::prior().score(&f("finger", "pinky_02_r", 15.0)) >= SAY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_family_called_fine_carries_to_its_other_joint_and_not_to_other_checks() {
|
||||
// the pinky's middle joint bent back a little is fine on both hands, a big bend real; the critic learns the
|
||||
// family's word and the size together
|
||||
let mut ex = Vec::new();
|
||||
for (j, v, real) in [("pinky_02_r", 12.0, false), ("pinky_02_l", 13.0, false), ("pinky_02_r", 11.0, false), ("pinky_02_r", 24.0, true), ("thumb_03_r", 20.0, true)] {
|
||||
let (x, t) = features(&f("finger", j, v));
|
||||
ex.push((x, t, if real { 1.0 } else { 0.0 }));
|
||||
}
|
||||
let c = Critic::fit(&ex);
|
||||
// the pinky's end joint was never judged: its family word says a small bend is fine
|
||||
assert!(c.score(&f("finger", "pinky_03_r", 12.0)) < SAY, "{}", c.score(&f("finger", "pinky_03_r", 12.0)));
|
||||
assert!(c.score(&f("finger", "pinky_02_r", 24.0)) >= SAY);
|
||||
// a buckle shares none of its words
|
||||
assert!(c.score(&f("buckle", "calf_l", 15.0)) >= SAY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn examples_keep_the_latest_verdict_on_a_finding() {
|
||||
let a = row(&f("grip", "thumb_03_r", 0.05), true, "fixed").to_string();
|
||||
let b = row(&f("grip", "thumb_03_r", 0.05), false, "claude").to_string();
|
||||
let ex = examples(&format!("{a}\n{b}\n"));
|
||||
assert_eq!(ex.len(), 1);
|
||||
assert_eq!(ex[0].2, 0.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Fingers held to their range, which raea-sys-body's limits table leaves out. Each finger joint's turn from rest is
|
||||
//! read about three axes of its own bone at rest: its twist about the bone; its flex, about the axis that curls the
|
||||
//! bone toward the palm (bone x palm: a flex past zero the other way is the finger bent back); and its side bend,
|
||||
//! across that. The palm is raea-sys-body's hand_rest. Ranges in degrees, from hand anatomy (a knuckle bends back
|
||||
//! about 30 and sideways about 30; the middle and end joints are hinges that hardly bend sideways or twist).
|
||||
|
||||
use glam::{Quat, Vec3};
|
||||
use raea_sys_body::arm::twist_about;
|
||||
use raea_sys_body::rig::{FINGERS, Pose, Side, Skeleton, hand_rest};
|
||||
|
||||
use crate::Hit;
|
||||
|
||||
/// flex, side and twist ranges of a finger's knuckle (01), middle (02) and end (03) joints
|
||||
const RANGE: [([f32; 2], [f32; 2], [f32; 2]); 3] = [([-30.0, 100.0], [-30.0, 30.0], [-20.0, 20.0]), ([-10.0, 115.0], [-12.0, 12.0], [-15.0, 15.0]), ([-20.0, 95.0], [-12.0, 12.0], [-15.0, 15.0])];
|
||||
/// the thumb turns round more than any finger: only its twist and how far it swings in all
|
||||
const THUMB_TWIST: f32 = 35.0;
|
||||
const THUMB_SWING: f32 = 110.0;
|
||||
/// Past its range by more than this before it's said.
|
||||
const SLACK: f32 = 8.0;
|
||||
|
||||
/// A turn read about a bone at rest: (flex about `curl`, side about the third axis, twist about `bone`), degrees.
|
||||
fn read(q: Quat, bone: Vec3, curl: Vec3) -> (f32, f32, f32) {
|
||||
let twist = twist_about(q, bone);
|
||||
let swing = q * twist.inverse();
|
||||
let swing = if swing.w < 0.0 { -swing } else { swing }.to_scaled_axis();
|
||||
let t = 2.0 * Vec3::new(twist.x, twist.y, twist.z).dot(bone).atan2(twist.w);
|
||||
let side = bone.cross(curl);
|
||||
(swing.dot(curl).to_degrees(), swing.dot(side).to_degrees(), t.to_degrees())
|
||||
}
|
||||
|
||||
fn over(v: f32, r: [f32; 2]) -> f32 {
|
||||
(r[0] - v).max(v - r[1]).max(0.0)
|
||||
}
|
||||
|
||||
pub(crate) fn check(skel: &Skeleton, poses: &[Pose]) -> Vec<Hit> {
|
||||
let mut hits = Vec::new();
|
||||
for s in Side::BOTH {
|
||||
let Some(hand) = hand_rest(skel, s) else { continue };
|
||||
for f in FINGERS {
|
||||
let Some(js) = skel.finger(f, s) else { continue };
|
||||
for (k, &i) in js.iter().enumerate() {
|
||||
let j = &skel.joints[i];
|
||||
let bone = (j.tail - j.head).normalize_or_zero();
|
||||
let palm = (hand.palm - bone * hand.palm.dot(bone)).normalize_or_zero();
|
||||
if bone == Vec3::ZERO || palm == Vec3::ZERO {
|
||||
continue;
|
||||
}
|
||||
// a turn about bone x palm by a positive angle carries the bone toward the palm: a curl
|
||||
let curl = bone.cross(palm).normalize();
|
||||
for (n, p) in poses.iter().enumerate() {
|
||||
let (flex, side, twist) = read(p.turns[i], bone, curl);
|
||||
let (by, what) = if f == "thumb" {
|
||||
let swing = flex.hypot(side);
|
||||
if twist.abs() - THUMB_TWIST > swing - THUMB_SWING { (twist.abs() - THUMB_TWIST, format!("twisted {twist:.0}° about its bone (it turns {THUMB_TWIST}° at most)")) } else { (swing - THUMB_SWING, format!("swung {swing:.0}° (it swings {THUMB_SWING}° at most)")) }
|
||||
} else {
|
||||
let (rf, rs, rt) = RANGE[k];
|
||||
let cands = [
|
||||
(over(flex, rf), if flex < rf[0] { format!("bent back {:.0}° (it bends back {:.0}° at most)", -flex, -rf[0]) } else { format!("folded {flex:.0}° (it folds {:.0}° at most)", rf[1]) }),
|
||||
(over(side, rs), format!("bent {:.0}° sideways (it bends {:.0}° at most)", side.abs(), rs[1])),
|
||||
(over(twist, rt), format!("twisted {:.0}° about its bone (it turns {:.0}° at most)", twist.abs(), rt[1])),
|
||||
];
|
||||
cands.into_iter().max_by(|a, b| a.0.total_cmp(&b.0)).unwrap()
|
||||
};
|
||||
if by > SLACK {
|
||||
hits.push(Hit { check: "finger", joint: j.name.clone(), f: n, value: by, unit: "degrees", what: format!("{} is {what}, frame {n}", j.name) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
hits
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//! A hand that holds something and hasn't closed on it: a thumb left beside a ladder post, a finger off a grip.
|
||||
//! Given a hand's fingertips' distances to the nearest surface (raea-sys-notice's `Scene::reach`), which of them are
|
||||
//! open. A hand holds when two or more tips rest on a surface; while it does, a tip left OFF or more away hasn't
|
||||
//! closed round what it holds.
|
||||
|
||||
/// A fingertip this close to a surface is on it.
|
||||
pub const ON: f32 = 0.015;
|
||||
/// While a hand holds, a tip this far off any surface hasn't closed on what it holds. Gambit's ladder lab before
|
||||
/// 68a505a ("the thumb not wrapping round what the hand holds"): with the fingers on the grab post, the thumb 50-54 mm
|
||||
/// off it and the index 26-46 mm; after, the thumb 22 mm at most (closed over the fingers, a finger's thickness out)
|
||||
/// and the fingertips 1-2 mm.
|
||||
pub const OFF: f32 = 0.03;
|
||||
/// How far out a surface is looked for from a tip.
|
||||
pub const LOOK: f32 = 0.06;
|
||||
|
||||
/// The tips (their places in `d`) open while the hand holds; none when it doesn't.
|
||||
pub fn open(d: &[f32]) -> Vec<usize> {
|
||||
if d.iter().filter(|&&x| x <= ON).count() < 2 {
|
||||
return Vec::new();
|
||||
}
|
||||
(0..d.len()).filter(|&i| d[i] >= OFF).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::open;
|
||||
|
||||
#[test]
|
||||
fn the_ladder_labs_thumb_before_and_after_its_fix() {
|
||||
// thumb, index, middle, ring, pinky: frame 200 of fp-lab-ladder-hand-r, right hand
|
||||
assert_eq!(open(&[0.052, 0.046, 0.008, 0.002, 0.001]), vec![0, 1], "before 68a505a: thumb and index off the post");
|
||||
assert!(open(&[0.022, 0.002, 0.002, 0.002, 0.001]).is_empty(), "after: the thumb closed over the fingers");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hand_that_holds_nothing_is_never_open() {
|
||||
assert!(open(&[0.06, 0.06, 0.06, 0.06, 0.06]).is_empty(), "in the air");
|
||||
assert!(open(&[0.003, 0.05, 0.05, 0.05, 0.05]).is_empty(), "one tip touching is a touch, not a hold");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Fingers, the thumb and the palm inside what the hand holds: each finger bone a capsule of a finger's thickness,
|
||||
//! sampled along its length against the thing's signed distance (raea-sys-body's shape), on every frame it's held.
|
||||
//! A finger resting on a grip is a little into it at most (skin gives); deeper is a thumb through a pistol's handle.
|
||||
|
||||
use glam::Vec3;
|
||||
use raea_sys_body::rig::{FINGERS, Posed, Side, Skeleton, hand_rest};
|
||||
|
||||
use crate::{Held, Hit, tip};
|
||||
|
||||
/// A finger's half thickness, and the thumb's, metres.
|
||||
const FINGER_R: f32 = 0.008;
|
||||
const THUMB_R: f32 = 0.010;
|
||||
/// The palm's: the thick of the hand over its middle.
|
||||
const PALM_R: f32 = 0.012;
|
||||
/// Skin pressed this far into a held thing is a grip; further is through it.
|
||||
const GIVE: f32 = 0.004;
|
||||
/// Points along each bone.
|
||||
const ALONG: usize = 6;
|
||||
|
||||
pub(crate) fn through(skel: &Skeleton, world: &[Posed], held: &Held) -> Vec<Hit> {
|
||||
let mut hits = Vec::new();
|
||||
for (n, (w, thing)) in world.iter().zip(held).enumerate() {
|
||||
let Some(thing) = thing else { continue };
|
||||
for s in Side::BOTH {
|
||||
// the palm's middle, carried by the hand
|
||||
if let (Some(arm), Some(rest)) = (skel.arm(s), hand_rest(skel, s)) {
|
||||
let h = arm[2];
|
||||
let mid = w.pos[h] + w.rot[h] * rest.mid;
|
||||
let depth = PALM_R - thing.distance(mid);
|
||||
if depth > GIVE {
|
||||
let name = skel.joints[h].name.clone();
|
||||
hits.push(Hit { check: "through", joint: name.clone(), f: n, value: depth, unit: "m", what: format!("{name}'s palm is {:.1} mm inside what it holds, frame {n}", depth * 1000.0) });
|
||||
}
|
||||
}
|
||||
for f in FINGERS {
|
||||
let Some(js) = skel.finger(f, s) else { continue };
|
||||
let r = if f == "thumb" { THUMB_R } else { FINGER_R };
|
||||
for &i in &js {
|
||||
let (a, b): (Vec3, Vec3) = (w.pos[i], tip(skel, w, i));
|
||||
let depth = (0..=ALONG).map(|k| r - thing.distance(a.lerp(b, k as f32 / ALONG as f32))).fold(f32::MIN, f32::max);
|
||||
if depth > GIVE {
|
||||
let name = skel.joints[i].name.clone();
|
||||
hits.push(Hit { check: "through", joint: name.clone(), f: n, value: depth, unit: "m", what: format!("{name} passes {:.1} mm into what the hand holds, frame {n}", depth * 1000.0) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
hits
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
//! The body's joints held to their range, jolts, and the legs while a foot stands: a knee that buckles and a foot that
|
||||
//! skates. A foot stands on a frame its ball or its ankle is within REACH of the lowest that joint goes in the clip
|
||||
//! (the ground, as the clip itself has it: no scene needed) and slower along the ground than STILL. The lines:
|
||||
//! - limit: raea-sys-body's anatomical ranges, past by more than SLACK degrees; a roll about a joint's own bone that
|
||||
//! its child takes back (a solve rolling a shin and undoing it at the foot) is moved to the child first: it moves
|
||||
//! nothing in the world, so it's no limit (settled);
|
||||
//! - jolt: a joint's turn changing by more than JOLT degrees a frame² (at 30 fps), and more than JOLT_OVER times its
|
||||
//! own usual change; the root's place by more than ROOT_JOLT metres a frame²;
|
||||
//!
|
||||
//! The lines sit just above what 107 ACCAD takes retargeted onto a raea body do (12,472 frames of walks, runs, turns,
|
||||
//! crouches and lifts, 2026-11-27): a standing knee's sharpest give 9.4° there, a standing foot's drift 10.5 cm at
|
||||
//! most (a 6 s crouch; 99% of stances under 6.7 cm), a joint's jolt 34°/frame² but for a retarget's forearm flip (63,
|
||||
//! a fault), the root's 70 mm/frame².
|
||||
//! - buckle: a standing knee that gives (folds, or snaps straight) by more than GIVE degrees and comes back within SNAP
|
||||
//! frames each side: a walk's knee folds and straightens over a stance and a squat folds slowly, neither in a snap;
|
||||
//! - skate: a standing foot drifting SLIDE metres or more along the ground from where it stood down, or a foot
|
||||
//! gliding: its ball within HUG of the ground for GLIDE frames or more and carried SLIDE over them, however fast.
|
||||
|
||||
use glam::Vec3;
|
||||
use raea_sys_body::arm::twist_about;
|
||||
use raea_sys_body::limits::{angles_of, over, violations};
|
||||
use raea_sys_body::rig::{Pose, Posed, Side, Skeleton};
|
||||
|
||||
use crate::{Fault, Hit};
|
||||
|
||||
const SLACK: f32 = 10.0;
|
||||
const JOLT: f32 = 25.0;
|
||||
const JOLT_OVER: f32 = 4.0;
|
||||
const ROOT_JOLT: f32 = 0.08;
|
||||
const REACH: f32 = 0.03;
|
||||
const STILL: f32 = 0.6;
|
||||
const STANCE: usize = 4;
|
||||
const SNAP: usize = 2;
|
||||
const GIVE: f32 = 12.0;
|
||||
const SLIDE: f32 = 0.08;
|
||||
const HUG: f32 = 0.015;
|
||||
const GLIDE: usize = 6;
|
||||
|
||||
/// Frames at 30 fps per frame of the clip: speeds and changes are read as if at 30 fps.
|
||||
fn per30(fps: f32) -> f32 {
|
||||
fps / 30.0
|
||||
}
|
||||
|
||||
/// A roll this far about a joint's own bone is looked at for its child taking it back.
|
||||
const ROLL: f32 = 15.0;
|
||||
|
||||
/// The pose with each roll its child takes back moved to the child. A turn about a joint's own bone moves no joint's
|
||||
/// place (the child's head is on that bone), so the world pose is the same; the roll is moved only where the two
|
||||
/// joints together are then less past their ranges, so a roll nothing takes back stays where it is.
|
||||
pub(crate) fn settled(skel: &Skeleton, p: &Pose) -> Pose {
|
||||
let mut p = p.clone();
|
||||
for i in 0..skel.joints.len() {
|
||||
let j = &skel.joints[i];
|
||||
let Some(bone) = (j.tail - j.head).try_normalize() else { continue };
|
||||
// the child at its tail, with limits of its own (a roll moved to a joint with none would only be hidden there),
|
||||
// and every other child on the bone's own line (a shin's twist joints): a turn about the bone moves none of
|
||||
// them, where a hand's roll moved to one finger would move the rest
|
||||
let kids: Vec<usize> = (0..skel.joints.len()).filter(|&k| skel.joints[k].parent == Some(i)).collect();
|
||||
let Some(&c) = kids.iter().find(|&&k| skel.joints[k].head.distance(j.tail) < 1e-3) else { continue };
|
||||
let on_line = |k: usize| {
|
||||
let d = skel.joints[k].head - j.head;
|
||||
(d - bone * d.dot(bone)).length() < 1e-3
|
||||
};
|
||||
if angles_of(skel, c, p.turns[c]).is_none() || !kids.iter().all(|&k| k == c || on_line(k)) {
|
||||
continue;
|
||||
}
|
||||
let t = twist_about(p.turns[i], bone);
|
||||
if t.angle_between(glam::Quat::IDENTITY).to_degrees() < ROLL {
|
||||
continue;
|
||||
}
|
||||
let (qi, qc) = ((p.turns[i] * t.inverse()).normalize(), (t * p.turns[c]).normalize());
|
||||
if over(skel, i, qi) + over(skel, c, qc) + 1.0 < over(skel, i, p.turns[i]) + over(skel, c, p.turns[c]) {
|
||||
(p.turns[i], p.turns[c]) = (qi, qc);
|
||||
}
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
pub(crate) fn limits(skel: &Skeleton, poses: &[Pose]) -> Vec<Hit> {
|
||||
let mut hits = Vec::new();
|
||||
for (n, p) in poses.iter().enumerate() {
|
||||
let p = &settled(skel, p);
|
||||
for (i, by) in violations(skel, p, SLACK) {
|
||||
let name = skel.joints[i].name.clone();
|
||||
let a = angles_of(skel, i, p.turns[i]);
|
||||
let how = a.map(|a| format!(" (flex {:.0}°, side {:.0}°, twist {:.0}°)", a.flex, a.side, a.twist)).unwrap_or_default();
|
||||
hits.push(Hit { check: "limit", joint: name.clone(), f: n, value: by, unit: "degrees", what: format!("{name} is {by:.0}° past its range{how}, frame {n}") });
|
||||
}
|
||||
}
|
||||
hits
|
||||
}
|
||||
|
||||
fn median(mut v: Vec<f32>) -> f32 {
|
||||
if v.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let mid = v.len() / 2;
|
||||
*v.select_nth_unstable_by(mid, f32::total_cmp).1
|
||||
}
|
||||
|
||||
/// The least and the most of `v` (f32::MAX and f32::MIN when it's empty).
|
||||
pub fn bounds(v: &[f32]) -> (f32, f32) {
|
||||
let (mut lo, mut hi) = (f32::MAX, f32::MIN);
|
||||
for &x in v {
|
||||
(lo, hi) = (lo.min(x), hi.max(x));
|
||||
}
|
||||
(lo, hi)
|
||||
}
|
||||
|
||||
pub(crate) fn jolts(skel: &Skeleton, poses: &[Pose], fps: f32) -> Vec<Hit> {
|
||||
let k = per30(fps);
|
||||
let mut hits = Vec::new();
|
||||
let n = poses.len();
|
||||
for i in 0..skel.joints.len() {
|
||||
// each frame's turn as a step from the last (in the parent's frame), and how much that step changed
|
||||
// (the short way round: a turn and its negative are one turn)
|
||||
let step: Vec<Vec3> = (1..n)
|
||||
.map(|f| {
|
||||
let q = poses[f].turns[i] * poses[f - 1].turns[i].inverse();
|
||||
if q.w < 0.0 { -q } else { q }.to_scaled_axis()
|
||||
})
|
||||
.collect();
|
||||
let change: Vec<f32> = (1..step.len()).map(|f| (step[f] - step[f - 1]).length().to_degrees() * k * k).collect();
|
||||
let usual = median(change.clone());
|
||||
for (f, &c) in change.iter().enumerate() {
|
||||
if c > JOLT && c > JOLT_OVER * usual.max(0.5) {
|
||||
let name = skel.joints[i].name.clone();
|
||||
hits.push(Hit { check: "jolt", joint: name.clone(), f: f + 1, value: c, unit: "degrees/frame²", what: format!("{name} jolts {c:.1}°/frame² at frame {} (it usually changes {usual:.1})", f + 1) });
|
||||
}
|
||||
}
|
||||
}
|
||||
for f in 1..n - 1 {
|
||||
let a = (poses[f + 1].root - poses[f].root) - (poses[f].root - poses[f - 1].root);
|
||||
let c = a.length() * k * k;
|
||||
if c > ROOT_JOLT {
|
||||
hits.push(Hit { check: "jolt", joint: "root".into(), f, value: c, unit: "m/frame²", what: format!("the body's root jolts {:.0} mm/frame² at frame {f}", c * 1000.0) });
|
||||
}
|
||||
}
|
||||
hits
|
||||
}
|
||||
|
||||
/// Each frame's standing joint of one foot (the ball before the ankle), or None: a joint stands while it's within
|
||||
/// REACH of the lowest it goes in the clip and moving along the ground slower than STILL. And the stretches of
|
||||
/// STANCE frames or more it stands, (first, last).
|
||||
fn stances(skel: &Skeleton, world: &[Posed], s: Side, fps: f32) -> Option<(Vec<(usize, usize)>, Vec<Option<usize>>)> {
|
||||
let foot = skel.joint(&format!("foot_{}", s.sx()))?;
|
||||
let ball = skel.joint(&format!("ball_{}", s.sx()));
|
||||
let n = world.len();
|
||||
let low = |j: usize| world.iter().map(|w| w.pos[j].y).fold(f32::MAX, f32::min);
|
||||
let speed = |j: usize, f: usize| {
|
||||
let (a, b) = (f.saturating_sub(1), (f + 1).min(n - 1));
|
||||
let d = world[b].pos[j] - world[a].pos[j];
|
||||
Vec3::new(d.x, 0.0, d.z).length() * fps / (b - a).max(1) as f32
|
||||
};
|
||||
let stands = |j: usize, lo: f32, f: usize| world[f].pos[j].y < lo + REACH && speed(j, f) < STILL;
|
||||
let (fl, bl) = (low(foot), ball.map(low));
|
||||
let on: Vec<Option<usize>> = (0..n)
|
||||
.map(|f| match ball {
|
||||
Some(b) if stands(b, bl.unwrap(), f) => Some(b),
|
||||
_ if stands(foot, fl, f) => Some(foot),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let mut runs = Vec::new();
|
||||
let mut start = None;
|
||||
for (f, o) in on.iter().chain([&None]).enumerate() {
|
||||
match (o, start) {
|
||||
(Some(_), None) => start = Some(f),
|
||||
(None, Some(a)) => {
|
||||
if f - a >= STANCE {
|
||||
runs.push((a, f - 1));
|
||||
}
|
||||
start = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Some((runs, on))
|
||||
}
|
||||
|
||||
/// The knee's sharpest give over a stance: a fold that rises and falls back within SNAP frames (at 30 fps) each side,
|
||||
/// or a snap straight that folds back as fast; its size (the smaller of the two sides) and frame.
|
||||
fn sharpest(flex: &[f32], k: f32) -> (f32, usize) {
|
||||
let w = ((SNAP as f32) * k).round().max(1.0) as usize;
|
||||
let mut best = (0.0f32, 0);
|
||||
for t in w..flex.len().saturating_sub(w) {
|
||||
let (before, after) = (&flex[t - w..t], &flex[t + 1..=t + w]);
|
||||
let ((lo_b, hi_b), (lo_a, hi_a)) = (bounds(before), bounds(after));
|
||||
let fold = (flex[t] - lo_b).min(flex[t] - lo_a);
|
||||
let snap = (hi_b - flex[t]).min(hi_a - flex[t]);
|
||||
let g = fold.max(snap);
|
||||
if g > best.0 {
|
||||
best = (g, t);
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Buckles and skates, one fault per stance at most for each.
|
||||
pub(crate) fn stance(skel: &Skeleton, poses: &[Pose], world: &[Posed], fps: f32) -> Vec<Fault> {
|
||||
let k = per30(fps);
|
||||
let mut out = Vec::new();
|
||||
for s in Side::BOTH {
|
||||
let (Some((runs, on)), Some(calf)) = (stances(skel, world, s, fps), skel.joint(&format!("calf_{}", s.sx()))) else { continue };
|
||||
let knee = skel.joints[calf].name.clone();
|
||||
for (a, b) in runs {
|
||||
let flex: Vec<f32> = (a..=b).map(|f| angles_of(skel, calf, poses[f].turns[calf]).map_or(0.0, |x| x.flex)).collect();
|
||||
let (give, at) = sharpest(&flex, k);
|
||||
if give > GIVE {
|
||||
out.push(Fault { check: "buckle", joint: knee.clone(), from: a, to: b, peak: a + at, value: give, unit: "degrees", says: format!("{knee} gives {give:.0}° and back within {SNAP} frames while its foot stands, frame {}", a + at) });
|
||||
}
|
||||
// the foot: how far a standing joint drifts along the ground from where it first stood this stance
|
||||
let mut anchor: [Option<(usize, Vec3)>; 2] = [None, None];
|
||||
let (mut drift, mut when) = (0.0f32, a);
|
||||
for f in a..=b {
|
||||
let Some(j) = on[f] else { continue };
|
||||
let p = world[f].pos[j];
|
||||
let slot = anchor.iter_mut().find(|x| x.is_none_or(|x| x.0 == j)).unwrap();
|
||||
let from = slot.get_or_insert((j, p)).1;
|
||||
let d = Vec3::new(p.x - from.x, 0.0, p.z - from.z).length();
|
||||
if d > drift {
|
||||
(drift, when) = (d, f);
|
||||
}
|
||||
}
|
||||
if drift >= SLIDE {
|
||||
let foot = format!("foot_{}", s.sx());
|
||||
out.push(Fault { check: "skate", joint: foot.clone(), from: a, to: b, peak: when, value: drift, unit: "m", says: format!("{foot} slides {:.0} mm while it stands (frames {a}-{b}, furthest at {when})", drift * 1000.0) });
|
||||
}
|
||||
}
|
||||
// a foot gliding along the ground too fast to count as standing: its ball within HUG of the lowest it goes
|
||||
// for GLIDE frames (at 30 fps) or more, however fast, and carried SLIDE or more over them
|
||||
let Some(ball) = skel.joint(&format!("ball_{}", s.sx())) else { continue };
|
||||
let low = world.iter().map(|w| w.pos[ball].y).fold(f32::MAX, f32::min);
|
||||
let need = ((GLIDE as f32) * k).round() as usize;
|
||||
let mut start = None;
|
||||
for f in 0..=world.len() {
|
||||
let hugs = f < world.len() && world[f].pos[ball].y < low + HUG;
|
||||
match (hugs, start) {
|
||||
(true, None) => start = Some(f),
|
||||
(false, Some(a)) => {
|
||||
start = None;
|
||||
let b = f - 1;
|
||||
let (p, q) = (world[a].pos[ball], world[b].pos[ball]);
|
||||
let drift = Vec3::new(q.x - p.x, 0.0, q.z - p.z).length();
|
||||
let foot = format!("foot_{}", s.sx());
|
||||
if f - a >= need && drift >= SLIDE && !out.iter().any(|o: &Fault| o.check == "skate" && o.joint == foot && o.from <= b && a <= o.to) {
|
||||
out.push(Fault { check: "skate", joint: foot.clone(), from: a, to: b, peak: b, value: drift, unit: "m", says: format!("{foot} glides {:.0} mm along the ground (frames {a}-{b})", drift * 1000.0) });
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
//! A clip's faults that only show in motion, which no still shows and a vision model reading stills misses (Shane,
|
||||
//! 2026-11-27: "its knees keep buckling when it walks", "a hand that grabbed a gun, its fingers are twisting up ...
|
||||
//! the thumb is clipping through the handle"). Every frame of the clip is posed (raea-sys-body's forward kinematics)
|
||||
//! and held to:
|
||||
//! - limit: a joint past its anatomical range (raea-sys-body's limits: a knee bent backwards, an elbow past straight);
|
||||
//! - finger: a finger joint twisted about its bone, bent sideways at a hinge, bent back past its range or folded past
|
||||
//! it (fingers.rs: the limits table has no fingers);
|
||||
//! - buckle: a knee folding fast while its foot stands on the ground;
|
||||
//! - skate: a foot that stands sliding along the ground;
|
||||
//! - jolt: a joint's (or the root's) turn changing speed more in a frame than a body does;
|
||||
//! - through: a finger, the thumb or the palm inside the thing the hand holds (held.rs).
|
||||
//!
|
||||
//! Each is said once per stretch of frames it lasts, with the frame it's worst on and by how much. What counts as too
|
||||
//! much is set below from anatomy and measured gait, written down so a learned critic (NT11) can replace it.
|
||||
|
||||
use glam::Vec3;
|
||||
use raea_sys_body::rig::{Posed, Skeleton};
|
||||
use raea_sys_body::shape::Thing;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
mod clip;
|
||||
/// The checks' version: a finding gone since a run of other checks went because the checks changed, not the motion,
|
||||
/// so a fix is only read between runs of the same checks (bump it with any change to what a check finds).
|
||||
pub const CHECKS: &str = "2026-11-27.3";
|
||||
|
||||
pub mod critic;
|
||||
mod fingers;
|
||||
pub mod grip;
|
||||
mod held;
|
||||
mod legs;
|
||||
pub mod plant;
|
||||
pub mod verdicts;
|
||||
|
||||
pub use clip::{Clip, clip_of};
|
||||
pub use legs::bounds;
|
||||
|
||||
/// A fault over a stretch of frames.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Fault {
|
||||
pub check: &'static str,
|
||||
/// the joint it's on (or "root")
|
||||
pub joint: String,
|
||||
pub from: usize,
|
||||
pub to: usize,
|
||||
/// the frame it's worst on, and how bad there
|
||||
pub peak: usize,
|
||||
pub value: f32,
|
||||
pub unit: &'static str,
|
||||
pub says: String,
|
||||
}
|
||||
|
||||
impl Fault {
|
||||
pub fn to_json(&self) -> Value {
|
||||
json!({"check": self.check, "joint": self.joint, "frames": [self.from, self.to + 1], "peak": self.peak, "value": (self.value * 1e3).round() / 1e3, "unit": self.unit, "says": self.says})
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame's reading of one joint: over the line by `value` on frame `f`.
|
||||
pub struct Hit {
|
||||
pub check: &'static str,
|
||||
pub joint: String,
|
||||
pub f: usize,
|
||||
pub value: f32,
|
||||
pub unit: &'static str,
|
||||
pub what: String,
|
||||
}
|
||||
|
||||
/// Frames this far apart still make one stretch.
|
||||
const GAP: usize = 2;
|
||||
|
||||
/// Hits joined into stretches: one per check and joint while the frames run on (GAP frames apart at most).
|
||||
pub fn stretches(mut hits: Vec<Hit>) -> Vec<Fault> {
|
||||
hits.sort_by(|a, b| (a.check, &a.joint, a.f).cmp(&(b.check, &b.joint, b.f)));
|
||||
let mut out: Vec<Fault> = Vec::new();
|
||||
for h in hits {
|
||||
if let Some(l) = out.last_mut()
|
||||
&& l.check == h.check
|
||||
&& l.joint == h.joint
|
||||
&& h.f <= l.to + GAP
|
||||
{
|
||||
l.to = h.f;
|
||||
if h.value > l.value {
|
||||
(l.peak, l.value, l.says) = (h.f, h.value, h.what);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
out.push(Fault { check: h.check, joint: h.joint, from: h.f, to: h.f, peak: h.f, value: h.value, unit: h.unit, says: h.what });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A JSON file read, or none when it's missing or isn't JSON (a judge's weights, the verdicts so far).
|
||||
pub(crate) fn read_json(path: &std::path::Path) -> Option<serde_json::Value> {
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
serde_json::from_str(&text).ok()
|
||||
}
|
||||
|
||||
/// The faults of a clip, worst first within each check, the checks in the order a viewer notices them.
|
||||
pub fn check(c: &Clip) -> Vec<Fault> {
|
||||
let world = c.world();
|
||||
let mut hits = Vec::new();
|
||||
hits.extend(legs::limits(&c.skel, &c.poses));
|
||||
hits.extend(fingers::check(&c.skel, &c.poses));
|
||||
hits.extend(legs::jolts(&c.skel, &c.poses, c.fps));
|
||||
let mut out = stretches(hits);
|
||||
out.extend(legs::stance(&c.skel, &c.poses, &world, c.fps));
|
||||
if let Some(things) = &c.held {
|
||||
out.extend(stretches(held::through(&c.skel, &world, things)));
|
||||
}
|
||||
let order = |k: &str| ["through", "buckle", "skate", "finger", "limit", "jolt"].iter().position(|x| *x == k).unwrap_or(9);
|
||||
out.sort_by(|a, b| order(a.check).cmp(&order(b.check)).then(b.value.total_cmp(&a.value)));
|
||||
out
|
||||
}
|
||||
|
||||
/// Where a joint's bone ends on a posed frame: its child's place, else its tail carried by its turn.
|
||||
pub fn tip(skel: &Skeleton, w: &Posed, i: usize) -> Vec3 {
|
||||
let j = &skel.joints[i];
|
||||
w.pos[i] + w.rot[i] * (j.tail - j.head)
|
||||
}
|
||||
|
||||
/// The things held, one a frame (None on a frame the hand holds nothing).
|
||||
pub type Held = Vec<Option<Thing>>;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,172 @@
|
||||
//! Faults of known size planted into a clip, to measure what `check` catches on real motion (NT10's recall): each
|
||||
//! kind as an animation tool gets it wrong.
|
||||
//! - buckle: a standing knee that gives and comes back over three frames, the body dipping with it so the foot stays
|
||||
//! planted (a solver's knee popping);
|
||||
//! - skate: the whole body carried along while a foot stands (root motion that doesn't match the steps);
|
||||
//! - jolt: one joint snapped round for one frame (a bad key);
|
||||
//! - limit: a knee bent backwards for a few frames;
|
||||
//! - finger: a finger's middle joint bent back or twisted for a stretch (a grip solved wrong);
|
||||
//! - through: a grip held so the thumb passes through it.
|
||||
|
||||
use glam::{Quat, Vec3};
|
||||
use raea_sys_body::limits::angles_of;
|
||||
use raea_sys_body::rig::{FINGERS, Side, Skeleton, hand_rest};
|
||||
use raea_sys_body::shape::{Solid, Thing};
|
||||
|
||||
use crate::{Clip, tip};
|
||||
|
||||
pub const KINDS: [&str; 6] = ["buckle", "skate", "jolt", "limit", "finger", "through"];
|
||||
|
||||
/// A small seeded generator (xorshift), so a run can be repeated.
|
||||
pub struct Rng(pub u64);
|
||||
|
||||
impl Rng {
|
||||
pub fn next(&mut self) -> f32 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
(self.0 >> 40) as f32 / (1u64 << 24) as f32
|
||||
}
|
||||
pub fn range(&mut self, a: f32, b: f32) -> f32 {
|
||||
a + (b - a) * self.next()
|
||||
}
|
||||
pub fn pick(&mut self, n: usize) -> usize {
|
||||
((self.next() * n as f32) as usize).min(n.saturating_sub(1))
|
||||
}
|
||||
}
|
||||
|
||||
/// What was planted: its kind, the joint and frame it's on, and its size.
|
||||
pub struct Planted {
|
||||
pub check: &'static str,
|
||||
pub joint: String,
|
||||
pub frame: usize,
|
||||
pub size: f32,
|
||||
pub says: String,
|
||||
}
|
||||
|
||||
/// a turn of `deg` of flex as the limits read it: about the joint's flex axis, found by how a degree about each of
|
||||
/// x, y and z reads (the axis isn't x on every rig: on a SOMA body a turn about x read a 27° bend as under 19°)
|
||||
pub fn bend(skel: &Skeleton, i: usize, deg: f32) -> Quat {
|
||||
let read = |q: Quat| angles_of(skel, i, q).map_or(0.0, |a| a.flex);
|
||||
let axis = Vec3::new(read(Quat::from_rotation_x(1f32.to_radians())), read(Quat::from_rotation_y(1f32.to_radians())), read(Quat::from_rotation_z(1f32.to_radians())));
|
||||
Quat::from_axis_angle(axis.normalize_or(Vec3::X), deg.to_radians())
|
||||
}
|
||||
|
||||
/// the frames a foot's ball is lowest and still: a stretch where it stands, (first, last), at least `len` frames
|
||||
fn standing(c: &Clip, s: Side, len: usize) -> Option<(usize, usize)> {
|
||||
let ball = c.skel.joint(&format!("ball_{}", s.sx()))?;
|
||||
let w = c.world();
|
||||
let low = w.iter().map(|w| w.pos[ball].y).fold(f32::MAX, f32::min);
|
||||
let ok: Vec<bool> = (0..w.len())
|
||||
.map(|f| {
|
||||
let g = (f + 1).min(w.len() - 1);
|
||||
let d = w[g].pos[ball] - w[f].pos[ball];
|
||||
w[f].pos[ball].y < low + 0.02 && Vec3::new(d.x, 0.0, d.z).length() * c.fps < 0.3
|
||||
})
|
||||
.collect();
|
||||
let mut best: Option<(usize, usize)> = None;
|
||||
let mut start = None;
|
||||
for (f, &o) in ok.iter().chain([&false]).enumerate() {
|
||||
match (o, start) {
|
||||
(true, None) => start = Some(f),
|
||||
(false, Some(a)) => {
|
||||
if f - a >= len && best.is_none_or(|b| f - a > b.1 - b.0 + 1) {
|
||||
best = Some((a, f - 1));
|
||||
}
|
||||
start = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
pub fn plant(c: &Clip, kind: &str, rng: &mut Rng) -> Option<(Clip, Planted)> {
|
||||
let skel = &c.skel;
|
||||
let mut poses = c.poses.clone();
|
||||
let mut held = None;
|
||||
let n = poses.len();
|
||||
let s = if rng.next() < 0.5 { Side::L } else { Side::R };
|
||||
let planted = match kind {
|
||||
"buckle" => {
|
||||
let (a, b) = standing(c, s, 9)?;
|
||||
let t = (a + b) / 2;
|
||||
let (thigh, calf, ball) = (skel.joint(&format!("thigh_{}", s.sx()))?, skel.joint(&format!("calf_{}", s.sx()))?, skel.joint(&format!("ball_{}", s.sx()))?);
|
||||
let deg = rng.range(15.0, 35.0);
|
||||
for (f, share) in [(t - 1, 0.5), (t, 1.0), (t + 1, 0.5)] {
|
||||
let before = skel.fk(&poses[f]).pos[ball];
|
||||
let p = &mut poses[f];
|
||||
p.turns[calf] = (bend(skel, calf, deg * share) * p.turns[calf]).normalize();
|
||||
p.turns[thigh] = (bend(skel, thigh, deg * share * 0.5) * p.turns[thigh]).normalize();
|
||||
let after = skel.fk(p).pos[ball];
|
||||
p.root += before - after;
|
||||
}
|
||||
Planted { check: "buckle", joint: skel.joints[calf].name.clone(), frame: t, size: deg, says: format!("{} gives {deg:.0}° at frame {t}", skel.joints[calf].name) }
|
||||
}
|
||||
"skate" => {
|
||||
let (a, b) = standing(c, s, 8)?;
|
||||
let total = rng.range(0.10, 0.30);
|
||||
let dir = Vec3::new(rng.range(-1.0, 1.0), 0.0, rng.range(-1.0, 1.0)).normalize_or(Vec3::X);
|
||||
for (f, p) in poses.iter_mut().enumerate() {
|
||||
let along = ((f as f32 - a as f32) / (b - a) as f32).clamp(0.0, 1.0);
|
||||
p.root += dir * total * along;
|
||||
}
|
||||
Planted { check: "skate", joint: format!("foot_{}", s.sx()), frame: (a + b) / 2, size: total, says: format!("foot_{} carried {:.0} mm over frames {a}-{b}", s.sx(), total * 1000.0) }
|
||||
}
|
||||
"jolt" => {
|
||||
let names = ["spine_02", "neck_01", "head", "upperarm_l", "lowerarm_r", "thigh_r", "hand_l"];
|
||||
let i = skel.joint(names[rng.pick(names.len())])?;
|
||||
let t = 2 + rng.pick(n - 4);
|
||||
let deg = rng.range(20.0, 45.0);
|
||||
let axis = Vec3::new(rng.range(-1.0, 1.0), rng.range(-1.0, 1.0), rng.range(-1.0, 1.0)).normalize_or(Vec3::Y);
|
||||
poses[t].turns[i] = (Quat::from_axis_angle(axis, deg.to_radians()) * poses[t].turns[i]).normalize();
|
||||
Planted { check: "jolt", joint: skel.joints[i].name.clone(), frame: t, size: deg, says: format!("{} snapped {deg:.0}° for frame {t}", skel.joints[i].name) }
|
||||
}
|
||||
"limit" => {
|
||||
let calf = skel.joint(&format!("calf_{}", s.sx()))?;
|
||||
let t = 2 + rng.pick(n - 8);
|
||||
let deg = rng.range(25.0, 55.0);
|
||||
for p in &mut poses[t..t + 5] {
|
||||
p.turns[calf] = bend(skel, calf, -deg);
|
||||
}
|
||||
// its size: how far past the knee's range that is (on a SOMA body the range ends near -17°, not -8°)
|
||||
let past = raea_sys_body::limits::violations(skel, &poses[t + 2], 0.0).iter().find(|v| v.0 == calf).map_or(0.0, |v| v.1);
|
||||
Planted { check: "limit", joint: skel.joints[calf].name.clone(), frame: t + 2, size: past, says: format!("{} bent {deg:.0}° backwards ({past:.0}° past its range) over frames {t}-{}", skel.joints[calf].name, t + 4) }
|
||||
}
|
||||
"finger" => {
|
||||
let rest = hand_rest(skel, s)?;
|
||||
let f = FINGERS[1 + rng.pick(4)];
|
||||
let i = skel.finger(f, s)?[1];
|
||||
let j = &skel.joints[i];
|
||||
let bone = (j.tail - j.head).normalize();
|
||||
let palm = (rest.palm - bone * rest.palm.dot(bone)).normalize();
|
||||
let twist = rng.next() < 0.5;
|
||||
let deg = rng.range(35.0, 70.0);
|
||||
let q = if twist { Quat::from_axis_angle(bone, deg.to_radians()) } else { Quat::from_axis_angle(bone.cross(palm).normalize(), -deg.to_radians()) };
|
||||
let t = rng.pick(n - 10);
|
||||
for p in &mut poses[t..t + 10] {
|
||||
p.turns[i] = (p.turns[i] * q).normalize();
|
||||
}
|
||||
Planted { check: "finger", joint: j.name.clone(), frame: t + 5, size: deg, says: format!("{} {} {deg:.0}° over frames {t}-{}", j.name, if twist { "twisted" } else { "bent back" }, t + 9) }
|
||||
}
|
||||
"through" => {
|
||||
let thumb = skel.finger("thumb", s)?[1];
|
||||
let into = rng.range(0.006, 0.02);
|
||||
let r = 0.015;
|
||||
let mut things = Vec::with_capacity(n);
|
||||
for p in &poses {
|
||||
let w = skel.fk(p);
|
||||
let (a, b) = (w.pos[thumb], tip(skel, &w, thumb));
|
||||
let mid = a.lerp(b, 0.5);
|
||||
// a grip beside the thumb, its axis across the thumb, its surface `into` past the thumb's skin
|
||||
let side = (b - a).cross(Vec3::Y).normalize_or(Vec3::X);
|
||||
let at = mid + side * (r + 0.010 - into);
|
||||
things.push(Some(Thing { solid: Solid::Cylinder { half: 0.06, r }, at, turn: Quat::from_rotation_arc(Vec3::Y, (b - a).normalize_or(Vec3::Y)) }));
|
||||
}
|
||||
held = Some(things);
|
||||
Planted { check: "through", joint: skel.joints[thumb].name.clone(), frame: n / 2, size: into, says: format!("{}: a grip {:.0} mm into it", skel.joints[thumb].name, into * 1000.0) }
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some((Clip { skel: skel.clone(), fps: c.fps, poses, held: held.or_else(|| c.held.clone()) }, planted))
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
use glam::{Quat, Vec3};
|
||||
use raea_sys_body::rig::{Pose, Side, Skeleton, hand_rest, mannequin};
|
||||
use raea_sys_body::shape::{Solid, Thing};
|
||||
|
||||
use crate::{Clip, Fault, check, clip_of};
|
||||
|
||||
fn clip(skel: &Skeleton, poses: Vec<Pose>, held: Option<crate::Held>) -> Clip {
|
||||
Clip { skel: skel.clone(), fps: 30.0, poses, held }
|
||||
}
|
||||
|
||||
fn kinds(f: &[Fault]) -> Vec<String> {
|
||||
f.iter().map(|f| format!("{}:{}", f.check, f.joint)).collect()
|
||||
}
|
||||
|
||||
use crate::plant::bend;
|
||||
|
||||
/// both legs bent like a squat by `a` degrees, the body moved so the left ball stays where it stands at rest
|
||||
fn squat(skel: &Skeleton, a: f32) -> Pose {
|
||||
let mut p = skel.rest();
|
||||
for s in Side::BOTH {
|
||||
let (t, c) = (skel.joint(&format!("thigh_{}", s.sx())).unwrap(), skel.joint(&format!("calf_{}", s.sx())).unwrap());
|
||||
p.turns[t] = bend(skel, t, a);
|
||||
p.turns[c] = bend(skel, c, 2.0 * a);
|
||||
}
|
||||
let ball = skel.joint("ball_l").unwrap();
|
||||
let (rest, now) = (skel.fk(&skel.rest()).pos[ball], skel.fk(&p).pos[ball]);
|
||||
p.root += rest - now;
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_standing_still_has_no_faults() {
|
||||
let skel = mannequin();
|
||||
let f = check(&clip(&skel, vec![skel.rest(); 12], None));
|
||||
assert!(f.is_empty(), "{:?}", kinds(&f));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stance_that_folds_once_is_fine_and_one_that_folds_again_buckles() {
|
||||
let skel = mannequin();
|
||||
let fine: Vec<Pose> = [0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 10.0, 8.0, 6.0, 4.0, 2.0, 0.0].iter().map(|&a| squat(&skel, a)).collect();
|
||||
let f = check(&clip(&skel, fine, None));
|
||||
assert!(f.iter().all(|f| f.check != "buckle" && f.check != "skate"), "{:?}", kinds(&f));
|
||||
let buckled: Vec<Pose> = [0.0, 4.0, 8.0, 12.0, 9.0, 5.0, 2.0, 10.0, 3.0, 0.0].iter().map(|&a| squat(&skel, a)).collect();
|
||||
let f = check(&clip(&skel, buckled, None));
|
||||
let b = f.iter().find(|f| f.check == "buckle").unwrap_or_else(|| panic!("no buckle: {:?}", kinds(&f)));
|
||||
assert_eq!(b.peak, 7, "{}", b.says);
|
||||
assert!(b.value > 10.0, "{}", b.says);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_standing_foot_that_slides_skates() {
|
||||
let skel = mannequin();
|
||||
let poses: Vec<Pose> = (0..10)
|
||||
.map(|k| {
|
||||
let mut p = skel.rest();
|
||||
p.root.x += 0.01 * k as f32;
|
||||
p
|
||||
})
|
||||
.collect();
|
||||
let f = check(&clip(&skel, poses, None));
|
||||
let s: Vec<&Fault> = f.iter().filter(|f| f.check == "skate").collect();
|
||||
assert_eq!(s.len(), 2, "{:?}", kinds(&f));
|
||||
assert!((s[0].value - 0.09).abs() < 0.005, "{}", s[0].says);
|
||||
assert!(f.iter().all(|f| f.check != "jolt"), "steady motion isn't a jolt: {:?}", kinds(&f));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_knee_bent_backwards_and_a_pop_are_said() {
|
||||
let skel = mannequin();
|
||||
let calf = skel.joint("calf_l").unwrap();
|
||||
let spine = skel.joint("spine_02").unwrap();
|
||||
let mut poses = vec![skel.rest(); 10];
|
||||
poses[5].turns[spine] = Quat::from_rotation_y(30f32.to_radians());
|
||||
for p in &mut poses[2..4] {
|
||||
p.turns[calf] = bend(&skel, calf, -30.0);
|
||||
}
|
||||
let f = check(&clip(&skel, poses, None));
|
||||
let limit = f.iter().find(|f| f.check == "limit" && f.joint == "calf_l").unwrap_or_else(|| panic!("{:?}", kinds(&f)));
|
||||
assert_eq!((limit.from, limit.to), (2, 3));
|
||||
assert!(f.iter().any(|f| f.check == "jolt" && f.joint == "spine_02" && f.peak == 5), "{:?}", kinds(&f));
|
||||
}
|
||||
|
||||
/// a finger joint turned about its bone's curl axis (positive folds it toward the palm) or about the bone itself
|
||||
fn finger_turn(skel: &Skeleton, i: usize, curl: f32, twist: f32) -> Quat {
|
||||
let j = &skel.joints[i];
|
||||
let bone = (j.tail - j.head).normalize();
|
||||
let palm = hand_rest(skel, Side::L).unwrap().palm;
|
||||
let palm = (palm - bone * palm.dot(bone)).normalize();
|
||||
// the curl after the twist (a turn read as swing x twist): twisted about its own bone, then folded
|
||||
Quat::from_axis_angle(bone.cross(palm).normalize(), curl.to_radians()) * Quat::from_axis_angle(bone, twist.to_radians())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fingers_bent_back_or_twisted_are_faults_and_a_fist_is_not() {
|
||||
let skel = mannequin();
|
||||
let mid = skel.finger("index", Side::L).unwrap()[1];
|
||||
let curl = |deg: f32, tw: f32| {
|
||||
let mut p = skel.rest();
|
||||
for f in ["index", "middle", "ring", "pinky"] {
|
||||
for &i in &skel.finger(f, Side::L).unwrap() {
|
||||
p.turns[i] = finger_turn(&skel, i, deg, 0.0);
|
||||
}
|
||||
}
|
||||
p.turns[mid] = finger_turn(&skel, mid, deg, tw);
|
||||
p
|
||||
};
|
||||
let f = check(&clip(&skel, vec![curl(80.0, 0.0); 4], None));
|
||||
assert!(f.is_empty(), "a fist: {:?}", kinds(&f));
|
||||
let mut back = skel.rest();
|
||||
back.turns[mid] = finger_turn(&skel, mid, -40.0, 0.0);
|
||||
let f = check(&clip(&skel, vec![back; 4], None));
|
||||
assert!(f.iter().any(|f| f.check == "finger" && f.joint == "index_02_l" && f.says.contains("bent back")), "{:?}", f.iter().map(|f| &f.says).collect::<Vec<_>>());
|
||||
let f = check(&clip(&skel, vec![curl(60.0, 45.0); 4], None));
|
||||
assert!(f.iter().any(|f| f.check == "finger" && f.says.contains("twisted")), "{:?}", f.iter().map(|f| &f.says).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thumb_through_the_grip_is_said_and_a_grip_beside_it_is_not() {
|
||||
let skel = mannequin();
|
||||
let thumb = skel.finger("thumb", Side::L).unwrap()[1];
|
||||
let w = skel.fk(&skel.rest());
|
||||
let at = w.pos[thumb].lerp(crate::tip(&skel, &w, thumb), 0.5);
|
||||
let grip = Solid::Cylinder { half: 0.05, r: 0.012 };
|
||||
let through = vec![Some(Thing::new(grip, at)); 4];
|
||||
let f = check(&clip(&skel, vec![skel.rest(); 4], Some(through)));
|
||||
let t = f.iter().find(|f| f.check == "through" && f.joint == "thumb_02_l").unwrap_or_else(|| panic!("{:?}", kinds(&f)));
|
||||
assert!(t.value > 0.015, "{}", t.says);
|
||||
let beside = vec![Some(Thing::new(grip, at + Vec3::new(0.0, 0.0, 0.2))); 4];
|
||||
let f = check(&clip(&skel, vec![skel.rest(); 4], Some(beside)));
|
||||
assert!(f.is_empty(), "{:?}", kinds(&f));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_reads_from_json() {
|
||||
let skel = mannequin();
|
||||
let joints: Vec<serde_json::Value> = skel
|
||||
.joints
|
||||
.iter()
|
||||
.map(|j| serde_json::json!({"name": j.name, "parent": j.parent.map_or(-1, |p| p as i64), "head": j.head.to_array(), "tail": j.tail.to_array()}))
|
||||
.collect();
|
||||
let rest: Vec<[f32; 4]> = skel.joints.iter().map(|_| [0.0, 0.0, 0.0, 1.0]).collect();
|
||||
let frames: Vec<serde_json::Value> = (0..5).map(|k| serde_json::json!({"root": [0.01 * k as f32, 0.0, 0.0], "turns": rest, "thing": {"at": [2.0, 0.0, 0.0]}})).collect();
|
||||
let v = serde_json::json!({"joints": joints, "fps": 30, "frames": frames, "thing": {"box": [0.1, 0.1, 0.1]}});
|
||||
let c = clip_of(&v).unwrap();
|
||||
assert_eq!(c.poses.len(), 5);
|
||||
assert!(c.held.as_ref().unwrap().iter().all(|t| t.is_some()));
|
||||
assert_eq!(c.skel.joints.len(), skel.joints.len());
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn verdicts_move_a_line_for_that_joint_only() {
|
||||
use crate::verdicts::{Verdicts, key};
|
||||
let f = |joint: &str, value: f32| Fault { check: "skate", joint: joint.into(), from: 0, to: 9, peak: 4, value, unit: "m", says: String::new() };
|
||||
let mut v = Verdicts::default();
|
||||
// a crouch's drag of 9 cm called fine: 9 cm again is held back, 15 cm still stands, the other foot unmoved
|
||||
v.give(&f("LeftFoot", 0.09), false);
|
||||
assert_eq!(key(&f("LeftFoot", 0.09)), "skate:foot_l");
|
||||
assert!(!v.stands(&f("LeftFoot", 0.09)));
|
||||
assert!(v.stands(&f("LeftFoot", 0.15)));
|
||||
assert!(v.stands(&f("RightFoot", 0.09)));
|
||||
// a smaller one called real stands, and so does anything that size or more
|
||||
v.give(&f("LeftFoot", 0.085), true);
|
||||
assert!(v.stands(&f("LeftFoot", 0.09)));
|
||||
let back = Verdicts::of_json(&v.to_json());
|
||||
assert_eq!(back.keys, v.keys);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finding_gone_after_a_change_was_fixed() {
|
||||
use crate::verdicts::{fixed, record};
|
||||
let f = |check: &'static str, joint: &str, from: usize, value: f32| Fault { check, joint: joint.into(), from, to: from + 5, peak: from, value, unit: "deg", says: String::new() };
|
||||
let last = vec![record(&f("finger", "thumb_03_r", 200, 40.0)), record(&f("skate", "foot_l", 30, 0.09)), record(&f("buckle", "calf_l", 100, 15.0))];
|
||||
// the thumb fixed; the skate still there, moved a few frames; the buckle still there
|
||||
let now = vec![f("skate", "foot_l", 36, 0.08), f("buckle", "calf_l", 100, 15.0)];
|
||||
let got = fixed(&last, &now);
|
||||
assert_eq!(got.len(), 1, "{got:?}");
|
||||
assert!(got[0].0.starts_with("finger:") && got[0].1 == 40.0);
|
||||
assert!(fixed(&last, &[f("finger", "thumb_03_r", 205, 40.0), f("skate", "foot_l", 30, 0.09), f("buckle", "calf_l", 100, 15.0)]).is_empty(), "nothing changed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_verdict_on_the_finding_outranks_the_critic() {
|
||||
use crate::critic::{Critic, SAY, features};
|
||||
use crate::verdicts::Verdicts;
|
||||
let f = |v: f32| Fault { check: "finger", joint: "pinky_02_r".into(), from: 0, to: 3, peak: 0, value: v, unit: "deg", says: String::new() };
|
||||
// the critic taught that the pinky's small bends are fine, and over-learns it onto the big one
|
||||
let ex: Vec<_> = (0..12).map(|k| { let (x, t) = features(&f(10.0 + k as f32 * 0.4)); (x, t, 0.0) }).collect();
|
||||
let c = Critic::fit(&ex);
|
||||
assert!(c.score(&f(24.0)) < SAY);
|
||||
let mut v = Verdicts::default();
|
||||
v.give(&f(24.0), true);
|
||||
assert!(v.real_at(&f(24.0)) && v.real_at(&f(30.0)) && !v.real_at(&f(12.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shin_roll_its_foot_takes_back_is_no_limit_and_one_it_doesnt_is() {
|
||||
// a crouch's shin, then the same shin rolled half a turn about its bone: with the foot rolled back (the world pose
|
||||
// unchanged, as a solve's flipped roll leaves it) nothing is past its range; with the foot left, the roll is real
|
||||
let skel = mannequin();
|
||||
let (calf, foot) = (skel.joint("calf_l").unwrap(), skel.joint("foot_l").unwrap());
|
||||
let j = &skel.joints[calf];
|
||||
let roll = Quat::from_axis_angle((j.tail - j.head).normalize(), std::f32::consts::PI);
|
||||
let mut bent = skel.rest();
|
||||
bent.turns[calf] = bend(&skel, calf, 70.0);
|
||||
let mut undone = bent.clone();
|
||||
undone.turns[calf] = bent.turns[calf] * roll;
|
||||
undone.turns[foot] = roll.inverse() * bent.turns[foot];
|
||||
let (a, b) = (skel.fk(&bent), skel.fk(&undone));
|
||||
assert!(a.pos.iter().zip(&b.pos).all(|(x, y)| x.distance(*y) < 1e-4), "the roll moved a joint");
|
||||
let hits = crate::legs::limits(&skel, &[undone.clone()]);
|
||||
assert!(hits.is_empty(), "{:?}", hits.iter().map(|h| h.what.clone()).collect::<Vec<_>>());
|
||||
let mut kept = bent.clone();
|
||||
kept.turns[calf] = bent.turns[calf] * roll;
|
||||
assert!(!crate::legs::limits(&skel, &[kept]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hands_roll_stays_on_the_hand_and_a_change_of_checks_is_no_fix() {
|
||||
// a hand has five children: its roll moved to one finger would move the others, so it stays and is judged
|
||||
let skel = mannequin();
|
||||
let hand = skel.joint("hand_l").unwrap();
|
||||
assert!(skel.joints.iter().filter(|j| j.parent == Some(hand)).count() > 1, "the mannequin's hand has fingers");
|
||||
let j = &skel.joints[hand];
|
||||
let mut p = skel.rest();
|
||||
p.turns[hand] = Quat::from_axis_angle((j.tail - j.head).normalize(), 60f32.to_radians());
|
||||
let hits = crate::legs::limits(&skel, &[p]);
|
||||
assert!(hits.iter().any(|h| h.joint == j.name), "{:?}", hits.iter().map(|h| h.what.clone()).collect::<Vec<_>>());
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
//! What the motion checks learn from verdicts: each finding's key is its check and its joint's role ("skate:foot_l",
|
||||
//! "finger:index_02_r", "buckle:calf_l"), and a verdict moves that key's line. `fine` at a size raises the line to just
|
||||
//! above it (a foot that drags in a crouch, a captured hand bent further than the table allows); `real` at a size
|
||||
//! lowers it to that size, never under what was called fine. A size is the finding's `value`: for a finger or a
|
||||
//! joint limit, degrees past its range (a pinky bent back 25° against a 10° range is 15), not the angle said. Kept as JSON beside the scene judge's model
|
||||
//! (raea's models folder, notice/motion.json; RAEA_NOTICE_MOTION names another file).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Fault;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Verdicts {
|
||||
/// key -> (the largest size called fine, the smallest called real)
|
||||
pub keys: BTreeMap<String, (Option<f32>, Option<f32>)>,
|
||||
}
|
||||
|
||||
/// A finding's key: its check and its joint by role (the game_engine rig's name), so a verdict on one body holds on
|
||||
/// another rig's.
|
||||
pub fn key(f: &Fault) -> String {
|
||||
format!("{}:{}", f.check, raea_sys_body::rig::role_name(&f.joint))
|
||||
}
|
||||
|
||||
impl Verdicts {
|
||||
pub fn of_json(v: &Value) -> Verdicts {
|
||||
let mut keys = BTreeMap::new();
|
||||
for (k, x) in v["keys"].as_object().into_iter().flatten() {
|
||||
let n = |s: &str| x[s].as_f64().map(|v| v as f32);
|
||||
keys.insert(k.clone(), (n("fine"), n("real")));
|
||||
}
|
||||
Verdicts { keys }
|
||||
}
|
||||
|
||||
pub fn to_json(&self) -> Value {
|
||||
json!({"keys": self.keys.iter().map(|(k, (f, r))| (k.clone(), json!({"fine": f, "real": r}))).collect::<serde_json::Map<_, _>>()})
|
||||
}
|
||||
|
||||
pub fn load(path: &std::path::Path) -> Verdicts {
|
||||
Self::of_json(&crate::read_json(path).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// A verdict on a finding at its size.
|
||||
pub fn give(&mut self, f: &Fault, real: bool) {
|
||||
self.give_at(&key(f), f.value, real);
|
||||
}
|
||||
|
||||
/// A verdict on a key at a size.
|
||||
pub fn give_at(&mut self, k: &str, value: f32, real: bool) {
|
||||
let e = self.keys.entry(k.to_string()).or_default();
|
||||
if real {
|
||||
e.1 = Some(e.1.map_or(value, |r| r.min(value)));
|
||||
} else {
|
||||
e.0 = Some(e.0.map_or(value, |x| x.max(value)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a verdict called this key real at this size or smaller: then it stands whatever the critic says (a
|
||||
/// verdict on the finding itself outranks what the critic generalised from its neighbours).
|
||||
pub fn real_at(&self, f: &Fault) -> bool {
|
||||
self.keys.get(&key(f)).and_then(|e| e.1).is_some_and(|r| f.value >= r)
|
||||
}
|
||||
|
||||
/// Whether a finding still stands after the verdicts: one called real at its size or smaller stands; else one no
|
||||
/// bigger than the largest called fine (by a twentieth) is held back.
|
||||
pub fn stands(&self, f: &Fault) -> bool {
|
||||
let Some((fine, real)) = self.keys.get(&key(f)) else { return true };
|
||||
if real.is_some_and(|r| f.value >= r) {
|
||||
return true;
|
||||
}
|
||||
!fine.is_some_and(|x| f.value <= x * 1.05)
|
||||
}
|
||||
}
|
||||
|
||||
/// A finding as the next run reads it back: its key, its frames and its size.
|
||||
pub fn record(f: &Fault) -> Value {
|
||||
json!({"key": key(f), "from": f.from, "to": f.to, "value": f.value})
|
||||
}
|
||||
|
||||
/// Frames a finding may move by between runs and still be the same one.
|
||||
const SLOP: usize = 10;
|
||||
|
||||
/// What a fix shows. Of the last run's findings (`record`s), each gone now, no finding of its key within SLOP frames
|
||||
/// of its own, was fixed: a person or an agent changed the motion until it went, so it was real at its size. The
|
||||
/// caller compares runs of one character over the same frames.
|
||||
pub fn fixed(last: &[Value], now: &[Fault]) -> Vec<(String, f32, usize)> {
|
||||
last.iter()
|
||||
.filter_map(|r| {
|
||||
let (k, from, to, v) = (r["key"].as_str()?, r["from"].as_u64()? as usize, r["to"].as_u64()? as usize, r["value"].as_f64()? as f32);
|
||||
let still = now.iter().any(|f| key(f) == k && f.from <= to + SLOP && from <= f.to + SLOP);
|
||||
(!still).then(|| (k.to_string(), v, to.saturating_sub(from) + 1))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "raea-sys-notice"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "Whether a viewer would notice a 3D scene's fault: where each camera of a shot sees it, how large it shows, and a small model that learns from what people mark real or fine (raea scene faults)"
|
||||
|
||||
[dependencies]
|
||||
raea-core-ease = { path = "../../core/ease" }
|
||||
raea-core-scene = { path = "../../core/scene" }
|
||||
# the models folder a trained judge is kept in
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,170 @@
|
||||
//! A finding as numbers a model can weigh: what kind of fault it is, how large it shows and how often, how large it is
|
||||
//! in the world, and what the parts are (structural, soft, small), with the words of their names kept apart for the
|
||||
//! model to learn which ones excuse or condemn (a "map" in the air is hung; a "mug" in the air is a fault).
|
||||
|
||||
use bevy::math::Vec3;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::sight::{Seen, Spot};
|
||||
|
||||
/// The features, in the model's order.
|
||||
pub const NAMES: [&str; N] = ["bias", "seen", "share", "px", "mm", "floats", "sunk", "air", "clips", "zfight", "inside", "tilted", "seated", "structural", "soft", "small", "mounted", "stands"];
|
||||
/// How many features.
|
||||
pub const N: usize = 18;
|
||||
|
||||
/// Words of a structural surface: a join between two of them is where a room's shell meets itself.
|
||||
const STRUCTURAL: [&str; 16] = ["wall", "walls", "floor", "ceiling", "carpet", "vinyl", "tile", "slab", "ground", "skirting", "baseboard", "trim", "cove", "plaster", "shell", "roof"];
|
||||
/// Words of a soft thing: cloth drapes, folds into what it lies on and lifts off it a little.
|
||||
const SOFT: [&str; 18] = ["cloth", "towel", "sheet", "sheets", "socks", "sock", "sweater", "jeans", "dress", "shirt", "curtain", "blanket", "spread", "pillow", "rug", "mat", "hung", "fabric"];
|
||||
|
||||
/// Words of a thing that stands on what's under it: mounted on a wall beside it with a gap below, it was lifted.
|
||||
const STANDS: [&str; 24] = ["lamp", "phone", "cup", "cups", "mug", "glass", "bottle", "book", "vase", "plant", "pot", "chair", "stool", "table", "clock", "radio", "tv", "box", "can", "soda", "ashtray", "bag", "case", "suitcase"];
|
||||
|
||||
/// The words of a part's name: lower case, split at anything not a letter, with words carrying digits (r106) and
|
||||
/// one-letter ones left out.
|
||||
pub fn words(name: &str) -> Vec<String> {
|
||||
let base = name.split(" (its").next().unwrap_or(name);
|
||||
let mut out: Vec<String> = base.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| w.len() > 1 && !w.chars().any(|c| c.is_ascii_digit())).map(str::to_ascii_lowercase).filter(|w| w != "glb" && w != "gltf").collect();
|
||||
// and the node it's about, inside a model ("r106_table (its \"table_lam\")")
|
||||
if let Some(node) = name.split(" (its").nth(1) {
|
||||
out.extend(words(node.trim_matches(|c: char| !c.is_ascii_alphanumeric())));
|
||||
}
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
fn any_of(ws: &[String], list: &[&str]) -> bool {
|
||||
ws.iter().any(|w| list.contains(&w.as_str()))
|
||||
}
|
||||
|
||||
/// A finding read once: its kind, its parts, where it would show, and its size in the world.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Fault {
|
||||
pub key: String,
|
||||
pub check: String,
|
||||
pub part: String,
|
||||
pub into: Option<String>,
|
||||
pub says: String,
|
||||
pub spots: Vec<Spot>,
|
||||
/// spots carry square metres (a z-fight), not metres
|
||||
pub area: bool,
|
||||
/// the fault's size in the world, metres (a z-fight's: the side of a square of its area)
|
||||
pub size: f32,
|
||||
pub small: bool,
|
||||
}
|
||||
|
||||
fn v3(v: &Value) -> Option<Vec3> {
|
||||
let a = v.as_array()?;
|
||||
Some(Vec3::new(a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32, a.get(2)?.as_f64()? as f32))
|
||||
}
|
||||
|
||||
/// The checks a viewer could see wrong; rests, mounts, the ground and notes of what was skipped aren't faults.
|
||||
pub const FAULTS: [&str; 8] = ["floats", "sunk", "air", "clips", "zfight", "tilted", "seated", "mounted"];
|
||||
|
||||
/// A mounted part this far over what's under it is a candidate (a picture on a wall is one, a lamp lifted against it another).
|
||||
const LIFTED: f64 = 0.003;
|
||||
|
||||
/// A lint finding (raea-sys-contact's own row, `raea scene lint|explain --json`) as a Fault, None if it's no fault.
|
||||
pub fn fault(v: &Value) -> Option<Fault> {
|
||||
let check = v["check"].as_str()?.to_string();
|
||||
let lifted = check == "mounted" && v["gap"].as_f64().is_some_and(|g| g > LIFTED);
|
||||
if !FAULTS.contains(&check.as_str()) || (v["level"] == "ok" && !lifted) {
|
||||
return None;
|
||||
}
|
||||
let part = v["part"].as_str()?.to_string();
|
||||
let into = v["into"].as_str().or(v["on"].as_str()).map(String::from);
|
||||
let into = if check == "mounted" { v["under"].as_str().map(String::from).or(into) } else { into };
|
||||
let lo = v3(&v["box"]["min"]);
|
||||
let hi = v3(&v["box"]["max"]);
|
||||
let small = matches!((lo, hi), (Some(l), Some(h)) if (h - l).max_element() < 0.15);
|
||||
let gap = v["gap"].as_f64().unwrap_or(0.0) as f32;
|
||||
let mut spots = Vec::new();
|
||||
let mut area = false;
|
||||
let size: f32;
|
||||
match check.as_str() {
|
||||
"zfight" => {
|
||||
area = true;
|
||||
let a = v["area"].as_f64().unwrap_or(0.0) as f32;
|
||||
size = a.sqrt();
|
||||
for s in v["spots"].as_array().into_iter().flatten() {
|
||||
let r: Vec<f32> = serde_json::from_value(s.clone()).unwrap_or_default();
|
||||
if r.len() == 7 {
|
||||
spots.push(Spot { at: Vec3::new(r[0], r[1], r[2]), facing: Some(Vec3::new(r[3], r[4], r[5])), size: r[6] });
|
||||
}
|
||||
}
|
||||
if spots.is_empty()
|
||||
&& let Some(at) = v3(&v["at"])
|
||||
{
|
||||
spots.push(Spot { at, facing: None, size: a });
|
||||
}
|
||||
}
|
||||
"clips" => {
|
||||
size = v["depth"].as_f64().unwrap_or(0.0) as f32;
|
||||
for p in v["seam"].as_array().into_iter().flatten().filter_map(v3) {
|
||||
spots.push(Spot { at: p, facing: None, size });
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// a gap under a part shows at its foot all round: the box's bottom edge, drawn in a little (a round foot
|
||||
// sits inside its box's corners), at the height of the surface it's over
|
||||
size = if check == "tilted" { 0.0 } else { gap.abs().max(if check == "air" { 0.05 } else { 0.0 }) };
|
||||
// a mounted part's gap is no fault by its size (a picture hangs a metre over the floor): its spots carry
|
||||
// nothing, so it shows by whether it's seen and what it is
|
||||
let shown = if check == "mounted" { 0.0 } else { size };
|
||||
if let (Some(l), Some(h)) = (lo, hi) {
|
||||
let y = match (check.as_str(), v3(&v["at"])) {
|
||||
("floats", Some(at)) => at.y + gap * 0.5,
|
||||
("sunk" | "seated", Some(at)) => at.y - gap,
|
||||
_ => l.y + 0.002,
|
||||
};
|
||||
let c = (l + h) * 0.5;
|
||||
let r = (h - l) * 0.5 * 0.85;
|
||||
for (dx, dz) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0), (0.0, -1.0), (1.0, 0.0), (0.0, 1.0), (-1.0, 0.0)] {
|
||||
spots.push(Spot { at: Vec3::new(c.x + dx * r.x, y, c.z + dz * r.z), facing: None, size: shown });
|
||||
}
|
||||
if check == "air" || check == "tilted" || check == "mounted" {
|
||||
spots.push(Spot { at: c, facing: None, size: shown });
|
||||
}
|
||||
}
|
||||
if let Some(at) = v3(&v["at"]) {
|
||||
spots.push(Spot { at, facing: None, size: shown });
|
||||
}
|
||||
}
|
||||
}
|
||||
let key = format!("{check}:{part}|{}", into.as_deref().unwrap_or(""));
|
||||
Some(Fault { key, check, part, into, says: v["says"].as_str().unwrap_or("").to_string(), spots, area, size, small })
|
||||
}
|
||||
|
||||
/// The finding's features (NAMES' order) and its words, each keyed by its kind ("air:map").
|
||||
pub fn features(f: &Fault, s: &Seen) -> (Vec<f32>, Vec<String>) {
|
||||
let (wp, wi) = (words(&f.part), f.into.as_deref().map(words).unwrap_or_default());
|
||||
let structural = if f.into.is_some() { any_of(&wp, &STRUCTURAL) && any_of(&wi, &STRUCTURAL) } else { any_of(&wp, &STRUCTURAL) };
|
||||
let soft = any_of(&wp, &SOFT) || any_of(&wi, &SOFT);
|
||||
let is = |k: &str| (f.check == k) as u8 as f32;
|
||||
let inside = (f.check == "zfight" && f.into.is_none()) as u8 as f32;
|
||||
let x = vec![
|
||||
1.0,
|
||||
(s.shown > 0) as u8 as f32,
|
||||
if s.frames > 0 { s.shown as f32 / s.frames as f32 } else { 0.0 },
|
||||
(1.0 + s.px).log2(),
|
||||
(1.0 + f.size * 1000.0).log2(),
|
||||
is("floats"),
|
||||
is("sunk"),
|
||||
is("air"),
|
||||
is("clips"),
|
||||
is("zfight") - inside,
|
||||
inside,
|
||||
is("tilted"),
|
||||
is("seated"),
|
||||
structural as u8 as f32,
|
||||
soft as u8 as f32,
|
||||
f.small as u8 as f32,
|
||||
is("mounted"),
|
||||
(f.check == "mounted" && any_of(&wp, &STANDS)) as u8 as f32,
|
||||
];
|
||||
let mut toks: Vec<String> = wp.iter().map(|w| format!("{}:{w}", f.check)).collect();
|
||||
toks.extend(wi.iter().map(|w| format!("{}:on:{w}", f.check)));
|
||||
toks.sort();
|
||||
toks.dedup();
|
||||
(x, toks)
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
//! What the judge learns from: verdicts kept beside each project, in review/faults.labels.jsonl, one row a verdict with
|
||||
//! the finding's features as they were (so training never re-runs a scene). Two kinds:
|
||||
//! - marked: a person or agent says a finding is real (`--real KEY`) or fine (`--fine KEY`, meant as it is);
|
||||
//! - fixed: a finding the last run reported where a camera saw it is gone, both its parts are still there and no
|
||||
//! finding names the part now, so someone moved one: it was real. A finding no camera of a shot saw teaches nothing
|
||||
//! from its fix there, and one whose part is still found under another check (a gap that became a mount) wasn't
|
||||
//! fixed, only renamed. The last run's findings are kept in review/faults.last.json for that.
|
||||
//!
|
||||
//! `raea scene faults train` gathers every project's labels under a folder and fits the model (model.rs).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// What marks a project's folder.
|
||||
const PROJECT_MARKS: [&str; 2] = ["brief.ts", "AGENTS.md"];
|
||||
|
||||
/// The project a composition belongs to: the nearest folder up holding brief.ts or AGENTS.md, else its own.
|
||||
pub fn project_of(tsx: &Path) -> PathBuf {
|
||||
let start = tsx.parent().unwrap_or(Path::new("."));
|
||||
start.ancestors().find(|d| PROJECT_MARKS.iter().any(|m| d.join(m).is_file())).unwrap_or(start).to_path_buf()
|
||||
}
|
||||
|
||||
fn now() -> u64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// One verdict's row.
|
||||
pub fn row(key: &str, label: bool, by: &str, shot: &str, x: &[f32], toks: &[String]) -> Value {
|
||||
let at = now();
|
||||
json!({"key": key, "label": label as u8, "by": by, "shot": shot, "x": x, "toks": toks, "at": at})
|
||||
}
|
||||
|
||||
/// Rows appended to the project's labels.
|
||||
pub fn append(project: &Path, rows: &[Value]) -> Result<(), String> {
|
||||
if rows.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
use std::io::Write;
|
||||
let dir = project.join("review");
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let p = dir.join("faults.labels.jsonl");
|
||||
let mut f = std::fs::OpenOptions::new().create(true).append(true).open(&p).map_err(|e| format!("{}: {e}", p.display()))?;
|
||||
for r in rows {
|
||||
writeln!(f, "{r}").map_err(|e| format!("{}: {e}", p.display()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The last run's findings for `shot`: key, parts, features, words.
|
||||
pub fn last(project: &Path, shot: &str) -> Vec<Value> {
|
||||
let p = project.join("review").join("faults.last.json");
|
||||
std::fs::read_to_string(p).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).and_then(|v| v[shot].as_array().cloned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// This run's findings kept as the last for `shot` (other shots' left as they were).
|
||||
pub fn keep_last(project: &Path, shot: &str, rows: Vec<Value>) -> Result<(), String> {
|
||||
let dir = project.join("review");
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let p = dir.join("faults.last.json");
|
||||
let mut all = std::fs::read_to_string(&p).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).filter(Value::is_object).unwrap_or(json!({}));
|
||||
all[shot] = Value::Array(rows);
|
||||
std::fs::write(&p, serde_json::to_string(&all).unwrap_or_default()).map_err(|e| format!("{}: {e}", p.display()))
|
||||
}
|
||||
|
||||
/// The part a finding's key is about ("floats:mug|table" is the mug's).
|
||||
fn part_of(key: &str) -> &str {
|
||||
key.split_once(':').and_then(|(_, r)| r.split('|').next()).unwrap_or("")
|
||||
}
|
||||
|
||||
/// The last run's findings, seen on this shot, now gone though both their parts are still in the scene and nothing
|
||||
/// else is found of the part: fixed, so real.
|
||||
pub fn fixed(last: &[Value], now_keys: &[String], parts: &[String]) -> Vec<Value> {
|
||||
let here = |n: &Value| n.as_str().is_none_or(|n| n.is_empty() || parts.iter().any(|p| p == n));
|
||||
let busy = |p: &Value| p.as_str().is_some_and(|p| now_keys.iter().any(|k| part_of(k) == p));
|
||||
let seen = |r: &Value| r["x"].get(1).and_then(Value::as_f64).is_some_and(|s| s > 0.0);
|
||||
last.iter()
|
||||
.filter(|r| r["key"].as_str().is_some_and(|k| !now_keys.iter().any(|n| n == k)))
|
||||
.filter(|r| here(&r["part"]) && here(&r["into"]) && !busy(&r["part"]) && seen(r))
|
||||
.map(|r| {
|
||||
let x: Vec<f32> = serde_json::from_value(r["x"].clone()).unwrap_or_default();
|
||||
let toks: Vec<String> = r["toks"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(String::from)).collect();
|
||||
row(r["key"].as_str().unwrap_or(""), true, "fixed", r["shot"].as_str().unwrap_or(""), &x, &toks)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every labels file under `root` (node_modules, .git, target and out left out), at most `depth` folders down.
|
||||
pub fn files(root: &Path, depth: usize) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
let p = root.join("review").join("faults.labels.jsonl");
|
||||
if p.is_file() {
|
||||
out.push(p);
|
||||
}
|
||||
if depth == 0 {
|
||||
return out;
|
||||
}
|
||||
let Ok(rd) = std::fs::read_dir(root) else { return out };
|
||||
for e in rd.flatten() {
|
||||
let name = e.file_name().to_string_lossy().to_string();
|
||||
if name.starts_with('.') || ["node_modules", "target", "out", "media", "assets", "review"].contains(&name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if e.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
out.extend(files(&e.path(), depth - 1));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A file's verdicts as examples, the newest verdict on each finding winning.
|
||||
pub fn examples(file: &Path) -> Vec<(Vec<f32>, Vec<String>, f32)> {
|
||||
shots(file).into_iter().map(|(_, x, t, y)| (x, t, y)).collect()
|
||||
}
|
||||
|
||||
/// The verdicts as `examples` reads them, each with the shot it was given on (for a fit held out a shot at a time).
|
||||
pub fn shots(file: &Path) -> Vec<(String, Vec<f32>, Vec<String>, f32)> {
|
||||
// per shot and key the newest verdict, a person's over a vision model's (`by: "ask"`) whatever their order
|
||||
let mut by: std::collections::BTreeMap<String, (Vec<f32>, Vec<String>, f32, bool)> = Default::default();
|
||||
for line in std::fs::read_to_string(file).unwrap_or_default().lines() {
|
||||
let Ok(r) = serde_json::from_str::<Value>(line) else { continue };
|
||||
let x: Vec<f32> = serde_json::from_value(r["x"].clone()).unwrap_or_default();
|
||||
if x.len() != crate::features::NAMES.len() {
|
||||
continue;
|
||||
}
|
||||
let toks = r["toks"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(String::from)).collect();
|
||||
let key = format!("{}|{}", r["shot"].as_str().unwrap_or(""), r["key"].as_str().unwrap_or(""));
|
||||
let asked = r["by"] == "ask";
|
||||
if asked && by.get(&key).is_some_and(|e| !e.3) {
|
||||
continue;
|
||||
}
|
||||
by.insert(key, (x, toks, r["label"].as_f64().unwrap_or(0.0) as f32, asked));
|
||||
}
|
||||
by.into_iter().map(|(k, (x, t, y, _))| (k.split('|').next().unwrap_or("").to_string(), x, t, y)).collect()
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
//! Whether a viewer would notice a 3D scene's fault (`raea scene faults`). The lint (raea-sys-contact) measures every
|
||||
//! part against every other wherever they meet, so it finds what no camera sees as readily as what every frame shows:
|
||||
//! on room 106 of the Halcyon (approved 11-27), 32 errors, most of them walls meeting the ceiling inside the slab.
|
||||
//! A list that long gets skimmed, and the clip that shows gets missed with the rest.
|
||||
//!
|
||||
//! This judges each finding as a viewer of the shot would: every frame's camera asked where the fault would show
|
||||
//! (sight.rs: in frame, facing it, not behind any part, against the scene's real triangles), how many pixels its gap,
|
||||
//! depth or patch covers there, and what the parts are (features.rs). A small logistic model (model.rs) turns that into
|
||||
//! the chance it's a fault. It starts from a written prior and learns from verdicts kept beside each project
|
||||
//! (labels.rs): findings people mark real or fine, and findings that went away because someone fixed them.
|
||||
|
||||
use raea_core_scene::Item;
|
||||
use serde_json::Value;
|
||||
|
||||
pub mod features;
|
||||
pub mod labels;
|
||||
pub mod model;
|
||||
pub mod sight;
|
||||
|
||||
pub use features::{Fault, fault, features};
|
||||
pub use model::{FAULT, Model};
|
||||
pub use sight::{Cam, Scene, Seen, camera, seen};
|
||||
|
||||
/// A finding judged: the fault, what the cameras saw of it, its features and words, and its chance of being a fault.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Judged {
|
||||
pub fault: Fault,
|
||||
pub seen: Seen,
|
||||
pub x: Vec<f32>,
|
||||
pub toks: Vec<String>,
|
||||
pub p: f32,
|
||||
}
|
||||
|
||||
/// Each fault the lint found on `frames[0]` judged over every frame's camera, the likeliest first. `w`, `h`: the
|
||||
/// picture's size in pixels.
|
||||
pub fn judge(found: &[Value], frames: &[Vec<Item>], w: u32, h: u32, model: &Model) -> Vec<Judged> {
|
||||
let Some(first) = frames.first() else { return Vec::new() };
|
||||
let scene = Scene::of(first);
|
||||
let cams: Vec<Cam> = frames.iter().filter_map(|f| camera(f)).collect();
|
||||
judge_in(found, &scene, &cams, w, h, model)
|
||||
}
|
||||
|
||||
/// judge, given the scene's triangles and the cameras.
|
||||
pub fn judge_in(found: &[Value], scene: &Scene, cams: &[Cam], w: u32, h: u32, model: &Model) -> Vec<Judged> {
|
||||
let mut out: Vec<Judged> = found
|
||||
.iter()
|
||||
.filter_map(fault)
|
||||
.map(|f| {
|
||||
let s = seen(&f.spots, f.area, cams, scene, w as f32, h as f32);
|
||||
let (x, toks) = features(&f, &s);
|
||||
let p = model.score(&x, &toks);
|
||||
Judged { fault: f, seen: s, x, toks, p }
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|a, b| b.p.total_cmp(&a.p));
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,152 @@
|
||||
//! The judge: a logistic model over a finding's features and the words of its parts' names, the chance a viewer would
|
||||
//! call it wrong. It starts from a prior written down here (seen, and large enough on screen, is a fault; hidden is
|
||||
//! not) and learns from every verdict people and fixes leave (labels.rs): a weight drifts from its prior only as far as
|
||||
//! the labels pull it, and a word's weight starts at nothing. Small enough to run on every lint in microseconds and to
|
||||
//! read whole.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::features::{N, NAMES};
|
||||
|
||||
/// The prior, NAMES' order: how the judge weighs a finding before any label.
|
||||
pub const PRIOR: [f32; N] = [
|
||||
-3.0, // bias: a finding no camera sees is no fault
|
||||
1.5, // seen on some frame
|
||||
1.0, // and on more of them
|
||||
1.4, // log2(1 + pixels): a millimetre gap at arm's length is a few pixels, at five metres under one
|
||||
0.0, // log2(1 + mm) in the world: what shows is what counts, the pixels say it
|
||||
0.0, // floats
|
||||
0.0, // sunk
|
||||
1.0, // in the air: a thing with weight touching nothing reads wrong at any size
|
||||
0.5, // clips
|
||||
0.0, // z-fight between two parts
|
||||
-1.0, // z-fight inside one model: doubled faces often share a material and draw alike
|
||||
-0.5, // tilted
|
||||
-2.5, // seated: a post in the ground, a frame in its wall
|
||||
-1.0, // both parts structural: a room's shell meeting itself
|
||||
-0.7, // soft: cloth folds into and lifts off what it lies on
|
||||
0.0, // small
|
||||
-1.5, // mounted with a gap under it: mostly what hangs (a picture, a shelf, a sconce)
|
||||
4.0, // ... and named as a thing that stands (a lamp, a phone, a cup): lifted against the wall beside it
|
||||
];
|
||||
|
||||
/// A finding's chance of being a fault at or over this is said as one.
|
||||
pub const FAULT: f32 = 0.5;
|
||||
/// A verdict its finding already scores this sure of, either way, stops teaching.
|
||||
const MARGIN: f32 = 0.9;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Model {
|
||||
pub w: [f32; N],
|
||||
pub tokens: BTreeMap<String, f32>,
|
||||
/// labels it was fitted on (0: the prior alone)
|
||||
pub labels: usize,
|
||||
pub from: String,
|
||||
}
|
||||
|
||||
use raea_core_ease::sigmoid;
|
||||
|
||||
impl Model {
|
||||
pub fn prior() -> Model {
|
||||
Model { w: PRIOR, tokens: BTreeMap::new(), labels: 0, from: "the prior".into() }
|
||||
}
|
||||
|
||||
/// The model kept in raea's models folder (notice/faults.json, what `raea scene faults train` writes), else the prior.
|
||||
pub fn load() -> Model {
|
||||
let p = path();
|
||||
std::fs::read_to_string(&p).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).and_then(|v| Model::of_json(&v)).map(|mut m| {
|
||||
m.from = p.display().to_string();
|
||||
m
|
||||
}).unwrap_or_else(Model::prior)
|
||||
}
|
||||
|
||||
pub fn logit(&self, x: &[f32], toks: &[String]) -> f32 {
|
||||
let mut z: f32 = self.w.iter().zip(x).map(|(w, x)| w * x).sum();
|
||||
for t in toks {
|
||||
z += self.tokens.get(t).copied().unwrap_or(0.0);
|
||||
}
|
||||
z
|
||||
}
|
||||
|
||||
pub fn score(&self, x: &[f32], toks: &[String]) -> f32 {
|
||||
sigmoid(self.logit(x, toks))
|
||||
}
|
||||
|
||||
pub fn to_json(&self) -> Value {
|
||||
let w: serde_json::Map<String, Value> = NAMES.iter().zip(self.w).map(|(n, w)| (n.to_string(), json!((w * 1e4).round() / 1e4))).collect();
|
||||
let t: serde_json::Map<String, Value> = self.tokens.iter().filter(|(_, w)| w.abs() >= 1e-3).map(|(k, w)| (k.clone(), json!((w * 1e4).round() / 1e4))).collect();
|
||||
json!({"weights": w, "tokens": t, "labels": self.labels})
|
||||
}
|
||||
|
||||
pub fn of_json(v: &Value) -> Option<Model> {
|
||||
let mut w = PRIOR;
|
||||
for (k, n) in NAMES.iter().enumerate() {
|
||||
if let Some(x) = v["weights"][n].as_f64() {
|
||||
w[k] = x as f32;
|
||||
}
|
||||
}
|
||||
let tokens = v["tokens"].as_object()?.iter().filter_map(|(k, x)| Some((k.clone(), x.as_f64()? as f32))).collect();
|
||||
Some(Model { w, tokens, labels: v["labels"].as_u64().unwrap_or(0) as usize, from: String::new() })
|
||||
}
|
||||
|
||||
/// Fitted to labelled findings (features, words, 1 for a fault, 0 for fine): logistic regression by gradient
|
||||
/// descent, each weight held toward its prior and each word's toward nothing, so a few labels nudge it and many
|
||||
/// move it.
|
||||
pub fn fit(examples: &[(Vec<f32>, Vec<String>, f32)]) -> Model {
|
||||
let mut m = Model::prior();
|
||||
m.labels = examples.len();
|
||||
if examples.is_empty() {
|
||||
return m;
|
||||
}
|
||||
let (hold_w, hold_t, rate, steps) = (0.5f32, 0.3f32, 0.3f32, 3000);
|
||||
let n = examples.len() as f32;
|
||||
for (_, toks, _) in examples {
|
||||
for t in toks {
|
||||
m.tokens.entry(t.clone()).or_insert(0.0);
|
||||
}
|
||||
}
|
||||
// verdicts all one way (every one real, say) say what's wrong but nothing about where the line between
|
||||
// wrong and fine sits: then only the words learn, and the weights stay at the prior. 15 real verdicts and no fine
|
||||
// ones on room 106 (11-27) otherwise raised every weight toward "fault" and flipped walls' fixtures, mounted as
|
||||
// they should be, to faults
|
||||
let both = examples.iter().any(|e| e.2 >= 0.5) && examples.iter().any(|e| e.2 < 0.5);
|
||||
for _ in 0..steps {
|
||||
let mut gw = [0f32; N];
|
||||
let mut gt: BTreeMap<&str, f32> = BTreeMap::new();
|
||||
for (x, toks, y) in examples {
|
||||
let p = m.score(x, toks);
|
||||
// one already on its side by a margin teaches no more (else agreeing verdicts push forever)
|
||||
if (*y >= 0.5 && p >= MARGIN) || (*y < 0.5 && p <= 1.0 - MARGIN) {
|
||||
continue;
|
||||
}
|
||||
let e = p - y;
|
||||
for k in 0..N {
|
||||
gw[k] += e * x[k];
|
||||
}
|
||||
for t in toks {
|
||||
*gt.entry(t).or_insert(0.0) += e;
|
||||
}
|
||||
}
|
||||
if both {
|
||||
for k in 0..N {
|
||||
m.w[k] -= rate * (gw[k] / n + hold_w * (m.w[k] - PRIOR[k]) / n);
|
||||
}
|
||||
}
|
||||
for (t, g) in gt {
|
||||
let w = m.tokens.get_mut(t).unwrap();
|
||||
*w -= rate * (g / n + hold_t * *w / n);
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the trained judge is kept: RAEA_NOTICE_MODEL when set (a trial fit kept apart), else the models folder.
|
||||
pub fn path() -> std::path::PathBuf {
|
||||
match std::env::var_os("RAEA_NOTICE_MODEL").filter(|v| !v.is_empty()) {
|
||||
Some(p) => p.into(),
|
||||
None => raea_io_home::models().join("notice").join("faults.json"),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
//! Where a shot's cameras see a point: in frame, in front, not behind any part, and how many pixels a metre there
|
||||
//! covers. Every frame's camera is asked, against the scene's real triangles (a BVH over every part's), not boxes.
|
||||
|
||||
use bevy::math::{Mat4, Vec3, Vec4};
|
||||
use raea_core_scene::{Item, parts_of, vec3};
|
||||
use serde_json::Value;
|
||||
|
||||
/// One frame's camera: world to view, its eye, the focal scale (1 / tan of half the vertical field of view) and the
|
||||
/// fog's far edge.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Cam {
|
||||
pub view: Mat4,
|
||||
pub eye: Vec3,
|
||||
pub focal: f32,
|
||||
pub far: f32,
|
||||
}
|
||||
|
||||
/// The frame's camera (its first PerspectiveCamera: Camera3d's fov in degrees, its position and lookAt).
|
||||
pub fn camera(its: &[Item]) -> Option<Cam> {
|
||||
let c = its.iter().find(|i| i.kind == "camera")?;
|
||||
let p = vec3(&c.props, "position", [0.0, 0.0, 5.0]);
|
||||
let l = vec3(&c.props, "lookAt", [0.0, 0.0, 0.0]);
|
||||
let fov = c.props.get("fov").and_then(Value::as_f64).unwrap_or(50.0) as f32;
|
||||
let eye = Vec3::new(p[0] as f32, p[1] as f32, p[2] as f32);
|
||||
let at = Vec3::new(l[0] as f32, l[1] as f32, l[2] as f32);
|
||||
let far = its.iter().find(|i| i.kind == "fog").and_then(|f| f.props.get("far").and_then(Value::as_f64)).unwrap_or(f64::MAX) as f32;
|
||||
Some(Cam { view: look_at(eye, at), eye, focal: 1.0 / (fov.to_radians() * 0.5).tan(), far })
|
||||
}
|
||||
|
||||
fn look_at(eye: Vec3, at: Vec3) -> Mat4 {
|
||||
let f = (at - eye).normalize_or(Vec3::NEG_Z);
|
||||
let s = f.cross(Vec3::Y).normalize_or(Vec3::X);
|
||||
let u = s.cross(f);
|
||||
Mat4::from_cols(Vec4::new(s.x, u.x, -f.x, 0.0), Vec4::new(s.y, u.y, -f.y, 0.0), Vec4::new(s.z, u.z, -f.z, 0.0), Vec4::new(-eye.dot(s), -eye.dot(u), eye.dot(f), 1.0))
|
||||
}
|
||||
|
||||
struct Node {
|
||||
lo: Vec3,
|
||||
hi: Vec3,
|
||||
/// a leaf's first triangle and count; an inner node's two children
|
||||
a: u32,
|
||||
b: u32,
|
||||
leaf: bool,
|
||||
}
|
||||
|
||||
/// Every part's triangles in a bounding-volume hierarchy, for rays.
|
||||
pub struct Scene {
|
||||
tris: Vec<[Vec3; 3]>,
|
||||
nodes: Vec<Node>,
|
||||
}
|
||||
|
||||
/// A leaf holds at most this many triangles.
|
||||
const LEAF: usize = 4;
|
||||
|
||||
impl Scene {
|
||||
/// The parts of a frame (every mesh and model, the excused ones too: a wall left out of the checks still hides).
|
||||
pub fn of(its: &[Item]) -> Scene {
|
||||
let (parts, ..) = parts_of(its, &vec![false; its.len()]);
|
||||
Scene::new(parts.into_iter().flat_map(|p| p.tris).collect())
|
||||
}
|
||||
|
||||
/// Its triangles' count.
|
||||
pub fn len(&self) -> usize {
|
||||
self.tris.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.tris.is_empty()
|
||||
}
|
||||
|
||||
/// The distance from `p` to the nearest surface, up to `look`: along the 26 directions of a cube's faces, edges and
|
||||
/// corners, each bisected to under a millimetre at a few centimetres. A fingertip's distance from what a hand holds.
|
||||
pub fn reach(&self, p: Vec3, look: f32) -> f32 {
|
||||
let mut best = look;
|
||||
for x in -1..=1i32 {
|
||||
for y in -1..=1i32 {
|
||||
for z in -1..=1i32 {
|
||||
if (x, y, z) == (0, 0, 0) {
|
||||
continue;
|
||||
}
|
||||
let d = Vec3::new(x as f32, y as f32, z as f32).normalize();
|
||||
if !self.blocked(p, p + d * best, 0.0) {
|
||||
continue;
|
||||
}
|
||||
let (mut lo, mut hi) = (0.0, best);
|
||||
for _ in 0..7 {
|
||||
let m = (lo + hi) / 2.0;
|
||||
if self.blocked(p, p + d * m, 0.0) { hi = m } else { lo = m }
|
||||
}
|
||||
best = hi;
|
||||
}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
pub fn new(tris: Vec<[Vec3; 3]>) -> Scene {
|
||||
let mut s = Scene { tris, nodes: Vec::new() };
|
||||
if !s.tris.is_empty() {
|
||||
let n = s.tris.len();
|
||||
s.build(0, n);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn build(&mut self, a: usize, b: usize) -> u32 {
|
||||
let (mut lo, mut hi) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
|
||||
let (mut clo, mut chi) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
|
||||
for t in &self.tris[a..b] {
|
||||
for p in t {
|
||||
lo = lo.min(*p);
|
||||
hi = hi.max(*p);
|
||||
}
|
||||
let c = (t[0] + t[1] + t[2]) / 3.0;
|
||||
clo = clo.min(c);
|
||||
chi = chi.max(c);
|
||||
}
|
||||
let me = self.nodes.len();
|
||||
self.nodes.push(Node { lo, hi, a: a as u32, b: (b - a) as u32, leaf: true });
|
||||
if b - a <= LEAF {
|
||||
return me as u32;
|
||||
}
|
||||
let e = chi - clo;
|
||||
let k = if e.x >= e.y && e.x >= e.z { 0 } else if e.y >= e.z { 1 } else { 2 };
|
||||
let mid = (a + b) / 2;
|
||||
self.tris[a..b].select_nth_unstable_by(mid - a, |p, q| (p[0][k] + p[1][k] + p[2][k]).total_cmp(&(q[0][k] + q[1][k] + q[2][k])));
|
||||
let left = self.build(a, mid);
|
||||
let right = self.build(mid, b);
|
||||
self.nodes[me] = Node { lo, hi, a: left, b: right, leaf: false };
|
||||
me as u32
|
||||
}
|
||||
|
||||
/// Whether anything lies on the segment from `a` to `b` (its first `skip` metres and last millimetre left out).
|
||||
pub fn blocked(&self, a: Vec3, b: Vec3, skip: f32) -> bool {
|
||||
let len = (b - a).length();
|
||||
if self.nodes.is_empty() || len <= skip + 0.001 {
|
||||
return false;
|
||||
}
|
||||
let d = (b - a) / len;
|
||||
let inv = d.recip();
|
||||
let (t0, t1) = (skip, len - 0.001);
|
||||
let mut stack = vec![0u32];
|
||||
while let Some(i) = stack.pop() {
|
||||
let n = &self.nodes[i as usize];
|
||||
if !slab(a, inv, n.lo, n.hi, t0, t1) {
|
||||
continue;
|
||||
}
|
||||
if n.leaf {
|
||||
for t in &self.tris[n.a as usize..(n.a + n.b) as usize] {
|
||||
if hit(a, d, t).is_some_and(|t| t > t0 && t < t1) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
stack.push(n.a);
|
||||
stack.push(n.b);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn slab(o: Vec3, inv: Vec3, lo: Vec3, hi: Vec3, mut t0: f32, mut t1: f32) -> bool {
|
||||
for k in 0..3 {
|
||||
let (a, b) = ((lo[k] - o[k]) * inv[k], (hi[k] - o[k]) * inv[k]);
|
||||
let (a, b) = if a <= b { (a, b) } else { (b, a) };
|
||||
// a ray along a box's face (inv infinite, 0 * inf NaN) counts as inside on that axis
|
||||
if a.is_nan() || b.is_nan() {
|
||||
if o[k] < lo[k] || o[k] > hi[k] {
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
t0 = t0.max(a);
|
||||
t1 = t1.min(b);
|
||||
if t0 > t1 {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Möller-Trumbore: the distance along `d` from `o` to triangle `t`, either side facing.
|
||||
fn hit(o: Vec3, d: Vec3, t: &[Vec3; 3]) -> Option<f32> {
|
||||
let (e1, e2) = (t[1] - t[0], t[2] - t[0]);
|
||||
let p = d.cross(e2);
|
||||
let det = e1.dot(p);
|
||||
if det.abs() < 1e-12 {
|
||||
return None;
|
||||
}
|
||||
let s = o - t[0];
|
||||
let u = s.dot(p) / det;
|
||||
if !(0.0..=1.0).contains(&u) {
|
||||
return None;
|
||||
}
|
||||
let q = s.cross(e1);
|
||||
let v = d.dot(q) / det;
|
||||
if v < 0.0 || u + v > 1.0 {
|
||||
return None;
|
||||
}
|
||||
Some(e2.dot(q) / det)
|
||||
}
|
||||
|
||||
/// A point where a fault would show, and the way its surface faces when that's known (a z-fight's faces).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Spot {
|
||||
pub at: Vec3,
|
||||
pub facing: Option<Vec3>,
|
||||
/// what of the fault this spot carries: metres (a gap, a depth) or square metres (a z-fight's patch)
|
||||
pub size: f32,
|
||||
}
|
||||
|
||||
/// What the shot's cameras saw of a fault.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Seen {
|
||||
/// frames asked, and frames on which some spot showed
|
||||
pub frames: usize,
|
||||
pub shown: usize,
|
||||
/// the most pixels it covered on one frame: a length's pixels, or a patch's side (the square root of its pixels)
|
||||
pub px: f32,
|
||||
/// the nearest it came to the camera, metres (0 when never seen)
|
||||
pub near: f32,
|
||||
/// the camera it shows largest to (its index), and where its spots show there: x and y from -1 to 1, y up
|
||||
pub best: Option<usize>,
|
||||
pub marks: Vec<[f32; 2]>,
|
||||
}
|
||||
|
||||
/// Pixels a metre covers at view depth `z`, on a picture `h` pixels tall.
|
||||
fn px_per_m(c: &Cam, z: f32, h: f32) -> f32 {
|
||||
c.focal * h * 0.5 / z
|
||||
}
|
||||
|
||||
/// Each camera asked whether any spot shows (in frame with a margin, in front, nearer than the fog, facing it, not
|
||||
/// behind a part), and how large: a gap's or depth's metres as pixels, a patch's area as pixels squared summed over the
|
||||
/// spots that show.
|
||||
pub fn seen(spots: &[Spot], area: bool, cams: &[Cam], scene: &Scene, w: f32, h: f32) -> Seen {
|
||||
let mut s = Seen { frames: cams.len(), ..Seen::default() };
|
||||
for (ci, c) in cams.iter().enumerate() {
|
||||
let (mut px, mut any, mut near) = (0f32, false, f32::MAX);
|
||||
let mut marks = Vec::new();
|
||||
for p in spots {
|
||||
let q = c.view.transform_point3(p.at);
|
||||
let z = -q.z;
|
||||
if z <= 0.05 || z >= c.far {
|
||||
continue;
|
||||
}
|
||||
let (x, y) = (q.x / z * c.focal * h / w, q.y / z * c.focal);
|
||||
if x.abs() > 1.02 || y.abs() > 1.02 {
|
||||
continue;
|
||||
}
|
||||
if p.facing.is_some_and(|n| n.dot(c.eye - p.at) <= 0.0) {
|
||||
continue;
|
||||
}
|
||||
// off the surface toward the eye first: the spot's own faces aren't in its way
|
||||
if scene.blocked(p.at, c.eye, 0.003) {
|
||||
continue;
|
||||
}
|
||||
any = true;
|
||||
marks.push([x, y]);
|
||||
near = near.min(z);
|
||||
let k = px_per_m(c, z, h);
|
||||
px = if area { px + p.size * k * k } else { px.max(p.size * k) };
|
||||
}
|
||||
if any {
|
||||
s.shown += 1;
|
||||
let px = if area { px.sqrt() } else { px };
|
||||
if s.best.is_none() || px > s.px {
|
||||
(s.best, s.marks) = (Some(ci), marks);
|
||||
}
|
||||
s.px = s.px.max(px);
|
||||
s.near = if s.near == 0.0 { near } else { s.near.min(near) };
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
use super::*;
|
||||
use bevy::math::{Mat4, Vec3};
|
||||
use serde_json::json;
|
||||
|
||||
fn cam(eye: [f32; 3], at: [f32; 3], fov: f32) -> Cam {
|
||||
let props = json!({"position": eye, "lookAt": at, "fov": fov}).as_object().unwrap().clone();
|
||||
camera(&[Item { kind: "camera", props: std::sync::Arc::new(props), shape: None, at: None, material: None, world: Mat4::IDENTITY }]).unwrap()
|
||||
}
|
||||
|
||||
/// A box's twelve triangles.
|
||||
fn cube(c: Vec3, s: Vec3) -> Vec<[Vec3; 3]> {
|
||||
let h = s / 2.0;
|
||||
let p = |x: f32, y: f32, z: f32| c + Vec3::new(x * h.x, y * h.y, z * h.z);
|
||||
let quads = [
|
||||
[p(-1., -1., 1.), p(1., -1., 1.), p(1., 1., 1.), p(-1., 1., 1.)],
|
||||
[p(1., -1., -1.), p(-1., -1., -1.), p(-1., 1., -1.), p(1., 1., -1.)],
|
||||
[p(-1., 1., 1.), p(1., 1., 1.), p(1., 1., -1.), p(-1., 1., -1.)],
|
||||
[p(-1., -1., -1.), p(1., -1., -1.), p(1., -1., 1.), p(-1., -1., 1.)],
|
||||
[p(1., -1., 1.), p(1., -1., -1.), p(1., 1., -1.), p(1., 1., 1.)],
|
||||
[p(-1., -1., -1.), p(-1., -1., 1.), p(-1., 1., 1.), p(-1., 1., -1.)],
|
||||
];
|
||||
quads.iter().flat_map(|q| [[q[0], q[1], q[2]], [q[0], q[2], q[3]]]).collect()
|
||||
}
|
||||
|
||||
/// A room: a floor slab, a wall at z = -2 and a table, with a mug on the table.
|
||||
fn room() -> Scene {
|
||||
let mut t = cube(Vec3::new(0.0, -0.05, 0.0), Vec3::new(6.0, 0.1, 6.0));
|
||||
t.extend(cube(Vec3::new(0.0, 1.25, -2.05), Vec3::new(6.0, 2.5, 0.1)));
|
||||
t.extend(cube(Vec3::new(0.0, 0.725, 0.0), Vec3::new(1.2, 0.05, 0.8)));
|
||||
Scene::new(t)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rays_stop_at_parts() {
|
||||
let s = room();
|
||||
// through the wall
|
||||
assert!(s.blocked(Vec3::new(0.0, 1.0, -3.0), Vec3::new(0.0, 1.0, 2.0), 0.003));
|
||||
// over the table, in the open
|
||||
assert!(!s.blocked(Vec3::new(0.0, 1.0, -1.5), Vec3::new(0.0, 1.0, 2.0), 0.003));
|
||||
// from the table's top straight up
|
||||
assert!(!s.blocked(Vec3::new(0.0, 0.751, 0.0), Vec3::new(0.0, 2.0, 0.0), 0.003));
|
||||
// from under the table, up through it
|
||||
assert!(s.blocked(Vec3::new(0.0, 0.5, 0.0), Vec3::new(0.0, 2.0, 0.0), 0.003));
|
||||
}
|
||||
|
||||
fn floats(name: &str, gap: f64, c: [f32; 3]) -> Value {
|
||||
let (lo, hi) = ([c[0] - 0.04, c[1], c[2] - 0.04], [c[0] + 0.04, c[1] + 0.1, c[2] + 0.04]);
|
||||
json!({"part": name, "check": "floats", "level": "error", "on": "table", "gap": gap, "at": [c[0], c[1] - gap as f32, c[2]], "box": {"min": lo, "max": hi}, "says": format!("{name} floats")})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gap_in_view_is_a_fault_and_one_out_of_it_is_not() {
|
||||
let s = room();
|
||||
let m = Model::prior();
|
||||
let near = [cam([0.0, 1.2, 1.0], [0.0, 0.75, 0.0], 40.0)];
|
||||
let far = [cam([0.0, 1.6, 5.0], [0.0, 0.75, 0.0], 40.0)];
|
||||
let behind = [cam([0.0, 1.2, -1.0], [0.0, 1.2, -3.0], 40.0)];
|
||||
let mug = [floats("mug", 0.004, [0.1, 0.754, 0.1])];
|
||||
let j = |c: &[Cam]| judge_in(&mug, &s, c, 1920, 1080, &m).remove(0);
|
||||
let (a, b, c) = (j(&near), j(&far), j(&behind));
|
||||
assert_eq!(a.seen.shown, 1);
|
||||
assert!(a.seen.px > 4.0, "{:?}", a.seen);
|
||||
assert!(a.p >= FAULT, "{}", a.p);
|
||||
// five metres off it covers under two pixels: still seen, less sure
|
||||
assert!(b.seen.px < a.seen.px / 3.0, "{:?}", b.seen);
|
||||
assert!(b.p < a.p);
|
||||
// the camera turned to the wall: not seen, no fault
|
||||
assert_eq!(c.seen.shown, 0);
|
||||
assert!(c.p < 0.1, "{}", c.p);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zfight_inside_a_wall_is_hidden() {
|
||||
let s = room();
|
||||
let m = Model::prior();
|
||||
let cams = [cam([0.0, 1.4, 1.5], [0.0, 1.0, -2.0], 50.0)];
|
||||
// a carpet's edge running under the wall: its faces in the floor's plane, but inside the wall's foot
|
||||
let under = json!({"part": "carpet", "into": "walls", "check": "zfight", "level": "error", "area": 0.03, "spots": [[0.5, 0.0, -2.05, 0.0, 1.0, 0.0, 0.03]], "says": "x"});
|
||||
// a rug's face in the floor's, out in the room
|
||||
let open = json!({"part": "rug", "into": "floor", "check": "zfight", "level": "error", "area": 0.5, "spots": [[1.5, 0.0, -1.0, 0.0, 1.0, 0.0, 0.25], [1.2, 0.0, -1.2, 0.0, 1.0, 0.0, 0.25]], "says": "x"});
|
||||
let j = judge_in(&[under, open], &s, &cams, 1920, 1080, &m);
|
||||
let by = |n: &str| j.iter().find(|x| x.fault.part == n).unwrap();
|
||||
assert_eq!(by("carpet").seen.shown, 0);
|
||||
assert!(by("carpet").p < 0.1);
|
||||
assert_eq!(by("rug").seen.shown, 1);
|
||||
assert!(by("rug").p >= FAULT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verdicts_teach_it_words() {
|
||||
// three maps in the air marked fine, three mugs in the air marked real, all seen alike
|
||||
let s = Seen { frames: 4, shown: 4, px: 40.0, near: 1.5, ..Seen::default() };
|
||||
let air = |name: &str| {
|
||||
let v = json!({"part": name, "check": "air", "level": "error", "box": {"min": [0, 1, 0], "max": [0.3, 1.4, 0.02]}, "says": "x"});
|
||||
features(&fault(&v).unwrap(), &s)
|
||||
};
|
||||
let mut ex = Vec::new();
|
||||
for _ in 0..3 {
|
||||
let (x, t) = air("r106_map");
|
||||
ex.push((x, t, 0.0));
|
||||
let (x, t) = air("mug");
|
||||
ex.push((x, t, 1.0));
|
||||
}
|
||||
let m = Model::fit(&ex);
|
||||
let (xm, tm) = air("office_map");
|
||||
let (xg, tg) = air("mug_b");
|
||||
assert!(m.score(&xm, &tm) < 0.5, "{}", m.score(&xm, &tm));
|
||||
assert!(m.score(&xg, &tg) > 0.8, "{}", m.score(&xg, &tg));
|
||||
// and the model round-trips through its file's JSON
|
||||
let back = Model::of_json(&m.to_json()).unwrap();
|
||||
assert!((back.score(&xm, &tm) - m.score(&xm, &tm)).abs() < 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fixed_finding_is_a_real_one() {
|
||||
let mut seen = vec![0.0f32; 18];
|
||||
seen[1] = 1.0;
|
||||
let row = |key: &str, part: &str, into: &str, x: &[f32]| json!({"key": key, "part": part, "into": into, "x": x, "toks": [], "shot": "a"});
|
||||
let last = vec![
|
||||
row("floats:mug|table", "mug", "table", &seen),
|
||||
row("air:lamp|", "lamp", "", &seen),
|
||||
// no camera saw this one: its going teaches nothing
|
||||
row("floats:cup|table", "cup", "table", &[0.0f32; 18]),
|
||||
// a gap that became a mount isn't fixed, only renamed
|
||||
row("floats:socks|carpet", "socks", "carpet", &seen),
|
||||
];
|
||||
let parts: Vec<String> = ["mug", "table", "cup", "socks", "carpet"].map(String::from).to_vec();
|
||||
// the mug's gap is gone, both parts still there; the lamp's finding went with the lamp
|
||||
let rows = labels::fixed(&last, &["mounted:socks|carpet".into()], &parts);
|
||||
assert_eq!(rows.len(), 1, "{rows:?}");
|
||||
assert_eq!(rows[0]["key"], "floats:mug|table");
|
||||
assert_eq!(rows[0]["label"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn words_of_names() {
|
||||
assert_eq!(features::words("r106_table (its \"table_lam\")"), vec!["table", "lam"]);
|
||||
assert_eq!(features::words("/media/props/bed_kit.glb"), vec!["media", "props", "bed", "kit"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lamp_lifted_against_the_wall_is_a_fault_and_a_picture_is_not() {
|
||||
let s = room();
|
||||
let m = Model::prior();
|
||||
let cams = [cam([0.0, 1.4, 1.5], [0.0, 1.0, -2.0], 50.0)];
|
||||
let mounted = |name: &str, y: f32, gap: f64| json!({"part": name, "check": "mounted", "level": "ok", "on": "wall", "gap": gap, "under": "floor",
|
||||
"box": {"min": [0.4, y, -2.0], "max": [0.7, y + 0.4, -1.8]}, "says": "x"});
|
||||
let j = judge_in(&[mounted("r106_lamp_b", 0.27, 0.27), mounted("r106_picture", 1.2, 1.2)], &s, &cams, 1920, 1080, &m);
|
||||
let by = |n: &str| j.iter().find(|x| x.fault.part == n).unwrap();
|
||||
assert!(by("r106_lamp_b").p >= FAULT, "{}", by("r106_lamp_b").p);
|
||||
assert!(by("r106_picture").p < 0.2, "{}", by("r106_picture").p);
|
||||
// and mounted flush on what's under it (no gap) is no candidate
|
||||
assert!(fault(&json!({"part": "shelf", "check": "mounted", "level": "ok", "on": "wall", "says": "x"})).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_persons_verdict_outranks_a_vision_models() {
|
||||
let dir = std::env::temp_dir().join(format!("notice-ask-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("faults.labels.jsonl");
|
||||
let x = vec![0.0f32; crate::features::NAMES.len()];
|
||||
let rows = [crate::labels::row("air:map|", false, "marked", "shot-tv", &x, &[]), crate::labels::row("air:map|", true, "ask", "shot-tv", &x, &[]), crate::labels::row("air:mug|", true, "ask", "shot-tv", &x, &[])];
|
||||
std::fs::write(&file, rows.iter().map(|r| r.to_string()).collect::<Vec<_>>().join("\n")).unwrap();
|
||||
let mut ex = crate::labels::examples(&file);
|
||||
ex.sort_by(|a, b| a.2.total_cmp(&b.2));
|
||||
// the map: Shane's fine stands over the later ask; the mug: only the ask, so it counts
|
||||
assert_eq!(ex.iter().map(|e| e.2).collect::<Vec<_>>(), vec![0.0, 1.0]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verdicts_all_one_way_teach_words_not_the_line() {
|
||||
use crate::model::{Model, PRIOR};
|
||||
let n = crate::features::NAMES.len();
|
||||
let mut x = vec![0.0f32; n];
|
||||
x[0] = 1.0;
|
||||
x[1] = 1.0;
|
||||
let ex: Vec<(Vec<f32>, Vec<String>, f32)> = (0..15).map(|_| (x.clone(), vec!["seated:carpet".to_string()], 1.0)).collect();
|
||||
let m = Model::fit(&ex);
|
||||
assert_eq!(m.w, PRIOR, "the weights stay at the prior");
|
||||
assert!(m.tokens["seated:carpet"] > 0.0, "the word learns");
|
||||
// a finding sharing no word scores as the prior did
|
||||
assert_eq!(m.score(&x, &["mounted:fixtures".to_string()]), Model::prior().score(&x, &["mounted:fixtures".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reach_is_the_distance_to_the_nearest_surface() {
|
||||
use bevy::math::Vec3;
|
||||
// a floor 2 m square at y = 0
|
||||
let (a, b, c, d) = (Vec3::new(-1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, 1.0), Vec3::new(-1.0, 0.0, 1.0));
|
||||
let floor = crate::Scene::new(vec![[a, b, c], [a, c, d]]);
|
||||
let r = floor.reach(Vec3::new(0.1, 0.02, 0.0), 0.06);
|
||||
assert!((r - 0.02).abs() < 0.002, "20 mm above the floor read as {r}");
|
||||
assert_eq!(floor.reach(Vec3::new(0.0, 0.5, 0.0), 0.06), 0.06, "nothing within the look");
|
||||
}
|
||||
@@ -1,155 +0,0 @@
|
||||
// The colour a procedural surface draws (lib.rs), as a module with no bindings, imports, stages or derivatives, so a
|
||||
// fragment shader and a compute kernel can both take it (docs/bake.feature BK3): what a pixel knows from its screen
|
||||
// derivatives comes in as an argument. NOT YET USED: procmat.wesl still has its own copy, and takes this one (the copy
|
||||
// deleted) in the commit that compiles it.
|
||||
|
||||
struct Proc {
|
||||
a: vec4<f32>,
|
||||
b: vec4<f32>,
|
||||
gap_color: vec4<f32>,
|
||||
dust_color: vec4<f32>,
|
||||
dirt_color: vec4<f32>,
|
||||
// kind, scale, rough_a, rough_b
|
||||
k: vec4<f32>,
|
||||
// bump, seed, tile_x, tile_y
|
||||
t: vec4<f32>,
|
||||
// gap, dust, dirt, edges
|
||||
w: vec4<f32>,
|
||||
}
|
||||
|
||||
fn proc_hash(p: vec3<f32>) -> f32 {
|
||||
let q = fract(p * 0.3183099 + vec3(0.1, 0.2, 0.3));
|
||||
let r = q * 17.0;
|
||||
return fract(r.x * r.y * r.z * (r.x + r.y + r.z));
|
||||
}
|
||||
|
||||
fn proc_vnoise(p: vec3<f32>) -> f32 {
|
||||
let i = floor(p);
|
||||
let f = fract(p);
|
||||
let u = f * f * (3.0 - 2.0 * f);
|
||||
let a = mix(mix(proc_hash(i), proc_hash(i + vec3(1.0, 0.0, 0.0)), u.x), mix(proc_hash(i + vec3(0.0, 1.0, 0.0)), proc_hash(i + vec3(1.0, 1.0, 0.0)), u.x), u.y);
|
||||
let b = mix(mix(proc_hash(i + vec3(0.0, 0.0, 1.0)), proc_hash(i + vec3(1.0, 0.0, 1.0)), u.x), mix(proc_hash(i + vec3(0.0, 1.0, 1.0)), proc_hash(i + vec3(1.0, 1.0, 1.0)), u.x), u.y);
|
||||
return mix(a, b, u.z);
|
||||
}
|
||||
|
||||
fn proc_fbm(p: vec3<f32>) -> f32 {
|
||||
var s = 0.0;
|
||||
var w = 0.5;
|
||||
var q = p;
|
||||
for (var k = 0; k < 5; k++) {
|
||||
s += w * proc_vnoise(q);
|
||||
q = q * 2.03 + vec3(1.7, 9.2, 3.1);
|
||||
w *= 0.5;
|
||||
}
|
||||
return s / 0.96875;
|
||||
}
|
||||
|
||||
// the face's own plane: the two axes across the dominant normal (a wall's x-y, a floor's x-z)
|
||||
fn proc_plane(p: vec3<f32>, n: vec3<f32>) -> vec2<f32> {
|
||||
let a = abs(n);
|
||||
if (a.y >= a.x && a.y >= a.z) { return p.xz; }
|
||||
if (a.x >= a.z) { return vec2(p.z, p.y); }
|
||||
return p.xy;
|
||||
}
|
||||
|
||||
// (mix between a and b, gap mask, height 0..1); duv: how much of the face's plane (proc_plane) a pixel or a texel covers
|
||||
fn proc_pattern(pm: Proc, p: vec3<f32>, n: vec3<f32>, duv: vec2<f32>) -> vec3<f32> {
|
||||
let kind = i32(pm.k.x + 0.5);
|
||||
let q = p / max(pm.k.y, 1e-4) + vec3(pm.t.y * 17.3);
|
||||
let uv = proc_plane(p, n);
|
||||
// wood: rings round the local y axis, wandering, and fine grain along it
|
||||
if (kind == 1) {
|
||||
let r = length(q.xz + vec2(proc_fbm(q * 0.4), proc_fbm(q * 0.4 + 7.0)) * 0.6) * 4.0;
|
||||
let ring = smoothstep(0.0, 0.6, fract(r)) * (1.0 - smoothstep(0.75, 1.0, fract(r)));
|
||||
let grain = proc_vnoise(vec3(q.x * 30.0, q.y * 1.5, q.z * 30.0));
|
||||
let m = clamp(ring * 0.75 + grain * 0.35, 0.0, 1.0);
|
||||
return vec3(m, 0.0, 0.3 * ring + 0.2 * grain);
|
||||
}
|
||||
// marble: sharp veins through soft clouding
|
||||
if (kind == 2) {
|
||||
let v = pow(1.0 - abs(sin(q.x * 2.0 + q.y * 0.7 + proc_fbm(q * 0.8) * 7.0)), 10.0);
|
||||
let cloud = proc_fbm(q * 0.5) * 0.3;
|
||||
return vec3(clamp(v + cloud, 0.0, 1.0), 0.0, 0.05 * v);
|
||||
}
|
||||
// stone / concrete: mottled, pitted, speckled
|
||||
if (kind == 3) {
|
||||
let m = proc_fbm(q);
|
||||
let pits = smoothstep(0.78, 0.84, proc_vnoise(q * 9.0));
|
||||
let speck = step(0.93, proc_hash(floor(q * 30.0)));
|
||||
return vec3(clamp(m * 0.8 + speck * 0.4, 0.0, 1.0), pits, m * 0.6 - pits * 0.5);
|
||||
}
|
||||
// brick (running bond) and tiles: cells on the face's plane with gaps between, each cell its own shade
|
||||
if (kind == 4 || kind == 5) {
|
||||
let size = vec2(max(pm.t.z, 1e-3), max(pm.t.w, 1e-3));
|
||||
var c = uv / size;
|
||||
let row = floor(c.y);
|
||||
if (kind == 4) { c.x += 0.5 * (row - 2.0 * floor(row / 2.0)); }
|
||||
let id = floor(c);
|
||||
let f = fract(c);
|
||||
let g = vec2(pm.w.x) / size;
|
||||
let edge = min(min(f.x, 1.0 - f.x) / max(g.x, 1e-4), min(f.y, 1.0 - f.y) / max(g.y, 1e-4));
|
||||
let gap = 1.0 - smoothstep(0.5, 1.0, edge);
|
||||
let shade = proc_hash(vec3(id, pm.t.y)) * 0.7 + proc_fbm(q * 2.0) * 0.3;
|
||||
let bevel = smoothstep(0.5, 2.0, edge);
|
||||
return vec3(shade, gap, bevel * (0.8 + 0.2 * proc_fbm(q * 3.0)));
|
||||
}
|
||||
// fabric: a plain weave
|
||||
if (kind == 6) {
|
||||
let f = uv / max(pm.k.y, 1e-4) * 6.2831;
|
||||
let warp = 0.5 + 0.5 * sin(f.x) * sign(sin(f.y * 0.5));
|
||||
let weft = 0.5 + 0.5 * sin(f.y) * sign(sin(f.x * 0.5 + 1.57));
|
||||
// threads finer than a pixel fade to the weave's mean shade, so a distant sofa doesn't shimmer in moire
|
||||
let far = smoothstep(0.8, 2.5, length(duv) / max(pm.k.y, 1e-4) * 6.2831);
|
||||
let m = mix(max(warp, weft), 0.72, far);
|
||||
return vec3(clamp(m * 0.6 + proc_fbm(q * 0.3) * 0.4, 0.0, 1.0), 0.0, m * (1.0 - far));
|
||||
}
|
||||
// brushed metal: long fine streaks along the face
|
||||
if (kind == 7) {
|
||||
let sy = uv.y / max(pm.k.y, 1e-4) * 60.0;
|
||||
let s = mix(proc_vnoise(vec3(uv.x / max(pm.k.y, 1e-4) * 0.4, sy, pm.t.y)), 0.5, smoothstep(0.5, 1.5, duv.y / max(pm.k.y, 1e-4) * 60.0));
|
||||
return vec3(s * 0.6 + proc_fbm(q * 0.2) * 0.4, 0.0, s * 0.15);
|
||||
}
|
||||
// plaster: soft trowel marks and fine bumps
|
||||
if (kind == 8) {
|
||||
let m = proc_fbm(q * 0.6);
|
||||
let fine = proc_vnoise(q * 18.0);
|
||||
return vec3(m, 0.0, m * 0.5 + fine * 0.2);
|
||||
}
|
||||
// noise: two colours by fractal noise
|
||||
let m = proc_fbm(q);
|
||||
return vec3(m, 0.0, m * 0.5);
|
||||
}
|
||||
|
||||
// Where a surface is drawn: its point and normal in the mesh's own space and the world's, and how fast its normal turns
|
||||
// (1 / metres: the raster's fwidth of the normal over the position's; a ray hit's, over its triangle's edges).
|
||||
struct ProcAt {
|
||||
p: vec3<f32>,
|
||||
wp: vec3<f32>,
|
||||
wn: vec3<f32>,
|
||||
curve: f32,
|
||||
}
|
||||
|
||||
// (colour, roughness) of the pattern with its use over it: dust on what faces up; dirt in the gaps, the hollows,
|
||||
// undersides and along the floor line; edges worn lighter and smoother where hands and feet go
|
||||
fn proc_drawn(pm: Proc, pat: vec3<f32>, at: ProcAt) -> vec4<f32> {
|
||||
let t = pat.x;
|
||||
let gap = pat.y;
|
||||
var c = mix(pm.a.rgb, pm.b.rgb, t);
|
||||
var rough = mix(pm.k.z, pm.k.w, t);
|
||||
c = mix(c, pm.gap_color.rgb, gap);
|
||||
rough = mix(rough, 0.95, gap);
|
||||
let wq = at.p / max(pm.k.y, 1e-4) * 0.7 + vec3(pm.t.y * 3.1);
|
||||
let up = smoothstep(0.55, 0.95, at.wn.y);
|
||||
let dust = clamp(up * pm.w.y * (0.55 + 0.45 * proc_fbm(wq * 2.0 + 30.0)), 0.0, 0.9);
|
||||
c = mix(c, pm.dust_color.rgb, dust);
|
||||
rough = mix(rough, 0.95, dust);
|
||||
let floor_line = 1.0 - smoothstep(0.0, 0.25, at.wp.y);
|
||||
let under = clamp(-at.wn.y, 0.0, 1.0);
|
||||
let dirt = clamp((gap * 0.8 + under * 0.5 + floor_line * 0.7 + smoothstep(0.6, 0.9, proc_fbm(wq * 0.8 + 50.0)) * 0.4) * pm.w.z, 0.0, 0.85) * (0.6 + 0.4 * proc_fbm(wq * 3.0 + 70.0));
|
||||
c = mix(c, pm.dirt_color.rgb, dirt);
|
||||
rough = mix(rough, 0.9, dirt);
|
||||
let edge = smoothstep(25.0, 90.0, at.curve) * pm.w.w * (0.5 + 0.5 * proc_fbm(wq * 4.0 + 90.0));
|
||||
c = mix(c, min(c * 1.35 + vec3(0.04), vec3(1.0)), edge);
|
||||
rough = mix(rough, rough * 0.6, edge);
|
||||
return vec4(c, rough);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ description = "Gaussian splats (<Splat>): .ply, .splat and .spz clouds drawn as
|
||||
native = []
|
||||
|
||||
[dependencies]
|
||||
raea-core-ease = { path = "../../core/ease" }
|
||||
raea-sys-frame = { path = "../frame" }
|
||||
raea-core-program = { path = "../../core/program" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }
|
||||
|
||||
@@ -53,9 +53,7 @@ pub(crate) struct Raw {
|
||||
|
||||
pub(crate) const SH_C0: f32 = 0.282_094_8;
|
||||
|
||||
pub(crate) fn sigmoid(x: f32) -> f32 {
|
||||
1.0 / (1.0 + (-x).exp())
|
||||
}
|
||||
pub(crate) use raea_core_ease::sigmoid;
|
||||
|
||||
pub(crate) fn read_cloud(path: &Path) -> Result<Cloud, String> {
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("splat {}: {e}", path.display()))?;
|
||||
|
||||
+2
-3
@@ -104,6 +104,8 @@ raea-runtime-jsengine = "runtime"
|
||||
raea-sys-a11y = "systems"
|
||||
raea-sys-bake = "systems"
|
||||
raea-sys-contact = "systems"
|
||||
raea-sys-notice = "systems" # raea scene faults: whether a viewer would notice a lint finding
|
||||
raea-sys-motionfaults = "systems" # raea scene faults --clip: faults that only show in motion
|
||||
raea-sys-light-meter = "systems"
|
||||
raea-sys-stage = "systems" # SG10-SG14: 3D type that reads, parts that don't snap, a camera that settles, a composed frame
|
||||
raea-sys-measure = "systems"
|
||||
@@ -222,7 +224,6 @@ raea-app-scene = "apps" # raea scene lint|explain|light|stage
|
||||
raea-app-voice = "apps" # raea voice: speech to speech on this computer, as lines of JSON
|
||||
raea-app-ask = "apps"
|
||||
raea-app-lightbake = "apps" # raea bake light (docs/bake.feature)
|
||||
raea-sys-lighttrace = "systems" # light paths on the GPU by wgpu ray queries: the kernel the bake, rt and the path tracer share (docs/bake.feature BK3)
|
||||
raea-sys-lightbake = "systems" # light baked over raea/wear's atlas on raea's ray tracer (docs/bake.feature)
|
||||
raea-app-double = "apps"
|
||||
raea-app-solid = "apps"
|
||||
@@ -337,5 +338,3 @@ raea-sys-damage = true
|
||||
raea-sys-glb = true
|
||||
# the atlas raea's bakes share: charts, packing, each texel's point (the cause maps and the light bake lie over it)
|
||||
raea-sys-atlas = true
|
||||
# the paths a bake traces its light along (the kernel and its Settings), which systems/rt and the path tracer may build on too
|
||||
raea-sys-lighttrace = true
|
||||
Reference in new issue
Block a user