Skip to main content

SceneContext

Struct SceneContext 

Source
pub struct SceneContext<'a> { /* private fields */ }
Expand description

Immutable scene evaluation inputs in signed ticks and logical coordinates.

The caller supplies time explicitly and can reuse one SceneCache across arbitrary frame orders and threads, without initializing rendering resources or interpreting design dimensions as output pixels.

use motion_core::prelude::*;
use motion_core::{
    DisplayList, RasterLimits, ResourcePool, ValidatedDisplayList, MAX_PATH_VERBS,
    MAX_STROKE_VERBS, MAX_SVG_PATH_BYTES, sample_offsets,
};
use std::sync::Arc;

let cache = SceneCache::new(32);
let tween = Tween::new(0.0, 100.0, 1.seconds());
let evaluate = |time| {
    let context = SceneContext::new(time, FrameRate::from(30), Size::new(640.0, 360.0), &cache)
        .with_clip_duration(2.seconds());
    let positions = context.cache(("dots", 8_u32), || {
        (0..8_u32)
            .map(|index| Point::new(context.random(("x", index)) * 640.0, 180.0))
            .collect::<Vec<_>>()
    });
    let local = context.shifted(500.milliseconds());
    assert_eq!(local.global_time(), time);
    (local.sample(&tween), positions)
};
let (late, first) = evaluate(1500.milliseconds());
let (early, second) = evaluate(500.milliseconds());
let (again, third) = evaluate(1500.milliseconds());
assert_eq!((late, early, again), (100.0, 0.0, 100.0));
assert!(Arc::ptr_eq(&first, &second) && Arc::ptr_eq(&first, &third));

Implementations§

Source§

impl<'a> SceneContext<'a>

Source

pub fn sound(&self, clip: AudioClip) -> Result

Declares local audio in a scene_with_sound metadata pass; visual snapshots never play sound. Declare outside time-dependent branches so arbitrary frame order cannot change the track.

Source

pub fn new( time: Time, frame_rate: FrameRate, size: Size, cache: &'a SceneCache, ) -> Self

Creates root evaluation inputs with matching local/global time.

Panics unless both design dimensions are finite and strictly positive.

Source

pub fn try_new( time: Time, frame_rate: FrameRate, size: Size, cache: &'a SceneCache, ) -> Result<Self, ValidationError>

Creates evaluation inputs with recoverable design-size validation.

Source

pub fn quality(self, quality: RenderQuality) -> Self

Selects preview approximations, preserved by nested and sampled contexts.

Source

pub fn render_quality(&self) -> RenderQuality

Explicit rendering quality; manually constructed contexts default to Final.

Source

pub fn assets(&self) -> &'a Assets

Always available resources; an unconfigured context uses an empty owner.

Source

pub fn with_assets(self, assets: &'a Assets) -> Self

Attaches the common resource owner without reading or decoding.

Source

pub fn with_diagnostics(self, diagnostics: &'a RequestDiagnostics) -> Self

Attaches a request-owned sink suitable for explicit background resource reads.

Source

pub fn diagnostics(&self) -> Option<&'a RequestDiagnostics>

Diagnostic scope retained by shifted, sampled and nested contexts.

Source

pub fn with_clip_duration(self, duration: Duration) -> Self

Sets finite clip metadata; zero denotes an instantaneous clip.

Panics for negative duration. Sampling time is not clamped to the clip.

Source

pub fn try_with_clip_duration( self, duration: Duration, ) -> Result<Self, ValidationError>

Sets clip metadata with a recoverable negative-duration diagnostic.

Source

pub fn time(&self) -> Time

Signed clip-local time.

Source

pub fn seconds(&self) -> f64

Clip-local time in floating-point seconds, for animation mathematics.

Source

pub fn global_time(&self) -> Time

Root evaluation time, unaffected by local shifts.

Source

pub fn clip_duration(&self) -> Option<Duration>

Explicit clip duration, absent for an unconstrained scene.

Source

pub fn progress(&self) -> f64

Clamped local progress; unconstrained scenes return zero.

A zero-duration clip jumps from zero to one at local time zero.

Source

pub fn progress_in(&self, start: Time, duration: Duration) -> f64

Clamped progress in a local interval, using integer boundary comparisons.

Zero duration jumps at start. Panics for negative duration. Wide integer differences allow queries across opposite signed tick extremes.

Source

pub fn ease_in( &self, start: Duration, duration: Duration, easing: Easing, ) -> f64

Eased local interval progress, with the same clamping as progress_in.

Source

pub fn frame_rate(&self) -> FrameRate

Exact rational authoring frame rate shared by still, preview and export clocks.

Source

pub fn frames(&self, count: i64) -> Duration

Converts a signed frame count directly to ticks without cumulative rounding.

Source

pub fn sample<Value>( &self, animation: &(impl Animation<Value> + ?Sized), ) -> Value

Samples an animation using local, not global, time.

Source

pub fn shifted(&self, offset: Duration) -> Self

Subtracts an offset from local time, preserving global time and clip metadata.

Offsets can be negative. Panics if the resulting local ticks overflow.

Source

pub fn try_shifted(&self, offset: Duration) -> Result<Self, ValidationError>

Subtracts a local offset without panicking on tick overflow.

Source

pub fn try_motion_blur( &self, shutter: Duration, samples: u32, build: impl FnMut(&SceneContext<'_>) -> Node, ) -> Result<Node, ValidationError>

Resamples a local subtree at 1..=64 centered integer shutter midpoints. Both local/global clocks move; clip metadata, resources and cache persist. Signed samples outside a clip are supplied unchanged for caller-owned gating.

Source

pub fn motion_blur( &self, shutter: Duration, samples: u32, build: impl FnMut(&SceneContext<'_>) -> Node, ) -> Node

Captures shutter samples, deferring invalid sampling parameters to compilation.

Source

pub fn during( &self, start: Time, duration: Duration, build: impl FnOnce(&SceneContext<'a>) -> Node, ) -> Node

Builds only in [start, start + duration), with shifted local clip inputs.

Outside the interval, including zero duration, returns an empty node and does not call build. Global time stays unchanged. Integer differences avoid overflowing the endpoint sum. Panics for negative duration.

Source

pub fn embed(&self, scene: &dyn Scene, offset: Duration) -> Node

Evaluates a child scene starting at a parent-local offset.

Finite children use their half-open duration. Infinite children are active from offset onward and clear inherited clip-duration metadata. The parent context itself is never clamped; its caller controls the parent interval. Panics for invalid child duration or unrepresentable shifted local ticks. Timeline children clip and contain their own design viewport; changing the child frame grid never quantizes the elapsed parent ticks.

Source

pub fn size(&self) -> Size

Logical design dimensions, not device pixels.

Source

pub fn bounds(&self) -> Rect

Opposite-corner logical bounds at the origin.

Source

pub fn center(&self) -> Point

Center of the logical design bounds.

Source

pub fn measure(&self, node: &Node) -> Result<Rect, ValidationError>

Measures content or declared layout in parent coordinates, independently of time.

Uses default structural limits without rendering or f32 pixel conversion. For explicit budgets use Node::measure. Leaves supply their own bounds with the shared explicit font environment. This does not invoke drawing or infer filter extents; command validation occurs during compilation.

Source

pub fn measure_or(&self, node: &Node, fallback: Rect) -> Rect

Measures like measure but substitutes fallback when measurement fails, for example context.measure_or(&label, Rect::default()). The failure still surfaces when the node is compiled.

Source

pub fn try_next_to( &self, node: impl Into<Node>, reference: &Node, side: Side, gap: f64, ) -> Result<Node, ValidationError>

Places a measured snapshot next to a reference in parent coordinates.

Vertical sides center horizontally; horizontal sides center vertically. Finite negative gaps intentionally overlap. Returns errors for unknown geometry, invalid gaps or unrepresentable offsets; inputs stay unchanged. This is immediate snapshot positioning, not a live constraint to reference.

use motion_core::prelude::*;
use motion_core::{
    DisplayList, RasterLimits, ResourcePool, ValidatedDisplayList, MAX_PATH_VERBS,
    MAX_STROKE_VERBS, MAX_SVG_PATH_BYTES, sample_offsets,
};
let cache = SceneCache::new(0);
let context = SceneContext::new(
    Time::ZERO,
    FrameRate::from(30),
    Size::new(200.0, 100.0),
    &cache,
);
let reference = Node::from(Rect::new(10.0, 10.0, 50.0, 30.0).fill(Color::WHITE));
let card = Node::from(Rect::new(0.0, 0.0, 8.0, 4.0).fill(Color::WHITE));
let card = context.next_to(card, &reference, Side::Right, 6.0);
assert_eq!(context.measure(&card)?, Rect::new(56.0, 18.0, 64.0, 22.0));
let card = context.align_to(card, &reference, Side::Bottom);
assert_eq!(context.measure(&card)?, Rect::new(56.0, 26.0, 64.0, 30.0));
Source

pub fn try_align_to( &self, node: impl Into<Node>, reference: &Node, edge: Side, ) -> Result<Node, ValidationError>

Aligns one measured edge with a reference, preserving the other axis.

Uses the already transformed parent-space AABBs. Existing position, rotation, scale and pivot remain intact; only translation is added.

Source

pub fn next_to( &self, node: impl Into<Node>, reference: &Node, side: Side, gap: f64, ) -> Node

Measures and places the snapshot next to its reference during compilation.

Source

pub fn align_to( &self, node: impl Into<Node>, reference: &Node, edge: Side, ) -> Node

Aligns one edge using the current compile-time font and drawing environment.

Source

pub fn random(&self, key: impl Hash) -> f64

Returns a key-derived value in [0, 1), independent of time and cache state.

Source

pub fn random_generator(&self, key: impl Hash) -> Random

Starts a fresh key-derived stream, independent of all other evaluations.

Source

pub fn cache<Key: Eq + Hash + Send + Sync + 'static, Value: Send + Sync + 'static>( &self, key: Key, build: impl FnOnce() -> Value, ) -> Arc<Value> ⓘ

Reuses a pure value by calling location, value type and an equal typed key.

Keys must distinguish all inputs, including resource revisions. Keys are retained, so use owned data or static references rather than borrowed locals. Hash collisions are resolved by key type and equality. Builders may be rerun after eviction, clear, disabled caching or races.

Source

pub fn memo<Key: Eq + Hash + Send + Sync + 'static, Output: Into<Node>>( &self, key: Key, build: impl FnOnce() -> Output, ) -> Node

Reuses a pure static subtree without exposing its shared Arc handle.

Source

pub fn cache_with_cost<Key: Eq + Hash + Send + Sync + 'static, Value: Send + Sync + 'static>( &self, key: Key, build: impl FnOnce() -> Value, cost: impl FnOnce(&Value) -> usize, ) -> Arc<Value> ⓘ

Caches a pure value with an explicit logical retained-byte estimate. Cost includes the key, value and their owned heap payloads, with a minimum of their combined inline sizes. Entry metadata, allocator overhead and shared external pins are excluded. Oversized values are returned without retention; cost runs outside the lock. Keys retain the same equality-checked, callsite-scoped contract as cache().

Trait Implementations§

Source§

impl<'a> Clone for SceneContext<'a>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'a> Copy for SceneContext<'a>

Auto Trait Implementations§

§

impl<'a> Forget for SceneContext<'a>

§

impl<'a> Freeze for SceneContext<'a>

§

impl<'a> RefUnwindSafe for SceneContext<'a>

§

impl<'a> Send for SceneContext<'a>

§

impl<'a> Sync for SceneContext<'a>

§

impl<'a> Unpin for SceneContext<'a>

§

impl<'a> UnsafeUnpin for SceneContext<'a>

§

impl<'a> UnwindSafe for SceneContext<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.