Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

Assembler tracing (OTLP), and thumbnails drawn with the viewer's camera (#1841)

Sid90cad606b5b5
diff --git a/.claude/rules/environment-configuration.md b/.claude/rules/environment-configuration.md
index 7f361ab34e..5f69397ea2 100644
--- a/.claude/rules/environment-configuration.md
+++ b/.claude/rules/environment-configuration.md
@@ -127,7 +127,8 @@ the OTel SDK (not `@carbon/env`): `OTEL_EXPORTER_OTLP_ENDPOINT` (or
`OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`) turns server tracing on,
`OTEL_EXPORTER_OTLP_HEADERS` carries the backend's auth, and
`OTEL_SERVICE_NAME` / `OTEL_TRACES_SAMPLER` / `OTEL_TRACES_SAMPLER_ARG` tune it.
-Unset = no tracing. See `packages/logger/AGENTS.md` → Tracing.
+Unset = no tracing. See `packages/logger/AGENTS.md` → Tracing. The Rust assembler
+reads the same variables (`apps/assembler/AGENTS.md` → Tracing).
**Deployment** — `VERCEL_URL` (required at module load; value unused off-Vercel,
set to `production` in prod compose), `VERCEL_ENV`, `NODE_ENV`. `ERP_URL` /
diff --git a/Cargo.lock b/Cargo.lock
index 96f7178bb3..f12fa5bab5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -58,6 +58,7 @@ name = "assembler"
version = "0.1.0"
dependencies = [
"async-compression",
+ "async-trait",
"axum",
"bytes",
"converter",
@@ -68,6 +69,10 @@ dependencies = [
"hmac",
"lru",
"memmap2",
+ "opentelemetry",
+ "opentelemetry-http",
+ "opentelemetry-otlp",
+ "opentelemetry_sdk",
"optimize",
"planner",
"redis",
@@ -1599,6 +1604,75 @@ dependencies = [
"vcpkg",
]
+[[package]]
+name = "opentelemetry"
+version = "0.33.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6cdb0b1b267eb9db3331b434ed9ddab10d50e280a9adf9d13e5233e2002b61b5"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+ "js-sys",
+ "pin-project-lite",
+ "thiserror 2.0.18",
+ "tracing",
+]
+
+[[package]]
+name = "opentelemetry-http"
+version = "0.33.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee2c3625b8aa04209f7e01e513bc8044da9687fa38a9eacf59628ca5f3b87300"
+dependencies = [
+ "async-trait",
+ "bytes",
+ "http",
+ "opentelemetry",
+]
+
+[[package]]
+name = "opentelemetry-otlp"
+version = "0.33.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "699a67345e21962a231955b9059a157e428b219fa5df8efe11f08346fb23a344"
+dependencies = [
+ "http",
+ "httpdate",
+ "opentelemetry",
+ "opentelemetry-http",
+ "opentelemetry-proto",
+ "opentelemetry_sdk",
+ "prost",
+ "thiserror 2.0.18",
+]
+
+[[package]]
+name = "opentelemetry-proto"
+version = "0.33.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "25da1ac11a0aeccf38d7f77ee0348715adaf8340f65ad46c94a02c6b20e2f65d"
+dependencies = [
+ "opentelemetry",
+ "opentelemetry_sdk",
+ "prost",
+]
+
+[[package]]
+name = "opentelemetry_sdk"
+version = "0.33.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb39533d9d1c912123efd7d41d7e0c29d16917b60ce15b4c8d87cb1af7f67520"
+dependencies = [
+ "futures-channel",
+ "futures-executor",
+ "futures-util",
+ "opentelemetry",
+ "percent-encoding",
+ "portable-atomic",
+ "rand 0.9.5",
+ "thiserror 2.0.18",
+]
+
[[package]]
name = "optimize"
version = "0.1.0"
@@ -1726,6 +1800,29 @@ dependencies = [
"version_check",
]
+[[package]]
+name = "prost"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"
+dependencies = [
+ "bytes",
+ "prost-derive",
+]
+
+[[package]]
+name = "prost-derive"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"
+dependencies = [
+ "anyhow",
+ "itertools",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "quick-xml"
version = "0.41.0"
@@ -1819,10 +1916,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a"
dependencies = [
"libc",
- "rand_chacha",
+ "rand_chacha 0.3.1",
"rand_core 0.6.4",
]
+[[package]]
+name = "rand"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
+dependencies = [
+ "rand_chacha 0.9.0",
+ "rand_core 0.9.5",
+]
+
[[package]]
name = "rand"
version = "0.10.2"
@@ -1844,6 +1951,16 @@ dependencies = [
"rand_core 0.6.4",
]
+[[package]]
+name = "rand_chacha"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
+dependencies = [
+ "ppv-lite86",
+ "rand_core 0.9.5",
+]
+
[[package]]
name = "rand_core"
version = "0.6.4"
@@ -1853,6 +1970,15 @@ dependencies = [
"getrandom 0.2.17",
]
+[[package]]
+name = "rand_core"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
+dependencies = [
+ "getrandom 0.3.4",
+]
+
[[package]]
name = "rand_core"
version = "0.10.1"
diff --git a/apps/assembler/AGENTS.md b/apps/assembler/AGENTS.md
index 0e19348995..6bf476d96d 100644
--- a/apps/assembler/AGENTS.md
+++ b/apps/assembler/AGENTS.md
@@ -29,7 +29,8 @@ crates/
│ # write_test_step generates hermetic multi-solid STEP fixtures for tests.
├── converter/ # STEP → graph.json + GLB. nodeid (sha1), graph (tree/bbox/source-unit), convert, glb.
├── thumbnail/ # GLB → PNG preview, on the CPU: reads plain or EXT_meshopt_compression GLBs,
-│ # z-buffer rasteriser from the viewer's default isometric direction (Z up),
+│ # z-buffer rasteriser through the viewer's camera (45° perspective, Z up; home
+│ # direction unless the caller names one),
│ # material base colours, transparent background, hand-written PNG encoder.
│ # `cargo run --release -p thumbnail --example render -- in.glb out.png` to eyeball one.
└── planner/ # assembly-by-disassembly motion planner: greedy/geom/fasteners/collide/steps.
@@ -101,6 +102,43 @@ a constant or derived in `config.rs` (max parts 5000, shutdown grace 600 s, job
and result TTLs 24 h, pending TTL 5 min, long-poll cap 25 s) — deliberately not
env-tunable.
+## Tracing
+
+`src/telemetry.rs` — OpenTelemetry traces over OTLP/HTTP, off unless
+`OTEL_EXPORTER_OTLP_ENDPOINT` (or `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`) is set.
+It reads the same variables as the Node apps (`packages/logger`):
+`OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_RESOURCE_ATTRIBUTES`, `OTEL_SERVICE_NAME`
+(default `assembler`), `OTEL_TRACES_SAMPLER[_ARG]`. Traces only — no metrics or
+logs; `eprintln!` stays the log.
+
+One trace per job: the caller's `traceparent` → the request span
+(`POST /v1/convert`, named by matched route; `/health` has none) → `job <action>`
+→ `download source` / `compute` / `upload artifact` / `callback`.
+
+- **A job is spawned with `telemetry::spawn_job`, never bare `tokio::spawn`.**
+ The job outlives its request, so the span context has to travel with the task;
+ a bare spawn starts a job whose spans belong to no trace.
+- **Across the Lambda self-invoke the parent rides in the run-job spec**
+ (`traceparent`, written by `telemetry::inject` in `lambda_dispatch`, restored
+ by `telemetry::attach` in `run::spawn_from_spec`). A spec built anywhere else
+ can carry the same key.
+- **Outbound requests go through `http::{download_hashed, upload, post_json}`**,
+ which record the host only. The URLs are signed, and error text that quotes
+ one is reduced to its origin before it is put on a span (`without_urls`).
+- **Export uses the reqwest already in the binary** (`ExportClient`), not the
+ exporter's bundled client: that one is reqwest 0.13 and brings a second TLS
+ stack (aws-lc) beside ours (ring).
+- **On Lambda every request flushes before it responds** — the process freezes
+ once the response is sent. That adds one export round trip to each response
+ there, capped at 3 s (`LAMBDA_FLUSH_WAIT`) so a slow collector cannot push a
+ 25 s job poll past API Gateway's 30 s; ECS and local runs export on the batch
+ timer.
+- **Every exit path calls `telemetry::shutdown()`** — `process::exit` runs no
+ destructors, so a path that skips it drops the last batch.
+
+`apps/assembler/sst.config.ts` forwards the `OTEL_*` variables that are set at
+deploy time; `ci/src/assembler.ts` does not set any yet.
+
## Completion & lifecycle
Every action is an async job: POST returns 202 and the job runs in a background
@@ -202,9 +240,20 @@ Built to sit as a small always-on pod beside other workloads.
## Thumbnails
-`POST /v1/thumbnail` `{ source: { url }, output: { path?, size? } }` renders the
-GLB at `source.url` to a square PNG (300 px unless `size` says otherwise) and
-late-mint uploads it as the `thumbnail` output. The caller is `@carbon/jobs`
+`POST /v1/thumbnail` `{ source: { url }, output: { path?, size?, direction? } }`
+renders the GLB at `source.url` to a square PNG (300 px unless `size` says
+otherwise) and late-mint uploads it as the `thumbnail` output.
+
+The camera is the viewer's: a 45° perspective looking at the centre of the
+bounding box, standing back far enough to fit the bounding sphere (`FOV_DEGREES`
+/ `FIT_MARGIN` in `crates/thumbnail`, mirroring `AssemblyViewer`'s camera and
+`frameBox` in `packages/viewer/src/ModelCanvas.tsx` — change one and change the
+other). `direction` is `[x, y, z]` from the model towards the camera, Z up;
+absent or unusable, it is the viewer's home view `[1, -1, 1]`. The viewer's
+camera button (`ModelPreview` `onCaptureThumbnail`) sends the direction its
+camera stands at, through `api+/model.thumbnail.ts` and the
+`carbon/model-thumbnail` event. Only the direction travels: the image is always
+re-framed to fit the whole model, whatever the viewer's zoom or pan. The caller is `@carbon/jobs`
`tasks/model-thumbnail.ts`, which hands it the model's optimised GLB (else the
lossless `convert` GLB). It replaced a headless-browser screenshot of the viewer
page. A Draco-compressed GLB is refused (`thumbnail_failed`); textures and vertex
diff --git a/apps/assembler/Cargo.toml b/apps/assembler/Cargo.toml
index 04d0f02e73..b80014fc20 100644
--- a/apps/assembler/Cargo.toml
+++ b/apps/assembler/Cargo.toml
@@ -38,6 +38,15 @@ tower-http = { version = "0.6", features = ["compression-zstd", "compression-gzi
memmap2 = "0.9"
file-format = "0.26"
tempfile = "3"
+# Tracing (OTLP over HTTP, traces only). Inert unless OTEL_EXPORTER_OTLP_ENDPOINT
+# is set — the same switch and variables as the Node apps (`@carbon/logger`).
+opentelemetry = "0.33"
+opentelemetry_sdk = "0.33"
+# No bundled HTTP client: its reqwest 0.13 would bring a second TLS stack
+# (aws-lc) beside ours (ring). Spans are sent with the reqwest already here.
+opentelemetry-otlp = { version = "0.33", default-features = false, features = ["trace", "http-proto"] }
+opentelemetry-http = { version = "0.33", default-features = false }
+async-trait = "0.1"
[target.'cfg(target_os = "linux")'.dependencies]
# Unprefixed: jemalloc is `malloc` for the whole process, so OCCT and FCL (C++,
diff --git a/apps/assembler/src/actions/compact.rs b/apps/assembler/src/actions/compact.rs
index c1e659878d..3d3a54daef 100644
--- a/apps/assembler/src/actions/compact.rs
+++ b/apps/assembler/src/actions/compact.rs
@@ -18,7 +18,7 @@
//! re-running compact on an already-compacted model is a no-op-safe passthrough.
use crate::jobs::{Done, Output};
-use crate::{admission, http, AppState};
+use crate::{admission, http, telemetry, AppState};
use serde_json::json;
use std::time::Instant;
@@ -56,7 +56,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: CompactReq) {
let jobs = state.jobs.clone();
let admission = state.admission.clone();
let job_id = job_id.to_string();
- tokio::spawn(async move {
+ telemetry::spawn_job(&job_id.clone(), "compact", async move {
if jobs.is_canceled(&job_id).await {
return;
}
@@ -79,7 +79,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: CompactReq) {
let _grant = admission
.acquire(admission::estimate_mb(http::file_len(&src).await))
.await;
- tokio::task::spawn_blocking(move || compress(&src_str, mode, level)).await
+ telemetry::in_span("compute", tokio::task::spawn_blocking(move || compress(&src_str, mode, level))).await
};
let _ = tokio::fs::remove_file(&src).await;
diff --git a/apps/assembler/src/actions/convert.rs b/apps/assembler/src/actions/convert.rs
index 7d327956c0..55817a1526 100644
--- a/apps/assembler/src/actions/convert.rs
+++ b/apps/assembler/src/actions/convert.rs
@@ -9,7 +9,7 @@
use crate::cache::{CachedConvert, ResultCache};
use crate::jobs::{Done, Output};
-use crate::{admission, config, http, progress, AppState};
+use crate::{admission, config, http, progress, telemetry, AppState};
use serde_json::json;
use std::sync::Arc;
use std::time::Instant;
@@ -35,7 +35,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: ConvertReq) {
let progress_store = state.progress.clone();
let admission = state.admission.clone();
let job_id = job_id.to_string();
- tokio::spawn(async move {
+ telemetry::spawn_job(&job_id.clone(), "convert", async move {
if jobs.is_canceled(&job_id).await {
return;
}
@@ -85,7 +85,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: ConvertReq) {
let tmp_str = tmp.to_string_lossy().to_string();
let cache_ins = Arc::clone(&cache);
let (lin, ang, optimize) = (req.lin, req.ang, req.optimize);
- let res = tokio::task::spawn_blocking(move || {
+ let res = telemetry::in_span("compute", tokio::task::spawn_blocking(move || {
// Compacted retained raws are BinXCAF (`.xbf`) — binary, no
// STEP header to unit-detect (already mm); running the lossy
// text scan on them is wasted work at best.
@@ -119,7 +119,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: ConvertReq) {
},
)
})
- })
+ }))
.await;
let _ = tokio::fs::remove_file(&tmp).await;
match res {
diff --git a/apps/assembler/src/actions/optimize.rs b/apps/assembler/src/actions/optimize.rs
index 6e099e9e0d..4d6925ac22 100644
--- a/apps/assembler/src/actions/optimize.rs
+++ b/apps/assembler/src/actions/optimize.rs
@@ -14,7 +14,7 @@
use crate::formats::{self, Format};
use crate::jobs::{Done, Output};
-use crate::{admission, http, AppState};
+use crate::{admission, http, telemetry, AppState};
use serde_json::json;
use std::time::{Duration, Instant};
@@ -87,7 +87,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: OptimizeReq) {
let jobs = state.jobs.clone();
let admission = state.admission.clone();
let job_id = job_id.to_string();
- tokio::spawn(async move {
+ telemetry::spawn_job(&job_id.clone(), "optimize", async move {
if jobs.is_canceled(&job_id).await {
return;
}
@@ -116,9 +116,9 @@ pub fn spawn(state: &AppState, job_id: &str, req: OptimizeReq) {
let _grant = admission
.acquire(admission::estimate_mb(http::file_len(&tmp).await))
.await;
- tokio::task::spawn_blocking(move || {
+ telemetry::in_span("compute", tokio::task::spawn_blocking(move || {
run_optimize(&tmp_str, &declared, ext.as_deref(), &opts)
- })
+ }))
.await
};
let _ = tokio::fs::remove_file(&tmp).await;
diff --git a/apps/assembler/src/actions/plan.rs b/apps/assembler/src/actions/plan.rs
index 1de95efc6f..d291187bf8 100644
--- a/apps/assembler/src/actions/plan.rs
+++ b/apps/assembler/src/actions/plan.rs
@@ -7,7 +7,7 @@
//! late-mint uploaded (a `planPath` was given) or returned inline in the result.
use crate::jobs::{opts_hash, Done, Output};
-use crate::{admission, config, http, AppState};
+use crate::{admission, config, http, telemetry, AppState};
use planner::steps::PlanUnit;
use serde_json::{json, Value};
use std::time::Instant;
@@ -27,7 +27,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: PlanReq) {
let jobs = state.jobs.clone();
let admission = state.admission.clone();
let job_id = job_id.to_string();
- tokio::spawn(async move {
+ telemetry::spawn_job(&job_id.clone(), "plan", async move {
if jobs.is_canceled(&job_id).await {
return;
}
@@ -72,7 +72,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: PlanReq) {
.acquire(admission::plan_estimate_mb(source_bytes, None))
.await;
let runtime = tokio::runtime::Handle::current();
- let res = tokio::task::spawn_blocking(move || {
+ let res = telemetry::in_span("compute", tokio::task::spawn_blocking(move || {
let grant = std::sync::Mutex::new(grant);
planner::steps::plan_step_observed(
&tmp_str,
@@ -90,7 +90,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: PlanReq) {
runtime.block_on(grant.resize(estimate));
},
)
- })
+ }))
.await;
let _ = tokio::fs::remove_file(&tmp).await;
diff --git a/apps/assembler/src/actions/thumbnail.rs b/apps/assembler/src/actions/thumbnail.rs
index 21996919bf..f6459c22c0 100644
--- a/apps/assembler/src/actions/thumbnail.rs
+++ b/apps/assembler/src/actions/thumbnail.rs
@@ -9,7 +9,7 @@
//! uploaded.
use crate::jobs::{Done, Output};
-use crate::{admission, http, AppState};
+use crate::{admission, http, telemetry, AppState};
use serde_json::json;
use std::time::Instant;
@@ -17,6 +17,9 @@ pub struct ThumbnailReq {
pub source_url: String,
/// Side of the square image in pixels (clamped by the renderer).
pub size: u32,
+ /// Where the camera stands: model towards camera, Z up. The viewer's home
+ /// direction unless the caller captured another.
+ pub direction: [f32; 3],
/// Storage path recorded in the completion pointer; the signed PUT URL is
/// late-minted per poll, key `thumbnail`.
pub path: Option<String>,
@@ -26,7 +29,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: ThumbnailReq) {
let jobs = state.jobs.clone();
let admission = state.admission.clone();
let job_id = job_id.to_string();
- tokio::spawn(async move {
+ telemetry::spawn_job(&job_id.clone(), "thumbnail", async move {
if jobs.is_canceled(&job_id).await {
return;
}
@@ -42,13 +45,13 @@ pub fn spawn(state: &AppState, job_id: &str, req: ThumbnailReq) {
return;
}
let src_str = src.to_string_lossy().to_string();
- let size = req.size;
+ let (size, direction) = (req.size, req.direction);
let res = {
let _grant = admission
.acquire(admission::estimate_mb(http::file_len(&src).await))
.await;
- tokio::task::spawn_blocking(move || render(&src_str, size)).await
+ telemetry::in_span("compute", tokio::task::spawn_blocking(move || render(&src_str, size, direction))).await
};
let _ = tokio::fs::remove_file(&src).await;
@@ -91,9 +94,9 @@ pub fn spawn(state: &AppState, job_id: &str, req: ThumbnailReq) {
});
}
-fn render(path: &str, size: u32) -> Result<Vec<u8>, String> {
+fn render(path: &str, size: u32, direction: [f32; 3]) -> Result<Vec<u8>, String> {
let file = std::fs::File::open(path).map_err(|e| format!("open {path}: {e}"))?;
// SAFETY: the temp file is ours alone and outlives the map; nothing writes it.
let glb = unsafe { memmap2::Mmap::map(&file) }.map_err(|e| format!("mmap {path}: {e}"))?;
- thumbnail::render_png(&glb, size).map_err(|e| e.0)
+ thumbnail::render_png(&glb, size, direction).map_err(|e| e.0)
}
diff --git a/apps/assembler/src/http.rs b/apps/assembler/src/http.rs
index f4627c853e..0a88c00048 100644
--- a/apps/assembler/src/http.rs
+++ b/apps/assembler/src/http.rs
@@ -6,6 +6,7 @@
use crate::config;
use crate::error::ApiError;
+use crate::telemetry;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
@@ -69,6 +70,14 @@ pub async fn download_hashed(
url: &str,
dest: &std::path::Path,
progress: Option<&crate::progress::JobProgress>,
+) -> Result<u128, ApiError> {
+ telemetry::outbound("download source", url, download(url, dest, progress)).await
+}
+
+async fn download(
+ url: &str,
+ dest: &std::path::Path,
+ progress: Option<&crate::progress::JobProgress>,
) -> Result<u128, ApiError> {
use async_compression::tokio::bufread::ZstdDecoder;
use futures_util::StreamExt;
@@ -202,11 +211,15 @@ pub async fn upload(
body: impl Into<reqwest::Body>,
content_type: &str,
) -> Result<(), ApiError> {
+ telemetry::outbound("upload artifact", url, put(url, body.into(), content_type)).await
+}
+
+async fn put(url: &str, body: reqwest::Body, content_type: &str) -> Result<(), ApiError> {
let resp = client()
.put(url)
.header("Content-Type", content_type)
.header("x-upsert", "true") // retried jobs re-upload to the same path
- .body(body.into())
+ .body(body)
.send()
.await
.map_err(|e| {
@@ -232,6 +245,10 @@ pub async fn upload(
/// POST a JSON body (the completion-callback delivery). Short timeout; the
/// caller owns retries.
pub async fn post_json(url: &str, body: &serde_json::Value) -> Result<(), ApiError> {
+ telemetry::outbound("callback", url, post(url, body)).await
+}
+
+async fn post(url: &str, body: &serde_json::Value) -> Result<(), ApiError> {
let resp = client()
.post(url)
.header("Content-Type", "application/json")
diff --git a/apps/assembler/src/jobs.rs b/apps/assembler/src/jobs.rs
index 0c28503caa..f071546c58 100644
--- a/apps/assembler/src/jobs.rs
+++ b/apps/assembler/src/jobs.rs
@@ -303,6 +303,7 @@ impl JobStore {
}
pub async fn set_error(&self, id: &str, code: &str, message: String) {
+ crate::telemetry::record_error(code, &message);
if let Some(mut rec) = self.read(id).await {
if rec.status == "canceled" {
return;
diff --git a/apps/assembler/src/main.rs b/apps/assembler/src/main.rs
index 8ddf2a025e..8193b20e0b 100644
--- a/apps/assembler/src/main.rs
+++ b/apps/assembler/src/main.rs
@@ -30,6 +30,7 @@ mod http;
mod jobs;
mod progress;
mod run;
+mod telemetry;
use axum::{
extract::{Path, Query, State},
@@ -103,6 +104,7 @@ pub async fn build_state() -> AppState {
}
async fn serve() {
+ telemetry::init();
http::clear_stale_sources();
let state = build_state().await;
let admission = state.admission.clone();
@@ -137,6 +139,7 @@ async fn serve() {
// entirely with `Accept-Encoding: identity`. Skip bodies under 1KB
// (pointer-sized job envelopes) where a frame would cost more than it saves.
.layer(CompressionLayer::new().compress_when(SizeAbove::new(1024)))
+ .layer(axum::middleware::from_fn(telemetry::http_span))
.with_state(state);
eprintln!(
@@ -167,6 +170,7 @@ async fn serve() {
// in shutdown_signal force-exits a wedged one.
eprintln!("assembler draining in-flight jobs");
admission.drain().await;
+ telemetry::shutdown();
eprintln!("assembler drained cleanly; exiting");
}
@@ -194,6 +198,7 @@ async fn shutdown_signal() {
tokio::spawn(async move {
tokio::time::sleep(grace).await;
eprintln!("assembler shutdown grace elapsed; forcing exit");
+ telemetry::shutdown();
std::process::exit(0);
});
}
@@ -398,6 +403,7 @@ async fn lambda_dispatch(
spec["token"] = k.into();
}
}
+ telemetry::inject(&mut spec);
if let Err(m) = dispatch::self_invoke(&spec).await {
state
.jobs
@@ -790,7 +796,8 @@ async fn create_thumbnail(
respond(&state, &headers, &job_id, "thumbnail", sync).await
}
-/// `output: { path?, size? }` — shared by the HTTP body and the run-job spec.
+/// `output: { path?, size?, direction? }` — shared by the HTTP body and the
+/// run-job spec. `direction` is `[x, y, z]`, model towards camera.
pub fn thumbnail_req(source_url: &str, output: &Value) -> actions::thumbnail::ThumbnailReq {
actions::thumbnail::ThumbnailReq {
source_url: source_url.to_string(),
@@ -798,6 +805,21 @@ pub fn thumbnail_req(source_url: &str, output: &Value) -> actions::thumbnail::Th
.as_u64()
.map_or(thumbnail::DEFAULT_SIZE, |s| s.min(u32::MAX as u64) as u32),
path: output["path"].as_str().map(str::to_string),
+ direction: view_direction(&output["direction"]),
+ }
+}
+
+/// Three finite numbers that are not all zero, else the viewer's home direction.
+fn view_direction(value: &Value) -> [f32; 3] {
+ let parsed: Option<Vec<f32>> = value
+ .as_array()
+ .filter(|a| a.len() == 3)
+ .and_then(|a| a.iter().map(|n| n.as_f64().map(|n| n as f32)).collect());
+ match parsed.as_deref() {
+ Some(&[x, y, z]) if [x, y, z].iter().all(|c| c.is_finite()) && (x, y, z) != (0.0, 0.0, 0.0) => {
+ [x, y, z]
+ }
+ _ => thumbnail::DEFAULT_DIRECTION,
}
}
diff --git a/apps/assembler/src/run.rs b/apps/assembler/src/run.rs
index 9e8c973b5f..abecc16743 100644
--- a/apps/assembler/src/run.rs
+++ b/apps/assembler/src/run.rs
@@ -23,7 +23,7 @@ use serde_json::{json, Value};
use std::collections::HashMap;
use std::time::{Duration, Instant};
-use crate::{actions, build_state, config, optimize_opts, thumbnail_req, AppState};
+use crate::{actions, build_state, config, optimize_opts, telemetry, thumbnail_req, AppState};
/// Overall wall-clock ceiling for a one-shot job. Generous: ECS has no 15-min
/// cap (that's exactly why the overflow path exists); Lambda's own timeout bounds
@@ -31,6 +31,7 @@ use crate::{actions, build_state, config, optimize_opts, thumbnail_req, AppState
const RUN_JOB_MAX_SECS: u64 = 60 * 60;
pub async fn run_job_cli() -> ! {
+ telemetry::init();
let spec = match load_spec() {
Ok(s) => s,
Err(m) => fail(&m),
@@ -69,6 +70,7 @@ pub async fn run_job_cli() -> ! {
// for the receiver).
state.jobs.send_callback(&job_id).await;
println!("{result}");
+ telemetry::shutdown();
let ok = matches!(result["job"]["status"].as_str(), Some("succeeded"));
std::process::exit(if ok { 0 } else { 1 });
}
@@ -84,6 +86,8 @@ pub fn spawn_from_spec(
action: &str,
spec: &Value,
) -> Result<(), String> {
+ // The submitting request's trace, when the spec carries it.
+ let _trace = telemetry::attach(spec);
let source_url = spec["source"]["url"]
.as_str()
.unwrap_or_default()
@@ -204,5 +208,6 @@ fn fail(msg: &str) -> ! {
"{}",
json!({ "ok": false, "error": { "code": "invalid_input", "message": msg } })
);
+ telemetry::shutdown();
std::process::exit(1);
}
diff --git a/apps/assembler/src/telemetry.rs b/apps/assembler/src/telemetry.rs
new file mode 100644
index 0000000000..db4787cf4a
--- /dev/null
+++ b/apps/assembler/src/telemetry.rs
@@ -0,0 +1,373 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+//! OpenTelemetry tracing, exported over OTLP/HTTP. Traces only.
+//!
+//! Inert unless `OTEL_EXPORTER_OTLP_ENDPOINT` (or the traces-specific variant)
+//! is set — the same switch as the Node apps (`@carbon/logger`), and the same
+//! variables: `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_RESOURCE_ATTRIBUTES`,
+//! `OTEL_SERVICE_NAME`, `OTEL_TRACES_SAMPLER[_ARG]`. With no provider installed
+//! every span below is a no-op.
+//!
+//! One trace per job: the caller's `traceparent` → the request span → a
+//! `job <action>` span → `download source` / `compute` / `upload artifact` /
+//! `callback`. The job runs detached from the request (and, on Lambda, in
+//! another invocation), so its parent travels explicitly: through the spawn
+//! (`spawn_job`) in-process, and through the run-job spec (`inject` / `attach`)
+//! across the self-invoke.
+
+use std::collections::HashMap;
+use std::future::Future;
+use std::sync::OnceLock;
+
+use axum::extract::{MatchedPath, Request};
+use axum::middleware::Next;
+use axum::response::Response;
+use opentelemetry::global::{self, BoxedTracer};
+use opentelemetry::trace::{FutureExt, SpanKind, Status, TraceContextExt, Tracer};
+use opentelemetry::{Context, ContextGuard, KeyValue};
+use opentelemetry_http::{Bytes, HeaderExtractor, HttpClient, HttpError};
+use opentelemetry_otlp::{SpanExporter, WithHttpConfig};
+use opentelemetry_sdk::propagation::TraceContextPropagator;
+use opentelemetry_sdk::trace::SdkTracerProvider;
+use opentelemetry_sdk::Resource;
+use serde_json::Value;
+
+use crate::error::ApiError;
+
+static PROVIDER: OnceLock<SdkTracerProvider> = OnceLock::new();
+
+/// The key the parent context travels under in a run-job spec.
+const SPEC_KEY: &str = "traceparent";
+
+fn tracer() -> BoxedTracer {
+ global::tracer("assembler")
+}
+
+/// Install the exporter. Call once, inside the tokio runtime.
+pub fn init() {
+ let configured = [
+ "OTEL_EXPORTER_OTLP_ENDPOINT",
+ "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
+ ]
+ .iter()
+ .any(|key| std::env::var(key).is_ok_and(|value| !value.is_empty()));
+ if !configured {
+ return;
+ }
+ let exporter = match SpanExporter::builder()
+ .with_http()
+ .with_http_client(ExportClient::new())
+ .build()
+ {
+ Ok(exporter) => exporter,
+ Err(e) => {
+ eprintln!("assembler: tracing disabled (exporter: {e})");
+ return;
+ }
+ };
+ // OTEL_SERVICE_NAME, when set, wins over the default name.
+ let mut resource = Resource::builder();
+ if std::env::var_os("OTEL_SERVICE_NAME").is_none() {
+ resource = resource.with_service_name("assembler");
+ }
+ let provider = SdkTracerProvider::builder()
+ .with_resource(resource.build())
+ .with_batch_exporter(exporter)
+ .build();
+ global::set_text_map_propagator(TraceContextPropagator::new());
+ global::set_tracer_provider(provider.clone());
+ let _ = PROVIDER.set(provider);
+ eprintln!("assembler: tracing enabled");
+}
+
+/// Export what is buffered and stop. For every path that ends the process —
+/// `process::exit` runs no destructors.
+pub fn shutdown() {
+ if let Some(provider) = PROVIDER.get() {
+ let _ = provider.shutdown();
+ }
+}
+
+/// Sends export requests with the reqwest already in the binary. The batch
+/// processor calls this from its own thread, outside tokio, so the request is
+/// handed to the runtime and awaited from there.
+#[derive(Debug)]
+struct ExportClient {
+ client: reqwest::Client,
+ runtime: tokio::runtime::Handle,
+}
+
+impl ExportClient {
+ fn new() -> Self {
+ ExportClient {
+ client: reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(10))
+ .build()
+ .expect("reqwest client"),
+ runtime: tokio::runtime::Handle::current(),
+ }
+ }
+}
+
+#[async_trait::async_trait]
+impl HttpClient for ExportClient {
+ async fn send_bytes(
+ &self,
+ request: axum::http::Request<Bytes>,
+ ) -> Result<axum::http::Response<Bytes>, HttpError> {
+ let request = reqwest::Request::try_from(request)?;
+ let client = self.client.clone();
+ self.runtime
+ .spawn(async move {
+ let response = client.execute(request).await?;
+ let status = response.status();
+ let headers = response.headers().clone();
+ let mut out = axum::http::Response::new(response.bytes().await?);
+ *out.status_mut() = status;
+ *out.headers_mut() = headers;
+ Ok::<_, HttpError>(out)
+ })
+ .await?
+ }
+}
+
+/// A SERVER span per request, continuing the caller's trace. `/health` is the
+/// load balancer's probe and is left out.
+pub async fn http_span(request: Request, next: Next) -> Response {
+ let route = request
+ .extensions()
+ .get::<MatchedPath>()
+ .map(|path| path.as_str().to_owned());
+ if PROVIDER.get().is_none() || route.as_deref() == Some("/health") {
+ return next.run(request).await;
+ }
+ let parent = global::get_text_map_propagator(|propagator| {
+ propagator.extract(&HeaderExtractor(request.headers()))
+ });
+ let method = request.method().as_str().to_owned();
+ // The matched route, never the raw path: an unmatched request must not mint
+ // a span name per URL.
+ let name = match &route {
+ Some(route) => format!("{method} {route}"),
+ None => method.clone(),
+ };
+ let mut attributes = vec![
+ KeyValue::new("http.request.method", method),
+ KeyValue::new("url.path", request.uri().path().to_owned()),
+ ];
+ if let Some(route) = route {
+ attributes.push(KeyValue::new("http.route", route));
+ }
+ let tracer = tracer();
+ let span = tracer
+ .span_builder(name)
+ .with_kind(SpanKind::Server)
+ .with_attributes(attributes)
+ .start_with_context(&tracer, &parent);
+ let cx = parent.with_span(span);
+
+ let response = next.run(request).with_context(cx.clone()).await;
+
+ let span = cx.span();
+ let status = response.status();
+ span.set_attribute(KeyValue::new(
+ "http.response.status_code",
+ i64::from(status.as_u16()),
+ ));
+ if status.is_server_error() {
+ span.set_status(Status::error(""));
+ }
+ span.end();
+ // Lambda freezes the process once the response is sent; whatever is still
+ // in the batch would wait for the next invocation, or be lost.
+ if std::env::var_os("AWS_LAMBDA_FUNCTION_NAME").is_some() {
+ flush().await;
+ }
+ response
+}
+
+/// How long a Lambda response waits for its spans to be exported. A job poll
+/// can already hold for the long-poll cap (25 s), and API Gateway gives the
+/// whole request 30 s, so a slow collector must cost a trace, not the response.
+const LAMBDA_FLUSH_WAIT: std::time::Duration = std::time::Duration::from_secs(3);
+
+async fn flush() {
+ if let Some(provider) = PROVIDER.get() {
+ // force_flush blocks until the export thread answers.
+ let flushed = tokio::task::spawn_blocking(move || provider.force_flush());
+ let _ = tokio::time::timeout(LAMBDA_FLUSH_WAIT, flushed).await;
+ }
+}
+
+/// `tokio::spawn` for a job: the task gets a `job <action>` span under the
+/// current context (the request, or the context `attach` restored), and every
+/// span the job starts becomes its child.
+pub fn spawn_job<F>(job_id: &str, action: &str, job: F)
+where
+ F: Future<Output = ()> + Send + 'static,
+{
+ let tracer = tracer();
+ let span = tracer
+ .span_builder(format!("job {action}"))
+ .with_attributes([
+ KeyValue::new("carbon.job.id", job_id.to_owned()),
+ KeyValue::new("carbon.job.action", action.to_owned()),
+ ])
+ .start(&tracer);
+ let cx = Context::current_with_span(span);
+ tokio::spawn(
+ async move {
+ job.await;
+ Context::current().span().end();
+ }
+ .with_context(cx),
+ );
+}
+
+/// Mark the current span failed. Called where a job records its error, so the
+/// job span carries the same code and message the caller is given.
+pub fn record_error(code: &str, message: &str) {
+ let cx = Context::current();
+ let span = cx.span();
+ span.set_attribute(KeyValue::new("error.type", code.to_owned()));
+ span.set_status(Status::error(without_urls(message)));
+}
+
+/// Error text quotes the URL that failed, and these URLs are signed. Keep the
+/// scheme and host, drop the path and query that carry the signature.
+fn without_urls(message: &str) -> String {
+ let mut out = String::with_capacity(message.len());
+ let mut rest = message;
+ while let Some(start) = rest.find("http://").or_else(|| rest.find("https://")) {
+ let (before, url) = rest.split_at(start);
+ let end = url
+ .find(|c: char| c.is_whitespace() || matches!(c, ')' | '"' | '\'' | '>'))
+ .unwrap_or(url.len());
+ out.push_str(before);
+ match reqwest::Url::parse(&url[..end]) {
+ Ok(parsed) => out.push_str(&parsed.origin().ascii_serialization()),
+ Err(_) => out.push_str("<url>"),
+ }
+ rest = &url[end..];
+ }
+ out.push_str(rest);
+ out
+}
+
+/// Run `work` in a child span of the current one.
+pub async fn in_span<T>(name: &'static str, work: impl Future<Output = T>) -> T {
+ let tracer = tracer();
+ let cx = Context::current_with_span(tracer.start(name));
+ let out = work.with_context(cx.clone()).await;
+ cx.span().end();
+ out
+}
+
+/// An outbound request as a CLIENT span. Records the host only: these URLs are
+/// signed, and the signature is in the path and query.
+pub async fn outbound<T>(
+ name: &'static str,
+ url: &str,
+ request: impl Future<Output = Result<T, ApiError>>,
+) -> Result<T, ApiError> {
+ let tracer = tracer();
+ let mut builder = tracer.span_builder(name).with_kind(SpanKind::Client);
+ if let Some(host) = reqwest::Url::parse(url)
+ .ok()
+ .and_then(|url| url.host_str().map(str::to_owned))
+ {
+ builder = builder.with_attributes([KeyValue::new("server.address", host)]);
+ }
+ let cx = Context::current_with_span(builder.start(&tracer));
+ let out = request.with_context(cx.clone()).await;
+ let span = cx.span();
+ if let Err(e) = &out {
+ span.set_attribute(KeyValue::new("error.type", e.code.clone()));
+ span.set_status(Status::error(without_urls(&e.message)));
+ }
+ span.end();
+ out
+}
+
+/// Write the current context into a run-job spec, so the worker invocation
+/// that runs it continues this trace.
+pub fn inject(spec: &mut Value) {
+ let mut carrier = HashMap::new();
+ global::get_text_map_propagator(|propagator| {
+ propagator.inject_context(&Context::current(), &mut carrier)
+ });
+ if let Some(traceparent) = carrier.remove(SPEC_KEY) {
+ spec[SPEC_KEY] = traceparent.into();
+ }
+}
+
+/// Make the context a run-job spec carries current until the guard drops. The
+/// guard is not `Send`: hold it across the spawn only, never across an await.
+pub fn attach(spec: &Value) -> Option<ContextGuard> {
+ let traceparent = spec[SPEC_KEY].as_str()?;
+ let carrier = HashMap::from([(SPEC_KEY.to_owned(), traceparent.to_owned())]);
+ let cx = global::get_text_map_propagator(|propagator| propagator.extract(&carrier));
+ Some(cx.attach())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn error_text_keeps_the_host_and_drops_the_signed_part() {
+ assert_eq!(
+ without_urls(
+ "could not download source: error sending request for url \
+ (https://x.supabase.co/storage/v1/object/sign/private/a.step?token=SECRET)"
+ ),
+ "could not download source: error sending request for url (https://x.supabase.co)"
+ );
+ assert_eq!(
+ without_urls("PUT http://127.0.0.1:9000/b/k?sig=1 then https://s3.aws/x?y=2 failed"),
+ "PUT http://127.0.0.1:9000 then https://s3.aws failed"
+ );
+ assert_eq!(without_urls("tessellation failed"), "tessellation failed");
+ }
+ use opentelemetry::trace::{SpanContext, SpanId, TraceFlags, TraceId, TraceState};
+
+ const TRACEPARENT: &str = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
+
+ #[test]
+ fn a_spec_carries_the_trace_across_the_self_invoke() {
+ global::set_text_map_propagator(TraceContextPropagator::new());
+
+ // Nothing to carry: the spec is left alone.
+ let mut spec = serde_json::json!({ "action": "convert" });
+ inject(&mut spec);
+ assert!(spec.get(SPEC_KEY).is_none());
+ assert!(attach(&spec).is_none());
+
+ let parent = SpanContext::new(
+ TraceId::from_hex("4bf92f3577b34da6a3ce929d0e0e4736").unwrap(),
+ SpanId::from_hex("00f067aa0ba902b7").unwrap(),
+ TraceFlags::SAMPLED,
+ true,
+ TraceState::default(),
+ );
+ {
+ let _guard = Context::current().with_remote_span_context(parent).attach();
+ inject(&mut spec);
+ }
+ assert_eq!(spec[SPEC_KEY], TRACEPARENT);
+
+ // The worker side: the spec's context is current while the guard lives.
+ let guard = attach(&spec);
+ let cx = Context::current();
+ let restored = cx.span().span_context().clone();
+ assert_eq!(
+ restored.trace_id().to_string(),
+ "4bf92f3577b34da6a3ce929d0e0e4736"
+ );
+ assert_eq!(restored.span_id().to_string(), "00f067aa0ba902b7");
+ drop(guard);
+ assert!(!Context::current().span().span_context().is_valid());
+ }
+}
diff --git a/apps/assembler/sst.config.ts b/apps/assembler/sst.config.ts
index 6206230d7b..9bac7767c7 100644
--- a/apps/assembler/sst.config.ts
+++ b/apps/assembler/sst.config.ts
@@ -48,6 +48,18 @@ export default $config({
// Job/result store — REQUIRED; the assembler refuses to boot without it.
REDIS_URL: process.env.REDIS_URL,
TZ: "UTC",
+ // Tracing (optional): forwarded only when set at deploy time. Without an
+ // endpoint the service exports nothing.
+ ...Object.fromEntries(
+ [
+ "OTEL_EXPORTER_OTLP_ENDPOINT",
+ "OTEL_EXPORTER_OTLP_HEADERS",
+ "OTEL_RESOURCE_ATTRIBUTES",
+ "OTEL_SERVICE_NAME",
+ "OTEL_TRACES_SAMPLER",
+ "OTEL_TRACES_SAMPLER_ARG",
+ ].flatMap((name) => (process.env[name] ? [[name, process.env[name]]] : [])),
+ ),
// Optimize time budget + dispatch mode are AUTO-DETECTED in-service from
// AWS_LAMBDA_FUNCTION_NAME (720s ladder budget on Lambda; self-invoke
// dispatch) — no env needed here.
diff --git a/apps/erp/app/components/CadModel.tsx b/apps/erp/app/components/CadModel.tsx
index c838f503c8..8993b7d3fa 100644
--- a/apps/erp/app/components/CadModel.tsx
+++ b/apps/erp/app/components/CadModel.tsx
@@ -35,6 +35,8 @@ import { LuCloudUpload, LuRefreshCw, LuZap } from "react-icons/lu";
import { useFetcher, useRevalidator } from "react-router";
import { useModelUpload, useUser } from "~/hooks";
import type { ModelUpload } from "~/types";
+import type { ViewDirection } from "~/utils/model-thumbnail";
+import { regenerateModelThumbnail } from "~/utils/model-thumbnail";
import { getPrivateUrl, getRawModelUrl, path } from "~/utils/path";
import { UploadProgress } from "./UploadProgress";
@@ -105,6 +107,35 @@ const CadModel = ({
// Never on top of the upload progress overlay.
const showOptimizeProgress = optimizeProgressActive && upload === null;
+ // The thumbnail is drawn from where the viewer's camera stands. The item
+ // panel reads the model's thumbnail from the loader, so revalidate once the
+ // new one lands.
+ // One at a time: two in flight both wait for "a new path", so the first to
+ // land would be reported as the second's view.
+ const [isCapturing, setIsCapturing] = useState(false);
+ const onCaptureThumbnail = async (direction: ViewDirection) => {
+ if (!modelUploadId || !carbon || isCapturing) return;
+ setIsCapturing(true);
+ toast.info(t`Regenerating thumbnail…`);
+ try {
+ const thumbnailPath = await regenerateModelThumbnail({
+ carbon,
+ modelId: modelUploadId,
+ direction
+ });
+ if (thumbnailPath) {
+ revalidator.revalidate();
+ toast.success(t`Thumbnail updated`);
+ } else {
+ toast.info(t`Thumbnail is still generating`);
+ }
+ } catch {
+ toast.error(t`Failed to regenerate thumbnail`);
+ } finally {
+ setIsCapturing(false);
+ }
+ };
+
const onDelete = async () => {
if (!carbon) {
toast.error("Failed to initialize carbon client");
@@ -278,6 +309,10 @@ const CadModel = ({
onRetry={modelPath && canRetry ? onRetry : undefined}
retryLabel={retryLabel}
onCancelWait={modelPath ? onCancelWait : undefined}
+ onCaptureThumbnail={
+ !isReadOnly && modelUploadId ? onCaptureThumbnail : undefined
+ }
+ isCapturingThumbnail={isCapturing}
onDelete={canDelete ? deleteModal.onOpen : undefined}
/>
{upload !== null && (
diff --git a/apps/erp/app/components/ItemThumnailUpload.tsx b/apps/erp/app/components/ItemThumnailUpload.tsx
index 3ff4e2bf86..0806ed0d19 100644
--- a/apps/erp/app/components/ItemThumnailUpload.tsx
+++ b/apps/erp/app/components/ItemThumnailUpload.tsx
@@ -22,6 +22,7 @@ import type { ChangeEvent } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { LuRefreshCw } from "react-icons/lu";
import { useUser } from "~/hooks";
+import { regenerateModelThumbnail } from "~/utils/model-thumbnail";
import { getPrivateUrl } from "~/utils/path";
const logger = getLogger("erp", "itemthumnailupload");
@@ -100,44 +101,20 @@ export function ItemThumbnailUpload({
const onRegenerate = useCallback(async () => {
if (!modelId || !carbon) return;
setIsRegenerating(true);
+ toast.info(t`Regenerating thumbnail…`);
try {
- // Snapshot the current model thumbnail so we can detect the new one.
- const before = await carbon
- .from("modelUpload")
- .select("thumbnailPath")
- .eq("id", modelId)
- .maybeSingle();
- const beforePath = before.data?.thumbnailPath ?? null;
-
- const body = new FormData();
- body.append("modelUploadId", modelId);
- const res = await fetch("/api/model/thumbnail", {
- method: "POST",
- body
+ const path = await regenerateModelThumbnail({
+ carbon,
+ modelId,
+ isActive: () => mountedRef.current
});
- if (!res.ok) throw new Error(`thumbnail ${res.status}`);
- toast.info(t`Regenerating thumbnail…`);
-
- // The render runs async in the background. Poll for the fresh path (unique
- // per generation) and swap the image in when it lands; bounded so it never
- // spins forever.
- const deadline = Date.now() + 90_000;
- while (mountedRef.current && Date.now() < deadline) {
- await new Promise((r) => setTimeout(r, 3000));
- if (!mountedRef.current) return;
- const cur = await carbon
- .from("modelUpload")
- .select("thumbnailPath")
- .eq("id", modelId)
- .maybeSingle();
- const curPath = cur.data?.thumbnailPath ?? null;
- if (curPath && curPath !== beforePath) {
- setThumbnailPath(getPrivateUrl(curPath));
- toast.success(t`Thumbnail updated`);
- return;
- }
+ if (!mountedRef.current) return;
+ if (path) {
+ setThumbnailPath(getPrivateUrl(path));
+ toast.success(t`Thumbnail updated`);
+ } else {
+ toast.info(t`Thumbnail is still generating`);
}
- if (mountedRef.current) toast.info(t`Thumbnail is still generating`);
} catch {
if (mountedRef.current) toast.error(t`Failed to regenerate thumbnail`);
} finally {
diff --git a/apps/erp/app/routes/api+/model.thumbnail.ts b/apps/erp/app/routes/api+/model.thumbnail.ts
index 972d104c9c..3bef25286f 100644
--- a/apps/erp/app/routes/api+/model.thumbnail.ts
+++ b/apps/erp/app/routes/api+/model.thumbnail.ts
@@ -19,6 +19,11 @@ export async function action({ request }: ActionFunctionArgs) {
if (!modelUploadId) {
return data({ success: false }, { status: 400 });
}
+ // The viewer's current camera, when the thumbnail is captured from it.
+ const direction = parseDirection(formData.get("direction"));
+ if (direction === null) {
+ return data({ success: false }, { status: 400 });
+ }
// Confirm the model belongs to this tenant before firing.
const model = await client
@@ -43,6 +48,33 @@ export async function action({ request }: ActionFunctionArgs) {
.eq("modelUploadId", modelUploadId)
.eq("companyId", companyId);
- await trigger("model-thumbnail", { modelId: modelUploadId, companyId });
+ await trigger("model-thumbnail", {
+ modelId: modelUploadId,
+ companyId,
+ ...(direction && { direction })
+ });
return { success: true };
}
+
+/** `undefined` when absent, `null` when present but not three finite numbers. */
+function parseDirection(
+ value: FormDataEntryValue | null
+): [number, number, number] | undefined | null {
+ if (value === null) return undefined;
+ if (typeof value !== "string") return null;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(value);
+ } catch {
+ return null;
+ }
+ if (
+ !Array.isArray(parsed) ||
+ parsed.length !== 3 ||
+ !parsed.every((n) => typeof n === "number" && Number.isFinite(n)) ||
+ parsed.every((n) => n === 0)
+ ) {
+ return null;
+ }
+ return [parsed[0], parsed[1], parsed[2]];
+}
diff --git a/apps/erp/app/utils/model-thumbnail.ts b/apps/erp/app/utils/model-thumbnail.ts
new file mode 100644
index 0000000000..fba03b3c02
--- /dev/null
+++ b/apps/erp/app/utils/model-thumbnail.ts
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+
+/** Model towards camera, in the model's own axes (Z up). */
+export type ViewDirection = [number, number, number];
+
+/**
+ * Ask for a model's thumbnail to be drawn again and wait for it. The render
+ * runs in the background, and each one is written to a new path, so the new
+ * path appearing on the model is the signal that it landed.
+ *
+ * Resolves to the new path, or `null` when it has not landed within the wait
+ * (it may still arrive). Throws when the request is refused or the model
+ * cannot be read. `isActive`
+ * lets a caller that has unmounted stop the wait.
+ */
+export async function regenerateModelThumbnail({
+ carbon,
+ modelId,
+ direction,
+ isActive = () => true
+}: {
+ carbon: SupabaseClient<Database>;
+ modelId: string;
+ /** Omit for the viewer's home view. */
+ direction?: ViewDirection;
+ isActive?: () => boolean;
+}): Promise<string | null> {
+ const currentPath = async () => {
+ const { data, error } = await carbon
+ .from("modelUpload")
+ .select("thumbnailPath")
+ .eq("id", modelId)
+ .maybeSingle();
+ // A failed read is not "no thumbnail": treated as one, the old path would
+ // later look like a new one.
+ if (error) throw error;
+ return data?.thumbnailPath ?? null;
+ };
+ const before = await currentPath();
+
+ const body = new FormData();
+ body.append("modelUploadId", modelId);
+ if (direction) body.append("direction", JSON.stringify(direction));
+ const response = await fetch("/api/model/thumbnail", {
+ method: "POST",
+ body
+ });
+ if (!response.ok) throw new Error(`thumbnail ${response.status}`);
+
+ const deadline = Date.now() + 90_000;
+ while (isActive() && Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, 3000));
+ if (!isActive()) return null;
+ const path = await currentPath();
+ if (path && path !== before) return path;
+ }
+ return null;
+}
diff --git a/crates/thumbnail/examples/render.rs b/crates/thumbnail/examples/render.rs
index 5023065daf..792c500fe7 100644
--- a/crates/thumbnail/examples/render.rs
+++ b/crates/thumbnail/examples/render.rs
@@ -16,7 +16,7 @@ fn main() {
.unwrap_or(thumbnail::DEFAULT_SIZE);
let glb = std::fs::read(input).expect("read GLB");
let started = std::time::Instant::now();
- let png = thumbnail::render_png(&glb, size).expect("render");
+ let png = thumbnail::render_png(&glb, size, thumbnail::DEFAULT_DIRECTION).expect("render");
eprintln!("{} bytes in {:?}", png.len(), started.elapsed());
std::fs::write(output, png).expect("write PNG");
}
diff --git a/crates/thumbnail/src/lib.rs b/crates/thumbnail/src/lib.rs
index 0ed5dc56a6..d354dccd91 100644
--- a/crates/thumbnail/src/lib.rs
+++ b/crates/thumbnail/src/lib.rs
@@ -6,8 +6,9 @@
//!
//! Reads the GLBs this service produces — plain buffers (`convert`) and
//! `EXT_meshopt_compression` (`optimize`) — walks the scene, and rasterises every
-//! triangle into a z-buffer from the viewer's default direction (front-top-right
-//! isometric, Z up). The background is transparent; the model is lit by two
+//! triangle into a z-buffer through the viewer's camera: a 45° perspective
+//! from its default direction (front-top-right, Z up) unless the caller names
+//! another. The background is transparent; the model is lit by two
//! fixed lights and coloured by each material's `baseColorFactor`.
//!
//! Textures, vertex colours and Draco-compressed primitives are not read: the
@@ -29,8 +30,14 @@ const SUPERSAMPLE: usize = 3;
const MARGIN: f32 = 0.06;
/// Colour of a primitive with no material — the converter's default part grey.
const DEFAULT_COLOR: [f32; 3] = [0.65, 0.65, 0.65];
-/// Towards the camera. The viewer frames a model from here (`ModelCanvas`).
-const VIEW_DIRECTION: [f32; 3] = [1.0, -1.0, 1.0];
+/// From the model towards the camera. The viewer's home view (`AssemblyViewer`'s
+/// camera at `[100, -100, 100]`).
+pub const DEFAULT_DIRECTION: [f32; 3] = [1.0, -1.0, 1.0];
+/// The viewer's vertical field of view, and how far back it stands to fit the
+/// model's bounding sphere (`frameBox` in `ModelCanvas`). Kept the same here so
+/// a thumbnail has the perspective the viewer shows.
+const FOV_DEGREES: f32 = 45.0;
+const FIT_MARGIN: f32 = 1.1;
/// A malformed scene whose nodes form a cycle would otherwise never finish.
const MAX_NODE_VISITS: usize = 1_000_000;
/// Ceilings on what one render holds in memory. The counts in a GLB are the
@@ -57,15 +64,17 @@ fn err<T>(message: impl Into<String>) -> Result<T, ThumbnailError> {
Err(ThumbnailError(message.into()))
}
-/// Render `glb` to a `size`×`size` RGBA PNG.
-pub fn render_png(glb: &[u8], size: u32) -> Result<Vec<u8>, ThumbnailError> {
+/// Render `glb` to a `size`×`size` RGBA PNG, seen from `direction` (model
+/// towards camera, Z up). A direction that is not a usable vector falls back to
+/// [`DEFAULT_DIRECTION`].
+pub fn render_png(glb: &[u8], size: u32, direction: [f32; 3]) -> Result<Vec<u8>, ThumbnailError> {
let size = size.clamp(MIN_SIZE, MAX_SIZE) as usize;
let doc = Doc::parse(glb)?;
let triangles = doc.triangles()?;
if triangles.indices.is_empty() {
return err("GLB has no triangles to render");
}
- let rgba = rasterize(&triangles, size)?;
+ let rgba = rasterize(&triangles, size, direction)?;
Ok(encode_png(&rgba, size))
}
@@ -554,10 +563,26 @@ fn normalize(v: [f32; 3]) -> [f32; 3] {
// ---- Rasteriser ---------------------------------------------------------------
-/// Orthographic z-buffer render to straight-alpha RGBA, `size`×`size`.
-fn rasterize(triangles: &Triangles, size: usize) -> Result<Vec<u8>, ThumbnailError> {
- let toward = normalize(VIEW_DIRECTION);
- let right = normalize(cross([0.0, 0.0, 1.0], toward));
+/// Perspective z-buffer render to straight-alpha RGBA, `size`×`size`.
+fn rasterize(
+ triangles: &Triangles,
+ size: usize,
+ direction: [f32; 3],
+) -> Result<Vec<u8>, ThumbnailError> {
+ // Scaled by its largest component first: squaring a large but finite
+ // direction overflows, and its length would come out infinite.
+ let largest = direction.iter().fold(0.0f32, |m, c| m.max(c.abs()));
+ let usable = direction.iter().all(|c| c.is_finite()) && largest > 0.0;
+ let toward = normalize(if usable {
+ direction.map(|c| c / largest)
+ } else {
+ DEFAULT_DIRECTION
+ });
+ // Straight down (or up) the Z axis there is no "right" to derive from Z.
+ let right = match cross([0.0, 0.0, 1.0], toward) {
+ r if dot(r, r) > 1e-12 => normalize(r),
+ _ => [1.0, 0.0, 0.0],
+ };
let up = cross(toward, right);
// Key light over the viewer's left shoulder, a weaker fill from the right.
let key = normalize([
@@ -571,11 +596,45 @@ fn rasterize(triangles: &Triangles, size: usize) -> Result<Vec<u8>, ThumbnailErr
toward[2] + 0.9 * right[2] - 0.2 * up[2],
]);
- // Screen x / y and depth (larger is nearer) for every vertex.
+ // The camera stands where the viewer's does: looking at the centre of the
+ // bounding box, far enough back that the bounding sphere fits the view.
+ let mut lo = [f32::INFINITY; 3];
+ let mut hi = [f32::NEG_INFINITY; 3];
+ for p in triangles
+ .positions
+ .iter()
+ .filter(|p| p.iter().all(|c| c.is_finite()))
+ {
+ for axis in 0..3 {
+ lo[axis] = lo[axis].min(p[axis]);
+ hi[axis] = hi[axis].max(p[axis]);
+ }
+ }
+ if !(lo[0] <= hi[0]) {
+ return err("GLB has no finite geometry to render");
+ }
+ let centre = [
+ (lo[0] + hi[0]) / 2.0,
+ (lo[1] + hi[1]) / 2.0,
+ (lo[2] + hi[2]) / 2.0,
+ ];
+ let diagonal = sub(hi, lo);
+ let radius = (dot(diagonal, diagonal).sqrt() / 2.0).max(f32::MIN_POSITIVE);
+ // In units of the radius, so a model renders the same at any scale.
+ let distance = (FIT_MARGIN / (FOV_DEGREES.to_radians() / 2.0).tan()).max(1.5);
+
+ // Screen x / y and depth (larger is nearer) for every vertex. The depth is
+ // 1/distance-along-the-view, which is what stays linear across a triangle
+ // on screen under perspective.
let projected: Vec<[f32; 3]> = triangles
.positions
.iter()
- .map(|p| [dot(*p, right), dot(*p, up), dot(*p, toward)])
+ .map(|p| {
+ let local = sub(*p, centre).map(|c| c / radius);
+ // Every vertex is inside the unit sphere and the camera outside it.
+ let along = distance - dot(local, toward);
+ [dot(local, right) / along, dot(local, up) / along, 1.0 / along]
+ })
.collect();
let mut min = [f32::INFINITY; 2];
let mut max = [f32::NEG_INFINITY; 2];
@@ -808,7 +867,12 @@ mod tests {
}
fn render(glb: &[u8], size: usize) -> Vec<u8> {
- rasterize(&Doc::parse(glb).unwrap().triangles().unwrap(), size).unwrap()
+ rasterize(
+ &Doc::parse(glb).unwrap().triangles().unwrap(),
+ size,
+ DEFAULT_DIRECTION,
+ )
+ .unwrap()
}
#[test]
@@ -834,6 +898,81 @@ mod tests {
assert_ne!(left, right);
}
+ #[test]
+ fn the_camera_direction_decides_what_is_drawn() {
+ let glb = optimize::stl_to_glb(&cube_stl(10.0)).unwrap();
+ let triangles = Doc::parse(&glb).unwrap().triangles().unwrap();
+ let from = |direction| rasterize(&triangles, 64, direction).unwrap();
+
+ let home = from(DEFAULT_DIRECTION);
+ // Any length names the same direction.
+ assert!(from([40.0, -40.0, 40.0]) == home);
+ assert!(from([1e30, -1e30, 1e30]) == home);
+ assert!(from([1e-30, -1e-30, 1e-30]) == home);
+ // A lower camera sees less of the top face. (A cube looks the same from
+ // each of its corners, so the test cannot just mirror the direction.)
+ assert!(from([1.0, -1.0, 0.2]) != home);
+ // Straight down has no "right" to derive from Z; it still renders.
+ let top = from([0.0, 0.0, 1.0]);
+ assert_eq!(alpha(&top, 64, 32, 32), 255);
+ // Not a direction at all: the home view.
+ assert!(from([0.0, 0.0, 0.0]) == home);
+ assert!(from([f32::NAN, 1.0, 1.0]) == home);
+ }
+
+ #[test]
+ fn nearer_edges_are_drawn_larger() {
+ // Seen from straight above, a tall box's top face is nearer than its
+ // base. Orthographic, both would cover the same pixels; in perspective
+ // the base is hidden inside the top's outline and the walls never show.
+ // Seen from the side the same box shows its near end wider than its far.
+ let mut stl = vec![0u8; 80];
+ let (w, h) = (1.0f32, 8.0f32);
+ let corners = |z: f32| [[-w, -w, z], [w, -w, z], [w, w, z], [-w, w, z]];
+ let (low, high) = (corners(0.0), corners(h));
+ let mut faces: Vec<[[f32; 3]; 3]> = vec![
+ [low[0], low[2], low[1]],
+ [low[0], low[3], low[2]],
+ [high[0], high[1], high[2]],
+ [high[0], high[2], high[3]],
+ ];
+ for i in 0..4 {
+ let j = (i + 1) % 4;
+ faces.push([low[i], low[j], high[j]]);
+ faces.push([low[i], high[j], high[i]]);
+ }
+ stl.extend_from_slice(&(faces.len() as u32).to_le_bytes());
+ for face in &faces {
+ stl.extend_from_slice(&[0u8; 12]);
+ for vertex in face {
+ for c in vertex {
+ stl.extend_from_slice(&c.to_le_bytes());
+ }
+ }
+ stl.extend_from_slice(&[0, 0]);
+ }
+ let glb = optimize::stl_to_glb(&stl).unwrap();
+ let size = 128;
+ // Looking along +X with the long axis (Z) up: measure the width of the
+ // silhouette on a row near the top and one near the bottom after
+ // tilting the view so the top end is nearer.
+ let rgba = rasterize(
+ &Doc::parse(&glb).unwrap().triangles().unwrap(),
+ size,
+ [1.0, 0.0, 2.0],
+ )
+ .unwrap();
+ let width = |y: usize| (0..size).filter(|&x| alpha(&rgba, size, x, y) > 0).count();
+ let rows: Vec<usize> = (0..size).filter(|&y| width(y) > 0).collect();
+ let (first, last) = (rows[0], rows[rows.len() - 1]);
+ let near_top = width(first + (last - first) / 4);
+ let near_bottom = width(first + (last - first) * 3 / 4);
+ assert!(
+ near_top > near_bottom,
+ "top (nearer) {near_top}px should be wider than bottom {near_bottom}px"
+ );
+ }
+
#[test]
fn the_model_is_framed_whatever_its_size_or_position() {
let small = render(&optimize::stl_to_glb(&cube_stl(0.001)).unwrap(), 64);
@@ -863,7 +1002,7 @@ mod tests {
#[test]
fn the_png_is_a_valid_rgba_image_of_the_requested_size() {
let glb = optimize::stl_to_glb(&cube_stl(10.0)).unwrap();
- let png = render_png(&glb, 64).unwrap();
+ let png = render_png(&glb, 64, DEFAULT_DIRECTION).unwrap();
assert_eq!(&png[..8], &[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]);
assert_eq!(&png[12..16], b"IHDR");
@@ -920,12 +1059,12 @@ mod tests {
}
fn message(glb: &[u8]) -> String {
- render_png(glb, 64).unwrap_err().0
+ render_png(glb, 64, DEFAULT_DIRECTION).unwrap_err().0
}
#[test]
fn counts_the_file_cannot_back_are_errors_not_allocations() {
- assert!(render_png(&triangle_glb(3, |_| {}), 64).is_ok());
+ assert!(render_png(&triangle_glb(3, |_| {}), 64, DEFAULT_DIRECTION).is_ok());
// An accessor claiming more elements than its view holds.
let glb = triangle_glb(3, |root| root["accessors"][0]["count"] = 1_000.into());
@@ -965,9 +1104,9 @@ mod tests {
#[test]
fn input_that_cannot_be_rendered_is_an_error() {
- assert!(render_png(b"not a glb", 64).is_err());
+ assert!(render_png(b"not a glb", 64, DEFAULT_DIRECTION).is_err());
let mut truncated = optimize::stl_to_glb(&cube_stl(10.0)).unwrap();
truncated.truncate(truncated.len() - 16);
- assert!(render_png(&truncated, 64).is_err());
+ assert!(render_png(&truncated, 64, DEFAULT_DIRECTION).is_err());
}
}
diff --git a/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts b/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
index 6a99132b11..6e4d7fcffd 100644
--- a/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
+++ b/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
@@ -35,7 +35,7 @@ export const modelThumbnailFunction = inngest.createFunction(
},
{ event: "carbon/model-thumbnail" },
async ({ event, step, logger }) => {
- const { modelId, companyId } = event.data;
+ const { modelId, companyId, direction } = event.data;
if (!assemblerEnabled()) {
logger.info("model thumbnail skipped — assembler not configured", {
@@ -99,7 +99,7 @@ export const modelThumbnailFunction = inngest.createFunction(
}
return {
source: { url: internalizeStorageUrl(signed.data.signedUrl) },
- output: { path: thumbnailPath }
+ output: { path: thumbnailPath, ...(direction && { direction }) }
};
},
mintUploadUrls: async () => {
diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.ts
index dd9807c1fd..1794c627cc 100644
--- a/packages/lib/src/events.ts
+++ b/packages/lib/src/events.ts
@@ -122,6 +122,8 @@ export type Events = {
data: {
modelId: string;
companyId: string;
+ /** Model towards camera (Z up). Absent = the viewer's home view. */
+ direction?: [number, number, number];
};
};
diff --git a/packages/viewer/src/ModelCanvas.tsx b/packages/viewer/src/ModelCanvas.tsx
index 8e42de48ab..142ee42929 100644
--- a/packages/viewer/src/ModelCanvas.tsx
+++ b/packages/viewer/src/ModelCanvas.tsx
@@ -3,6 +3,7 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { useThree } from "@react-three/fiber";
+import type { MutableRefObject } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { LuRotateCw } from "react-icons/lu";
import {
@@ -17,6 +18,9 @@ import { AssemblyViewer } from "./AssemblyViewer";
import { useAssembly } from "./useAssembly";
import { cn } from "./utils";
+/** From the model towards the camera, in the model's axes (Z up). */
+export type ViewDirection = [number, number, number];
+
/** Model measurements in model-space units (CAD tessellations are mm). */
export type ModelMetrics = {
dimensions: { x: number; y: number; z: number };
@@ -43,6 +47,9 @@ export type ModelCanvasProps = {
interactive?: boolean;
/** Bump this to re-frame the camera (the "reset view" action). */
resetSignal?: number;
+ /** Filled with a function that reads where the camera stands right now, as a
+ * direction from the model towards it. `null` until a model is on screen. */
+ viewDirectionRef?: MutableRefObject<(() => ViewDirection) | null>;
/** Fired once the GLB has loaded and framed — the cross-fade trigger. */
onLoaded?: () => void;
/** Fired once with the loaded model's measurements (bbox always; area/volume
@@ -72,6 +79,7 @@ export function ModelCanvas({
autoFrame = true,
interactive = true,
resetSignal = 0,
+ viewDirectionRef,
onLoaded,
onMetrics,
className
@@ -105,6 +113,7 @@ export function ModelCanvas({
scene={scene}
autoFrame={autoFrame}
resetSignal={resetSignal}
+ viewDirectionRef={viewDirectionRef}
/>
)}
</AssemblyViewer>
@@ -196,11 +205,13 @@ function useLoadedObject(
function ModelScene({
scene,
autoFrame,
- resetSignal
+ resetSignal,
+ viewDirectionRef
}: {
scene: Object3D;
autoFrame: boolean;
resetSignal: number;
+ viewDirectionRef?: MutableRefObject<(() => ViewDirection) | null>;
}) {
const camera = useThree((state) => state.camera);
const controls = useThree(
@@ -268,6 +279,20 @@ function ModelScene({
frameBox(new Box3().setFromObject(scene));
}, [resetSignal, scene, frameBox]);
+ useEffect(() => {
+ if (!viewDirectionRef || !controls) return;
+ viewDirectionRef.current = () => {
+ const direction = camera.position
+ .clone()
+ .sub(controls.target)
+ .normalize();
+ return [direction.x, direction.y, direction.z];
+ };
+ return () => {
+ viewDirectionRef.current = null;
+ };
+ }, [viewDirectionRef, camera, controls]);
+
return <primitive object={scene} />;
}
diff --git a/packages/viewer/src/ModelPreview.tsx b/packages/viewer/src/ModelPreview.tsx
index c6c4e75cbf..c86565b976 100644
--- a/packages/viewer/src/ModelPreview.tsx
+++ b/packages/viewer/src/ModelPreview.tsx
@@ -6,6 +6,7 @@ import { Button, cn, IconButton } from "@carbon/react";
import { lazy, Suspense, useEffect, useMemo, useRef, useState } from "react";
import {
LuBox,
+ LuCamera,
LuChevronDown,
LuDownload,
LuMaximize,
@@ -14,7 +15,7 @@ import {
LuTriangleAlert,
LuX
} from "react-icons/lu";
-import type { ModelMetrics } from "./ModelCanvas";
+import type { ModelMetrics, ViewDirection } from "./ModelCanvas";
import { isRawRenderable } from "./raw/formats";
// The three.js renderer is code-split: a page with a model ships only this tier
@@ -76,6 +77,11 @@ export type ModelPreviewProps = {
* the in-flight optimise (job + run) so the row doesn't stay stuck. */
onCancelWait?: () => void;
mode?: "dark" | "light";
+ /** Shows a camera button that hands over where the viewer's camera stands
+ * right now, for the host to redraw the model's thumbnail from there. */
+ onCaptureThumbnail?: (direction: ViewDirection) => void;
+ /** A capture is in flight: the camera button is disabled until it lands. */
+ isCapturingThumbnail?: boolean;
onDelete?: () => void;
className?: string;
};
@@ -105,10 +111,13 @@ export function ModelPreview({
retryLabel = "Retry",
onCancelWait,
mode = "dark",
+ onCaptureThumbnail,
+ isCapturingThumbnail = false,
onDelete,
className
}: ModelPreviewProps) {
const containerRef = useRef<HTMLDivElement>(null);
+ const viewDirectionRef = useRef<(() => ViewDirection) | null>(null);
const inView = useInView(containerRef);
const [fullLoaded, setFullLoaded] = useState(false);
const [metrics, setMetrics] = useState<ModelMetrics | null>(null);
@@ -197,6 +206,7 @@ export function ModelPreview({
mode={mode}
interactive={interactive}
resetSignal={resetSignal}
+ viewDirectionRef={viewDirectionRef}
onLoaded={() => setFullLoaded(true)}
onMetrics={setMetrics}
/>
@@ -282,7 +292,7 @@ export function ModelPreview({
</button>
)}
- {/* Toolbar: download + reset view + delete. */}
+ {/* Toolbar: download + reset view + thumbnail + delete. */}
<div className="absolute bottom-2 right-2 z-20 flex items-center gap-1">
{mainUrl && (
<IconButton
@@ -302,6 +312,21 @@ export function ModelPreview({
onClick={() => setResetSignal((n) => n + 1)}
/>
)}
+ {/* Only over a server GLB: that is what the thumbnail is drawn from. */}
+ {fullLoaded && hasServerModel && onCaptureThumbnail && (
+ <IconButton
+ aria-label="Use this view as the thumbnail"
+ title="Use this view as the thumbnail"
+ className="text-muted-foreground"
+ icon={<LuCamera />}
+ variant="ghost"
+ isDisabled={isCapturingThumbnail}
+ onClick={() => {
+ const direction = viewDirectionRef.current?.();
+ if (direction) onCaptureThumbnail(direction);
+ }}
+ />
+ )}
{onDelete && (
<IconButton
aria-label="Delete model"