M7.7: viewer and colour completion

View > Switch 3D View > Default, Split with New Locked Viewer, Use Display Color
Management (sRGB/P3 display in Settings > Previews), Simulate Output (Rec. 709/2020,
P3, sRGB, Linear, NTSC, PAL, Mac 1.8, Custom; Preserve RGB). Project Settings: Color
Engine (OCIO built-in config with ACEScg/ACES2065-1 working spaces), HDR clip/compand/
tone map, output space incl. Rec. 2100 PQ/HLG (SMPTE ST 2084, BT.2100, BT.2408
reference white; GPU curves too), Time Display Feet + Frames (35mm/16mm) display and
entry. OCIO effects read custom .ocio configs (YAML subset; Matrix/File/Exponent/Log/
LogAffine/CDL/Range/Group transforms, roles, displays/views).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-03 02:25:56 -04:00
co-authored by Claude Opus 5.5
parent 8696d1e9ba
commit 9994f5d309
29 changed files with 2362 additions and 84 deletions
+42 -5
View File
@@ -258,15 +258,52 @@ fn project_settings(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(l) = p.get("blendLinear").or_else(|| p.get("blendColorsUsing1Gamma")).and_then(Value::as_bool) {
proj.settings.blend_linear = l;
}
use effectcraft_project::{ColorEngine, ColorSpace, HdrMode};
let cmd = "file.projectSettings";
if let Some(e) = str_p(p, "colorEngine") {
let engine = match e.to_ascii_lowercase().replace([' ', '-', '_'], "").as_str() {
"adobe" | "adobemanaged" | "builtin" => ColorEngine::Adobe,
"ocio" | "ociomanaged" => ColorEngine::Ocio,
_ => return Err(bad(cmd, format!("colorEngine: adobe|ocio, not `{e}`"))),
};
if engine == ColorEngine::Ocio && proj.settings.color_engine != ColorEngine::Ocio {
// The OCIO built-in config works in ACES and renders the display through its
// tone-mapped view.
if !proj.settings.working_space.is_some_and(|w| w.is_linear()) {
proj.settings.working_space = Some(ColorSpace::AcesCg);
}
if proj.settings.hdr == HdrMode::Clip {
proj.settings.hdr = HdrMode::ToneMap;
}
}
proj.settings.color_engine = engine;
}
if let Some(w) = p.get("workingSpace") {
let ids = ColorSpace::WORKING.iter().map(|c| c.id()).collect::<Vec<_>>().join("|");
proj.settings.working_space = match w.as_str() {
None | Some("none" | "None" | "") => None,
Some(n) => Some(
effectcraft_project::ColorSpace::parse(n)
.ok_or_else(|| bad("file.projectSettings", format!("workingSpace: none|srgb|rec709|rec2020|p3, not `{n}`")))?,
ColorSpace::parse(n).filter(|c| ColorSpace::WORKING.contains(c)).ok_or_else(|| bad(cmd, format!("workingSpace: none|{ids}, not `{n}`")))?,
),
};
}
if proj.settings.color_engine == ColorEngine::Ocio && !proj.settings.working_space.is_some_and(|w| w.is_linear()) {
return Err(bad(cmd, "the OCIO built-in config's working spaces are acescg and aces2065"));
}
if let Some(h) = str_p(p, "hdr") {
proj.settings.hdr = match h.to_ascii_lowercase().replace([' ', '-', '_'], "").as_str() {
"clip" | "off" | "none" => HdrMode::Clip,
"compand" => HdrMode::Compand,
"tonemap" | "tonemapped" => HdrMode::ToneMap,
_ => return Err(bad(cmd, format!("hdr: clip|compand|toneMap, not `{h}`"))),
};
}
if let Some(o) = p.get("outputSpace") {
proj.settings.output_space = match o.as_str() {
None | Some("none" | "None" | "" | "default") => None,
Some(n) => Some(ColorSpace::parse(n).ok_or_else(|| bad(cmd, format!("outputSpace: srgb|rec709|rec2020|p3|rec2100pq|rec2100hlg, not `{n}`")))?),
};
}
if let Some(r) = p.get("renderer").or_else(|| p.get("gpuAcceleration")) {
proj.settings.gpu_acceleration = match r {
Value::Bool(b) => *b,
@@ -279,8 +316,8 @@ fn project_settings(s: &mut Session, p: &Value) -> Result<Value> {
};
}
if let Some(t) = str_p(p, "timeDisplay") {
proj.settings.time_display =
if t.eq_ignore_ascii_case("frames") { effectcraft_project::TimeDisplayStyle::Frames } else { effectcraft_project::TimeDisplayStyle::Timecode };
proj.settings.time_display = effectcraft_project::TimeDisplayStyle::parse(t)
.ok_or_else(|| bad("file.projectSettings", format!("timeDisplay: timecode|frames|feet35|feet16, not `{t}`")))?;
}
Ok(())
})?;
@@ -353,7 +390,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Project Settings...",
["File"],
Some("Cmd+Alt+Shift+K"),
"{bitDepth?: 8|16|32, workingSpace?: none|srgb|rec709|rec2020|p3, linearize?, blendLinear?, renderer?: gpu|software, timeDisplay?: timecode|frames}",
"{bitDepth?: 8|16|32, colorEngine?: adobe|ocio, workingSpace?: none|srgb|rec709|rec2020|p3|acescg|aces2065, linearize?, blendLinear?, hdr?: clip|compand|toneMap, outputSpace?: srgb|rec709|rec2020|p3|rec2100pq|rec2100hlg, renderer?: gpu|software, timeDisplay?: timecode|frames|feet35|feet16}",
always,
project_settings
),
+1 -1
View File
@@ -44,7 +44,7 @@ mod styles;
mod text_anim;
pub mod text_edit;
mod three_d;
mod time;
pub mod time;
mod track;
mod view;
pub mod viewer_cmds;
-5
View File
@@ -29,11 +29,6 @@ pub fn specs() -> Vec<CommandSpec> {
stub!("camera.linkFocusToPoi", "Link Focus Distance to Point of Interest", ["Layer", "Camera"], "{}"),
stub!("camera.linkFocusToLayer", "Link Focus Distance to Layer", ["Layer", "Camera"], "{}"),
stub!("camera.setFocusToLayer", "Set Focus Distance to Layer", ["Layer", "Camera"], "{}"),
stub!("view.3d.default", "Default", ["View", "Switch 3D View"], "{}"),
stub!("view.splitLockedViewer", "Split with New Locked Viewer", ["View"], "{}"),
// Color management.
stub!("view.displayColorManagement", "Use Display Color Management", ["View"], "{}"),
stub!("view.simulateOutput", "Simulate Output", [], "{profile}"),
// Keyframes / text / tracking.
stub!("keys.audioToKeyframes", "Convert Audio to Keyframes", ["Animation", "Keyframe Assistant"], "{}"),
stub!("keys.rpfCameraImport", "RPF Camera Import", ["Animation", "Keyframe Assistant"], "{}"),
+4 -2
View File
@@ -297,7 +297,7 @@ fn views(s: &mut Session, cid: ItemId) -> &mut Views3D {
}
fn view_p(p: &Value, cmd: &str) -> Result<View3D> {
let v = str_p(p, "view").ok_or_else(|| bad(cmd, "missing `view` (activeCamera|front|left|top|back|right|bottom|custom1|custom2|custom3)"))?;
let v = str_p(p, "view").ok_or_else(|| bad(cmd, "missing `view` (activeCamera|default|front|left|top|back|right|bottom|custom1|custom2|custom3)"))?;
View3D::from_id(v).ok_or_else(|| bad(cmd, format!("unknown view `{v}`")))
}
@@ -334,6 +334,7 @@ view_cmd!(view_bottom, View3D::Bottom);
view_cmd!(view_custom1, View3D::Custom1);
view_cmd!(view_custom2, View3D::Custom2);
view_cmd!(view_custom3, View3D::Custom3);
view_cmd!(view_default, View3D::Default);
fn last_view(s: &mut Session, p: &Value) -> Result<Value> {
let cid = comp_id(s, p)?;
@@ -697,11 +698,12 @@ pub fn specs() -> Vec<CommandSpec> {
"Switch 3D View",
[],
None,
"{view: activeCamera|front|left|top|back|right|bottom|custom1|custom2|custom3, comp?}",
"{view: activeCamera|default|front|left|top|back|right|bottom|custom1|custom2|custom3, comp?}",
has_comp,
set_3d_view
),
cmd!("view.3d.activeCamera", "Active Camera", ["View", "Switch 3D View"], Some("F12"), "{comp?}", has_comp, view_active),
cmd!("view.3d.default", "Default", ["View", "Switch 3D View"], None, "{comp?}", has_comp, view_default),
cmd!("view.3d.front", "Front", ["View", "Switch 3D View"], Some("F10"), "{comp?}", has_comp, view_front),
cmd!("view.3d.left", "Left", ["View", "Switch 3D View"], None, "{comp?}", has_comp, view_left),
cmd!("view.3d.top", "Top", ["View", "Switch 3D View"], None, "{comp?}", has_comp, view_top),
+32 -2
View File
@@ -1,5 +1,6 @@
//! Time navigation (CTI) commands.
use effectcraft_project::{Comp, TimeDisplayStyle};
use effectcraft_time::Tick;
use serde_json::{Value, json};
@@ -9,7 +10,36 @@ use crate::{EngineError, Result, Session, cmd};
fn report(s: &Session) -> Value {
let t = s.time();
let frame = s.active_comp().map(|c| c.frame_rate.frame_at(t)).unwrap_or(0);
json!({"time": t.seconds(), "frame": frame})
let display = s.active_comp().map(|c| display_time(s, c, t));
json!({"time": t.seconds(), "frame": frame, "display": display})
}
/// A comp time as the project's Time Display Style shows it: timecode (`0:00:02:15`, `;` for
/// drop-frame), frames (`00063`, from Start Numbering Frames At) or Feet + Frames (`0003+15`).
pub fn display_time(s: &Session, comp: &Comp, t: Tick) -> String {
let fr = comp.frame_rate;
let st = &s.project.settings;
match st.time_display {
TimeDisplayStyle::Frames => format!("{:05}", fr.frame_at(t) + st.frame_start),
TimeDisplayStyle::Feet35 | TimeDisplayStyle::Feet16 => {
effectcraft_time::format_feet_frames(fr.frame_at(t + comp.display_start) + st.frame_start, st.time_display.frames_per_foot().unwrap_or(16))
}
TimeDisplayStyle::Timecode => effectcraft_time::format_timecode_ae(fr.frame_at(t + comp.display_start), fr, false),
}
}
/// Parse a time typed in the project's Time Display Style (relative `+n`/`-n` from frame
/// `current`) into a comp frame.
pub fn parse_display_time(s: &Session, comp: &Comp, text: &str, current: i64) -> std::result::Result<i64, String> {
let fr = comp.frame_rate;
let st = &s.project.settings;
match st.time_display.frames_per_foot() {
Some(pf) => {
let start = fr.frame_at(comp.display_start) + st.frame_start;
effectcraft_time::parse_feet_frames(text, pf, current + start).map(|f| f - start).map_err(|e| e.0)
}
None => effectcraft_time::parse_timecode(text, fr, fr.supports_drop_frame(), current).map_err(|e| e.0),
}
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
@@ -18,7 +48,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
comp.frame_rate.tick_of(f)
} else if let Some(tc) = str_p(p, "timecode") {
let cur = comp.frame_rate.frame_at(s.time());
let f = effectcraft_time::parse_timecode(tc, comp.frame_rate, comp.frame_rate.supports_drop_frame(), cur).map_err(|e| super::bad("time.set", e.0))?;
let f = parse_display_time(s, comp, tc, cur).map_err(|e| super::bad("time.set", e))?;
comp.frame_rate.tick_of(f)
} else {
Tick::from_seconds_f64(f_p(p, "time").ok_or_else(|| super::bad("time.set", "need `time`, `frame` or `timecode`"))?)
+122 -4
View File
@@ -10,8 +10,8 @@ use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::{CommandSpec, always, b_p, bad, comp_id, f_p, has_comp, merge_p, str_p};
use crate::viewer::{Channel, Snapshot};
use crate::{EngineError, Result, Session, VertexRef, cmd};
use crate::viewer::{Channel, SimProfile, Simulation, Snapshot};
use crate::{EngineError, Result, Session, VertexRef, cmd, query};
/// Composition ▸ Preview ▸ Fast Previews modes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
@@ -61,8 +61,8 @@ impl FastPreviews {
}
}
/// Viewer display options (Show Channel, exposure, snapshot, Fast Previews).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
/// Viewer display options (Show Channel, exposure, snapshot, Fast Previews, display colour).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ViewOptions {
pub channel: Channel,
@@ -73,6 +73,36 @@ pub struct ViewOptions {
/// Show Snapshot (F5 held): the viewer shows the snapshot instead of the frame.
pub show_snapshot: bool,
pub fast_previews: FastPreviews,
/// View ▸ Use Display Color Management (with a working space): the frame is converted
/// from the working space to the display; off shows the working space's numbers.
pub display_color_management: bool,
/// View ▸ Simulate Output.
pub simulation: Simulation,
/// The profile View ▸ Simulate Output ▸ Custom... uses.
pub custom_simulation: Simulation,
}
impl Default for ViewOptions {
fn default() -> Self {
ViewOptions {
channel: Channel::default(),
colorized: false,
exposure: 0.0,
show_snapshot: false,
fast_previews: FastPreviews::default(),
display_color_management: true,
simulation: Simulation::default(),
custom_simulation: Simulation { profile: SimProfile::Linear, preserve_rgb: true },
}
}
}
/// View ▸ Split with New Locked Viewer: a second Composition viewer that keeps showing one
/// comp and 3D view whatever comp is active.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct LockedViewer {
pub comp: effectcraft_project::ItemId,
pub view: effectcraft_render::three_d::View3D,
}
fn snapping(s: &mut Session, p: &Value) -> Result<Value> {
@@ -281,9 +311,97 @@ fn shape_layer_or_none(s: &Session) -> std::result::Result<(), String> {
has_comp(s)
}
// ---------------------------------------------------------------- display colour, locked viewer
/// View ▸ Use Display Color Management (toggle, or `value`).
fn display_cm(s: &mut Session, p: &Value) -> Result<Value> {
let v = b_p(p, "value").unwrap_or(!s.state.viewer.display_color_management);
s.state.viewer.display_color_management = v;
s.events.push(crate::Event::ProjectChanged { revision: s.revision });
Ok(json!({"displayColorManagement": v, "workingSpace": s.project.settings.working_space.map(|w| w.id()), "display": s.prefs.previews.display_profile}))
}
/// View ▸ Simulate Output ▸ (profile). `custom` uses (and with `space` sets) the Custom profile.
fn simulate_output(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "view.simulateOutput";
let name = str_p(p, "profile").unwrap_or("none");
let ids = SimProfile::ALL.iter().map(|p| p.id()).collect::<Vec<_>>().join("|");
let sim = if name.eq_ignore_ascii_case("custom") {
let mut c = s.state.viewer.custom_simulation;
if let Some(sp) = str_p(p, "space") {
c.profile = SimProfile::parse(sp).ok_or_else(|| bad(cmd, format!("space: {ids}")))?;
}
if let Some(v) = b_p(p, "preserveRgb") {
c.preserve_rgb = v;
}
s.state.viewer.custom_simulation = c;
c
} else {
let profile = SimProfile::parse(name).ok_or_else(|| bad(cmd, format!("profile: {ids}|custom")))?;
Simulation { profile, preserve_rgb: b_p(p, "preserveRgb").unwrap_or(false) }
};
s.state.viewer.simulation = sim;
s.events.push(crate::Event::ProjectChanged { revision: s.revision });
Ok(json!({"profile": sim.profile.id(), "label": sim.profile.label(), "preserveRgb": sim.preserve_rgb}))
}
/// View ▸ Split with New Locked Viewer: lock a second viewer to the comp (default the active
/// one) and its current 3D view (or `view`).
fn split_locked(s: &mut Session, p: &Value) -> Result<Value> {
let cid = comp_id(s, p)?;
let view = match str_p(p, "view") {
Some(v) => effectcraft_render::three_d::View3D::from_id(v).ok_or_else(|| bad("view.splitLockedViewer", format!("unknown view `{v}`")))?,
None => s.state.views3d.get(&cid).map(|v| v.current).unwrap_or_default(),
};
s.state.locked_viewer = Some(LockedViewer { comp: cid, view });
s.events.push(crate::Event::ProjectChanged { revision: s.revision });
Ok(json!({"comp": cid.0, "view": view.id()}))
}
fn close_locked(s: &mut Session, _: &Value) -> Result<Value> {
let was = s.state.locked_viewer.take().is_some();
s.events.push(crate::Event::ProjectChanged { revision: s.revision });
Ok(json!({"closed": was}))
}
fn has_locked(s: &Session) -> std::result::Result<(), String> {
if s.state.locked_viewer.is_some() { Ok(()) } else { Err("no locked viewer".into()) }
}
/// The viewer's colour settings and what they do.
fn display_color_state(s: &mut Session, _: &Value) -> Result<Value> {
let v = &s.state.viewer;
Ok(json!({
"displayColorManagement": v.display_color_management,
"simulation": {"profile": v.simulation.profile.id(), "preserveRgb": v.simulation.preserve_rgb},
"display": s.prefs.previews.display_profile,
"workingSpace": s.project.settings.working_space.map(|w| w.id()),
"active": crate::viewer::DisplayColor::of(s).is_some(),
"lockedViewer": s.state.locked_viewer.map(|l| json!({"comp": l.comp.0, "view": l.view.id()})),
}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("view.snapping", "Snapping", ["View"], None, "{value?}", always, snapping),
cmd!("view.displayColorManagement", "Use Display Color Management", ["View"], None, "{value?}", always, display_cm),
cmd!(
"view.simulateOutput",
"Simulate Output",
[],
None,
"{profile: none|rec709|ntsc|pal|mac18|srgb|rec2020|p3|linear|custom, preserveRgb?, space? (custom)}",
always,
simulate_output
),
cmd!("view.splitLockedViewer", "Split with New Locked Viewer", ["View"], None, "{comp?, view?: 3D view id}", has_comp, split_locked),
cmd!("view.closeLockedViewer", "Close Locked Viewer", [], None, "{}", has_locked, close_locked),
query!(
"view.displayColor",
"Viewer Color State",
"{} → display colour management, output simulation, display profile, locked viewer",
display_color_state
),
cmd!("view.channel", "Show Channel", [], None, "{channel: rgb|red|green|blue|alpha|rgbStraight, colorized?, toggle?}", always, channel),
cmd!("view.exposure", "Adjust Exposure", [], None, "{stops? | delta?}", always, exposure),
cmd!("view.resetExposure", "Reset Exposure", [], None, "{}", always, reset_exposure),
+5
View File
@@ -215,6 +215,9 @@ pub struct EditorState {
/// Essential Graphics can expose).
#[serde(default)]
pub essential_solo: bool,
/// View ▸ Split with New Locked Viewer: the second viewer's comp and 3D view.
#[serde(default)]
pub locked_viewer: Option<commands::viewer_cmds::LockedViewer>,
}
fn one_view() -> u8 {
@@ -651,6 +654,8 @@ mod tests_anim_tools;
#[cfg(test)]
mod tests_camera_track;
#[cfg(test)]
mod tests_color_view;
#[cfg(test)]
mod tests_disk_cache;
#[cfg(test)]
mod tests_effects;
+14
View File
@@ -168,6 +168,17 @@ pub fn checked(s: &Session, command: &str, params: &Value) -> Option<bool> {
"view.layout" => Some(params.get("views").and_then(Value::as_u64) == Some(s.state.view_layout.max(1) as u64)),
"view.shareViewOptions" => Some(s.state.share_view_options),
"view.snapping" => Some(s.state.snapping),
"view.displayColorManagement" => Some(s.state.viewer.display_color_management),
"view.simulateOutput" => {
let want = pstr("profile")?;
let sim = s.state.viewer.simulation;
Some(if want == "custom" {
sim.profile != crate::viewer::SimProfile::None && sim == s.state.viewer.custom_simulation
} else {
crate::viewer::SimProfile::parse(want) == Some(sim.profile)
&& (sim != s.state.viewer.custom_simulation || sim.profile == crate::viewer::SimProfile::None)
})
}
"layer.mask.motionBlur" | "layer.mask.featherFalloff" | "path.rotoBezier" => {
use effectcraft_project::{FeatherFalloff, GroupKind, MaskMotionBlur};
let GroupKind::Mask { motion_blur, feather_falloff, roto_bezier, .. } = layer?.masks()?.groups().next()?.kind else { return None };
@@ -853,6 +864,9 @@ View
SDTV PAL | view.simulateOutput {"profile":"pal"}
Legacy Macintosh RGB (Gamma 1.8) | view.simulateOutput {"profile":"mac18"}
Internet Standard RGB (sRGB) | view.simulateOutput {"profile":"srgb"}
UHDTV (Rec. 2020) | view.simulateOutput {"profile":"rec2020"}
Display P3 | view.simulateOutput {"profile":"p3"}
Linear (1.0 Gamma) | view.simulateOutput {"profile":"linear"}
Custom... | view.simulateOutput {"profile":"custom"}
---
Show Rulers | view.rulers
+3
View File
@@ -104,6 +104,8 @@ page!(Previews {
/// `faster` or `moreAccurate`.
zoom_quality: String = "moreAccurate".into(),
show_gpu_info: bool = false,
/// The monitor's colour space for View ▸ Use Display Color Management: `srgb` or `p3`.
display_profile: String = "srgb".into(),
});
page!(Appearance {
@@ -728,6 +730,7 @@ pub fn pages() -> Vec<Page> {
s("previews.cacheFramesWhenIdle", "Cache Frames When Idle", B, true),
s("previews.fastPreviews", "Fast Previews (Draft 3D, Faster Effects)", B, true),
s("previews.zoomQuality", "Viewer Zoom Quality", Kind::Choice(&[("Faster", "faster"), ("More Accurate", "moreAccurate")]), false),
s("previews.displayProfile", "Display Color Space", Kind::Choice(&[("sRGB", "srgb"), ("Display P3", "p3")]), true),
Button { label: "GPU Information...", command: "app.gpuInfo", params: "{}" },
],
},
+223
View File
@@ -0,0 +1,223 @@
//! Viewer and colour completion (M7.7): View ▸ Switch 3D View ▸ Default, Split with New Locked
//! Viewer, Use Display Color Management, Simulate Output; Project Settings ▸ Color Engine,
//! ACES working spaces, HDR compand / tone mapping, Rec. 2100 output, Feet + Frames.
use effectcraft_project::{ColorEngine, ColorSpace, HdrMode, Project, TimeDisplayStyle};
use effectcraft_render::RenderOpts;
use effectcraft_render::three_d::View3D;
use effectcraft_time::Tick;
use serde_json::json;
use crate::Session;
use crate::viewer::{DisplayColor, SimProfile, Simulation};
fn session() -> Session {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "C", "width": 64, "height": 48, "frameRate": 24, "duration": 10})).unwrap();
s
}
#[test]
fn default_3d_view_ignores_camera_layers() {
let mut s = session();
let cid = s.active_comp_id().unwrap();
s.execute("layer.newCamera", json!({"position": [32, 24, -300], "poi": [32, 24, 0]})).unwrap();
assert_eq!(s.execute("view.3d.default", json!({})).unwrap()["view"], "default");
let vs = s.state.views3d.get(&cid).unwrap().clone();
assert_eq!(vs.current, View3D::Default);
// The comp's default camera: at −zoom looking at the centre, not the camera layer.
let cam = s.view_camera(cid).unwrap();
let zoom = effectcraft_geom::default_camera_zoom(64.0);
assert!((cam.eye.z + zoom).abs() < 1e-9 && (cam.eye.x - 32.0).abs() < 1e-9 && !cam.ortho, "{:?}", cam.eye);
// Orbitable like a custom view; Reset 3D View restores it; Last view goes back.
s.execute("camera.orbit", json!({"yaw": 30})).unwrap();
assert!((s.view_camera(cid).unwrap().eye.x - 32.0).abs() > 1.0);
s.execute("view.reset3DView", json!({})).unwrap();
assert!((s.view_camera(cid).unwrap().eye.x - 32.0).abs() < 1e-9);
s.execute("view.3d.last", json!({})).unwrap();
assert_eq!(s.state.views3d[&cid].current, View3D::ActiveCamera);
assert_eq!(s.execute("view.set3DView", json!({"view": "Default"})).unwrap()["view"], "default");
}
#[test]
fn locked_viewer_keeps_its_comp() {
let mut s = session();
let a = s.active_comp_id().unwrap();
s.execute("view.3d.top", json!({})).unwrap();
assert!(!s.is_enabled("view.closeLockedViewer"));
let r = s.execute("view.splitLockedViewer", json!({})).unwrap();
assert_eq!(r, json!({"comp": a.0, "view": "top"}));
// Another comp becomes active; the locked viewer stays on the first.
s.execute("comp.new", json!({"name": "B"})).unwrap();
assert_ne!(s.active_comp_id(), Some(a));
assert_eq!(s.state.locked_viewer.unwrap().comp, a);
let st = s.execute("view.displayColor", json!({})).unwrap();
assert_eq!(st["lockedViewer"]["comp"], a.0);
// Serde of the editor state; explicit comp and view.
let back: crate::EditorState = serde_json::from_value(serde_json::to_value(&s.state).unwrap()).unwrap();
assert_eq!(back.locked_viewer, s.state.locked_viewer);
s.execute("view.splitLockedViewer", json!({"comp": a.0, "view": "custom2"})).unwrap();
assert_eq!(s.state.locked_viewer.unwrap().view, View3D::Custom2);
assert!(s.execute("view.splitLockedViewer", json!({"view": "sideways"})).is_err());
assert_eq!(s.execute("view.closeLockedViewer", json!({})).unwrap()["closed"], true);
assert!(s.state.locked_viewer.is_none());
}
fn px(r: u8, g: u8, b: u8) -> Vec<[u8; 4]> {
vec![[r, g, b, 255]]
}
#[test]
fn display_color_management_and_simulation() {
let mut s = session();
// Unmanaged projects: nothing to convert.
assert!(DisplayColor::of(&s).is_none());
s.execute("file.projectSettings", json!({"workingSpace": "rec2020"})).unwrap();
// Managed, sRGB display, no simulation: the frame is already display-referred.
assert!(DisplayColor::of(&s).is_none());
assert_eq!(crate::menus::checked(&s, "view.displayColorManagement", &json!({})), Some(true));
// A Display P3 monitor: pure sRGB red becomes less saturated P3 numbers.
s.execute("prefs.set", json!({"key": "previews.displayProfile", "value": "p3"})).unwrap();
let mut p = px(255, 0, 0);
DisplayColor::of(&s).unwrap().apply(&mut p);
assert!((p[0][0] as i32 - 234).abs() <= 2 && (p[0][1] as i32 - 51).abs() <= 3 && (p[0][2] as i32 - 35).abs() <= 3, "{p:?}");
// Display colour management off: the working space's (Rec. 2020) numbers go to the screen.
s.execute("view.displayColorManagement", json!({})).unwrap();
assert_eq!(crate::menus::checked(&s, "view.displayColorManagement", &json!({})), Some(false));
let mut q = px(255, 0, 0);
DisplayColor::of(&s).unwrap().apply(&mut q);
assert!(q[0][0] < 230 && q[0][1] > 60, "raw Rec. 2020 numbers: {q:?}");
s.execute("view.displayColorManagement", json!({"value": true})).unwrap();
s.execute("prefs.set", json!({"key": "previews.displayProfile", "value": "srgb"})).unwrap();
// Simulate Output ▸ Linear with Preserve RGB: linear numbers shown as-is (darker mid-grey).
s.execute("view.simulateOutput", json!({"profile": "linear", "preserveRgb": true})).unwrap();
let mut g = px(128, 128, 128);
DisplayColor::of(&s).unwrap().apply(&mut g);
assert!((g[0][0] as i32 - 55).abs() <= 2, "{g:?}");
// Without Preserve RGB the round trip through 8-bit linear bands the shadows.
s.execute("view.simulateOutput", json!({"profile": "linear"})).unwrap();
let dc = DisplayColor::of(&s).unwrap();
let levels: std::collections::BTreeSet<u8> = (0..32u8)
.map(|v| {
let mut p = px(v, v, v);
dc.apply(&mut p);
p[0][0]
})
.collect();
assert!(levels.len() < 20, "banding: {levels:?}");
assert_eq!(crate::menus::checked(&s, "view.simulateOutput", &json!({"profile": "linear"})), Some(true));
// Rec. 709 simulation keeps in-gamut colours; legacy Mac gamma 1.8 with Preserve RGB darkens.
s.execute("view.simulateOutput", json!({"profile": "rec709"})).unwrap();
let mut c = px(200, 100, 50);
DisplayColor::of(&s).unwrap().apply(&mut c);
assert!((c[0][0] as i32 - 200).abs() <= 2 && (c[0][1] as i32 - 100).abs() <= 2, "{c:?}");
s.execute("view.simulateOutput", json!({"profile": "mac18", "preserveRgb": true})).unwrap();
let mut m = px(128, 128, 128);
DisplayColor::of(&s).unwrap().apply(&mut m);
assert!(m[0][0] < 120, "gamma 1.8 numbers on an sRGB display look darker: {m:?}");
// Custom… uses (and sets) the custom profile.
let r = s.execute("view.simulateOutput", json!({"profile": "custom", "space": "p3", "preserveRgb": false})).unwrap();
assert_eq!(r["profile"], "p3");
assert_eq!(s.state.viewer.custom_simulation, Simulation { profile: SimProfile::P3, preserve_rgb: false });
assert_eq!(crate::menus::checked(&s, "view.simulateOutput", &json!({"profile": "custom"})), Some(true));
s.execute("view.simulateOutput", json!({"profile": "none"})).unwrap();
assert!(DisplayColor::of(&s).is_none());
assert!(s.execute("view.simulateOutput", json!({"profile": "cmyk"})).is_err());
// Every menu profile parses.
for p in SimProfile::ALL {
assert_eq!(SimProfile::parse(p.id()), Some(p));
}
}
fn red_solid(s: &mut Session, hex: &str) {
s.execute("layer.newSolid", json!({"color": hex, "width": 64, "height": 48})).unwrap();
}
#[test]
fn color_engine_aces_working_spaces_and_hdr() {
let mut s = session();
let cid = s.active_comp_id().unwrap();
// OCIO engine: ACEScg working space and the tone-mapped display by default.
s.execute("file.projectSettings", json!({"colorEngine": "ocio"})).unwrap();
let st = s.project.settings.clone();
assert_eq!((st.color_engine, st.working_space, st.hdr), (ColorEngine::Ocio, Some(ColorSpace::AcesCg), HdrMode::ToneMap));
assert!(s.execute("file.projectSettings", json!({"workingSpace": "rec709"})).is_err(), "not in the OCIO config");
s.execute("file.projectSettings", json!({"workingSpace": "aces2065"})).unwrap();
assert!(s.execute("file.projectSettings", json!({"workingSpace": "rec2100pq"})).is_err(), "not a working space");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.project.settings.working_space, Some(ColorSpace::AcesCg));
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.project.settings.color_engine, ColorEngine::Adobe);
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(s.project.settings.color_engine, ColorEngine::Ocio);
// 32 bpc, a solid of 4.0 (over-range) in ACEScg: tone mapped below white, not clipped.
s.execute("file.projectSettings", json!({"bitDepth": 32, "hdr": "toneMap"})).unwrap();
s.execute("layer.newSolid", json!({"color": "#ffffff", "width": 64, "height": 48})).unwrap();
let lid = s.active_comp().unwrap().layers[0].id.0;
s.execute("effect.apply", json!({"layers": [lid], "effect": "Exposure"})).unwrap();
s.execute("prop.set", json!({"layer": lid, "path": "effects/#1/exposure", "value": 2.0})).unwrap();
let mapped = s.render(cid, Tick::ZERO, RenderOpts::default()).data[0];
assert!(mapped[0] > 0.5 && mapped[0] < 0.99, "tone mapped: {mapped:?}");
s.execute("file.projectSettings", json!({"hdr": "clip"})).unwrap();
let clipped = s.render(cid, Tick::ZERO, RenderOpts::default()).data[0];
assert!(clipped[0] > 1.1, "32 bpc keeps over-range: {clipped:?}");
s.execute("file.projectSettings", json!({"hdr": "compand"})).unwrap();
let comp = s.render(cid, Tick::ZERO, RenderOpts::default()).data[0];
assert!(comp[0] > 0.9 && comp[0] < 1.0, "companded: {comp:?}");
// Rec. 2100 PQ output: HDR, no tone mapping: over-range white encodes above SDR white's 0.58.
s.execute("file.projectSettings", json!({"outputSpace": "rec2100pq", "hdr": "toneMap"})).unwrap();
let pq = s.render(cid, Tick::ZERO, RenderOpts::default()).data[0];
assert!(pq[0] > 0.6 && pq[0] < 0.8, "PQ: {pq:?}");
s.execute("file.projectSettings", json!({"outputSpace": "rec2100hlg"})).unwrap();
let hlg = s.render(cid, Tick::ZERO, RenderOpts::default()).data[0];
assert!(hlg[0] > 0.85, "HLG: {hlg:?}");
assert!(s.execute("file.projectSettings", json!({"hdr": "glow"})).is_err());
// Serde keeps the new settings; older files load with the defaults.
let back: Project = serde_json::from_str(&serde_json::to_string(&*s.project).unwrap()).unwrap();
assert_eq!(back.settings, s.project.settings);
let mut v = serde_json::to_value(&s.project.settings).unwrap();
for k in ["color_engine", "hdr", "output_space"] {
v.as_object_mut().unwrap().remove(k);
}
let old: effectcraft_project::ProjectSettings = serde_json::from_value(v).unwrap();
assert_eq!((old.color_engine, old.hdr, old.output_space), (ColorEngine::Adobe, HdrMode::Clip, None));
}
#[test]
fn aces_working_space_matches_the_ocio_config() {
// ACEScg in the colour module and in the OCIO effects' built-in config agree.
let mut s = session();
s.execute("file.projectSettings", json!({"workingSpace": "acescg"})).unwrap();
red_solid(&mut s, "#808080");
let cid = s.active_comp_id().unwrap();
// Authored ACEScg values (0.5 linear AP1 grey) → sRGB display.
let out = s.render(cid, Tick::ZERO, RenderOpts::default()).data[0];
let want = effectcraft_color::linear_to_srgb(128.0 / 255.0);
assert!((out[0] - want).abs() < 0.01 && (out[1] - want).abs() < 0.01, "{out:?} vs {want}");
}
#[test]
fn feet_and_frames_display_and_entry() {
let mut s = session();
let comp = s.active_comp().unwrap().clone();
s.execute("file.projectSettings", json!({"timeDisplay": "feet35"})).unwrap();
assert_eq!(s.project.settings.time_display, TimeDisplayStyle::Feet35);
let t = comp.frame_rate.tick_of(16 * 3 + 5);
assert_eq!(crate::commands::time::display_time(&s, &comp, t), "0003+05");
// Typed feet+frames in the time field.
let r = s.execute("time.set", json!({"timecode": "2+10"})).unwrap();
assert_eq!(r["frame"], 42);
assert_eq!(r["display"], "0002+10");
let r = s.execute("time.set", json!({"timecode": "+6"})).unwrap();
assert_eq!(r["frame"], 48);
s.execute("file.projectSettings", json!({"timeDisplay": "feet16"})).unwrap();
assert_eq!(crate::commands::time::display_time(&s, &comp, comp.frame_rate.tick_of(95)), "0002+15");
s.execute("file.projectSettings", json!({"timeDisplay": "frames"})).unwrap();
assert_eq!(crate::commands::time::display_time(&s, &comp, comp.frame_rate.tick_of(95)), "00095");
s.execute("file.projectSettings", json!({"timeDisplay": "timecode"})).unwrap();
assert_eq!(crate::commands::time::display_time(&s, &comp, comp.frame_rate.tick_of(48)), "0:00:02:00");
assert!(s.execute("file.projectSettings", json!({"timeDisplay": "furlongs"})).is_err());
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.project.settings.time_display, TimeDisplayStyle::Frames);
assert_eq!(serde_json::to_value(TimeDisplayStyle::Feet16).unwrap(), json!("Feet16"));
}
+268
View File
@@ -5,6 +5,7 @@
use std::sync::Arc;
use effectcraft_color::{ColorSpace, space};
use effectcraft_geom::vec2;
use effectcraft_project::{Layer, LayerId};
use effectcraft_raster::Image;
@@ -359,6 +360,273 @@ pub fn display_transform(px: &mut [[u8; 4]], channel: Channel, colorized: bool,
}
}
// ---------------------------------------------------------------- display colour management
/// View ▸ Simulate Output: the output device a preview imitates.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SimProfile {
#[default]
None,
/// HDTV (Rec. 709): ITU-R BT.709 primaries, BT.1886 gamma 2.4.
Rec709,
/// UHDTV (Rec. 2020): ITU-R BT.2020 primaries, gamma 2.4.
Rec2020,
/// Display P3: SMPTE EG 432-1 primaries, D65, the sRGB curve.
P3,
/// Internet Standard RGB (sRGB, IEC 61966-2-1).
Srgb,
/// Linear light with Rec. 709 primaries (no transfer curve).
Linear,
/// SDTV NTSC: SMPTE 170M primaries, gamma 2.4.
Ntsc,
/// SDTV PAL: EBU Tech 3213 primaries, gamma 2.4.
Pal,
/// Legacy Macintosh RGB: Rec. 709 primaries, gamma 1.8.
Mac18,
}
/// A transfer curve of a simulated or display profile.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Curve {
Srgb,
Gamma(f32),
Linear,
/// A colour space's own curve (PQ, HLG…).
Space(space::Curve),
}
impl Curve {
fn decode(self, v: f32) -> f32 {
let a = v.abs();
let l = match self {
Curve::Srgb => srgb_to_linear(a),
Curve::Gamma(g) => a.powf(g),
Curve::Linear => a,
Curve::Space(c) => c.decode(a),
};
l.copysign(v)
}
fn encode(self, v: f32) -> f32 {
let a = v.abs();
let e = match self {
Curve::Srgb => linear_to_srgb(a),
Curve::Gamma(g) => a.powf(1.0 / g),
Curve::Linear => a,
Curve::Space(c) => c.encode(a),
};
e.copysign(v)
}
}
const P709: [[f64; 2]; 3] = [[0.640, 0.330], [0.300, 0.600], [0.150, 0.060]];
impl SimProfile {
pub const ALL: [SimProfile; 9] = [
SimProfile::None,
SimProfile::Rec709,
SimProfile::Ntsc,
SimProfile::Pal,
SimProfile::Mac18,
SimProfile::Srgb,
SimProfile::Rec2020,
SimProfile::P3,
SimProfile::Linear,
];
pub fn id(self) -> &'static str {
match self {
SimProfile::None => "none",
SimProfile::Rec709 => "rec709",
SimProfile::Rec2020 => "rec2020",
SimProfile::P3 => "p3",
SimProfile::Srgb => "srgb",
SimProfile::Linear => "linear",
SimProfile::Ntsc => "ntsc",
SimProfile::Pal => "pal",
SimProfile::Mac18 => "mac18",
}
}
pub fn label(self) -> &'static str {
match self {
SimProfile::None => "No Output Simulation",
SimProfile::Rec709 => "HDTV (Rec. 709)",
SimProfile::Rec2020 => "UHDTV (Rec. 2020)",
SimProfile::P3 => "Display P3",
SimProfile::Srgb => "Internet Standard RGB (sRGB)",
SimProfile::Linear => "Linear (1.0 Gamma)",
SimProfile::Ntsc => "SDTV NTSC",
SimProfile::Pal => "SDTV PAL",
SimProfile::Mac18 => "Legacy Macintosh RGB (Gamma 1.8)",
}
}
pub fn parse(s: &str) -> Option<SimProfile> {
let k: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();
SimProfile::ALL
.into_iter()
.find(|p| p.id() == k || p.label().chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase() == k)
.or(match k.as_str() {
"off" => Some(SimProfile::None),
"hdtv" | "bt709" => Some(SimProfile::Rec709),
"bt2020" | "uhdtv" => Some(SimProfile::Rec2020),
"displayp3" => Some(SimProfile::P3),
"lin" | "linearlight" => Some(SimProfile::Linear),
_ => None,
})
}
/// (primaries, curve); `None` for No Output Simulation.
pub fn space(self) -> Option<([[f64; 2]; 3], Curve)> {
Some(match self {
SimProfile::None => return None,
SimProfile::Rec709 => (P709, Curve::Gamma(2.4)),
SimProfile::Rec2020 => (ColorSpace::Rec2020.primaries(), Curve::Gamma(2.4)),
SimProfile::P3 => (ColorSpace::DisplayP3.primaries(), Curve::Srgb),
SimProfile::Srgb => (P709, Curve::Srgb),
SimProfile::Linear => (P709, Curve::Linear),
SimProfile::Ntsc => ([[0.630, 0.340], [0.310, 0.595], [0.155, 0.070]], Curve::Gamma(2.4)),
SimProfile::Pal => ([[0.640, 0.330], [0.290, 0.600], [0.150, 0.060]], Curve::Gamma(2.4)),
SimProfile::Mac18 => (P709, Curve::Gamma(1.8)),
})
}
}
/// View ▸ Simulate Output setting: the profile, and Preserve RGB (the output numbers are sent
/// to the display unconverted, as on a device that doesn't colour-manage).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(default)]
pub struct Simulation {
pub profile: SimProfile,
pub preserve_rgb: bool,
}
/// An RGB space for viewer conversions: primaries (D65) and curve.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Prof {
/// Linear RGB → XYZ D65.
xyz: [[f64; 3]; 3],
curve: Curve,
}
impl Prof {
fn new(prims: [[f64; 2]; 3], curve: Curve) -> Prof {
Prof { xyz: space::rgb_to_xyz(prims, D65), curve }
}
/// A colour space (linear when `linear`).
fn of(cs: ColorSpace, linear: bool) -> Prof {
let curve = if linear { Curve::Linear } else { Curve::Space(cs.curve()) };
Prof { xyz: cs.to_xyz(), curve }
}
}
/// A linear-RGB matrix plus curves between two profiles.
#[derive(Clone, Copy, Debug)]
struct Conv {
from: Curve,
m: Option<[[f32; 3]; 3]>,
to: Curve,
}
impl Conv {
fn new(a: Prof, b: Prof) -> Conv {
let m = (a.xyz != b.xyz).then(|| {
let m = space::mul(&space::invert(&b.xyz), &a.xyz);
m.map(|r| r.map(|v| v as f32))
});
Conv { from: a.curve, m, to: b.curve }
}
fn apply(&self, c: [f32; 3]) -> [f32; 3] {
let l = c.map(|v| self.from.decode(v));
let l = match &self.m {
Some(m) => [0, 1, 2].map(|i| m[i][0] * l[0] + m[i][1] * l[1] + m[i][2] * l[2]),
None => l,
};
l.map(|v| self.to.encode(v))
}
}
const D65: [f64; 2] = [0.3127, 0.3290];
/// The viewer's colour conversion from the rendered frame (sRGB-encoded display pixels) to
/// what the monitor shows (View ▸ Use Display Color Management, View ▸ Simulate Output and
/// the display profile in Settings ▸ Previews). `None` when nothing changes.
#[derive(Clone, Copy, Debug)]
pub struct DisplayColor {
sim: Option<(Conv, Option<Conv>)>,
display: Option<Conv>,
}
impl DisplayColor {
/// `working`: the project working space (None = unmanaged: nothing is converted, as in
/// After Effects); `linear`: the working space is linear; `source`: the space rendered
/// frames are in (the project's output space, sRGB by default); `dcm`: Use Display Color
/// Management; `display`: the monitor's space.
pub fn new(working: Option<ColorSpace>, linear: bool, source: ColorSpace, dcm: bool, display: ColorSpace, sim: Simulation) -> Option<DisplayColor> {
let ws = working?;
let src = Prof::of(source, false);
if !dcm {
// Without display colour management the working space's numbers go to the screen.
let raw = Conv::new(src, Prof::of(ws, linear));
return Some(DisplayColor { sim: None, display: Some(raw) });
}
let sim = sim.profile.space().map(|(prims, curve)| {
let out = Prof::new(prims, curve);
(
Conv::new(src, out),
Some(if sim.preserve_rgb {
Conv::new(Prof::new(P709, Curve::Srgb), Prof::of(display, false))
} else {
Conv::new(out, Prof::of(display, false))
}),
)
});
let display = (display != source).then(|| Conv::new(src, Prof::of(display, false)));
(sim.is_some() || display.is_some()).then_some(DisplayColor { sim, display })
}
/// The conversion a session's viewer uses.
pub fn of(s: &crate::Session) -> Option<DisplayColor> {
let st = &s.project.settings;
let display = ColorSpace::parse(&s.prefs.previews.display_profile).unwrap_or(ColorSpace::Srgb);
let v = &s.state.viewer;
let linear = st.working_space.is_some_and(|w| st.linearize || w.is_linear());
DisplayColor::new(st.working_space, linear, st.output_space.unwrap_or(ColorSpace::Srgb), v.display_color_management, display, v.simulation)
}
/// One straight colour (0..1 floats).
pub fn apply_straight(&self, c: [f32; 3]) -> [f32; 3] {
let c = match &self.sim {
// Through the output's 8-bit encoding (clipped and quantised like the real output),
// then shown on the display: converted from the output profile, or — Preserve RGB —
// the output numbers taken as if they were sRGB.
Some((to, show)) => {
let o = to.apply(c).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0);
show.map_or(o, |b| b.apply(o))
}
None => self.display.map_or(c, |d| d.apply(c)),
};
c.map(|v| v.clamp(0.0, 1.0))
}
/// Premultiplied 8-bit RGBA pixels in place.
pub fn apply(&self, px: &mut [[u8; 4]]) {
use rayon::prelude::*;
px.par_iter_mut().for_each(|p| {
let a = p[3];
if a == 0 {
return;
}
let af = a as f32 / 255.0;
let c = [0, 1, 2].map(|i| (p[i] as f32 / 255.0 / af).min(1.0));
let o = self.apply_straight(c);
for i in 0..3 {
p[i] = (o[i] * af * 255.0 + 0.5) as u8;
}
});
}
}
// ---------------------------------------------------------------- snapshot
/// Take Snapshot (Shift+F5): a rendered frame kept for comparison (Show Snapshot, F5).