@volter/blender-engine 0.1.131 → 0.1.132

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -129,6 +129,7 @@ export interface BlenderEngineOptions {
129
129
  * answered as a whole frame is.
130
130
  */
131
131
  export interface SessionAsk {
132
+ evaluation?: 'render';
132
133
  checkpoint?: string;
133
134
  frame?: unknown;
134
135
  hold?: unknown;
@@ -179,6 +179,9 @@ export interface FileListSnapshot {
179
179
  }
180
180
 
181
181
  export interface CaptureRequest {
182
+ /** Geometry was exported from the render engine's RENDER depsgraph. It belongs
183
+ * to this capture alone and must never replace the live viewport frame. */
184
+ evaluation?: 'render';
182
185
  /** A viewport screenshot's bound, the longer side of a square frame.
183
186
  * Absent on a render, which states its exact pixel dimensions instead. */
184
187
  size?: number;
@@ -33,7 +33,7 @@ type Request = DistributiveOmit<WorkerRequest, 'id'>;
33
33
 
34
34
  export interface BlenderRuntimeOptions {
35
35
  /** Stage one verified mesh/image without replacing the displayed frame. */
36
- stage?(part: { session: string; revision: number; abort?: boolean; mesh?: string; image?: string; piece?: unknown }): Promise<void> | void;
36
+ stage?(part: { session: string; revision: number; evaluation?: 'render'; abort?: boolean; mesh?: string; image?: string; piece?: unknown }): Promise<void> | void;
37
37
  /** Operation-only diagnostics, never request payloads. The optional observer
38
38
  * must not affect work, even if it throws. End calls balance overlapping work. */
39
39
  work?(label: string): () => void;
@@ -645,7 +645,7 @@ export class BlenderRuntime {
645
645
  }
646
646
 
647
647
  readonly #frameStream = new FrameStreamReader();
648
- #stagedIdentity: { session: string; revision: number } | null = null;
648
+ #stagedIdentity: { session: string; revision: number; evaluation?: 'render' } | null = null;
649
649
  #discardStagedFrame(): void {
650
650
  this.#frameStream.reset();
651
651
  const part = this.#stagedIdentity; this.#stagedIdentity = null;
@@ -661,13 +661,13 @@ export class BlenderRuntime {
661
661
  try {
662
662
  const decoded = await this.#frameStream.accept(reply.chunk);
663
663
  if (decoded) {
664
- const value = decoded.value as ({ op: 'stage'; session: string; revision: number } | Omit<Extract<WorkerReply, { op: 'present' }>, 'id'>);
664
+ const value = decoded.value as ({ op: 'stage'; session: string; revision: number; evaluation?: 'render' } | Omit<Extract<WorkerReply, { op: 'present' }>, 'id'>);
665
665
  if (value.op === 'present') {
666
666
  await this.#receive({ ...value, id: reply.id } as WorkerReply);
667
667
  return;
668
668
  }
669
669
  if (value.op !== 'stage' || !this.#options.stage) throw new Error('The presenter does not support staged Blender frames');
670
- this.#stagedIdentity = { session: value.session, revision: value.revision };
670
+ this.#stagedIdentity = { session: value.session, revision: value.revision, ...(value.evaluation ? { evaluation: value.evaluation } : {}) };
671
671
  await this.#options.stage(value);
672
672
  }
673
673
  this.#worker.postMessage({ op: 'present-result', id: reply.id } satisfies WorkerRequest);
@@ -708,7 +708,7 @@ export class BlenderRuntime {
708
708
  // true the moment the frame arrives. A presenter that refuses the frame
709
709
  // has not un-modelled it.
710
710
  const frame = reply.frame as { session?: unknown; revision?: unknown } | null;
711
- if (typeof frame?.session === 'string' && typeof frame.revision === 'number')
711
+ if (reply.capture?.evaluation !== 'render' && typeof frame?.session === 'string' && typeof frame.revision === 'number')
712
712
  this.#presented = { session: frame.session, revision: frame.revision };
713
713
  const end = this.#work('presenting worker frame');
714
714
  try {
@@ -1085,7 +1085,10 @@ def material_graph(material):
1085
1085
  if surface is None or surface.bl_idname not in _GRAPH_SURFACES:
1086
1086
  return None
1087
1087
  sockets = [surface.inputs[name] for name in _GRAPH_SURFACES[surface.bl_idname]]
1088
- if not any(_links_into(s) for s in sockets):
1088
+ # Emission reflects no light even when its inputs are constants. The
1089
+ # reduced MeshPhysicalMaterial otherwise adds diffuse/specular response
1090
+ # to it (including a black Emission used as an unlit control).
1091
+ if surface.bl_idname != "ShaderNodeEmission" and not any(_links_into(s) for s in sockets):
1089
1092
  return None
1090
1093
  # The door is quiet about a material whose graph ships, so a linked input
1091
1094
  # the graph does not carry is named here.
@@ -1480,7 +1483,7 @@ class Session:
1480
1483
 
1481
1484
  # -- the export
1482
1485
 
1483
- def _export(self):
1486
+ def _export(self, depsgraph=None):
1484
1487
  """THE EXPORT IS THE C++ DOOR (`bpy_web_export.cc`).
1485
1488
 
1486
1489
  One call evaluates the scene, walks the depsgraph's own update record
@@ -1497,14 +1500,14 @@ class Session:
1497
1500
  bones and the active vertex group's weights (`_armatures`,
1498
1501
  `_weights`). All per-scene, none of them geometry.
1499
1502
  """
1500
- scene = bpy.context.scene
1503
+ scene = depsgraph.scene if depsgraph is not None else bpy.context.scene
1501
1504
  graphs = material_graphs(scene)
1502
1505
  _mark("export:graphs")
1503
1506
  # An IMAGE EMPTY's picture travels with the graphs' images: the overlay draws it
1504
1507
  # (`overlay_empty.hh` `image_sync`).
1505
1508
  empty_images = {obj.data.name for obj in scene.objects
1506
1509
  if obj.type == "EMPTY" and obj.empty_display_type == "IMAGE" and obj.data is not None}
1507
- options = {"session": self.session, "evaluate": True, "known": self._known, "instance_sources": True,
1510
+ options = {"session": self.session, "evaluate": depsgraph is None, "known": self._known, "instance_sources": True,
1508
1511
  "graph_materials": sorted(graphs),
1509
1512
  "graph_images": sorted({i for g in graphs.values() for i in g["images"]} | empty_images),
1510
1513
  "graph_generated": sorted(n for n, g in graphs.items() if g["generated"])}
@@ -1563,7 +1566,7 @@ class Session:
1563
1566
  # A MANUAL TEXTURE SPACE, which Generated coordinates map through; the
1564
1567
  # automatic one is the evaluated bounds the presenter already holds.
1565
1568
  if graphs:
1566
- depsgraph = bpy.context.evaluated_depsgraph_get()
1569
+ depsgraph = depsgraph if depsgraph is not None else bpy.context.evaluated_depsgraph_get()
1567
1570
  # BY NAME THROUGH ONE MAP: `scene.objects.get` searches the collection linearly, so a
1568
1571
  # lookup per row was quadratic -- measured on the Stoneguard file (11,702 rows): 11,343
1569
1572
  # calls, 14.4 s of every present.
@@ -1598,7 +1601,8 @@ class Session:
1598
1601
  "roughness": float(material.roughness),
1599
1602
  "metallic": float(material.metallic),
1600
1603
  }
1601
- frame["instances"] = _depsgraph_placements(frame, bpy.context.evaluated_depsgraph_get())
1604
+ graph = depsgraph if depsgraph is not None else bpy.context.evaluated_depsgraph_get()
1605
+ frame["instances"] = _depsgraph_placements(frame, graph)
1602
1606
  frame["world"] = draw_world(scene)
1603
1607
  frame["cameras"] = {
1604
1608
  obj.name: draw_camera(obj) for obj in scene.objects if obj.type == "CAMERA"
@@ -1610,7 +1614,7 @@ class Session:
1610
1614
  render = scene.render
1611
1615
  frame["camera_view"] = {
1612
1616
  "scene_camera": scene.camera.name if scene.camera is not None else None,
1613
- "view_layer_cameras": [o.name for o in bpy.context.view_layer.objects if o.type == "CAMERA"],
1617
+ "view_layer_cameras": [o.name for o in graph.view_layer.objects if o.type == "CAMERA"],
1614
1618
  "aspect": (render.resolution_x * render.pixel_aspect_x) / max(render.resolution_y * render.pixel_aspect_y, 1e-6),
1615
1619
  }
1616
1620
  # THE 3D CURSOR, `Scene.cursor`: where Blender's own "to 3D Cursor"
@@ -1620,7 +1624,7 @@ class Session:
1620
1624
  frame["cursor"] = [[float(v) for v in row] for row in scene.cursor.matrix]
1621
1625
  # THE OVERLAYS, after the door's frame stands: `_weights` reads the
1622
1626
  # mesh's own revision out of it (see there), so it cannot run before.
1623
- view_layer = bpy.context.view_layer
1627
+ view_layer = graph.view_layer
1624
1628
  # THE VIEWPORT'S SUBJECT LINE and the units its grid step is named in: Blender composes
1625
1629
  # both from the scene, so they come from here (`_subject_line`).
1626
1630
  frame["subject"] = _subject_line(scene, view_layer)
@@ -1665,12 +1669,12 @@ class Session:
1665
1669
  self._known.clear()
1666
1670
  return self._present(capture)
1667
1671
 
1668
- def _present(self, capture=None):
1672
+ def _present(self, capture=None, depsgraph=None):
1669
1673
  known = dict(self._known)
1670
1674
  _mark("present:before")
1671
- frame = self._export()
1675
+ frame = self._export(depsgraph)
1672
1676
  _mark("present:exported")
1673
- pulled = self._pull(frame)
1677
+ pulled = self._pull(frame, render=depsgraph is not None)
1674
1678
  _mark("present:pulled")
1675
1679
  self._drop_unreachable_textures(frame)
1676
1680
  # WHAT THIS FRAME SHIPPED, for the session's own accounting: the ids
@@ -1729,7 +1733,7 @@ class Session:
1729
1733
  self._reconcile_with_presenter(answer, frame)
1730
1734
  return answer
1731
1735
 
1732
- def _pull(self, frame):
1736
+ def _pull(self, frame, render=False):
1733
1737
  """THE PULL, one datablock at a time, as Hydra's render delegate pulls each prim's data
1734
1738
  during Sync after the scene index's notice (`HydraSceneIndex::populate`). The door named
1735
1739
  the changed meshes and pictures as deferred; the worker first copies the frame's own
@@ -1743,9 +1747,9 @@ class Session:
1743
1747
  anything was pulled; the worker then presents the frame with its pieces."""
1744
1748
  meshes = [key for key, mesh in frame["meshes"].items() if mesh.get("deferred")]
1745
1749
  images = [name for name, image in frame["images"].items() if image.get("deferred")]
1746
- if not meshes and not images:
1750
+ if not meshes and not images and not render:
1747
1751
  return False
1748
- _asked({"hold": frame})
1752
+ _asked({"hold": frame, **({"evaluation": "render"} if render else {})})
1749
1753
  options = {"buffer_path": EXPORT_BUFFER_PATH} if EXPORT_BUFFER_PATH else {}
1750
1754
  for kind, keys, door in (("mesh", meshes, _blender_web.export_mesh),
1751
1755
  ("image", images, _blender_web.export_image)):
@@ -1765,6 +1769,20 @@ class Session:
1765
1769
  _asked({kind: key, "piece": piece[kind]})
1766
1770
  return True
1767
1771
 
1772
+ def photograph(self, depsgraph, capture):
1773
+ """Render evaluation owns different geometry and visibility than a viewport.
1774
+ Keep its native revisions, deferred pulls and presenter separate for the
1775
+ entire blocking capture, and restore the authoring export in finally."""
1776
+ if not hasattr(_blender_web, "begin_render_export"):
1777
+ raise RuntimeError("This Blender artifact has no render-evaluated export; update the artifact and its corresponding source")
1778
+ _blender_web.begin_render_export(depsgraph)
1779
+ try:
1780
+ rendering = Session()
1781
+ rendering.session = "%s:render:%d" % (self.session, time.time_ns())
1782
+ return rendering._present({**capture, "evaluation": "render"}, depsgraph)
1783
+ finally:
1784
+ _blender_web.end_render_export()
1785
+
1768
1786
  def _send_encoded_image(self, key, deferred):
1769
1787
  """A PICTURE AS ITS FILE'S OWN BYTES, when that is exactly what the frame would carry.
1770
1788
 
@@ -2336,8 +2354,8 @@ def _photograph(depsgraph, width, height, linear=False):
2336
2354
  # result is what a render leaves, and it holds scene-linear pixels.
2337
2355
  if linear:
2338
2356
  render["linear"] = True
2339
- answer = SESSION.present(
2340
- {"position": position, "target": target, "up": up, "render": render}
2357
+ answer = SESSION.photograph(
2358
+ depsgraph, {"position": position, "target": target, "up": up, "render": render}
2341
2359
  )
2342
2360
  if not isinstance(answer, dict) or "base64" not in answer:
2343
2361
  raise RuntimeError("The renderer did not answer with a photograph")
@@ -14,6 +14,7 @@
14
14
  * built from the mesh's texture space (`orcoAttribute`).
15
15
  */
16
16
  import * as THREE from 'three';
17
+ import {ISLAND_RANDOM_ATTRIBUTE} from './blender-island-random';
17
18
  import {presenterChanged} from './blender-presenter-change';
18
19
  import {attributeVarying, type CompiledGraph, rampTexture, uvVarying} from './blender-node-graph';
19
20
  import {graphAttributeName} from './blender-runtime-geometry';
@@ -458,7 +459,7 @@ varying vec3 vBlenderObjectNormal;
458
459
  varying vec3 vBlenderWorldPosition;
459
460
  varying vec3 vBlenderWorldNormal;
460
461
  varying vec3 vBlenderOrco;
461
- ${compiled.attributes.map(n => `varying vec4 ${attributeVarying(n)};`).join('\n')}
462
+ ${compiled.attributes.map(n => `${n===ISLAND_RANDOM_ATTRIBUTE?'flat ':''}varying vec4 ${attributeVarying(n)};`).join('\n')}
462
463
  ${compiled.uvs.map(n => `varying vec2 ${uvVarying(n)};`).join('\n')}`;
463
464
  const attributes = compiled.attributes.map(n => `attribute vec4 ${graphAttributeName(n)};`).join('\n');
464
465
  shader.vertexShader = `attribute vec3 blenderOrco;\n${attributes}\n${varyings}\n${shader.vertexShader}`.replace(
@@ -0,0 +1,41 @@
1
+ /* SPDX-FileCopyrightText: 2011-2022 Blender Foundation
2
+ * SPDX-License-Identifier: Apache-2.0 */
3
+ /** Cycles' attr_create_random_per_island, util/disjoint_set.h and
4
+ * util/hash.h (Blender Foundation, Apache-2.0). Connectivity uses the
5
+ * evaluated mesh's STORED edge order and union-by-rank representative,
6
+ * including loose edges. It is independent of draw/UV/normal splitting. */
7
+ export const ISLAND_RANDOM_ATTRIBUTE='.cycles.random_per_island';
8
+
9
+ function hashUint(value:number):number {
10
+ let a=(0xdeadbeef+17+value)>>>0,b=(0xdeadbeef+17)>>>0,c=b;
11
+ const rotate=(x:number,n:number)=>(x<<n)|(x>>>(32-n));
12
+ c=((c^b)-rotate(b,14))>>>0;a=((a^c)-rotate(c,11))>>>0;
13
+ b=((b^a)-rotate(a,25))>>>0;c=((c^b)-rotate(b,16))>>>0;
14
+ a=((a^c)-rotate(c,4))>>>0;b=((b^a)-rotate(a,14))>>>0;
15
+ c=((c^b)-rotate(b,24))>>>0;
16
+ // Native converts uint to float BEFORE the float reciprocal/multiply.
17
+ return Math.fround(Math.fround(c)*Math.fround(1/Math.fround(0xffffffff)));
18
+ }
19
+
20
+ export function cyclesIslandRandom(vertexCount:number,edges:Iterable<readonly [number,number]>):Float32Array {
21
+ const parents=Uint32Array.from({length:vertexCount},(_,i)=>i),ranks=new Uint8Array(vertexCount);
22
+ const find=(x:number):number=>{
23
+ let root=x;while(parents[root]!==root)root=parents[root]!;
24
+ while(parents[x]!==root){const parent=parents[x]!;parents[x]=root;x=parent;}
25
+ return root;
26
+ };
27
+ for(const [x,y] of edges) {
28
+ if(x<0 || y<0 || x>=vertexCount || y>=vertexCount || !Number.isInteger(x) || !Number.isInteger(y))
29
+ throw new Error('Island connectivity references a missing Blender vertex');
30
+ let a=find(x),b=find(y);if(a===b)continue;
31
+ if(ranks[a]!<ranks[b]!)[a,b]=[b,a];
32
+ parents[b]=a;if(ranks[a]===ranks[b])ranks[a]=ranks[a]!+1;
33
+ }
34
+ const result=new Float32Array(vertexCount);
35
+ for(let i=0;i<vertexCount;i++)result[i]=hashUint(find(i));
36
+ return result;
37
+ }
38
+
39
+ export function* storedMeshEdges(edges:Uint32Array):Iterable<readonly [number,number]> {
40
+ for(let i=0;i<edges.length;i+=2)yield [edges[i]!,edges[i+1]!];
41
+ }
@@ -25,6 +25,7 @@ import * as THREE from 'three';
25
25
  import {z} from 'zod';
26
26
  import {BLENDER_NODE_GLSL, BLENDER_NODE_GLSL_PRELUDE} from './blender-node-glsl.generated';
27
27
  import {graphAttributeName} from './blender-runtime-geometry';
28
+ import {ISLAND_RANDOM_ATTRIBUTE} from './blender-island-random';
28
29
 
29
30
  const scalar = z.number().finite();
30
31
  const gpuType = z.enum(['float', 'vec2', 'vec3', 'vec4']);
@@ -436,6 +437,13 @@ class Compiler {
436
437
  if (!node) throw new Error(`The graph links to ${key}, which it does not carry`);
437
438
  if (node.type === 'ShaderNodeParticleInfo' && node.outputs[index]?.id !== 'Random')
438
439
  throw new Error(`Particle Info output ${node.outputs[index]?.id ?? index} is not compiled by the presenter`);
440
+ // EEVEE's node_geometry returns zero here; reference rendering uses
441
+ // Cycles' evaluated per-island attribute instead. Keep it face constant.
442
+ if(node.type==='ShaderNodeNewGeometry' && node.outputs[index]?.id==='Random Per Island') {
443
+ this.s.attributes.add(ISLAND_RANDOM_ATTRIBUTE);
444
+ this.s.structure.push(['cycles-island',key,index]);
445
+ return convert(`${attributeVarying(ISLAND_RANDOM_ATTRIBUTE)}.x`,'float',to);
446
+ }
439
447
  const outputs = this.node(key, node);
440
448
  const output = outputs[index];
441
449
  if (!output) throw new Error(`${key} has no output ${index}`);
@@ -19,6 +19,7 @@ import * as THREE from 'three';
19
19
  import { customCornerNormals, type Normal } from './blender-corner-normals';
20
20
  import { ATTRIBUTE_LAYOUT, type MeshColumns } from './blender-frame-columns';
21
21
  import { triangulatePolygon } from './blender-triangulate';
22
+ import {cyclesIslandRandom,ISLAND_RANDOM_ATTRIBUTE,storedMeshEdges} from './blender-island-random';
22
23
 
23
24
  type MeshData = {
24
25
  v: [number, number, number][];
@@ -43,7 +44,8 @@ export interface DrawArrays {
43
44
  uvLayers?: {name: string; data: Float32Array}[] | undefined;
44
45
  /** The mesh's generic attribute layers a material's Attribute or Color
45
46
  * Attribute node can read, four floats per drawn vertex as EEVEE loads them
46
- * (`graphAttributeLayers`). */
47
+ * (`graphAttributeLayers`). The derived Cycles island layer stores one
48
+ * scalar per drawn vertex rather than an authored float4. */
47
49
  attributeLayers?: {name: string; data: Float32Array}[] | undefined;
48
50
  /** Per drawn vertex, a deformed mesh's Generated coordinates (0..1), or
49
51
  * null when the positions are undeformed and orco derives from them. */
@@ -294,7 +296,11 @@ export function geometryFromDrawArrays(
294
296
  }
295
297
  geometry.userData['blenderUvChannels'] = channels;
296
298
  for (const layer of arrays.attributeLayers ?? [])
297
- geometry.setAttribute(graphAttributeName(layer.name), new THREE.BufferAttribute(layer.data, 4));
299
+ // Engine-derived island values use one float, while ordinary Blender
300
+ // material attributes retain EEVEE's float4 storage. Snapshots preserve
301
+ // the same name/stride, without inventing an authored mesh attribute.
302
+ geometry.setAttribute(graphAttributeName(layer.name), new THREE.BufferAttribute(layer.data,
303
+ layer.name===ISLAND_RANDOM_ATTRIBUTE?1:4));
298
304
  geometry.userData['blenderAttributes'] = (arrays.attributeLayers ?? []).map(layer => layer.name);
299
305
  if (arrays.orco) {
300
306
  geometry.setAttribute('blenderOrco', new THREE.BufferAttribute(arrays.orco, 3));
@@ -419,7 +425,7 @@ function drawNativeColumns(c: MeshColumns, hash: string): DrawArrays {
419
425
 
420
426
  /** The worker's door: the mesh store's columns, drawn into buffers. */
421
427
  export function drawArraysFromColumns(c: MeshColumns, hash: string): DrawArrays {
422
- if (c.cornerTri && c.cornerNormal) return drawNativeColumns(c, hash);
428
+ if (c.cornerTri && c.cornerNormal) return withIslandRandom(drawNativeColumns(c, hash),c.co.length/3,storedMeshEdges(c.edge));
423
429
  const nv = c.co.length / 3;
424
430
  const maps = c.attributes.filter((a) => a.type === 'FLOAT2' && a.domain === 'CORNER');
425
431
  const mapName = c.renderUv ?? c.activeUv ?? maps[0]?.name;
@@ -482,7 +488,15 @@ export function drawArraysFromColumns(c: MeshColumns, hash: string): DrawArrays
482
488
  attributeLayers: graphAttributeLayers(c.attributes, data => data as ArrayLike<number>),
483
489
  };
484
490
  if (map && ATTRIBUTE_LAYOUT.FLOAT2.size !== 2) throw new Error('FLOAT2 layout');
485
- return { ...drawCore(view), hash };
491
+ return {...withIslandRandom(drawCore(view),nv,edges),hash};
492
+ }
493
+
494
+ function withIslandRandom<T extends Omit<DrawArrays,'hash'>>(arrays:T,vertexCount:number,
495
+ edges:Iterable<readonly [number,number]>):T {
496
+ const native=cyclesIslandRandom(vertexCount,edges);
497
+ const data=Float32Array.from(arrays.sourceVertex,vertex=>native[vertex]!);
498
+ arrays.attributeLayers=[...(arrays.attributeLayers??[]),{name:ISLAND_RANDOM_ATTRIBUTE,data}];
499
+ return arrays;
486
500
  }
487
501
 
488
502
  /** The boundary JSON door. */
@@ -546,5 +560,8 @@ export function drawRuntimeGeometry(data: MeshData): THREE.BufferGeometry {
546
560
  attributeLayers: graphAttributeLayers(data.attributes ?? [],
547
561
  values => (Array.from(values) as (number | number[])[]).flat()),
548
562
  };
549
- return geometryFromDrawArrays(drawCore(view));
563
+ // Native frames always supply stored edges. Legacy JSON without that
564
+ // order retains its old unsupported zero input rather than guessing IDs.
565
+ const arrays=drawCore(view);
566
+ return geometryFromDrawArrays(view.edges?withIslandRandom(arrays,vertices.length,view.edges):arrays);
550
567
  }
@@ -2421,6 +2421,40 @@ export class BlenderRuntimeView {
2421
2421
  };
2422
2422
  }
2423
2423
 
2424
+ /** Build a render-evaluated frame without ever publishing it to a viewport. */
2425
+ static forPhotograph(): BlenderRuntimeView {
2426
+ const view = new BlenderRuntimeView();
2427
+ view.photograph = true;
2428
+ return view;
2429
+ }
2430
+
2431
+ /** Transfer this render-only view to its capture owner. Its resources are
2432
+ * already independent, so a second geometry/texture copy is unnecessary. */
2433
+ takeCaptureSnapshot(): ReturnType<BlenderRuntimeView['captureSnapshot']> {
2434
+ if (!this.photograph || !this.frame) throw new Error('A render-evaluated frame is required');
2435
+ const source = this.frame;
2436
+ const effect = this.createWorldVolumePass();
2437
+ let disposed = false;
2438
+ return {
2439
+ effect, root: this.root, session: source.session, revision: source.revision,
2440
+ prepare: camera => {
2441
+ if (disposed) throw new Error('Blender capture snapshot is disposed');
2442
+ return this.setRendered(true, camera);
2443
+ },
2444
+ prepareDraw: (renderer, camera) => {
2445
+ if (disposed) throw new Error('Blender capture snapshot is disposed');
2446
+ return this.prepareDraw(camera, { interactive: false, height: renderer.domElement.height, renderer });
2447
+ },
2448
+ dispose: () => {
2449
+ if (disposed) return;
2450
+ disposed = true;
2451
+ effect?.dispose();
2452
+ this.dispose();
2453
+ this.root.removeFromParent();
2454
+ },
2455
+ };
2456
+ }
2457
+
2424
2458
  createWorldVolumePass(): WorldVolumePass | undefined {
2425
2459
  const medium = worldMedium(this.frame?.world);
2426
2460
  return medium ? new WorldVolumePass(medium) : undefined;
@@ -90,6 +90,22 @@ export function createPresenter(options: PresenterOptions = {}): Presenter {
90
90
  frame: unknown,
91
91
  description: unknown,
92
92
  capture?: CaptureRequest,
93
+ ): Promise<PresentAnswer> {
94
+ if (capture?.evaluation === 'render') {
95
+ const detached = BlenderRuntimeView.forPhotograph();
96
+ const captureScene = new THREE.Scene();
97
+ view.root.updateWorldMatrix(true, false);
98
+ detached.root.matrix.copy(view.root.matrixWorld);
99
+ captureScene.add(detached.root);
100
+ try { return await presentFrame(detached, captureScene, frame, description, capture); }
101
+ finally { detached.dispose(); detached.root.removeFromParent(); }
102
+ }
103
+ return presentFrame(view, scene, frame, description, capture);
104
+ }
105
+
106
+ async function presentFrame(
107
+ view: BlenderRuntimeView, scene: THREE.Scene, frame: unknown, description: unknown,
108
+ capture?: CaptureRequest,
93
109
  ): Promise<PresentAnswer> {
94
110
  const applied = view.applyFrame(frame) as { held?: unknown } | null | undefined;
95
111
  const held =
@@ -169,6 +185,7 @@ export function createPresenter(options: PresenterOptions = {}): Presenter {
169
185
  renderer.setClearColor(0, 0);
170
186
  }
171
187
  try {
188
+ view.prepareDraw(camera, { interactive: false, height, renderer });
172
189
  renderer.render(scene, camera);
173
190
  } finally {
174
191
  scene.background = background;
@@ -212,7 +212,7 @@ def _world(scene):
212
212
  }
213
213
 
214
214
 
215
- def _export():
215
+ def _export(depsgraph):
216
216
  """The C++ door's frame, with what the door does not describe merged in.
217
217
 
218
218
  `known` is ALWAYS EMPTY: this process keeps no record of what a presenter
@@ -221,7 +221,7 @@ def _export():
221
221
  """
222
222
  options = {
223
223
  "session": SESSION,
224
- "evaluate": True,
224
+ "evaluate": False,
225
225
  "known": {},
226
226
  "buffer_path": EXPORT_BUFFER_PATH,
227
227
  }
@@ -236,7 +236,7 @@ def _export():
236
236
  _REVISION[0] += 1
237
237
  frame["session"] = SESSION
238
238
  frame["revision"] = _REVISION[0]
239
- scene = bpy.context.scene
239
+ scene = depsgraph.scene
240
240
  frame["world"] = _world(scene)
241
241
  frame["volumes"] = {}
242
242
  # THE INSPECTION OVERLAYS ARE THE EDITOR'S, and a render hides them anyway.
@@ -249,8 +249,14 @@ def _export():
249
249
  return frame
250
250
 
251
251
 
252
- def _present(capture):
253
- answer = ask({"frame": _export(), "capture": capture})
252
+ def _present(depsgraph, capture):
253
+ if not hasattr(_blender_web, "begin_render_export"):
254
+ raise RuntimeError("This Blender artifact has no render-evaluated export")
255
+ _blender_web.begin_render_export(depsgraph)
256
+ try:
257
+ answer = ask({"frame": _export(depsgraph), "capture": {**capture, "evaluation": "render"}})
258
+ finally:
259
+ _blender_web.end_render_export()
254
260
  if isinstance(answer, dict) and answer.get("error"):
255
261
  raise RuntimeError(answer["error"])
256
262
  return answer
@@ -334,7 +340,7 @@ def _photograph(depsgraph, width, height, linear=False):
334
340
  if linear:
335
341
  render["linear"] = True
336
342
  answer = _present(
337
- {"position": position, "target": target, "up": up, "render": render}
343
+ depsgraph, {"position": position, "target": target, "up": up, "render": render}
338
344
  )
339
345
  if not isinstance(answer, dict) or "base64" not in answer:
340
346
  raise RuntimeError("The renderer did not answer with a photograph")
package/browser/worker.ts CHANGED
@@ -116,6 +116,7 @@ interface Copied {
116
116
  description: unknown;
117
117
  }
118
118
  interface PendingFrame {
119
+ evaluation?: 'render';
119
120
  session: string;
120
121
  revision: number;
121
122
  columns: Map<number, Copied>;
@@ -270,7 +271,7 @@ async function startBlender(project: string, document?: string): Promise<unknown
270
271
  const started = await startBlenderEngine({
271
272
  project,
272
273
  log,
273
- ask: async ({ frame, hold, mesh, image, piece, present, capture, saveDue, checkpoint }) => {
274
+ ask: async ({ frame, hold, mesh, image, piece, present, capture, saveDue, checkpoint, evaluation }) => {
274
275
  if (typeof checkpoint === 'string') { await loadCheckpoint?.(checkpoint); return {}; }
275
276
  if (!holder.engine) throw new Error('The Blender session presented before it started');
276
277
  // Save once after the whole command, never during a partial frame.
@@ -286,8 +287,8 @@ async function startBlender(project: string, document?: string): Promise<unknown
286
287
  // gets the whole frame at `present`.
287
288
  if (hold !== undefined) {
288
289
  const identity = hold as { session: string; revision: number };
289
- pending = { session: identity.session, revision: identity.revision, columns: await copyColumns(arena, hold), meshes: new Map(), images: new Map() };
290
- await streamToTab({ op: 'stage', session: identity.session, revision: identity.revision });
290
+ pending = { ...(evaluation ? { evaluation } : {}), session: identity.session, revision: identity.revision, columns: await copyColumns(arena, hold), meshes: new Map(), images: new Map() };
291
+ await streamToTab({ op: 'stage', evaluation, session: identity.session, revision: identity.revision });
291
292
  return {};
292
293
  }
293
294
  if (mesh !== undefined || image !== undefined) {
@@ -312,7 +313,7 @@ async function startBlender(project: string, document?: string): Promise<unknown
312
313
  description: await describeFrame(arena, piece),
313
314
  };
314
315
  }
315
- await streamToTab({ op: 'stage', session: pending.session, revision: pending.revision,
316
+ await streamToTab({ op: 'stage', evaluation: pending.evaluation, session: pending.session, revision: pending.revision,
316
317
  ...(mesh !== undefined ? { mesh } : { image }), piece: copied.typed });
317
318
  // Keep only the manifest and digest; the presenter already built this
318
319
  // resource, and the next pull may overwrite the engine arena.
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@volter/blender-engine",
3
3
  "author": "Volter AI, Inc.",
4
4
  "license": "GPL-3.0-or-later",
5
- "version": "0.1.131",
5
+ "version": "0.1.132",
6
6
  "publishConfig": {
7
7
  "access": "public"
8
8
  },
package/wasm/BUNDLE.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "blender": "5.2.0 LTS",
3
- "source": "434072350c0577eb155068d5a1b62bb45daf19f9",
3
+ "source": "5a3cb1250fc1fd7df59e3ff823949c06e52d9422",
4
4
  "upstream": "fbe6228777e7d9afefcd61a413844e790ae75db7",
5
5
  "sourceRepository": "https://github.com/volter-ai/blender",
6
- "sourceRecipe": "https://github.com/volter-ai/blender/blob/434072350c0577eb155068d5a1b62bb45daf19f9/build_files/emscripten/RELEASE.md",
6
+ "sourceRecipe": "https://github.com/volter-ai/blender/blob/5a3cb1250fc1fd7df59e3ff823949c06e52d9422/build_files/emscripten/RELEASE.md",
7
7
  "factoryEngine": "BLENDER_EEVEE",
8
8
  "files": {
9
9
  "blender_browser.js": "raw",
@@ -16,8 +16,8 @@
16
16
  "sha256": "d818e8d746bc62ebf810206ac564d2dc75dc645b3121f4a3919d13ecef11e419"
17
17
  },
18
18
  "blender_browser.wasm": {
19
- "bytes": 86344416,
20
- "sha256": "f5b988d30a9f29708254bc84600f7b88d9c9eb41af904b84c9f398d5c41595e4"
19
+ "bytes": 86351436,
20
+ "sha256": "d4c3a8002cb1686f3c5299e28bcbb356934bbe910f2485b2572032b115cf67bd"
21
21
  },
22
22
  "blender_browser.data": {
23
23
  "bytes": 52699590,
@@ -30,8 +30,8 @@
30
30
  "sha256": "d818e8d746bc62ebf810206ac564d2dc75dc645b3121f4a3919d13ecef11e419"
31
31
  },
32
32
  "blender_browser.wasm.br": {
33
- "bytes": 18611942,
34
- "sha256": "b415a2fce0f2d2f796a2a3362b38420df063866898cc04c61d4604c5caf13e0d"
33
+ "bytes": 18605311,
34
+ "sha256": "97e3bc2c772e9fd6da5a3e28086c1ee1dfd62b35ebdeb127a413b4bd5904031f"
35
35
  },
36
36
  "blender_browser.data.br": {
37
37
  "bytes": 8056485,
@@ -42,9 +42,9 @@
42
42
  "sha256": "4085e9336266cf66f061d4d5c962a5929cc96d5732c746b5c13ea05cd104a75b"
43
43
  }
44
44
  },
45
- "note": "Stoneguard c7/c14/c15 engine. Emscripten 6.0.5, Release -O3 objects and -O2 link. Portable native arm64 matrix reciprocal plus fused generic OpenSubdiv stencil and patch accumulation; bodice four-stage comparison 28/28 arrays exact. Full-scene comparison and memory scope recorded in provenance/stoneguard-memory.json. Historical battery absent; no full-battery or hosted acceptance claim. Rebuilt from the public instance-source commit with the same Emscripten 6.0.5, Release -O3 objects and -O2 link. All 6287 drawable Lone Monk placements resolve to 26 native source objects and 24 deferred mesh resources. Live raster rendering still differs from native Cycles; no full-scene visual parity claim. Rebuilt from the public evaluated-geometry identity commit with the same Emscripten 6.0.5 Release recipe. Distinct Array/Mirror/deformation outputs no longer borrow another object’s geometry. Native linked-input sharing and every deferred probe vertex are checked independently. Live raster illumination remains unoccluded environment lighting and differs substantially from native Cycles; no visual parity claim.",
45
+ "note": "Emscripten 6.0.5, Release -O3 objects and -O2 link, retained public build recipe and dependency licenses. Scoped render-evaluated export preserves render-only geometry and render-specific modifier results without replacing the viewport export state. Prior geometry identity and memory fixes remain. Full-scene Three versus Cycles rendering parity remains incomplete.",
46
46
  "callTrampoline": "CPython 3.13.13 is compiled with PY_CALL_TRAMPOLINE for Blender CPython slot arity casts. This applies to CPython dispatch, not arbitrary indirect calls.",
47
47
  "engineIds": "The session preserves the compiled native CYCLES engine. VOLTER_THREE selects the explicit raster presenter; BLENDER_EEVEE and BLENDER_WORKBENCH remain presentation engines.",
48
- "exportDoor": "The source-owned bpy_web_export.cc exports Principled physical inputs, normal images, eight named UV layers and evaluated corner normals, and takes graph_materials/graph_images/graph_generated (a graph-drawn shader mix reduced to the one Principled BSDF it reaches, graph images at the door revisions with every UDIM tile, orco for deformed meshes whose graph reads Generated coordinates). A frame can defer its changed meshes and pictures (defer) for the caller to pull one at a time (export_mesh, export_image), each call freeing the previous one's columns and a picture it decoded; an undo step keeps the revisions when Blender kept the depsgraph (session_undo); Blender's CPU subdivision descriptor is released once a mesh is read; the memory door reports malloc in-use and free. Datablock revisions are keyed by session_uid. writefile.cc writes one copy of the document per save in the browser build. CPU evaluators adopt stencil tables without cloning; browser subdivision descriptors are released immediately after CPU tessellation/deformation. Native evaluated corner triangles accompany corner normals. Consumed local conversion stencils are released before later UV channels are constructed. Caller-thread file-read, evaluated-object and subdivision checkpoints provide backpressure for resumable startup. Shared geometry revisions advance once per frame. Existing synchronous export remains available. Optional instance_sources exports stable evaluated collection and particle source meshes, including excluded library meshes and converted curves. Frame-local instance_geometry tokens verify Python placement metadata against the exported geometry and are consumed before presentation. Geometry resource identity preserves implicit input storage only for unmodified geometry and separates evaluated modifier/deformation outputs. Object and mesh resource keys have independent namespaces.",
48
+ "exportDoor": "The source-owned bpy_web_export.cc exports Principled physical inputs, normal images, eight named UV layers and evaluated corner normals, and takes graph_materials/graph_images/graph_generated (a graph-drawn shader mix reduced to the one Principled BSDF it reaches, graph images at the door revisions with every UDIM tile, orco for deformed meshes whose graph reads Generated coordinates). A frame can defer its changed meshes and pictures (defer) for the caller to pull one at a time (export_mesh, export_image), each call freeing the previous one's columns and a picture it decoded; an undo step keeps the revisions when Blender kept the depsgraph (session_undo); Blender's CPU subdivision descriptor is released once a mesh is read; the memory door reports malloc in-use and free. Datablock revisions are keyed by session_uid. writefile.cc writes one copy of the document per save in the browser build. CPU evaluators adopt stencil tables without cloning; browser subdivision descriptors are released immediately after CPU tessellation/deformation. Native evaluated corner triangles accompany corner normals. Consumed local conversion stencils are released before later UV channels are constructed. Caller-thread file-read, evaluated-object and subdivision checkpoints provide backpressure for resumable startup. Shared geometry revisions advance once per frame. Existing synchronous export remains available. Optional instance_sources exports stable evaluated collection and particle source meshes, including excluded library meshes and converted curves. Frame-local instance_geometry tokens verify Python placement metadata against the exported geometry and are consumed before presentation. Geometry resource identity preserves implicit input storage only for unmodified geometry and separates evaluated modifier/deformation outputs. Object and mesh resource keys have independent namespaces. Scoped begin_render_export/end_render_export reads the render engine depsgraph and isolates viewport revision, undo, deferred resource and image watcher state. Geometry resource identity preserves implicit input storage only for unmodified geometry and separates evaluated modifier/deformation outputs. Object and mesh resource keys have independent namespaces.",
49
49
  "preloadedPayload": "releasePreloadedFileData releases the JS preload buffer after session ready. The measured working payload exclusions are retained."
50
50
  }
Binary file