Skip to main content

euv_cli/blender/
fn.rs

1use super::*;
2
3/// Validates that a Live-Link asset identifier contains only safe ASCII filename characters with zero path traversal.
4///
5/// # Arguments
6///
7/// - `&str` - Candidate asset identifier (`{id}`).
8///
9/// # Returns
10///
11/// - `io::Result<()>` - `Ok(())` when safe, or `ErrorKind::InvalidInput`.
12pub fn validate_blender_asset_id(asset_id: &str) -> io::Result<()> {
13    let all_allowed: bool = asset_id.bytes().all(|byte: u8| {
14        byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_' || byte == b'.'
15    });
16    if asset_id.is_empty()
17        || asset_id == "."
18        || asset_id == ".."
19        || asset_id.contains("..")
20        || asset_id.contains('/')
21        || asset_id.contains('\\')
22        || !all_allowed
23    {
24        return Err(Error::new(
25            ErrorKind::InvalidInput,
26            format!("{ERR_BLENDER_INVALID_ASSET_ID}: `{asset_id}`"),
27        ));
28    }
29    Ok(())
30}
31
32/// Detects the 3D asset container format from leading magic bytes first, falling back to file extension.
33///
34/// # Arguments
35///
36/// - `&Path` - Source file path (for extension fallback).
37/// - `&[u8]` - Raw file bytes (may be empty during `--plan` checks).
38///
39/// # Returns
40///
41/// - `io::Result<BlenderAssetFormat>` - Recognized asset format or `InvalidInput`.
42pub fn detect_blender_asset_format(path: &Path, bytes: &[u8]) -> io::Result<BlenderAssetFormat> {
43    if bytes.len() >= 8 && bytes[0..8] == EUV3D_MAGIC {
44        return Ok(BlenderAssetFormat::Euv3d);
45    }
46    if bytes.len() >= 4 && bytes[0..4] == BLENDER_GLB_MAGIC {
47        return Ok(BlenderAssetFormat::Glb);
48    }
49    if bytes.len() >= 7 && &bytes[0..7] == BLEND_MAGIC {
50        return Ok(BlenderAssetFormat::Blend);
51    }
52    if bytes.len() >= 2 && bytes[0..2] == BLENDER_GZIP_MAGIC {
53        let is_blend_ext: bool = path
54            .extension()
55            .and_then(OsStr::to_str)
56            .map(|ext: &str| ext.eq_ignore_ascii_case(BLENDER_EXT_BLEND))
57            .unwrap_or(false);
58        if is_blend_ext {
59            return Ok(BlenderAssetFormat::Blend);
60        }
61    }
62    if bytes.len() >= 4 && bytes[0..4] == BLENDER_ZSTD_MAGIC {
63        return Ok(BlenderAssetFormat::Blend);
64    }
65    let ext_lower: String = path
66        .extension()
67        .and_then(OsStr::to_str)
68        .map(str::to_ascii_lowercase)
69        .unwrap_or_default();
70    match ext_lower.as_str() {
71        BLENDER_EXT_BLEND => Ok(BlenderAssetFormat::Blend),
72        BLENDER_EXT_GLB => Ok(BlenderAssetFormat::Glb),
73        BLENDER_EXT_GLTF => Ok(BlenderAssetFormat::Gltf),
74        BLENDER_EXT_EUV3D => Ok(BlenderAssetFormat::Euv3d),
75        BLENDER_EXT_OBJ => Ok(BlenderAssetFormat::Obj),
76        _ => Err(Error::new(
77            ErrorKind::InvalidInput,
78            format!("{ERR_BLENDER_UNSUPPORTED_FORMAT}: {}", path.display()),
79        )),
80    }
81}
82
83/// Parses a `blender --version` output line (e.g., `"Blender 5.1.0"`) into `(major, minor, patch)`.
84///
85/// # Arguments
86///
87/// - `&str` - Raw stdout text emitted by `blender --version`.
88///
89/// # Returns
90///
91/// - `Option<(u16, u16, u16)>` - Parsed semantic version triplet if present.
92#[must_use]
93pub fn parse_blender_version_line(stdout: &str) -> Option<(u16, u16, u16)> {
94    for line in stdout.lines() {
95        let trimmed: &str = line.trim();
96        let Some(rest) = trimmed.strip_prefix(BLENDER_VERSION_PREFIX) else {
97            continue;
98        };
99        let token: &str = rest.split_whitespace().next()?;
100        let mut parts: Vec<u16> = Vec::with_capacity(3);
101        for piece in token.split('.') {
102            let digits: String = piece
103                .chars()
104                .take_while(|ch: &char| ch.is_ascii_digit())
105                .collect();
106            if digits.is_empty() {
107                break;
108            }
109            if let Ok(parsed) = digits.parse::<u16>() {
110                parts.push(parsed);
111            }
112        }
113        if parts.len() >= 2 {
114            let major: u16 = parts[0];
115            let minor: u16 = parts[1];
116            let patch: u16 = parts.get(2).copied().unwrap_or(0);
117            return Some((major, minor, patch));
118        }
119    }
120    None
121}
122
123/// Resolves the local Blender executable checking `--blender-bin`, `EUV_BLENDER_BIN`, `PATH`, and OS install paths.
124///
125/// # Arguments
126///
127/// - `Option<&Path>` - Optional explicit `--blender-bin` override path.
128///
129/// # Returns
130///
131/// - `(Option<PathBuf>, BlenderBinarySource)` - Resolved binary path and discovery origin.
132#[must_use]
133pub fn resolve_blender_binary(explicit: Option<&Path>) -> (Option<PathBuf>, BlenderBinarySource) {
134    if let Some(path) = explicit {
135        if path.is_file() {
136            return (Some(path.to_path_buf()), BlenderBinarySource::CliFlag);
137        }
138        return (None, BlenderBinarySource::NotFound);
139    }
140    if let Ok(env_val) = env::var(ENV_EUV_BLENDER_BIN) {
141        let trimmed: &str = env_val.trim();
142        if !trimmed.is_empty() {
143            let candidate: PathBuf = PathBuf::from(trimmed);
144            if candidate.is_file() {
145                return (Some(candidate), BlenderBinarySource::EnvVar);
146            }
147        }
148    }
149    if let Some(in_path) = find_blender_in_path() {
150        return (Some(in_path), BlenderBinarySource::Path);
151    }
152    if let Some(os_bin) = find_blender_in_os_locations() {
153        return (Some(os_bin), BlenderBinarySource::OsInstall);
154    }
155    (None, BlenderBinarySource::NotFound)
156}
157
158/// Searches `PATH` entries for a `blender` (or `blender.exe`) executable.
159///
160/// # Returns
161///
162/// - `Option<PathBuf>` - First matching Blender executable on `PATH`.
163#[must_use]
164fn find_blender_in_path() -> Option<PathBuf> {
165    let raw_path: OsString = env::var_os(BLENDER_ENV_PATH)?;
166    let names: [&str; 2] = if cfg!(windows) {
167        [BLENDER_BIN_WINDOWS, BLENDER_BIN_UNIX]
168    } else {
169        [BLENDER_BIN_UNIX, BLENDER_BIN_WINDOWS]
170    };
171    for dir in env::split_paths(&raw_path) {
172        for name in names {
173            let candidate: PathBuf = dir.join(name);
174            if candidate.is_file() {
175                return Some(candidate);
176            }
177        }
178    }
179    None
180}
181
182/// Searches standard macOS, Windows, and Linux Blender application installation directories.
183///
184/// # Returns
185///
186/// - `Option<PathBuf>` - Detected OS-installed Blender binary, preferring newest version.
187#[must_use]
188fn find_blender_in_os_locations() -> Option<PathBuf> {
189    if cfg!(target_os = "macos") {
190        let sys_app: PathBuf = PathBuf::from(BLENDER_MACOS_APP_BIN);
191        if sys_app.is_file() {
192            return Some(sys_app);
193        }
194        if let Ok(home) = env::var(BLENDER_ENV_HOME) {
195            let user_app: PathBuf = PathBuf::from(home).join(BLENDER_MACOS_HOME_APP_REL);
196            if user_app.is_file() {
197                return Some(user_app);
198            }
199        }
200    }
201    if cfg!(windows)
202        && let Ok(program_files) = env::var(BLENDER_ENV_PROGRAM_FILES)
203    {
204        let foundation_dir: PathBuf =
205            PathBuf::from(program_files).join(BLENDER_WINDOWS_FOUNDATION_DIR);
206        if let Ok(entries) = fs::read_dir(&foundation_dir) {
207            let mut candidates: Vec<PathBuf> = Vec::new();
208            for entry in entries.flatten() {
209                let exe: PathBuf = entry.path().join(BLENDER_BIN_WINDOWS);
210                if exe.is_file() {
211                    candidates.push(exe);
212                }
213            }
214            candidates.sort();
215            if let Some(latest) = candidates.pop() {
216                return Some(latest);
217            }
218        }
219    }
220    for linux_path in BLENDER_LINUX_CANDIDATE_BINS {
221        let candidate: PathBuf = PathBuf::from(linux_path);
222        if candidate.is_file() {
223            return Some(candidate);
224        }
225    }
226    None
227}
228
229/// Locates standard Blender user add-on directories (`scripts/addons`) on the current host.
230///
231/// # Returns
232///
233/// - `Vec<PathBuf>` - Ordered list of existing Blender user add-on directories (newest version first).
234#[must_use]
235pub fn discover_blender_addon_dirs() -> Vec<PathBuf> {
236    let mut config_roots: Vec<PathBuf> = Vec::new();
237    if cfg!(target_os = "macos")
238        && let Ok(home) = env::var(BLENDER_ENV_HOME)
239    {
240        config_roots.push(PathBuf::from(home).join(BLENDER_MACOS_CONFIG_REL));
241    } else if cfg!(windows)
242        && let Ok(appdata) = env::var(BLENDER_ENV_APPDATA)
243    {
244        config_roots.push(
245            PathBuf::from(appdata)
246                .join(BLENDER_WINDOWS_FOUNDATION_DIR)
247                .join(BLENDER_BIN_UNIX),
248        );
249    } else if let Ok(home) = env::var(BLENDER_ENV_HOME) {
250        config_roots.push(PathBuf::from(home).join(BLENDER_LINUX_CONFIG_REL));
251    }
252    let mut addon_dirs: Vec<PathBuf> = Vec::new();
253    for root in config_roots.into_iter() {
254        let Ok(entries) = fs::read_dir(&root) else {
255            continue;
256        };
257        let mut versions: Vec<PathBuf> = Vec::new();
258        for entry in entries.flatten() {
259            let path: PathBuf = entry.path();
260            if path.is_dir() {
261                versions.push(path);
262            }
263        }
264        versions.sort();
265        versions.reverse();
266        for version_dir in versions.into_iter() {
267            addon_dirs.push(version_dir.join(BLENDER_ADDONS_REL));
268        }
269    }
270    addon_dirs
271}
272
273/// Probes whether a TCP listener (such as the Blender Lab MCP bridge) is accepting connections on `127.0.0.1:<port>`.
274///
275/// # Arguments
276///
277/// - `u16` - Localhost TCP port to probe.
278///
279/// # Returns
280///
281/// - `bool` - `true` when TCP handshake succeeds within the bounded timeout.
282#[must_use]
283pub fn probe_localhost_tcp_port(port: u16) -> bool {
284    if port == 0 {
285        return false;
286    }
287    let addr: SocketAddr = SocketAddr::from(([127, 0, 0, 1], port));
288    TcpStream::connect_timeout(&addr, Duration::from_millis(BLENDER_MCP_PROBE_TIMEOUT_MS)).is_ok()
289}
290
291/// Runs `euv blender doctor`, checking Blender binary, version, glTF exporter readiness, Live-Link add-on, and MCP reachability.
292///
293/// # Arguments
294///
295/// - `&BlenderDoctorConfig` - Optional binary override, MCP port, and glTF probe toggle.
296///
297/// # Returns
298///
299/// - `BlenderDoctorReport` - Structured host readiness report.
300#[must_use]
301pub fn detect_blender_doctor(config: &BlenderDoctorConfig) -> BlenderDoctorReport {
302    let (resolved_bin, binary_source): (Option<PathBuf>, BlenderBinarySource) =
303        resolve_blender_binary(config.try_get_blender_bin().as_deref());
304    let mut version_raw: Option<String> = None;
305    let mut version_major: Option<u16> = None;
306    let mut version_minor: Option<u16> = None;
307    let mut version_patch: Option<u16> = None;
308    let mut gltf_exporter_ready: bool = false;
309    if let Some(bin_path) = resolved_bin.as_ref() {
310        if let Ok(out) = Command::new(bin_path)
311            .arg(BLENDER_ARG_VERSION)
312            .stdin(Stdio::null())
313            .output()
314            && out.status.success()
315        {
316            let text: String = String::from_utf8_lossy(&out.stdout).into_owned();
317            if let Some(first_line) = text.lines().next() {
318                version_raw = Some(first_line.trim().to_string());
319            }
320            if let Some((maj, min, pat)) = parse_blender_version_line(&text) {
321                version_major = Some(maj);
322                version_minor = Some(min);
323                version_patch = Some(pat);
324            }
325        }
326        if config.get_probe_gltf_exporter()
327            && let Ok(out) = Command::new(bin_path)
328                .args([
329                    BLENDER_ARG_BACKGROUND,
330                    BLENDER_ARG_PYTHON_EXPR,
331                    BLENDER_PROBE_GLTF_EXPR,
332                ])
333                .stdin(Stdio::null())
334                .output()
335            && out.status.success()
336        {
337            let text: String = String::from_utf8_lossy(&out.stdout).into_owned();
338            gltf_exporter_ready = text.contains(BLENDER_GLTF_READY_MARKER);
339        }
340    }
341    let supports_gltf_exporter: bool = version_major
342        .map(|maj: u16| maj >= BLENDER_MIN_GLTF_MAJOR)
343        .unwrap_or(false);
344    let supports_blender_mcp_version: bool = match (version_major, version_minor) {
345        (Some(maj), Some(min)) => {
346            maj > BLENDER_MCP_MIN_MAJOR
347                || (maj == BLENDER_MCP_MIN_MAJOR && min >= BLENDER_MCP_MIN_MINOR)
348        }
349        _ => false,
350    };
351    let addon_dirs: Vec<PathBuf> = discover_blender_addon_dirs();
352    let live_link_addon_path: Option<String> = addon_dirs
353        .iter()
354        .map(|dir: &PathBuf| dir.join(BLENDER_LIVE_LINK_ADDON_FILENAME))
355        .find(|candidate: &PathBuf| candidate.is_file())
356        .map(|found: PathBuf| found.display().to_string());
357    let live_link_addon_installed: bool = live_link_addon_path.is_some();
358    let mcp_port: u16 = config.get_mcp_port();
359    let mcp_reachable: bool = probe_localhost_tcp_port(mcp_port);
360    let mut hints: Vec<String> = Vec::new();
361    if resolved_bin.is_none() {
362        hints.push(format!(
363            "Install Blender 4.0+/5.1+ or set {ENV_EUV_BLENDER_BIN}=/path/to/blender (native .blend/.glb/.euv3d inspection works without Blender)"
364        ));
365    } else if !supports_gltf_exporter {
366        hints.push(
367            "Upgrade Blender to 4.0+ (5.1+ recommended) for Principled BSDF glTF 2.0 export"
368                .to_string(),
369        );
370    }
371    if !live_link_addon_installed {
372        hints.push(format!(
373            "Run `euv blender addon-install` to generate `{BLENDER_LIVE_LINK_ADDON_FILENAME}` for 50ms Live-Link sync on port {DEFAULT_BLENDER_SYNC_PORT}"
374        ));
375    }
376    if !mcp_reachable {
377        hints.push(format!(
378            "Blender Lab MCP bridge not detected on 127.0.0.1:{mcp_port}; enable the official MCP add-on in Blender 5.1+ if AI scene editing is desired"
379        ));
380    }
381    BlenderDoctorReport {
382        blender_found: resolved_bin.is_some(),
383        blender_path: resolved_bin.map(|p: PathBuf| p.display().to_string()),
384        binary_source,
385        version_raw,
386        version_major,
387        version_minor,
388        version_patch,
389        supports_gltf_exporter,
390        gltf_exporter_ready,
391        supports_blender_mcp_version,
392        live_link_addon_installed,
393        live_link_addon_path,
394        live_sync_default_port: DEFAULT_BLENDER_SYNC_PORT,
395        mcp_port,
396        mcp_reachable,
397        hints,
398    }
399}
400
401/// Formats a `BlenderDoctorReport` into concise terminal diagnostics.
402///
403/// # Arguments
404///
405/// - `&BlenderDoctorReport` - Collected Blender toolchain report.
406///
407/// # Returns
408///
409/// - `String` - Multi-line human-readable report.
410#[must_use]
411pub fn format_blender_doctor_report(report: &BlenderDoctorReport) -> String {
412    let bin_line: &str = report
413        .try_get_blender_path()
414        .as_deref()
415        .unwrap_or(BLENDER_STATUS_MISSING);
416    let ver_line: &str = report
417        .try_get_version_raw()
418        .as_deref()
419        .unwrap_or(BLENDER_STATUS_MISSING);
420    let gltf_mark: &str = if report.get_gltf_exporter_ready() {
421        BLENDER_STATUS_OK
422    } else {
423        BLENDER_STATUS_MISSING
424    };
425    let addon_mark: &str = if report.get_live_link_addon_installed() {
426        BLENDER_STATUS_OK
427    } else {
428        BLENDER_STATUS_MISSING
429    };
430    let mcp_mark: &str = if report.get_mcp_reachable() {
431        BLENDER_STATUS_OK
432    } else {
433        BLENDER_STATUS_MISSING
434    };
435    let mut out: String = format!(
436        "blender: {} [source={}]\nversion: {}\ngltf-exporter: [{}] (4.0+ supported={})\nlive-link-addon: [{}] (default sync port={})\nblender-mcp (127.0.0.1:{}): [{}] (5.1+ supported={})\n",
437        bin_line,
438        report.get_binary_source().as_str(),
439        ver_line,
440        gltf_mark,
441        report.get_supports_gltf_exporter(),
442        addon_mark,
443        report.get_live_sync_default_port(),
444        report.get_mcp_port(),
445        mcp_mark,
446        report.get_supports_blender_mcp_version(),
447    );
448    if !report.get_hints().is_empty() {
449        out.push_str("hints:\n");
450        for hint in report.get_hints().iter() {
451            out.push_str(&format!("  - {hint}\n"));
452        }
453    }
454    out
455}
456
457/// Maps an `Euv3dSectionKind` discriminant to a stable lowercase section label.
458///
459/// # Arguments
460///
461/// - `Euv3dSectionKind` - Decoded `.euv3d` section kind.
462///
463/// # Returns
464///
465/// - `&'static str` - Snake-case section label.
466#[must_use]
467fn section_kind_label(kind: Euv3dSectionKind) -> &'static str {
468    match kind {
469        Euv3dSectionKind::SceneMetadataJson => SECTION_LABEL_METADATA,
470        Euv3dSectionKind::Vertices => SECTION_LABEL_VERTICES,
471        Euv3dSectionKind::Indices => SECTION_LABEL_INDICES,
472        Euv3dSectionKind::SkinInfluences => SECTION_LABEL_SKINS,
473        Euv3dSectionKind::MorphDeltas => SECTION_LABEL_MORPHS,
474        Euv3dSectionKind::Meshlets => SECTION_LABEL_MESHLETS,
475        Euv3dSectionKind::LodTable => SECTION_LABEL_LOD_TABLE,
476        Euv3dSectionKind::Bvh4Nodes => SECTION_LABEL_BVH4_NODES,
477        Euv3dSectionKind::BvhTri4Packets => SECTION_LABEL_BVH_PACKETS,
478        Euv3dSectionKind::BvhTriangles => SECTION_LABEL_BVH_TRIANGLES,
479        Euv3dSectionKind::AnimationsBlob => SECTION_LABEL_ANIMATIONS,
480        Euv3dSectionKind::TexturesBlob => SECTION_LABEL_TEXTURES,
481    }
482}
483
484/// Converts a parsed Wavefront `ImportedModel3D` (`.obj`) into an `ImportedScene3D` compatible with `.euv3d` baking.
485///
486/// # Arguments
487///
488/// - `&ImportedModel3D` - Parsed Wavefront OBJ model bundle.
489///
490/// # Returns
491///
492/// - `ImportedScene3D` - Equivalent scene with hierarchy and Principled BSDF materials.
493#[must_use]
494fn imported_obj_to_scene(model: &ImportedModel3D) -> ImportedScene3D {
495    let mut scene_graph: SceneGraph3D = SceneGraph3D::default();
496    let mut meshes: Vec<Mesh3D> = Vec::with_capacity(model.get_meshes().len());
497    let mut materials: Vec<PrincipledMaterial3D> = Vec::with_capacity(model.get_meshes().len());
498    for (idx, chain) in model.get_meshes().iter().enumerate() {
499        let Some(base_mesh) = chain.get_levels().first() else {
500            continue;
501        };
502        let mut mesh_copy: Mesh3D = base_mesh.clone();
503        let mat_idx: u32 = materials.len() as u32;
504        mesh_copy.set_material_index(Some(mat_idx));
505        let legacy: PbrMaterial = mesh_copy.get_material();
506        let mut principled: PrincipledMaterial3D = PrincipledMaterial3D::default();
507        let _: &mut PrincipledMaterial3D = principled
508            .set_name(format!("{}_mat_{idx}", mesh_copy.get_name()))
509            .set_base_color_factor([
510                legacy.get_base_color().get_x(),
511                legacy.get_base_color().get_y(),
512                legacy.get_base_color().get_z(),
513                1.0,
514            ])
515            .set_metallic_factor(legacy.get_metallic())
516            .set_roughness_factor(legacy.get_roughness())
517            .set_emissive_factor(legacy.get_emissive().to_array());
518        materials.push(principled);
519        let mesh_id: u32 = meshes.len() as u32;
520        let node_name: String = mesh_copy.get_name().clone();
521        meshes.push(mesh_copy);
522        let mut node: SceneNode3D = SceneNode3D::from_name(&node_name, None);
523        let _: &mut SceneNode3D = node.set_mesh_id(Some(mesh_id));
524        let _: u32 = scene_graph.add_node(node);
525    }
526    let _: usize = scene_graph.propagate_world_matrices();
527    let mut scene: ImportedScene3D = ImportedScene3D::default();
528    let _: &mut ImportedScene3D = scene
529        .set_name(model.get_name().clone())
530        .set_generator(BLENDER_OBJ_GENERATOR.to_string())
531        .set_scene_graph(scene_graph)
532        .set_meshes(meshes)
533        .set_materials(materials);
534    scene
535}
536
537/// Loads a Wavefront `.obj` file (plus sibling `.mtl` when referenced via `mtllib`) into an `ImportedScene3D`.
538///
539/// # Arguments
540///
541/// - `&Path` - Path to the `.obj` source file.
542/// - `&[u8]` - Raw `.obj` file bytes.
543///
544/// # Returns
545///
546/// - `io::Result<ImportedScene3D>` - Converted scene bundle or parse error.
547fn load_obj_scene_from_bytes(path: &Path, bytes: &[u8]) -> io::Result<ImportedScene3D> {
548    let source: &str =
549        from_utf8(bytes).map_err(|err: Utf8Error| Error::new(ErrorKind::InvalidData, err))?;
550    let mtl_text: Option<String> = source
551        .lines()
552        .find_map(|line: &str| line.trim().strip_prefix(OBJ_DIRECTIVE_MTLLIB))
553        .and_then(|rel_name: &str| {
554            let trimmed: &str = rel_name.trim();
555            let base: &Path = path.parent().unwrap_or_else(|| Path::new("."));
556            let mtl_path: PathBuf = base.join(trimmed);
557            fs::read_to_string(mtl_path).ok()
558        })
559        .or_else(|| {
560            let sibling: PathBuf = path.with_extension(BLENDER_EXT_MTL);
561            fs::read_to_string(sibling).ok()
562        });
563    let model: ImportedModel3D =
564        ModelImporter3D::parse_obj_with_mtl(source, mtl_text.as_deref(), PbrMaterial::default())
565            .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
566    Ok(imported_obj_to_scene(&model))
567}
568
569/// Inspects a `.blend`, `.glb`, `.gltf`, `.euv3d`, or `.obj` file natively in pure Rust with zero Blender installation required.
570///
571/// # Arguments
572///
573/// - `&Path` - Source 3D asset file path.
574///
575/// # Returns
576///
577/// - `io::Result<BlenderInspectReport>` - Structured asset inspection report.
578pub fn inspect_blender_asset(path: &Path) -> io::Result<BlenderInspectReport> {
579    if !path.is_file() {
580        return Err(Error::new(
581            ErrorKind::NotFound,
582            format!("{ERR_BLENDER_INPUT_MISSING}: {}", path.display()),
583        ));
584    }
585    let bytes: Vec<u8> = fs::read(path)?;
586    let file_bytes: u64 = bytes.len() as u64;
587    let format: BlenderAssetFormat = detect_blender_asset_format(path, &bytes)?;
588    match format {
589        BlenderAssetFormat::Blend => {
590            let native: BlendInspectionReport = inspect_blend_bytes(&bytes)
591                .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
592            Ok(BlenderInspectReport {
593                path: path.display().to_string(),
594                format,
595                file_bytes,
596                blend: Some(BlenderNativeBlendSummary::from_blend_report(&native)),
597                scene: None,
598                euv3d: None,
599            })
600        }
601        BlenderAssetFormat::Glb | BlenderAssetFormat::Gltf => {
602            let base_dir: PathBuf = path
603                .parent()
604                .map(Path::to_path_buf)
605                .unwrap_or_else(|| PathBuf::from("."));
606            let resolver: DirectoryGltfResolver = DirectoryGltfResolver::from_dir(base_dir);
607            let scene: ImportedScene3D = parse_gltf_or_glb_bytes(&bytes, Some(&resolver))
608                .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
609            Ok(BlenderInspectReport {
610                path: path.display().to_string(),
611                format,
612                file_bytes,
613                blend: None,
614                scene: Some(BlenderSceneSummary::from_imported_scene(&scene)),
615                euv3d: None,
616            })
617        }
618        BlenderAssetFormat::Euv3d => {
619            let view: Euv3dPackageView<'_> = Euv3dPackageView::from_bytes(&bytes)
620                .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
621            let decoded: BakedAssetBundle3D = Euv3dPackage::decode_bytes(&bytes)
622                .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
623            let header: Euv3dHeader = view.get_header();
624            let sections: Vec<BlenderEuv3dSectionSummary> = view
625                .get_sections()
626                .iter()
627                .map(|entry: &Euv3dSectionEntry| {
628                    let aligned_64: bool =
629                        (entry.get_offset() as usize).is_multiple_of(EUV3D_SECTION_ALIGNMENT);
630                    BlenderEuv3dSectionSummary::new(
631                        section_kind_label(entry.get_kind()).to_string(),
632                        entry.get_offset(),
633                        entry.get_byte_length(),
634                        entry.get_element_count(),
635                        aligned_64,
636                    )
637                })
638                .collect();
639            let has_bvh4: bool = view.section_entry(Euv3dSectionKind::Bvh4Nodes).is_some();
640            let has_meshlets: bool = view.section_entry(Euv3dSectionKind::Meshlets).is_some();
641            let max_lod_levels: usize = decoded
642                .get_lod_chains()
643                .iter()
644                .map(|chain: &MeshLodChain| chain.get_levels().len())
645                .max()
646                .unwrap_or(0);
647            let euv3d_summary: BlenderEuv3dSummary = BlenderEuv3dSummary {
648                format_version: header.get_version(),
649                content_crc32: header.get_content_crc32(),
650                digest_fnv1a: header.get_digest_fnv1a(),
651                has_bvh4,
652                has_meshlets,
653                has_lods: max_lod_levels > 1,
654                max_lod_levels,
655                bvh_count: decoded.get_local_bvhs().len(),
656                sections,
657            };
658            Ok(BlenderInspectReport {
659                path: path.display().to_string(),
660                format,
661                file_bytes,
662                blend: None,
663                scene: Some(BlenderSceneSummary::from_imported_scene(
664                    decoded.get_scene(),
665                )),
666                euv3d: Some(euv3d_summary),
667            })
668        }
669        BlenderAssetFormat::Obj => {
670            let scene: ImportedScene3D = load_obj_scene_from_bytes(path, &bytes)?;
671            Ok(BlenderInspectReport {
672                path: path.display().to_string(),
673                format,
674                file_bytes,
675                blend: None,
676                scene: Some(BlenderSceneSummary::from_imported_scene(&scene)),
677                euv3d: None,
678            })
679        }
680    }
681}
682
683/// Formats a `BlenderInspectReport` into concise terminal output.
684///
685/// # Arguments
686///
687/// - `&BlenderInspectReport` - Completed asset inspection report.
688///
689/// # Returns
690///
691/// - `String` - Multi-line formatted summary.
692#[must_use]
693pub fn format_blender_inspect_report(report: &BlenderInspectReport) -> String {
694    let mut out: String = format!(
695        "path: {}\nformat: {}\nsize_bytes: {}\n",
696        report.get_path(),
697        report.get_format().as_str(),
698        report.get_file_bytes(),
699    );
700    if let Some(blend) = report.try_get_blend() {
701        out.push_str(&format!(
702            "blender_version: {} (v5_large_header={}, ptr={}B, le={}, compression={})\nblocks: {} (dna_structs={})\nscenes: {} | collections: {} | objects: {} | meshes: {} | materials: {} | cameras: {} | lights: {} | armatures: {} | actions: {}\n",
703            blend.get_version(),
704            blend.get_is_large_header_v5(),
705            blend.get_pointer_size_bytes(),
706            blend.get_is_little_endian(),
707            blend.get_compression(),
708            blend.get_block_count(),
709            blend.get_dna_struct_count(),
710            blend.get_scenes().len(),
711            blend.get_collections().len(),
712            blend.get_objects().len(),
713            blend.get_meshes().len(),
714            blend.get_materials().len(),
715            blend.get_cameras().len(),
716            blend.get_lights().len(),
717            blend.get_armatures().len(),
718            blend.get_actions().len(),
719        ));
720    }
721    if let Some(euv3d) = report.try_get_euv3d() {
722        out.push_str(&format!(
723            "euv3d: v{} crc32=0x{:08x} digest=0x{:016x} lods={} bvh4={} ({}) meshlets={} sections={}\n",
724            euv3d.get_format_version(),
725            euv3d.get_content_crc32(),
726            euv3d.get_digest_fnv1a(),
727            euv3d.get_max_lod_levels(),
728            euv3d.get_has_bvh4(),
729            euv3d.get_bvh_count(),
730            euv3d.get_has_meshlets(),
731            euv3d.get_sections().len(),
732        ));
733    }
734    if let Some(scene) = report.try_get_scene() {
735        out.push_str(&format!(
736            "scene: {} (generator={})\nnodes: {} | meshes: {} | vertices: {} | triangles: {} | materials: {} | textures: {} | skins: {} | animations: {} | cameras: {} | lights: {}\n",
737            scene.get_name(),
738            scene.get_generator(),
739            scene.get_node_count(),
740            scene.get_mesh_count(),
741            scene.get_total_vertices(),
742            scene.get_total_triangles(),
743            scene.get_material_count(),
744            scene.get_texture_count(),
745            scene.get_skin_count(),
746            scene.get_animation_count(),
747            scene.get_camera_count(),
748            scene.get_light_count(),
749        ));
750    }
751    out
752}
753
754/// Builds the headless Blender CLI argument vector used to convert a `.blend` file to `.glb`.
755///
756/// # Arguments
757///
758/// - `&Path` - Resolved Blender executable path.
759/// - `&Path` - Source `.blend` file path.
760/// - `&Path` - Script file path containing `EXPORT_BLEND_TO_GLB_PY`.
761/// - `&Path` - Destination `.glb` output path.
762///
763/// # Returns
764///
765/// - `Vec<String>` - Complete argv list `[blender_bin, --background, ...]`.
766#[must_use]
767pub fn build_headless_blend_export_argv(
768    blender_bin: &Path,
769    blend_input: &Path,
770    script_path: &Path,
771    glb_output: &Path,
772) -> Vec<String> {
773    vec![
774        blender_bin.display().to_string(),
775        BLENDER_ARG_BACKGROUND.to_string(),
776        blend_input.display().to_string(),
777        BLENDER_ARG_PYTHON.to_string(),
778        script_path.display().to_string(),
779        BLENDER_ARG_SEP.to_string(),
780        glb_output.display().to_string(),
781    ]
782}
783
784/// Exports a `.blend` file to `.glb` by executing embedded `EXPORT_BLEND_TO_GLB_PY` inside headless Blender.
785///
786/// # Arguments
787///
788/// - `&Path` - Source `.blend` file path.
789/// - `&Path` - Destination `.glb` output file path.
790/// - `Option<&Path>` - Optional explicit Blender binary override.
791///
792/// # Returns
793///
794/// - `io::Result<Vec<String>>` - Executed command argv on success, or descriptive I/O error.
795pub fn export_blend_file_to_glb(
796    blend_input: &Path,
797    glb_output: &Path,
798    explicit_blender_bin: Option<&Path>,
799) -> io::Result<Vec<String>> {
800    let (resolved_bin, _): (Option<PathBuf>, BlenderBinarySource) =
801        resolve_blender_binary(explicit_blender_bin);
802    let Some(blender_bin) = resolved_bin else {
803        return Err(Error::new(ErrorKind::NotFound, ERR_BLENDER_BINARY_MISSING));
804    };
805    if let Some(parent) = glb_output.parent() {
806        fs::create_dir_all(parent)?;
807    }
808    let seq: u64 = BLENDER_TMP_SCRIPT_SEQ.fetch_add(1, Ordering::Relaxed);
809    let script_path: PathBuf = env::temp_dir().join(format!(
810        "{BLENDER_EXPORT_SCRIPT_PREFIX}_{}_{seq}.py",
811        process::id()
812    ));
813    fs::write(&script_path, EXPORT_BLEND_TO_GLB_PY)?;
814    let argv: Vec<String> =
815        build_headless_blend_export_argv(&blender_bin, blend_input, &script_path, glb_output);
816    let result: io::Result<Output> = Command::new(&blender_bin)
817        .args(&argv[1..])
818        .stdin(Stdio::null())
819        .output();
820    let _: io::Result<()> = fs::remove_file(&script_path);
821    let output: Output = result?;
822    if !output.status.success() || !glb_output.is_file() {
823        let stderr: String = String::from_utf8_lossy(&output.stderr).trim().to_string();
824        let stdout: String = String::from_utf8_lossy(&output.stdout).trim().to_string();
825        return Err(Error::other(format!(
826            "{ERR_BLENDER_EXPORT_FAILED}: stderr={stderr} stdout={stdout}"
827        )));
828    }
829    Ok(argv)
830}
831
832/// Loads any supported source file (`.blend`, `.glb`, `.gltf`, `.obj`, `.euv3d`) into an `ImportedScene3D`.
833///
834/// # Arguments
835///
836/// - `&Path` - Source 3D asset path.
837/// - `Option<&Path>` - Optional explicit Blender binary override for `.blend` files.
838///
839/// # Returns
840///
841/// - `io::Result<(BlenderAssetFormat, ImportedScene3D, Vec<String>, u64)>` - Format, imported scene, optional Blender argv, and input size in bytes.
842fn load_scene_for_pipeline(
843    input: &Path,
844    explicit_blender_bin: Option<&Path>,
845) -> io::Result<(BlenderAssetFormat, ImportedScene3D, Vec<String>, u64)> {
846    if !input.is_file() {
847        return Err(Error::new(
848            ErrorKind::NotFound,
849            format!("{ERR_BLENDER_INPUT_MISSING}: {}", input.display()),
850        ));
851    }
852    let raw_bytes: Vec<u8> = fs::read(input)?;
853    let input_bytes: u64 = raw_bytes.len() as u64;
854    let format: BlenderAssetFormat = detect_blender_asset_format(input, &raw_bytes)?;
855    match format {
856        BlenderAssetFormat::Blend => {
857            let seq: u64 = BLENDER_TMP_SCRIPT_SEQ.fetch_add(1, Ordering::Relaxed);
858            let tmp_glb: PathBuf = env::temp_dir().join(format!(
859                "euv_blender_stage_{}_{seq}.{BLENDER_EXT_GLB}",
860                process::id()
861            ));
862            let argv: Vec<String> =
863                export_blend_file_to_glb(input, &tmp_glb, explicit_blender_bin)?;
864            let glb_bytes: Vec<u8> = fs::read(&tmp_glb)?;
865            let _: io::Result<()> = fs::remove_file(&tmp_glb);
866            let scene: ImportedScene3D = parse_gltf_or_glb_bytes(&glb_bytes, None)
867                .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
868            Ok((format, scene, argv, input_bytes))
869        }
870        BlenderAssetFormat::Glb | BlenderAssetFormat::Gltf => {
871            let base_dir: PathBuf = input
872                .parent()
873                .map(Path::to_path_buf)
874                .unwrap_or_else(|| PathBuf::from("."));
875            let resolver: DirectoryGltfResolver = DirectoryGltfResolver::from_dir(base_dir);
876            let scene: ImportedScene3D = parse_gltf_or_glb_bytes(&raw_bytes, Some(&resolver))
877                .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
878            Ok((format, scene, Vec::new(), input_bytes))
879        }
880        BlenderAssetFormat::Obj => {
881            let scene: ImportedScene3D = load_obj_scene_from_bytes(input, &raw_bytes)?;
882            Ok((format, scene, Vec::new(), input_bytes))
883        }
884        BlenderAssetFormat::Euv3d => {
885            let decoded: BakedAssetBundle3D = Euv3dPackage::decode_bytes(&raw_bytes)
886                .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
887            Ok((format, decoded.get_scene().clone(), Vec::new(), input_bytes))
888        }
889    }
890}
891
892/// Replaces non-finite float fields (such as default `f32::INFINITY` `attenuation_distance` on materials without `KHR_materials_volume`) with finite bounds so JSON `.euv3d` metadata round-trips cleanly.
893///
894/// # Arguments
895///
896/// - `&mut ImportedScene3D` - Imported scene about to be baked into `.euv3d`.
897fn sanitize_scene_for_euv3d_bake(scene: &mut ImportedScene3D) {
898    for mat in scene.get_mut_materials().iter_mut() {
899        if !mat.get_attenuation_distance().is_finite() {
900            let _: &mut PrincipledMaterial3D = mat.set_attenuation_distance(1.0e9);
901        }
902    }
903}
904
905/// Imports a `.blend`, `.glb`, `.gltf`, or `.obj` asset into `--out <dir>`, generating `asset-manifest.json` and optional `.euv3d`.
906///
907/// # Arguments
908///
909/// - `&BlenderImportConfig` - Input path, output directory, optional Blender binary, and bake flags.
910///
911/// # Returns
912///
913/// - `io::Result<BlenderImportReport>` - Structured import report or error.
914pub fn import_blender_asset(config: &BlenderImportConfig) -> io::Result<BlenderImportReport> {
915    let started: Instant = Instant::now();
916    let input: &Path = config.get_input();
917    let out_dir: &Path = config.get_out_dir();
918    let stem: String = input
919        .file_stem()
920        .and_then(OsStr::to_str)
921        .filter(|name: &&str| !name.is_empty())
922        .unwrap_or(BLENDER_DEFAULT_ASSET_STEM)
923        .to_string();
924    let preview_bytes: Vec<u8> = if input.is_file() {
925        fs::read(input)?
926    } else if config.get_plan() {
927        Vec::new()
928    } else {
929        return Err(Error::new(
930            ErrorKind::NotFound,
931            format!("{ERR_BLENDER_INPUT_MISSING}: {}", input.display()),
932        ));
933    };
934    let input_format: BlenderAssetFormat = detect_blender_asset_format(input, &preview_bytes)?;
935    if config.get_plan() {
936        let planned_glb: PathBuf = out_dir.join(format!("{stem}.{BLENDER_EXT_GLB}"));
937        let planned_cmd: Vec<String> = if input_format == BlenderAssetFormat::Blend {
938            let bin_ref: PathBuf = resolve_blender_binary(config.try_get_blender_bin().as_deref())
939                .0
940                .unwrap_or_else(|| PathBuf::from(BLENDER_BIN_UNIX));
941            build_headless_blend_export_argv(
942                &bin_ref,
943                input,
944                Path::new(BLENDER_EXPORT_SCRIPT_PREFIX),
945                &planned_glb,
946            )
947        } else {
948            Vec::new()
949        };
950        let baked_path: Option<String> = if config.get_bake() {
951            Some(
952                out_dir
953                    .join(format!("{stem}.{BLENDER_EXT_EUV3D}"))
954                    .display()
955                    .to_string(),
956            )
957        } else {
958            None
959        };
960        return Ok(BlenderImportReport {
961            input_path: input.display().to_string(),
962            input_format,
963            out_dir: out_dir.display().to_string(),
964            asset_output_path: Some(planned_glb.display().to_string()),
965            baked_euv3d_path: baked_path,
966            manifest_path: Some(
967                out_dir
968                    .join(BLENDER_IMPORT_MANIFEST_FILE)
969                    .display()
970                    .to_string(),
971            ),
972            planned_command: planned_cmd,
973            scene: None,
974            elapsed_ms: started.elapsed().as_millis() as u64,
975        });
976    }
977    fs::create_dir_all(out_dir)?;
978    let (asset_output_path, mut scene, planned_command): (PathBuf, ImportedScene3D, Vec<String>) =
979        if input_format == BlenderAssetFormat::Blend {
980            let glb_out: PathBuf = out_dir.join(format!("{stem}.{BLENDER_EXT_GLB}"));
981            let argv: Vec<String> =
982                export_blend_file_to_glb(input, &glb_out, config.try_get_blender_bin().as_deref())?;
983            let glb_bytes: Vec<u8> = fs::read(&glb_out)?;
984            let parsed_scene: ImportedScene3D = parse_gltf_or_glb_bytes(&glb_bytes, None)
985                .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
986            (glb_out, parsed_scene, argv)
987        } else {
988            let (_, parsed_scene, argv, _): (
989                BlenderAssetFormat,
990                ImportedScene3D,
991                Vec<String>,
992                u64,
993            ) = load_scene_for_pipeline(input, config.try_get_blender_bin().as_deref())?;
994            let copied_path: PathBuf = out_dir.join(format!("{stem}.{}", input_format.as_str()));
995            atomic_write_synced(&copied_path, &preview_bytes)?;
996            (copied_path, parsed_scene, argv)
997        };
998    let baked_euv3d_path: Option<String> = if config.get_bake() {
999        sanitize_scene_for_euv3d_bake(&mut scene);
1000        let euv3d_out: PathBuf = out_dir.join(format!("{stem}.{BLENDER_EXT_EUV3D}"));
1001        let mut bake_cfg: Euv3dBakeConfig = Euv3dBakeConfig::default();
1002        let _: &mut Euv3dBakeConfig = bake_cfg
1003            .set_lod_levels(config.get_lods().clamp(1, EUV3D_DEFAULT_LOD_LEVELS))
1004            .set_build_meshlets(config.get_build_meshlets())
1005            .set_bake_bvh4(config.get_bake_bvh4());
1006        let euv3d_bytes: Vec<u8> = Euv3dPackage::bake_from_scene(&scene, &bake_cfg)
1007            .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
1008        let _: Euv3dPackageView<'_> = Euv3dPackageView::from_bytes(&euv3d_bytes)
1009            .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
1010        atomic_write_synced(&euv3d_out, &euv3d_bytes)?;
1011        Some(euv3d_out.display().to_string())
1012    } else {
1013        None
1014    };
1015    let scene_summary: BlenderSceneSummary = BlenderSceneSummary::from_imported_scene(&scene);
1016    let manifest_path: PathBuf = out_dir.join(BLENDER_IMPORT_MANIFEST_FILE);
1017    let manifest_json: String = to_string_pretty(&scene_summary)
1018        .map_err(|err: serde_json::Error| Error::other(err.to_string()))?;
1019    atomic_write_synced(&manifest_path, manifest_json.as_bytes())?;
1020    Ok(BlenderImportReport {
1021        input_path: input.display().to_string(),
1022        input_format,
1023        out_dir: out_dir.display().to_string(),
1024        asset_output_path: Some(asset_output_path.display().to_string()),
1025        baked_euv3d_path,
1026        manifest_path: Some(manifest_path.display().to_string()),
1027        planned_command,
1028        scene: Some(scene_summary),
1029        elapsed_ms: started.elapsed().as_millis() as u64,
1030    })
1031}
1032
1033/// Compiles a `.blend`, `.glb`, `.gltf`, or `.obj` source into a zero-copy 64-byte-aligned `.euv3d` package with QEM LODs, spatial meshlets, and SIMD BVH4.
1034///
1035/// # Arguments
1036///
1037/// - `&BlenderBakeConfig` - Input path, output `.euv3d` file, LOD depth, meshlet/BVH4 flags, and optional `--plan`.
1038///
1039/// # Returns
1040///
1041/// - `io::Result<BlenderBakeReport>` - Verified archive metrics and checksum report.
1042pub fn bake_blender_asset(config: &BlenderBakeConfig) -> io::Result<BlenderBakeReport> {
1043    let started: Instant = Instant::now();
1044    let input: &Path = config.get_input();
1045    let out_file: &Path = config.get_out_file();
1046    let lods: usize = config.get_lods().clamp(1, EUV3D_DEFAULT_LOD_LEVELS);
1047    if config.get_plan() {
1048        let preview: Vec<u8> = if input.is_file() {
1049            fs::read(input)?
1050        } else {
1051            Vec::new()
1052        };
1053        let input_format: BlenderAssetFormat = detect_blender_asset_format(input, &preview)?;
1054        let planned_command: Vec<String> = if input_format == BlenderAssetFormat::Blend {
1055            let bin_ref: PathBuf = resolve_blender_binary(config.try_get_blender_bin().as_deref())
1056                .0
1057                .unwrap_or_else(|| PathBuf::from(BLENDER_BIN_UNIX));
1058            build_headless_blend_export_argv(
1059                &bin_ref,
1060                input,
1061                Path::new(BLENDER_EXPORT_SCRIPT_PREFIX),
1062                &out_file.with_extension(BLENDER_EXT_GLB),
1063            )
1064        } else {
1065            Vec::new()
1066        };
1067        return Ok(BlenderBakeReport {
1068            input_path: input.display().to_string(),
1069            input_format,
1070            out_file: out_file.display().to_string(),
1071            input_bytes: preview.len() as u64,
1072            output_bytes: 0,
1073            lod_levels: lods,
1074            meshlets_enabled: config.get_build_meshlets(),
1075            bvh4_enabled: config.get_bake_bvh4(),
1076            content_crc32: 0,
1077            digest_fnv1a: 0,
1078            section_count: 0,
1079            scene: None,
1080            planned_command,
1081            elapsed_ms: started.elapsed().as_millis() as u64,
1082        });
1083    }
1084    let (input_format, mut scene, planned_command, input_bytes): (
1085        BlenderAssetFormat,
1086        ImportedScene3D,
1087        Vec<String>,
1088        u64,
1089    ) = load_scene_for_pipeline(input, config.try_get_blender_bin().as_deref())?;
1090    sanitize_scene_for_euv3d_bake(&mut scene);
1091    let mut bake_cfg: Euv3dBakeConfig = Euv3dBakeConfig::default();
1092    let _: &mut Euv3dBakeConfig = bake_cfg
1093        .set_lod_levels(lods)
1094        .set_build_meshlets(config.get_build_meshlets())
1095        .set_bake_bvh4(config.get_bake_bvh4());
1096    let euv3d_bytes: Vec<u8> = Euv3dPackage::bake_from_scene(&scene, &bake_cfg)
1097        .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
1098    let view: Euv3dPackageView<'_> = Euv3dPackageView::from_bytes(&euv3d_bytes)
1099        .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
1100    atomic_write_synced(out_file, &euv3d_bytes)?;
1101    let header: Euv3dHeader = view.get_header();
1102    Ok(BlenderBakeReport {
1103        input_path: input.display().to_string(),
1104        input_format,
1105        out_file: out_file.display().to_string(),
1106        input_bytes,
1107        output_bytes: euv3d_bytes.len() as u64,
1108        lod_levels: lods,
1109        meshlets_enabled: config.get_build_meshlets(),
1110        bvh4_enabled: config.get_bake_bvh4(),
1111        content_crc32: header.get_content_crc32(),
1112        digest_fnv1a: header.get_digest_fnv1a(),
1113        section_count: view.get_sections().len(),
1114        scene: Some(BlenderSceneSummary::from_imported_scene(&scene)),
1115        planned_command,
1116        elapsed_ms: started.elapsed().as_millis() as u64,
1117    })
1118}
1119
1120/// Emits or installs the embedded `euv_live_link.py` Blender 4.x/5.x add-on.
1121///
1122/// # Arguments
1123///
1124/// - `&BlenderAddonInstallConfig` - Destination path override or `--print` flag.
1125///
1126/// # Returns
1127///
1128/// - `io::Result<BlenderAddonInstallReport>` - Written file path, digest, and activation guide.
1129pub fn install_blender_addon(
1130    config: &BlenderAddonInstallConfig,
1131) -> io::Result<BlenderAddonInstallReport> {
1132    let source_bytes: &[u8] = EUV_LIVE_LINK_ADDON_PY.as_bytes();
1133    let sha256: String = sha256_hex(source_bytes);
1134    let instructions: String = format!(
1135        "In Blender 4.x/5.x: Edit > Preferences > Add-ons > Install from Disk -> select `{BLENDER_LIVE_LINK_ADDON_FILENAME}`, enable 'Euv Live-Link', open View3D Sidebar (N) > Euv, and run `euv blender live-sync --port {DEFAULT_BLENDER_SYNC_PORT}`."
1136    );
1137    if config.get_print_only() {
1138        return Ok(BlenderAddonInstallReport {
1139            filename: BLENDER_LIVE_LINK_ADDON_FILENAME.to_string(),
1140            installed_path: None,
1141            byte_length: source_bytes.len(),
1142            sha256,
1143            default_port: DEFAULT_BLENDER_SYNC_PORT,
1144            instructions,
1145        });
1146    }
1147    let destination: PathBuf = match config.try_get_out() {
1148        Some(target) => {
1149            if target.is_dir() {
1150                target.join(BLENDER_LIVE_LINK_ADDON_FILENAME)
1151            } else {
1152                target.to_path_buf()
1153            }
1154        }
1155        None => {
1156            let dirs: Vec<PathBuf> = discover_blender_addon_dirs();
1157            if let Some(first_dir) = dirs.first() {
1158                first_dir.join(BLENDER_LIVE_LINK_ADDON_FILENAME)
1159            } else {
1160                PathBuf::from(BLENDER_LIVE_LINK_ADDON_FILENAME)
1161            }
1162        }
1163    };
1164    atomic_write_synced(&destination, source_bytes)?;
1165    Ok(BlenderAddonInstallReport {
1166        filename: BLENDER_LIVE_LINK_ADDON_FILENAME.to_string(),
1167        installed_path: Some(destination.display().to_string()),
1168        byte_length: source_bytes.len(),
1169        sha256,
1170        default_port: DEFAULT_BLENDER_SYNC_PORT,
1171        instructions,
1172    })
1173}
1174
1175/// Validates an uploaded Live-Link binary asset payload (`.glb`, `.gltf`, or `.euv3d`) and returns its format and mesh/triangle counts.
1176///
1177/// # Arguments
1178///
1179/// - `&[u8]` - Raw binary asset bytes received on `POST /blender/asset/{id}`.
1180///
1181/// # Returns
1182///
1183/// - `io::Result<(BlenderAssetFormat, usize, usize)>` - `(format, mesh_count, triangle_count)` or `InvalidData`.
1184#[cfg(feature = "update-server")]
1185pub(crate) fn validate_live_asset_payload(
1186    bytes: &[u8],
1187) -> io::Result<(BlenderAssetFormat, usize, usize)> {
1188    if bytes.len() >= 8 && bytes[0..8] == EUV3D_MAGIC {
1189        let decoded: BakedAssetBundle3D = Euv3dPackage::decode_bytes(bytes)
1190            .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
1191        let summary: BlenderSceneSummary =
1192            BlenderSceneSummary::from_imported_scene(decoded.get_scene());
1193        return Ok((
1194            BlenderAssetFormat::Euv3d,
1195            summary.get_mesh_count(),
1196            summary.get_total_triangles(),
1197        ));
1198    }
1199    let format: BlenderAssetFormat = if bytes.len() >= 4 && bytes[0..4] == BLENDER_GLB_MAGIC {
1200        BlenderAssetFormat::Glb
1201    } else {
1202        BlenderAssetFormat::Gltf
1203    };
1204    let scene: ImportedScene3D = parse_gltf_or_glb_bytes(bytes, None)
1205        .map_err(|err: String| Error::new(ErrorKind::InvalidData, err))?;
1206    let summary: BlenderSceneSummary = BlenderSceneSummary::from_imported_scene(&scene);
1207    Ok((
1208        format,
1209        summary.get_mesh_count(),
1210        summary.get_total_triangles(),
1211    ))
1212}
1213
1214/// Registers the Blender Live-Link HTTP and SSE routes onto a Hyperlane `Server`.
1215///
1216/// # Arguments
1217///
1218/// - `&mut Server` - Hyperlane server instance receiving Live-Link routes.
1219/// - `Arc<BlenderLiveSyncState>` - Shared Live-Link state.
1220#[cfg(feature = "update-server")]
1221pub fn register_blender_live_sync_routes(server: &mut Server, state: Arc<BlenderLiveSyncState>) {
1222    let slot: &RwLock<Option<Arc<BlenderLiveSyncState>>> =
1223        DEFAULT_BLENDER_LIVE_SYNC_STATE.get_or_init(|| RwLock::new(None));
1224    if let Ok(mut guard) = slot.write() {
1225        *guard = Some(state);
1226    }
1227    let _: &mut Server = server
1228        .route::<BlenderDeltaRouteHook>(BLENDER_ROUTE_DELTA)
1229        .route::<BlenderAssetRouteHook>(BLENDER_ROUTE_ASSET)
1230        .route::<BlenderEventsRouteHook>(BLENDER_ROUTE_EVENTS)
1231        .route::<BlenderStatusRouteHook>(BLENDER_ROUTE_STATUS)
1232        .route::<BlenderStatusRouteHook>(BLENDER_ROUTE_HEALTHZ);
1233}
1234
1235/// Starts a live Hyperlane HTTP+SSE Blender Live-Link daemon supporting ephemeral ports (`port == 0`).
1236///
1237/// # Arguments
1238///
1239/// - `BlenderLiveSyncConfig` - Host, port, optional disk mirror directory, heartbeat, and replay settings.
1240///
1241/// # Returns
1242///
1243/// - `io::Result<BlenderLiveSyncHandle>` - Active Live-Link server handle.
1244#[cfg(feature = "update-server")]
1245pub fn start_blender_live_sync_server(
1246    config: BlenderLiveSyncConfig,
1247) -> io::Result<BlenderLiveSyncHandle> {
1248    if let Some(dir) = config.try_get_out_dir() {
1249        fs::create_dir_all(dir)?;
1250    }
1251    let sse_config: SseConfig = SseConfig::default()
1252        .with_heartbeat_ms(config.get_heartbeat_ms())
1253        .with_retry_ms(2_000)
1254        .with_replay_capacity(config.get_replay_capacity());
1255    let state: Arc<BlenderLiveSyncState> = Arc::new(BlenderLiveSyncState::new(
1256        sse_config,
1257        config.try_get_out_dir().clone(),
1258        config.get_max_asset_bytes(),
1259        config.get_replay_capacity(),
1260    ));
1261    let runtime_ref: runtime::Runtime = runtime::Builder::new_multi_thread()
1262        .worker_threads(2)
1263        .enable_all()
1264        .build()?;
1265    let max_attempts: usize = if config.get_port() == 0 { 8 } else { 1 };
1266    let mut last_err: Option<Error> = None;
1267    let mut bound_pair: Option<(SocketAddr, ServerControlHook)> = None;
1268    for _ in 0..max_attempts {
1269        let candidate_addr: SocketAddr =
1270            resolve_blender_bind_addr(config.get_host(), config.get_port())?;
1271        register_blender_live_sync_state(candidate_addr, Arc::clone(&state));
1272        let mut server_cfg: ServerConfig = ServerConfig::default();
1273        server_cfg.set_address(candidate_addr.to_string());
1274        let mut server: Server = Server::from(server_cfg);
1275        register_blender_live_sync_routes(&mut server, Arc::clone(&state));
1276        match runtime_ref.block_on(async move { server.run().await }) {
1277            Ok(control) => {
1278                bound_pair = Some((candidate_addr, control));
1279                break;
1280            }
1281            Err(err) => {
1282                unregister_blender_live_sync_state(candidate_addr);
1283                last_err = Some(Error::other(err.to_string()));
1284            }
1285        }
1286    }
1287    let (resolved_addr, control): (SocketAddr, ServerControlHook) = match bound_pair {
1288        Some(pair) => pair,
1289        None => {
1290            return Err(last_err.unwrap_or_else(|| Error::from(ErrorKind::AddrInUse)));
1291        }
1292    };
1293    Ok(BlenderLiveSyncHandle {
1294        address: resolved_addr,
1295        state,
1296        control: Some(control),
1297        runtime: Some(runtime_ref),
1298    })
1299}
1300
1301/// Runs the Hyperlane HTTP+SSE Blender Live-Link daemon in blocking CLI mode (or exits immediately when `--once` is set).
1302///
1303/// # Arguments
1304///
1305/// - `BlenderLiveSyncConfig` - Live-Link bind address, heartbeat, and `--once` flag.
1306///
1307/// # Returns
1308///
1309/// - `io::Result<BlenderLiveSyncReport>` - Machine-readable server startup report.
1310#[cfg(feature = "update-server")]
1311pub fn run_blender_live_sync_blocking(
1312    config: BlenderLiveSyncConfig,
1313) -> io::Result<BlenderLiveSyncReport> {
1314    let once: bool = config.get_once();
1315    let mut handle: BlenderLiveSyncHandle = start_blender_live_sync_server(config)?;
1316    let report: BlenderLiveSyncReport = handle.report(once);
1317    if once {
1318        handle.shutdown();
1319        return Ok(report);
1320    }
1321    eprintln!(
1322        "[euv-blender] live-sync listening on {} (delta={} asset={} events={})",
1323        report.get_url(),
1324        report.get_delta_url(),
1325        report.get_asset_url(),
1326        report.get_events_url(),
1327    );
1328    while handle.is_running() {
1329        thread::sleep(Duration::from_millis(250));
1330    }
1331    handle.shutdown();
1332    Ok(report)
1333}
1334
1335/// Returns a clear feature error when `euv blender live-sync` is invoked without the `update-server` feature enabled.
1336///
1337/// # Arguments
1338///
1339/// - `BlenderLiveSyncConfig` - Unused Live-Link configuration.
1340///
1341/// # Returns
1342///
1343/// - `io::Result<BlenderLiveSyncReport>` - Always returns `ErrorKind::Unsupported`.
1344#[cfg(not(feature = "update-server"))]
1345pub fn run_blender_live_sync_blocking(
1346    _config: BlenderLiveSyncConfig,
1347) -> io::Result<BlenderLiveSyncReport> {
1348    Err(Error::new(
1349        ErrorKind::Unsupported,
1350        ERR_BLENDER_LIVE_SYNC_DISABLED,
1351    ))
1352}
1353
1354/// Collects watchable 3D source files (`.blend`, `.glb`, `.gltf`, `.obj`) under a file or directory path.
1355///
1356/// # Arguments
1357///
1358/// - `&Path` - Watched file or directory root.
1359///
1360/// # Returns
1361///
1362/// - `io::Result<Vec<PathBuf>>` - Sorted list of source 3D asset paths.
1363fn collect_watched_blender_sources(root: &Path) -> io::Result<Vec<PathBuf>> {
1364    if root.is_file() {
1365        return Ok(vec![root.to_path_buf()]);
1366    }
1367    if !root.is_dir() {
1368        return Err(Error::new(
1369            ErrorKind::NotFound,
1370            format!("{ERR_BLENDER_INPUT_MISSING}: {}", root.display()),
1371        ));
1372    }
1373    let mut found: Vec<PathBuf> = Vec::new();
1374    for entry_res in fs::read_dir(root)? {
1375        let entry: DirEntry = entry_res?;
1376        let path: PathBuf = entry.path();
1377        if !path.is_file() {
1378            continue;
1379        }
1380        let ext: String = path
1381            .extension()
1382            .and_then(OsStr::to_str)
1383            .map(str::to_ascii_lowercase)
1384            .unwrap_or_default();
1385        let ext_str: &str = ext.as_str();
1386        let supported: bool = ext_str == BLENDER_EXT_BLEND
1387            || ext_str == BLENDER_EXT_GLB
1388            || ext_str == BLENDER_EXT_GLTF
1389            || ext_str == BLENDER_EXT_OBJ;
1390        if supported {
1391            found.push(path);
1392        }
1393    }
1394    found.sort();
1395    Ok(found)
1396}
1397
1398/// Watches a `.blend`/`.glb`/`.gltf`/`.obj` file or directory, compiling `.euv3d` bundles to `--out` and pushing live updates over SSE.
1399///
1400/// # Arguments
1401///
1402/// - `BlenderWatchConfig` - Watched path, output directory, Live-Link port, poll cadence, and `--once` mode.
1403///
1404/// # Returns
1405///
1406/// - `io::Result<BlenderWatchReport>` - Summary of baked outputs and Live-Link endpoints.
1407pub fn run_blender_watch(config: BlenderWatchConfig) -> io::Result<BlenderWatchReport> {
1408    let watch_path: PathBuf = config.get_path().clone();
1409    let out_dir: PathBuf = config.get_out_dir().clone();
1410    fs::create_dir_all(&out_dir)?;
1411    let initial_sources: Vec<PathBuf> = collect_watched_blender_sources(&watch_path)?;
1412    #[cfg(feature = "update-server")]
1413    let mut live_handle: Option<BlenderLiveSyncHandle> = {
1414        let mut srv_cfg: BlenderLiveSyncConfig = BlenderLiveSyncConfig::default();
1415        let _: &mut BlenderLiveSyncConfig = srv_cfg
1416            .set_host(config.get_host().clone())
1417            .set_port(config.get_port())
1418            .set_out_dir(Some(out_dir.clone()));
1419        Some(start_blender_live_sync_server(srv_cfg)?)
1420    };
1421    let mut digests: BTreeMap<PathBuf, String> = BTreeMap::new();
1422    let mut baked_assets: Vec<BlenderBakeReport> = Vec::new();
1423    for src in initial_sources.iter() {
1424        let raw: Vec<u8> = fs::read(src)?;
1425        let digest: String = sha256_hex(&raw);
1426        let _: Option<String> = digests.insert(src.clone(), digest);
1427        let stem: String = src
1428            .file_stem()
1429            .and_then(OsStr::to_str)
1430            .filter(|name: &&str| !name.is_empty())
1431            .unwrap_or(BLENDER_DEFAULT_ASSET_STEM)
1432            .to_string();
1433        let out_euv3d: PathBuf = out_dir.join(format!("{stem}.{BLENDER_EXT_EUV3D}"));
1434        let mut bake_cfg: BlenderBakeConfig = BlenderBakeConfig::default();
1435        let _: &mut BlenderBakeConfig = bake_cfg
1436            .set_input(src.clone())
1437            .set_out_file(out_euv3d.clone())
1438            .set_blender_bin(config.try_get_blender_bin().clone())
1439            .set_lods(config.get_lods());
1440        let report: BlenderBakeReport = bake_blender_asset(&bake_cfg)?;
1441        #[cfg(feature = "update-server")]
1442        if let Some(handle) = live_handle.as_ref()
1443            && let Ok(baked_bytes) = fs::read(&out_euv3d)
1444        {
1445            let _: io::Result<BlenderLiveAssetNotice> =
1446                handle.state().record_asset(&stem, baked_bytes);
1447        }
1448        baked_assets.push(report);
1449    }
1450    #[cfg(feature = "update-server")]
1451    let (live_sync_url, events_url): (Option<String>, Option<String>) = live_handle
1452        .as_ref()
1453        .map(|handle: &BlenderLiveSyncHandle| {
1454            let base: String = handle.url();
1455            let ev: String = format!("{base}{BLENDER_ROUTE_EVENTS}");
1456            (Some(base), Some(ev))
1457        })
1458        .unwrap_or((None, None));
1459    #[cfg(not(feature = "update-server"))]
1460    let (live_sync_url, events_url): (Option<String>, Option<String>) = (None, None);
1461    let report: BlenderWatchReport = BlenderWatchReport {
1462        watch_path: watch_path.display().to_string(),
1463        out_dir: out_dir.display().to_string(),
1464        live_sync_url,
1465        events_url,
1466        baked_assets,
1467        once: config.get_once(),
1468    };
1469    if config.get_once() {
1470        #[cfg(feature = "update-server")]
1471        if let Some(mut handle) = live_handle.take() {
1472            handle.shutdown();
1473        }
1474        return Ok(report);
1475    }
1476    let poll_delay: Duration = Duration::from_millis(config.get_poll_ms().max(50));
1477    while watch_path.exists() {
1478        thread::sleep(poll_delay);
1479        #[cfg(feature = "update-server")]
1480        if let Some(handle) = live_handle.as_ref()
1481            && !handle.is_running()
1482        {
1483            break;
1484        }
1485        let Ok(current_sources) = collect_watched_blender_sources(&watch_path) else {
1486            continue;
1487        };
1488        for src in current_sources.into_iter() {
1489            let Ok(raw) = fs::read(&src) else {
1490                continue;
1491            };
1492            let next_sha: String = sha256_hex(&raw);
1493            if digests.get(&src).map(String::as_str) == Some(next_sha.as_str()) {
1494                continue;
1495            }
1496            let stem: String = src
1497                .file_stem()
1498                .and_then(OsStr::to_str)
1499                .filter(|name: &&str| !name.is_empty())
1500                .unwrap_or(BLENDER_DEFAULT_ASSET_STEM)
1501                .to_string();
1502            let out_euv3d: PathBuf = out_dir.join(format!("{stem}.{BLENDER_EXT_EUV3D}"));
1503            let mut bake_cfg: BlenderBakeConfig = BlenderBakeConfig::default();
1504            let _: &mut BlenderBakeConfig = bake_cfg
1505                .set_input(src.clone())
1506                .set_out_file(out_euv3d.clone())
1507                .set_blender_bin(config.try_get_blender_bin().clone())
1508                .set_lods(config.get_lods());
1509            if let Ok(baked_rep) = bake_blender_asset(&bake_cfg) {
1510                let _: Option<String> = digests.insert(src, next_sha);
1511                #[cfg(feature = "update-server")]
1512                if let Some(handle) = live_handle.as_ref()
1513                    && let Ok(baked_bytes) = fs::read(&out_euv3d)
1514                {
1515                    let _: io::Result<BlenderLiveAssetNotice> =
1516                        handle.state().record_asset(&stem, baked_bytes);
1517                }
1518                eprintln!(
1519                    "[euv-blender] rebaked {} -> {} ({} bytes)",
1520                    baked_rep.get_input_path(),
1521                    baked_rep.get_out_file(),
1522                    baked_rep.get_output_bytes()
1523                );
1524            }
1525        }
1526    }
1527    #[cfg(feature = "update-server")]
1528    if let Some(mut handle) = live_handle.take() {
1529        handle.shutdown();
1530    }
1531    Ok(report)
1532}
1533
1534/// Resolves a concrete bind `SocketAddr`, allocating an ephemeral port when `port == 0`.
1535///
1536/// # Arguments
1537///
1538/// - `&str` - Host address string.
1539/// - `u16` - Requested TCP port (`0` allocates an ephemeral port).
1540///
1541/// # Returns
1542///
1543/// - `io::Result<SocketAddr>` - Resolved concrete socket address.
1544#[cfg(feature = "update-server")]
1545fn resolve_blender_bind_addr(host: &str, port: u16) -> io::Result<SocketAddr> {
1546    if port != 0 {
1547        let raw: String = format!("{host}:{port}");
1548        return raw
1549            .parse::<SocketAddr>()
1550            .map_err(|err: AddrParseError| Error::new(ErrorKind::InvalidInput, err.to_string()));
1551    }
1552    let probe: TcpListener = TcpListener::bind(format!("{host}:0"))?;
1553    let addr: SocketAddr = probe.local_addr()?;
1554    drop(probe);
1555    Ok(addr)
1556}
1557
1558/// Registers `state` for `addr` in the per-listener Live-Link server registry.
1559///
1560/// # Arguments
1561///
1562/// - `SocketAddr` - Bound listener address.
1563/// - `Arc<BlenderLiveSyncState>` - Shared Live-Link daemon state.
1564#[cfg(feature = "update-server")]
1565pub(crate) fn register_blender_live_sync_state(addr: SocketAddr, state: Arc<BlenderLiveSyncState>) {
1566    let map: &RwLock<HashMap<SocketAddr, Arc<BlenderLiveSyncState>>> =
1567        BLENDER_LIVE_SYNC_REGISTRY.get_or_init(|| RwLock::new(HashMap::new()));
1568    if let Ok(mut guard) = map.write() {
1569        let _: Option<Arc<BlenderLiveSyncState>> = guard.insert(addr, state);
1570    }
1571}
1572
1573/// Removes `addr` from the per-listener Live-Link server registry upon shutdown.
1574///
1575/// # Arguments
1576///
1577/// - `SocketAddr` - Listener address being closed.
1578#[cfg(feature = "update-server")]
1579pub(crate) fn unregister_blender_live_sync_state(addr: SocketAddr) {
1580    if let Some(map) = BLENDER_LIVE_SYNC_REGISTRY.get()
1581        && let Ok(mut guard) = map.write()
1582    {
1583        let _: Option<Arc<BlenderLiveSyncState>> = guard.remove(&addr);
1584    }
1585}
1586
1587/// Resolves the `BlenderLiveSyncState` associated with the active Hyperlane client `Stream`.
1588///
1589/// # Arguments
1590///
1591/// - `&Stream` - Active Hyperlane client stream.
1592///
1593/// # Returns
1594///
1595/// - `Option<Arc<BlenderLiveSyncState>>` - Matching server state if registered.
1596#[cfg(feature = "update-server")]
1597pub(crate) fn resolve_blender_live_sync_state(
1598    stream: &Stream,
1599) -> Option<Arc<BlenderLiveSyncState>> {
1600    if let Ok(local_addr) = stream.get_local_addr()
1601        && let Some(map) = BLENDER_LIVE_SYNC_REGISTRY.get()
1602        && let Ok(guard) = map.read()
1603        && let Some(found) = guard.get(&local_addr)
1604    {
1605        return Some(Arc::clone(found));
1606    }
1607    DEFAULT_BLENDER_LIVE_SYNC_STATE
1608        .get()
1609        .and_then(|lock: &RwLock<Option<Arc<BlenderLiveSyncState>>>| lock.read().ok())
1610        .and_then(|guard: RwLockReadGuard<'_, Option<Arc<BlenderLiveSyncState>>>| guard.clone())
1611}
1612
1613/// Streams buffered `Last-Event-ID` replay frames followed by live `blender.delta` and `blender.asset` SSE events.
1614///
1615/// # Arguments
1616///
1617/// - `&mut Stream` - Active Hyperlane client stream.
1618/// - `&mut Context` - Active Hyperlane request context.
1619/// - `Vec<BlenderLiveEventRecord>` - Buffered events strictly newer than `Last-Event-ID`.
1620/// - `SseSubscription` - Live Hyperlane SSE subscription.
1621/// - `&SseConfig` - Heartbeat and reconnect configuration.
1622///
1623/// # Returns
1624///
1625/// - `Result<(), SseError>` - Completes cleanly when the stream closes or disconnects.
1626#[cfg(feature = "update-server")]
1627pub(crate) async fn serve_blender_sse_stream(
1628    stream: &mut Stream,
1629    ctx: &mut Context,
1630    replay_events: Vec<BlenderLiveEventRecord>,
1631    mut subscription: SseSubscription,
1632    config: &SseConfig,
1633) -> Result<(), SseError> {
1634    SseStream::prepare(ctx);
1635    apply_update_cors_headers(ctx);
1636    let _: &mut Response = ctx
1637        .get_mut_response()
1638        .set_header(CACHE_CONTROL, BLENDER_CACHE_NO_CACHE)
1639        .set_header(BLENDER_HDR_ACCEL_BUFFERING, BLENDER_VAL_NO_BUFFER);
1640    let head: ResponseData = ctx.get_mut_response().build_head();
1641    stream
1642        .try_send(&head)
1643        .await
1644        .map_err(|err: ResponseError| SseError::Transport(err.to_string()))?;
1645    let mut scratch: Vec<u8> = Vec::with_capacity(256);
1646    if config.get_retry_ms() > 0 {
1647        let hint: SseEvent =
1648            SseEvent::comment_only(BLENDER_SSE_CONNECTED_COMMENT).with_retry(config.get_retry_ms());
1649        SseStream::send_event_buffered(stream, &hint, &mut scratch).await?;
1650    }
1651    let mut last_sent_seq: u64 = 0;
1652    for rec in replay_events.into_iter() {
1653        let sse_ev: SseEvent = SseEvent::new(rec.get_json_data().clone())
1654            .with_id(rec.get_seq().to_string())
1655            .with_event(rec.get_event_name().clone());
1656        SseStream::send_event_buffered(stream, &sse_ev, &mut scratch).await?;
1657        if rec.get_seq() > last_sent_seq {
1658            last_sent_seq = rec.get_seq();
1659        }
1660    }
1661    let heartbeat_ms: u64 = config.get_heartbeat_ms();
1662    if heartbeat_ms == 0 {
1663        loop {
1664            match subscription.recv().await {
1665                Ok(event) => {
1666                    let ev_seq: u64 = event
1667                        .get_id()
1668                        .as_deref()
1669                        .and_then(|event_id_text: &str| event_id_text.parse::<u64>().ok())
1670                        .unwrap_or(u64::MAX);
1671                    if ev_seq <= last_sent_seq {
1672                        continue;
1673                    }
1674                    SseStream::send_event_buffered(stream, &event, &mut scratch).await?;
1675                    if ev_seq != u64::MAX {
1676                        last_sent_seq = ev_seq;
1677                    }
1678                }
1679                Err(SseError::Lagged(_)) => continue,
1680                Err(SseError::ChannelClosed) => return Ok(()),
1681                Err(err) => return Err(err),
1682            }
1683        }
1684    }
1685    let heartbeat_frame: Vec<u8> = SseEvent::comment_only(BLENDER_SSE_HEARTBEAT_COMMENT).encode();
1686    let mut ticker: Interval = interval(Duration::from_millis(heartbeat_ms));
1687    ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
1688    let _: Instant = ticker.tick().await.into_std();
1689    loop {
1690        select! {
1691            _ = ticker.tick() => {
1692                stream
1693                    .try_send(&heartbeat_frame)
1694                    .await
1695                    .map_err(|err: ResponseError| SseError::Transport(err.to_string()))?;
1696            }
1697            next = subscription.recv() => {
1698                match next {
1699                    Ok(event) => {
1700                        let ev_seq: u64 = event
1701                            .get_id()
1702                            .as_deref()
1703                            .and_then(|event_id_text: &str| event_id_text.parse::<u64>().ok())
1704                            .unwrap_or(u64::MAX);
1705                        if ev_seq <= last_sent_seq {
1706                            continue;
1707                        }
1708                        SseStream::send_event_buffered(stream, &event, &mut scratch).await?;
1709                        if ev_seq != u64::MAX {
1710                            last_sent_seq = ev_seq;
1711                        }
1712                    }
1713                    Err(SseError::Lagged(_)) => continue,
1714                    Err(SseError::ChannelClosed) => return Ok(()),
1715                    Err(err) => return Err(err),
1716                }
1717            }
1718        }
1719    }
1720}