M9.11: 3D Channel effects on auxiliary channels
Aux-channel model (effectcraft_raster::channels3d: depth, object/material ID, normals, UV, coverage, Cryptomatte ranks + manifests, MurmurHash3); EffectHost::aux; multi-layer OpenEXR channels via the exr crate (FootageSource::aux); the compositor's depth / layer-ID / Cryptomatte pass (Renderer::comp_aux) so the effects work on precomps of 3D comps. 3D Channel Extract, Cryptomatte, Depth Matte, Depth of Field, EXtractoR, Fog 3D, ID Matte, IDentifier. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
7b815bcbb2
commit
9a11c577f3
@@ -39,6 +39,12 @@ pub trait FootageSource: Send + Sync {
|
||||
fn audio(&self, _item: ItemId, _footage: &Footage, _t: Tick, _frames: usize, _rate: u32) -> Option<Vec<f32>> {
|
||||
None
|
||||
}
|
||||
/// Auxiliary 3D channels of `item` at source time `t` (multi-layer OpenEXR: depth, IDs,
|
||||
/// Cryptomatte, any named channel), with `scale` relative to the file's pixels. `None` when
|
||||
/// the footage has none.
|
||||
fn aux(&self, _item: ItemId, _footage: &Footage, _t: Tick) -> Option<Arc<effectcraft_raster::AuxChannels>> {
|
||||
None
|
||||
}
|
||||
/// Set the decoded-frame cache budget in bytes (Settings ▸ Memory & CPU); sources without
|
||||
/// a cache ignore it.
|
||||
fn set_cache_budget(&self, _bytes: usize) {}
|
||||
@@ -107,6 +113,29 @@ impl EffectHost for FxHost<'_, '_, '_> {
|
||||
sub.layer_input(&self.ctx.at(t), self.layer, n).map(|b| (*b).clone())
|
||||
}
|
||||
|
||||
fn aux(&self) -> Option<Arc<effectcraft_raster::AuxChannels>> {
|
||||
match &self.layer.source {
|
||||
LayerSource::Footage { item } => {
|
||||
let ItemKind::Footage(f) = &self.r.project.item(*item)?.kind else { return None };
|
||||
let a = self.r.footage.aux(*item, f, self.ctx.source_time(self.layer))?;
|
||||
// Aux pixels per layer pixel (the layer is the footage at its nominal size).
|
||||
if f.width > 0 && a.width > 0 {
|
||||
let mut a = (*a).clone();
|
||||
a.scale = a.width as f64 / f.width as f64;
|
||||
return Some(Arc::new(a));
|
||||
}
|
||||
Some(a)
|
||||
}
|
||||
LayerSource::Comp { item } => {
|
||||
if self.r.depth > MAX_FX_DEPTH || self.r.project.comp_contains(*item, self.ctx.comp_id) {
|
||||
return None;
|
||||
}
|
||||
self.r.nested().comp_aux(*item, self.ctx.source_time(self.layer)).map(Arc::new)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn layer_at(&self, id: u64, comp_time: f64, masks_and_effects: bool) -> Option<LayerPixels> {
|
||||
let other = self.ctx.layer(effectcraft_project::LayerId(id))?;
|
||||
if other.id == self.layer.id || self.r.depth > MAX_FX_DEPTH {
|
||||
@@ -1175,6 +1204,13 @@ impl<'a> Renderer<'a> {
|
||||
self.depth
|
||||
}
|
||||
|
||||
/// The auxiliary 3D channels of comp `comp_id` at comp time `t` (depth, layer IDs, normals,
|
||||
/// UVs, Cryptomatte; see `three_d::compose::aux_pass`), at the renderer's output scale.
|
||||
pub fn comp_aux(&self, comp_id: ItemId, t: Tick) -> Option<effectcraft_raster::AuxChannels> {
|
||||
let ctx = self.eval_ctx(comp_id, t)?;
|
||||
Some(three_d::compose::aux_pass(self, &ctx))
|
||||
}
|
||||
|
||||
/// Evaluation context of comp `comp_id` at comp time `t`.
|
||||
pub fn eval_ctx(&self, comp_id: ItemId, t: Tick) -> Option<EvalCtx<'a>> {
|
||||
Some(self.ctx(comp_id, self.project.comp(comp_id)?, t))
|
||||
@@ -1295,6 +1331,8 @@ pub fn kurbo_path(sp: &effectcraft_keyframe::ShapePath) -> kurbo::BezPath {
|
||||
#[cfg(test)]
|
||||
mod tests_audio_fx;
|
||||
#[cfg(test)]
|
||||
mod tests_aux;
|
||||
#[cfg(test)]
|
||||
mod tests_collapse;
|
||||
#[cfg(test)]
|
||||
mod tests_color;
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
//! Auxiliary 3D channels: the comp's depth / ID / Cryptomatte pass and the 3D Channel effects on
|
||||
//! a precomp of a 3D comp.
|
||||
|
||||
use effectcraft_color::Label;
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::build::{self, Ids};
|
||||
use effectcraft_project::{Comp, ItemId, ItemKind, Layer, LayerSource, Project, Solid};
|
||||
use effectcraft_raster::channels3d::{BACKGROUND_DEPTH, crypto_hash};
|
||||
use effectcraft_time::{FrameRate, Tick};
|
||||
|
||||
use crate::{NoFootage, RenderOpts, Renderer, render_frame};
|
||||
|
||||
const W: u32 = 200;
|
||||
const H: u32 = 100;
|
||||
|
||||
fn zoom() -> f64 {
|
||||
W as f64 * 50.0 / 36.0
|
||||
}
|
||||
|
||||
fn solid3(p: &mut Project, comp: &Comp, name: &str, color: [f32; 3], pos: [f64; 3]) -> Layer {
|
||||
let sid = p.add_item(name, Label::Red, None, ItemKind::Solid(Solid { color, width: 60, height: 60, pixel_aspect: 1.0 }));
|
||||
let mut l = build::layer(p, comp, name, LayerSource::Solid { item: sid }, (60, 60), None);
|
||||
l.name = name.to_string();
|
||||
l.switches.three_d = true;
|
||||
l.props.prop_mut("transform/position").unwrap().value = Value::Vec3(pos);
|
||||
l
|
||||
}
|
||||
|
||||
/// Inner 3D comp: "Near" (red, z 0, left) above "Far" (green, z 500, right). Outer comp: the
|
||||
/// precomp layer, optionally with an effect.
|
||||
fn scene(effect: Option<(&str, Vec<(&str, Value)>)>) -> (Project, ItemId, ItemId) {
|
||||
let mut p = Project::default();
|
||||
p.settings.bit_depth = effectcraft_project::BitDepth::Bpc32;
|
||||
let inner = Comp::new(W, H, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
|
||||
let iid = p.add_item("Inner", Label::Sandstone, None, ItemKind::Comp(inner.clone().into()));
|
||||
let near = solid3(&mut p, &inner, "Near", [1.0, 0.0, 0.0], [60.0, 50.0, 0.0]);
|
||||
let far = solid3(&mut p, &inner, "Far", [0.0, 1.0, 0.0], [140.0, 50.0, 500.0]);
|
||||
p.comp_mut(iid).unwrap().layers.push(near);
|
||||
p.comp_mut(iid).unwrap().layers.push(far);
|
||||
let outer = Comp::new(W, H, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
|
||||
let oid = p.add_item("Outer", Label::Sandstone, None, ItemKind::Comp(outer.clone().into()));
|
||||
let mut pre = build::layer(&mut p, &outer, "Inner", LayerSource::Comp { item: iid }, (W, H), None);
|
||||
if let Some((id, vals)) = effect {
|
||||
let spec = effectcraft_effects::find(id).unwrap();
|
||||
let mut next = p.next_id;
|
||||
let mut g = effectcraft_effects::instantiate(spec, &mut Ids(&mut next), spec.name, [W as f64, H as f64]);
|
||||
p.next_id = next;
|
||||
for (k, v) in vals {
|
||||
g.prop_mut(k).unwrap().value = v.clone();
|
||||
}
|
||||
pre.props.sub_mut("effects").unwrap().children.push(g.into());
|
||||
}
|
||||
p.comp_mut(oid).unwrap().layers.push(pre);
|
||||
(p, iid, oid)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comp_aux_pass_has_depth_ids_and_cryptomatte() {
|
||||
let (p, iid, _) = scene(None);
|
||||
let r = Renderer::new(&p, &NoFootage, RenderOpts::default());
|
||||
let a = r.comp_aux(iid, Tick::ZERO).unwrap();
|
||||
assert_eq!((a.width, a.height), (W, H));
|
||||
let at = |name: &str, x: usize, y: usize| a.get(name).unwrap()[y * W as usize + x];
|
||||
// Near plane at the camera's zoom distance, the far one 500 px behind it.
|
||||
assert!((at("Z", 60, 50) as f64 - zoom()).abs() < 1e-2, "{}", at("Z", 60, 50));
|
||||
assert!((at("Z", 114, 50) as f64 - (zoom() + 500.0)).abs() < 1e-2, "{}", at("Z", 114, 50));
|
||||
assert_eq!(at("Z", 5, 5), BACKGROUND_DEPTH);
|
||||
assert_eq!((at("ObjectID", 60, 50), at("ObjectID", 114, 50), at("ObjectID", 5, 5)), (1.0, 2.0, 0.0));
|
||||
assert_eq!(at("Coverage", 60, 50), 1.0);
|
||||
// Planes face the camera.
|
||||
assert!((at("N.Z", 60, 50) + 1.0).abs() < 1e-5);
|
||||
// Cryptomatte rank 0 = the layer under the pixel, full coverage; manifest lists names.
|
||||
assert_eq!(at("CryptoObject00.R", 60, 50).to_bits(), crypto_hash("Near"));
|
||||
assert_eq!(at("CryptoObject00.G", 60, 50), 1.0);
|
||||
assert_eq!(a.manifest_name("CryptoObject", crypto_hash("Far")), Some("Far"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_d_channel_effects_work_on_a_precomp_of_a_3d_comp() {
|
||||
let near = (60, 50);
|
||||
let far = (114, 50);
|
||||
let alpha = |p: &Project, oid: ItemId, (x, y): (i64, i64)| render_frame(p, oid, Tick::ZERO, 1.0).get(x, y)[3];
|
||||
let (p, _, oid) = scene(Some(("ec.3d.idmatte", vec![("idSelection", Value::Scalar(2.0))])));
|
||||
assert_eq!(alpha(&p, oid, near), 0.0);
|
||||
assert!(alpha(&p, oid, far) > 0.99);
|
||||
let (p, _, oid) = scene(Some(("ec.3d.depthmatte", vec![("depth", Value::Scalar(zoom() + 250.0))])));
|
||||
assert_eq!(alpha(&p, oid, near), 0.0);
|
||||
assert!(alpha(&p, oid, far) > 0.99);
|
||||
let (p, _, oid) = scene(Some(("ec.3d.cryptomatte", vec![("selection", Value::Str("Near".into())), ("display", Value::Enum(1))])));
|
||||
assert!(alpha(&p, oid, near) > 0.99);
|
||||
assert_eq!(alpha(&p, oid, far), 0.0);
|
||||
// Half resolution: the pass follows the render scale.
|
||||
let (p, iid, _) = scene(None);
|
||||
let r = Renderer::new(&p, &NoFootage, RenderOpts { scale: 0.5, ..Default::default() });
|
||||
let a = r.comp_aux(iid, Tick::ZERO).unwrap();
|
||||
assert_eq!((a.width, a.height, a.scale), (W / 2, H / 2, 0.5));
|
||||
assert_eq!(a.get("ObjectID").unwrap()[25 * 100 + 30], 1.0);
|
||||
}
|
||||
@@ -583,3 +583,182 @@ fn occlusion(c: &Item, p: Vec3, l: &LightState) -> [f32; 3] {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ auxiliary render pass
|
||||
|
||||
/// One surface seen through an output pixel (aux pass).
|
||||
#[derive(Clone, Copy)]
|
||||
struct AuxFrag {
|
||||
z: f32,
|
||||
a: f32,
|
||||
obj: f32,
|
||||
mat: f32,
|
||||
n: [f32; 3],
|
||||
uv: [f32; 2],
|
||||
obj_hash: u32,
|
||||
mat_hash: u32,
|
||||
}
|
||||
|
||||
/// The comp's auxiliary channels at the context time, at output resolution: camera-space depth
|
||||
/// (`Z`), `ObjectID` (layer number), `MaterialID` (source item id), `Coverage`, camera-space
|
||||
/// normals (`N.X/Y/Z`), texture coordinates (`UV.U/V`) and Cryptomatte `CryptoObject` (layer
|
||||
/// names) / `CryptoMaterial` (source names) with two ranks each, plus their manifests.
|
||||
///
|
||||
/// Layers are gathered in stack order (top first); a run of 3D layers contributes its planes
|
||||
/// sorted near → far at each pixel, a 2D layer its coverage on the plane of the comp. The
|
||||
/// front-most surface with ≥ 50 % opacity (else the strongest one) provides depth, IDs, normal
|
||||
/// and UV; Cryptomatte coverage is each surface's visible share (`α · Π(1 − α_front)`).
|
||||
pub(crate) fn aux_pass(r: &Renderer, ctx: &EvalCtx) -> effectcraft_raster::AuxChannels {
|
||||
use effectcraft_raster::channels3d::{BACKGROUND_DEPTH, crypto_float, crypto_hash};
|
||||
let s = r.opts.scale;
|
||||
let (w, h) = (((ctx.comp.width as f64 * s).round() as u32).max(1), ((ctx.comp.height as f64 * s).round() as u32).max(1));
|
||||
let out = (w, h);
|
||||
let (wu, n) = (w as usize, w as usize * h as usize);
|
||||
let cam = camera_for(r, ctx);
|
||||
let visible: Vec<&Layer> = r.visible_layers(ctx).into_iter().filter(|l| !l.switches.adjustment).collect();
|
||||
let number = |l: &Layer| ctx.comp.layers.iter().position(|x| x.id == l.id).map_or(0.0, |i| i as f32 + 1.0);
|
||||
let source_name = |l: &Layer| l.source.item().and_then(|i| r.project.item(i)).map(|it| it.name.clone()).unwrap_or_else(|| l.name.clone());
|
||||
let source_id = |l: &Layer| l.source.item().map_or(0.0, |i| i.0 as f32);
|
||||
let mut manifest_obj: Vec<(String, u32)> = vec![];
|
||||
let mut manifest_mat: Vec<(String, u32)> = vec![];
|
||||
for l in &visible {
|
||||
let (on, mn) = (l.name.clone(), source_name(l));
|
||||
if !manifest_obj.iter().any(|(x, _)| *x == on) {
|
||||
manifest_obj.push((on.clone(), crypto_hash(&on)));
|
||||
}
|
||||
if !manifest_mat.iter().any(|(x, _)| *x == mn) {
|
||||
manifest_mat.push((mn.clone(), crypto_hash(&mn)));
|
||||
}
|
||||
}
|
||||
// Groups in stack order: runs of 3D layers, single 2D layers.
|
||||
let mut groups: Vec<&[&Layer]> = vec![];
|
||||
let mut i = 0;
|
||||
while i < visible.len() {
|
||||
let mut j = i + 1;
|
||||
if visible[i].is_3d() {
|
||||
while j < visible.len() && visible[j].is_3d() {
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
groups.push(&visible[i..j]);
|
||||
i = j;
|
||||
}
|
||||
let mut frags: Vec<Vec<AuxFrag>> = vec![Vec::new(); n];
|
||||
let plane_z = cam.depth(vec3(ctx.comp.width as f64 * 0.5, ctx.comp.height as f64 * 0.5, 0.0)) as f32;
|
||||
for g in groups.iter().rev() {
|
||||
if g[0].is_3d() {
|
||||
let items: Vec<Item> = g.iter().enumerate().flat_map(|(k, l)| prepare_all(r, ctx, l, k, out, true)).collect();
|
||||
let meta: Vec<(f32, f32, u32, u32, [f32; 3], [f64; 2])> = items
|
||||
.iter()
|
||||
.map(|it| {
|
||||
let nrm = it.geos.first().map_or(vec3(0.0, 0.0, -1.0), |gm| cam.view.apply_vec(gm.normal));
|
||||
let mut nv = [nrm.x as f32, nrm.y as f32, nrm.z as f32];
|
||||
if nv[2] > 0.0 {
|
||||
nv = nv.map(|v| -v);
|
||||
}
|
||||
let (sw, sh) = crate::source_size(r.project, it.layer);
|
||||
let size = if sw == 0 { [ctx.comp.width as f64, ctx.comp.height as f64] } else { [sw as f64, sh as f64] };
|
||||
(number(it.layer), source_id(it.layer), crypto_hash(&it.layer.name), crypto_hash(&source_name(it.layer)), nv, size)
|
||||
})
|
||||
.collect();
|
||||
frags.par_chunks_mut(wu).enumerate().for_each(|(y, row)| {
|
||||
let yi = y as i64;
|
||||
let mut local: Vec<AuxFrag> = Vec::new();
|
||||
for (x, cell) in row.iter_mut().enumerate() {
|
||||
let xi = x as i64;
|
||||
local.clear();
|
||||
for (it, m) in items.iter().zip(&meta) {
|
||||
if xi < it.bbox[0] || xi >= it.bbox[2] || yi < it.bbox[1] || yi >= it.bbox[3] {
|
||||
continue;
|
||||
}
|
||||
let Some(gm) = it.geos.first() else { continue };
|
||||
let Some((u, v, z)) = unproject(gm, x as f64 + 0.5, y as f64 + 0.5) else { continue };
|
||||
let a = it.texel(u, v)[3] * it.opacity;
|
||||
if a > 1e-4 {
|
||||
let uv = [(u / m.5[0]) as f32, (v / m.5[1]) as f32];
|
||||
local.push(AuxFrag { z: z as f32, a: a.min(1.0), obj: m.0, mat: m.1, n: m.4, uv, obj_hash: m.2, mat_hash: m.3 });
|
||||
}
|
||||
}
|
||||
local.sort_by(|p, q| p.z.total_cmp(&q.z));
|
||||
cell.extend_from_slice(&local);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
let l = g[0];
|
||||
let mut img = Image::new(w, h);
|
||||
if let Some(b) = r.layer_buf(ctx, l) {
|
||||
r.place(ctx, l, &b, &mut img, BlendMode::Normal, ctx.opacity(l) as f32);
|
||||
}
|
||||
let (obj, mat, oh, mh) = (number(l), source_id(l), crypto_hash(&l.name), crypto_hash(&source_name(l)));
|
||||
frags.par_chunks_mut(wu).zip(img.data.par_chunks(wu)).enumerate().for_each(|(y, (row, px))| {
|
||||
for (x, (cell, p)) in row.iter_mut().zip(px).enumerate() {
|
||||
if p[3] > 1e-4 {
|
||||
let uv = [(x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32];
|
||||
cell.push(AuxFrag { z: plane_z, a: p[3].min(1.0), obj, mat, n: [0.0, 0.0, -1.0], uv, obj_hash: oh, mat_hash: mh });
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
// Resolve per pixel.
|
||||
const NAMES: [&str; 9] = ["Z", "ObjectID", "MaterialID", "Coverage", "N.X", "N.Y", "N.Z", "UV.U", "UV.V"];
|
||||
const CRYPTO: usize = 16;
|
||||
let resolved: Vec<([f32; 9], [f32; CRYPTO])> = frags
|
||||
.par_iter()
|
||||
.map(|fs| {
|
||||
let mut o = [BACKGROUND_DEPTH, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
|
||||
let mut crypto = [0.0f32; CRYPTO];
|
||||
if fs.is_empty() {
|
||||
return (o, crypto);
|
||||
}
|
||||
let mut t = 1.0f32;
|
||||
let mut obj: Vec<(u32, f32)> = vec![];
|
||||
let mut mat: Vec<(u32, f32)> = vec![];
|
||||
let mut best: Option<(usize, f32)> = None;
|
||||
let mut front: Option<usize> = None;
|
||||
for (k, f) in fs.iter().enumerate() {
|
||||
let c = f.a * t;
|
||||
if front.is_none() && f.a >= 0.5 {
|
||||
front = Some(k);
|
||||
}
|
||||
if best.is_none_or(|(_, bc)| c > bc) {
|
||||
best = Some((k, c));
|
||||
}
|
||||
for (list, hsh) in [(&mut obj, f.obj_hash), (&mut mat, f.mat_hash)] {
|
||||
match list.iter_mut().find(|(x, _)| *x == hsh) {
|
||||
Some(e) => e.1 += c,
|
||||
None => list.push((hsh, c)),
|
||||
}
|
||||
}
|
||||
t *= 1.0 - f.a;
|
||||
if t <= 1e-5 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let f = fs[front.or(best.map(|b| b.0)).unwrap_or(0)];
|
||||
o = [f.z, f.obj, f.mat, 1.0 - t, f.n[0], f.n[1], f.n[2], f.uv[0], f.uv[1]];
|
||||
for (base, list) in [(0usize, &mut obj), (8usize, &mut mat)] {
|
||||
list.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0)));
|
||||
for (rank, (hsh, c)) in list.iter().take(4).enumerate() {
|
||||
crypto[base + rank * 2] = crypto_float(*hsh);
|
||||
crypto[base + rank * 2 + 1] = *c;
|
||||
}
|
||||
}
|
||||
(o, crypto)
|
||||
})
|
||||
.collect();
|
||||
let mut aux = effectcraft_raster::AuxChannels::new(w, h, s);
|
||||
for (k, name) in NAMES.iter().enumerate() {
|
||||
aux.channels.push((name.to_string(), resolved.iter().map(|r| r.0[k]).collect()));
|
||||
}
|
||||
for (base, layer) in [(0usize, "CryptoObject"), (8usize, "CryptoMaterial")] {
|
||||
for rank_pair in 0..2 {
|
||||
for (c, ch) in ["R", "G", "B", "A"].iter().enumerate() {
|
||||
let k = base + rank_pair * 4 + c;
|
||||
aux.channels.push((format!("{layer}{rank_pair:02}.{ch}"), resolved.iter().map(|r| r.1[k]).collect()));
|
||||
}
|
||||
}
|
||||
}
|
||||
aux.manifests = vec![("CryptoObject".into(), manifest_obj), ("CryptoMaterial".into(), manifest_mat)];
|
||||
aux
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user