Skip to main content

Crate embree3

Crate embree3 

Source
Expand description

Crates.io CI

Safe Rust bindings to Embree 3.13.5, Intel’s high-performance ray-tracing kernels.

This crate is a thin unsafe FFI wrapper whose one job is to turn Embree’s raw pointers and C callbacks into a memory-safe Rust API: callback closures are heap-owned and reached through a lock-free per-geometry table; geometry mutation is gated by the GeometryBuilder / Geometry typestate; and Scene is a non-Clone unique owner of its handle (share a committed one across threads with Arc<Scene>).

§Overview

§Quick start

use embree3::{BufferUsage, Device, Format, GeometryKind, IntersectContext, Ray, RayHit};

let device = Device::new().unwrap();
let mut scene = device.create_scene().unwrap();

// One triangle.
let mut tri = device.create_geometry(GeometryKind::TRIANGLE).unwrap();
tri.set_new_buffer::<[f32; 3]>(BufferUsage::VERTEX, 0, Format::FLOAT3, 3 * 4, 3)
    .unwrap()
    .copy_from_slice(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]);
tri.set_new_buffer::<[u32; 3]>(BufferUsage::INDEX, 0, Format::UINT3, 3 * 4, 1)
    .unwrap()
    .copy_from_slice(&[[0, 1, 2]]);
let tri = tri.commit();
scene.attach_geometry(&tri);
scene.commit();

// Trace one ray at it.
let mut ctx = IntersectContext::coherent();
let mut rayhit = RayHit::from(Ray::segment(
    [0.25, 0.25, -1.0],
    [0.0, 0.0, 1.0],
    0.0,
    f32::INFINITY,
));
scene.intersect(&mut ctx, &mut rayhit);
assert!(rayhit.hit.is_valid());

§Documentation

Rust doc can be found here. Embree documentation can be found here. See the examples/ for some example applications using the bindings.

§Intentionally unwrapped embree functions

A few embree C entry points are deliberately not exposed, because a safer or more idiomatic Rust mechanism already covers them. Reach for the alternative listed here:

embree C functionUse insteadWhy
rtcNewSharedBufferGeometryBuilder::set_shared_bufferApp-owned, zero-copy data is bound through a real &'buf [u8] borrow, so the compiler enforces “the data outlives the geometry”. The C buffer object exists to share a raw pointer across bindings, which a Rust reference already does, so it adds no capability.
rtcSetGeometryPointQueryFunctionScene::point_queryIts callback receives no per-geometry pointer (only the scene query’s userPtr), so it cannot host a capturing closure. Branch on geomID inside the Scene::point_query closure for per-geometry logic.
rtcGetSceneDeviceScene::deviceThe scene already tracks (and hands back) its Device; the raw getter would only duplicate it.
rtcSetDeviceProperty(none)Embree exposes no public writable device properties (the only settable ones are hidden internal debug integers), so a wrapper would reject every public DeviceProperty. Use Device::get_property for the read-only queries.
rtcRetainBVH(none)Bvh is a non-Clone build target (the build result borrows it exclusively), so there is never a second handle to retain; rtcReleaseBVH runs once in Drop.
rtcRetainSceneArc<Scene>Scene is a non-Clone unique owner of its handle (so &mut Scene stays exclusive for mutation/commit); share a committed scene with Arc<Scene>. There is never a second handle to retain, and rtcReleaseScene runs once in Drop.

Two further functions, rtcGetGeometryUserData and rtcRetainGeometry, are not exposed because the crate’s geometry ownership model (an internal Arc plus a lock-free callback table) supersedes them; no user action is needed.

§Panics in callbacks

User closures registered as embree callbacks (geometry intersect/occluded/bounds/filter/displacement, the scene progress monitor, point queries, the BVH builder, and Scene::collide) run behind embree’s non-unwinding extern "C" ABI. A panic that escapes such a callback aborts the process – Rust turns an unwind that reaches a non--unwind extern "C" boundary into an abort, so this is defined behavior, not UB. The hot per-ray/per-primitive trampolines therefore call the closure directly (no per-call catch_unwind landing pad). Handle recoverable errors inside the closure (e.g. record them in captured state); do not rely on catching a panic across a query.

Modules§

packet
Ray packet types and traits.
stream
Ray stream types in SOA layout.
sys
Automatically generated bindings to the Embree C API.

Structs§

AlignedArray
16 bytes aligned with known size at compile time.
AlignedVector
Utility for making specifically aligned vector.
Allocator
Per-callback-thread bump allocator over the BVH arena (rtcThreadLocalAlloc). !Send + !Sync: valid only on its current callback thread.
Buffer
Handle to a buffer managed by Embree.
BufferLayout
Layout of a geometry buffer binding: how embree reads the bound bytes. Carried by every binding and reported by Geometry::get_buffer.
BufferView
A read-only view into mapped buffer.
BufferViewMut
A write-only view into mapped buffer.
BuildConfig
Build settings. Default reproduces rtcDefaultBuildArguments.
Bvh
A reference-counted standalone BVH (RTCBVH). Build target for Bvh::build_scoped.
BvhResult
Result of a build, valid only inside the generative scope. Branded by 'id.
ChildBounds
Checked accessor over embree’s RTCBounds* array. References borrow the view (the bounds may live in callback-local storage).
Children
Checked, view-scoped accessor over embree’s void** child array.
Config
Embree device configuration.
Device
Handle to an Embree device.
Geometry
The committed, shareable phase of an Embree geometry.
GeometryBuilder
The mutable build/edit phase of an Embree geometry.
HitN
Hit packet of runtime size.
HitNp
A hit stream in SoA format.
InstanceGeometryBuilder
Typed GeometryBuilder for a fixed geometry kind. Build via its Deref/DerefMut to GeometryBuilder, then commit to a shareable Geometry.
InterpolateInput
The arguments for the Geometry::interpolate function.
InterpolateNInput
The arguments for the Geometry::interpolate_n function.
InterpolateOutput
The output of the Geometry::interpolate and Geometry::interpolate_n functions in structure of array (SOA) layout.
IntersectContextExt
Extended intersection context with additional ray query specific data.
IntersectFunctionNArgs
Arguments handed to a user-geometry intersect callback registered via GeometryBuilder::set_intersect_function.
IntersectLane
A single active lane of an intersect callback’s packet, yielded by IntersectFunctionNArgs::for_each_active_lane. Its index is already known in-range and active, so the per-lane operations take no index argument.
NodePtr
Opaque, generatively branded handle to an arena node. Copy, pointer-sized, and not dereferenceable except through BvhResult::resolve inside the build scope.
OccludedFunctionNArgs
Arguments handed to a user-geometry occluded callback registered via GeometryBuilder::set_occluded_function. The occlusion analogue of IntersectFunctionNArgs: there is no hit buffer in the packet, so on survival mark the lane occluded with set_occluded.
OccludedLane
A single active lane of an occluded callback’s packet, yielded by OccludedFunctionNArgs::for_each_active_lane. Its index is already known in-range and active.
QuadMeshBuilder
Typed GeometryBuilder for a fixed geometry kind. Build via its Deref/DerefMut to GeometryBuilder, then commit to a shareable Geometry.
RayHitN
Combined ray and hit packet of runtime size.
RayHitNp
RayN
Ray packet of runtime size.
RayNp
A ray stream stored in SoA format.
Scene
A scene containing various geometries.
SoAHitIter
SoAHitIterMut
SoAHitRef
SoAHitRefMut
SoARayIter
SoARayIterMut
SoARayRef
SoARayRefMut
TriangleMeshBuilder
Typed GeometryBuilder for a fixed geometry kind. Build via its Deref/DerefMut to GeometryBuilder, then commit to a shareable Geometry.
UserGeometryBuilder
Typed GeometryBuilder for a fixed geometry kind. Build via its Deref/DerefMut to GeometryBuilder, then commit to a shareable Geometry.
ValidMaskN
A per-lane validity mask for the packet query methods (intersect{4,8,16}, occluded{4,8,16}, point_query{4,8,16}): each lane is ValidMask::Valid (-1) or ValidMask::Invalid (0). N is the packet width.
ValidityN
Struct holding data for validity masks used in the callback function set by GeometryBuilder::set_intersect_filter_function, GeometryBuilder::set_occluded_filter_function, GeometryBuilder::set_intersect_function and GeometryBuilder::set_occluded_function.
ValidityNIter
Shared iterator over a ValidityN’s lanes, yielding each lane’s flag.
ValidityNIterMut
Mutable iterator over a ValidityN’s lanes. Like std::slice::IterMut, it owns the raw pointer and a PhantomData<&'b mut i32> borrow rather than the ValidityN, and yields &'b mut i32 tied to that borrow – so a yielded reference cannot outlive the iterator’s borrow of the ValidityN (which would otherwise let safe code alias a lane).
Vertices
Struct holding data for a set of vertices in SoA layout. This is used as a parameter to the callback function set by GeometryBuilder::set_displacement_function.
VerticesIterMut
Mutable iterator over a geometry’s Vertices, yielding each vertex in turn.

Enums§

BufferSource
The data source bound to a geometry buffer slot.
CbKind
Identifies one of a geometry’s callback slots.
FrequencyLevel
Frequency level of the application.
Isa
Instruction Set Architecture.
ValidMask
Validity mask value for rays or hits in the filter functions. See ValidityN.

Constants§

INVALID_ID
The invalid ID for Embree intersection results (e.g. Hit::geomID, Hit::primID, etc.)

Traits§

AsIntersectContext
Trait for extended intersection context enabling passing of additional ray-query specific data.
BufferData
Types that may safely alias the raw bytes of an embree buffer when mapping it as [Self].
BvhBuilder
Materializes embree’s BVH topology into a caller-defined node layout.
BvhNode
Marker for a type that may live in the BVH arena.
HitPacket
Represents a packet of hits.
RayHitPacket
Represents a packet of ray/hit pairs.
RayPacket
Represents a packet of rays.
SoAHit
Per-lane accessors for a hit packet in structure-of-arrays (SoA) layout.
SoARay
Per-lane accessors for a ray packet in structure-of-arrays (SoA) layout.
UserData
Marker trait for types usable as callback user data: geometry callback user data (bound via GeometryBuilder’s _owned / _borrowed callback setters) or point-query user data (Scene::point_query).

Functions§

enable_ftz_and_daz
Set the flush zero and denormals modes from Embrees’s perf. recommendations <https://embree.github.io/api.html#performance-recommendations>.

Type Aliases§

Bounds
An axis-aligned bounding box, given by its lower and upper corners. Returned by Scene::get_bounds and filled in by user-geometry bounds callbacks.
BufferSize
Non-zero integer type used to describe the size of a buffer.
BufferUsage
Defines the type of slots to assign data buffers to.
BuildFlags
Flags controlling a standalone BVH build (e.g. dynamic / refittable). See BuildConfig.
BuildPrimitive
Primitives that can be used to build a BVH.
BuildQuality
Speed-vs-quality trade-off for a scene or BVH build (see Scene::set_build_quality and BuildConfig).
Collision
A candidate colliding primitive pair reported by Scene::collide: the geomID/primID of one primitive in each scene. It is a potentially-intersecting pair from a leaf pair reached during broad-phase traversal; embree does not test the bounds before reporting, so the pair’s bounds need not overlap and the callback must narrow-phase.
CurveFlags
Per-segment flags for curve geometries (e.g. neighbor joins).
DeviceProperty
A queryable, read-only device property (see Device::get_property).
Error
An Embree error code. Returned by fallible operations and reported through the device error callback; see Device::get_error.
Format
The element format of a data buffer, e.g. Format::FLOAT3 for vertex positions or Format::UINT3 for a triangle index.
GeometryKind
The type of a geometry, used to determine which geometry type to create.
Hit
New type alias for sys::RTCHit that provides some convenience methods.
Hit4
A hit packet of size 4.
Hit8
A hit packet of size 8.
Hit16
A hit packet of size 16.
IntersectContext
Per ray-query intersection context.
IntersectContextFlags
Flags on an IntersectContext selecting the traversal mode (e.g. coherent vs incoherent ray distributions).
LinearBounds
Linear (motion-blur) bounds: the axis-aligned bounding box at the start (bounds0) and end (bounds1) of the scene’s time range. See Scene::get_linear_bounds.
PointQuery
Object used to traverses the BVH and calls a user defined callback function for each primitive of the scene that intersects the query domain.
PointQuery4
A SoA packet of 4 point queries (see Scene::point_query4).
PointQuery8
A SoA packet of 8 point queries (see Scene::point_query8).
PointQuery16
A SoA packet of 16 point queries (see Scene::point_query16).
PointQueryContext
A stack which stores the IDs and instance transformations during a BVH traversal for a point query.
QuaternionDecomposition
Structure that represents a quaternion decomposition of an affine transformation.
Ray
New type alias for sys::RTCRay that provides some convenience methods.
Ray4
A ray packet of size 4.
Ray8
A ray packet of size 8.
Ray16
A ray packet of size 16.
RayHit
New type alias for sys::RTCRayHit that provides some convenience methods.
RayHit4
A ray/hit packet of size 4.
RayHit8
A ray/hit packet of size 8.
RayHit16
A ray/hit packet of size 16.
SceneFlags
Scene-level flags (e.g. DYNAMIC, ROBUST, COMPACT); see Scene::set_flags.
SubdivisionMode
Subdivision mode for subdivision-surface geometries (how the limit surface is evaluated near boundaries and creases).