Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(texture): z-buffer occlusion from the mesh itself instead of pyrender's depth
nirholasbfced9e583b8
diff --git a/workers/texture/main.py b/workers/texture/main.pyindex 7c1bfe33d..f43bf1ffb 100644--- a/workers/texture/main.py+++ b/workers/texture/main.py@@ -383,13 +383,15 @@ def _load_mesh(url: str):# ── Depth rendering ─────────────────────────────────────────────────────────────-def _render_view_depth(mesh, view: tp.OrthographicView) -> tuple[Image.Image, np.ndarray]:- """Render one viewpoint's depth.-- Returns the ControlNet conditioning image (near bright, background black) and- the raw depth buffer in world units. The raw buffer is not a debug artifact:- back-projection needs it to reject texels that some nearer part of the mesh- hides from this camera, and it comes free with the render we already do.+def _render_view_depth(mesh, view: tp.OrthographicView) -> Image.Image:+ """Render one viewpoint as the ControlNet conditioning image.++ Near is bright, background black. Only the ordering of the values matters+ here, which is just as well: pyrender un-projects its depth buffer with the+ perspective formula whatever camera drew it, so under an orthographic camera+ the numbers are a monotonic but nonlinear remap of true depth. That is fine+ for conditioning and useless for geometry, which is why the occlusion test in+ texture_projection builds its own z-buffer instead of reusing this render."""import pyrender@@ -406,8 +408,7 @@ def _render_view_depth(mesh, view: tp.OrthographicView) -> tuple[Image.Image, npfinally:renderer.delete()- depth = np.asarray(depth, dtype=np.float32)- return Image.fromarray(tp.depth_to_control_image(depth)), depth+ return Image.fromarray(tp.depth_to_control_image(np.asarray(depth, dtype=np.float32)))# ── Texture generation ──────────────────────────────────────────────────────────@@ -446,7 +447,6 @@ def _project_texture_onto_uv(mesh,views: list[tp.OrthographicView],view_images: list[Image.Image],- depth_buffers: list[np.ndarray],texture_size: int,) -> Image.Image:"""Back-project the generated views onto the mesh's UV atlas.@@ -462,7 +462,6 @@ def _project_texture_onto_uv(views,[np.asarray(img.convert("RGB")) for img in view_images],texture_size,- depth_buffers=depth_buffers,)total = int(covered.sum())seen = int((weight > 0).sum())@@ -494,9 +493,7 @@ def _run_texturing(views = tp.canonical_views(sphere.center, sphere.radius, viewpoints, texture_size)log.info("Rendering %d depth maps at %dpx", len(views), texture_size)- rendered = [_render_view_depth(mesh, view) for view in views]- depth_maps = [image for image, _ in rendered]- depth_buffers = [buffer for _, buffer in rendered]+ depth_maps = [_render_view_depth(mesh, view) for view in views]log.info("Generating texture views with SDXL+ControlNet (material_class=%s)", material_class or "default")view_images = [@@ -505,7 +502,7 @@ def _run_texturing(]log.info("Projecting views onto UV atlas (%dpx)", texture_size)- texture_atlas = _project_texture_onto_uv(mesh, views, view_images, depth_buffers, texture_size)+ texture_atlas = _project_texture_onto_uv(mesh, views, view_images, texture_size)log.info("Baking textured GLB with metallic=%.2f roughness=%.2f", pbr["metallic"], pbr["roughness"])material = trimesh.visual.material.PBRMaterial(diff --git a/workers/texture/test_texture_projection.py b/workers/texture/test_texture_projection.pyindex 4d6758636..6b2368cab 100644--- a/workers/texture/test_texture_projection.py+++ b/workers/texture/test_texture_projection.py@@ -198,29 +198,61 @@ def test_back_facing_views_are_refused():print("ok surfaces turned away from a view take no colour from it")-def test_occluded_texels_are_refused_against_the_depth_buffer():+def _occluded_pair():+ """A back quad, and a nearer quad covering its left half from the front view.++ The back quad owns the top half of the atlas, the front quad the bottom+ half, so which texels each one contributed to is unambiguous.+ """+ back_pos = np.array([+ [-1.0, -1.0, 0.0], [1.0, -1.0, 0.0], [1.0, 1.0, 0.0], [-1.0, 1.0, 0.0],+ ], dtype=np.float32)+ front_pos = np.array([+ [-1.0, -1.0, 0.5], [0.0, -1.0, 0.5], [0.0, 1.0, 0.5], [-1.0, 1.0, 0.5],+ ], dtype=np.float32)+ positions = np.concatenate([back_pos, front_pos])+ normals = np.tile(np.array([0.0, 0.0, 1.0], dtype=np.float32), (8, 1))+ # v in [0.5, 1] is the back quad (atlas rows 0..31), v in [0, 0.5] the front.+ uv = np.array([+ [0.0, 0.5], [1.0, 0.5], [1.0, 1.0], [0.0, 1.0],+ [0.0, 0.0], [1.0, 0.0], [1.0, 0.5], [0.0, 0.5],+ ], dtype=np.float32)+ faces = np.array([[0, 1, 2], [0, 2, 3], [4, 5, 6], [4, 6, 7]], dtype=np.int64)+ return positions, normals, uv, faces+++def test_occluded_texels_are_refused():"""A texel hidden behind nearer geometry must not take that geometry's colour."""- positions, normals, uv, faces = _unit_plane()- size = 32+ positions, normals, uv, faces = _occluded_pair()+ size = 64view = _quad_view(0, size)image = np.full((size, size, 3), (10, 20, 30), dtype=np.uint8)- # The quad sits at z=0, so its depth from this camera is exactly `distance`.- # A buffer claiming a surface half a radius nearer over the left half of the- # frame means that half is hidden.- buffer = np.full((size, size), view.distance, dtype=np.float32)- buffer[:, : size // 2] = view.distance - view.radius * 0.5+ atlas, weight, covered = tp.project_views_to_uv(+ positions, normals, uv, faces, [view], [image], texture_size=size+ )- atlas, weight, _ = tp.project_views_to_uv(- positions, normals, uv, faces, [view], [image], texture_size=size,- depth_buffers=[buffer],+ back_half = weight[: size // 2]+ front_half = weight[size // 2:]+ # The back quad's left half sits behind the front quad, so it must stay+ # unpainted. The occluder's edge is only resolved to a z-buffer bin (here 2+ # atlas columns) plus the dilation around it, so the assertions skip a+ # 4-column band either side of the boundary rather than pretend the cut is+ # texel-exact.+ edge = 4+ hidden = back_half[:, : size // 2 - edge]+ visible = back_half[:, size // 2 + edge:]+ assert not hidden.any(), f"occluded region kept {int((hidden > 0).sum())} texels"+ assert (visible > 0).all(), "the unobstructed half of the back quad should be painted"+ assert (front_half[:, : size // 2 - edge] > 0).all(), "the occluder itself is visible"+ # Gap filling still leaves a complete atlas rather than black holes.+ assert (atlas == (10, 20, 30)).all()++ # With the gate off, the hidden region takes colour it should never see.+ _, weight_no_gate, _ = tp.project_views_to_uv(+ positions, normals, uv, faces, [view], [image], texture_size=size, occlude=False)- left = weight[:, : size // 2 - 1]- right = weight[:, size // 2 + 1:]- assert not left.any(), f"occluded half kept {int((left > 0).sum())} texels"- assert (right > 0).all(), "visible half should be fully painted"- # Gap filling still leaves a complete atlas, sourced from the visible half.- assert (atlas[:, : size // 2 - 1] == (10, 20, 30)).all()+ assert (weight_no_gate[: size // 2, : size // 2 - edge] > 0).all()print("ok occlusion gate refuses texels hidden behind nearer geometry")@@ -264,7 +296,7 @@ TESTS = [test_back_projection_lands_the_view_pixels_where_they_belong,test_a_view_rendered_at_another_size_still_lands_correctly,test_back_facing_views_are_refused,- test_occluded_texels_are_refused_against_the_depth_buffer,+ test_occluded_texels_are_refused,test_grazing_views_lose_to_face_on_views,test_gap_fill_never_leaves_a_hole,]diff --git a/workers/texture/texture_projection.py b/workers/texture/texture_projection.pyindex 11f29b13f..733662762 100644--- a/workers/texture/texture_projection.py+++ b/workers/texture/texture_projection.py@@ -47,10 +47,11 @@ FACING_EXPONENT = 2.0# to. Those samples are dropped rather than down-weighted.MIN_FACING = 0.12-# Depth-test slack, as a fraction of the mesh's bounding radius. Absorbs the-# rasterization error between the GPU depth buffer and the analytic projection of-# a texel's position, while staying far tighter than the gap between an arm and-# the torso behind it.+# Floor on the depth-test slack, as a fraction of the mesh's bounding radius.+# Absorbs the quantisation between a texel's analytic depth and the binned+# z-buffer it is tested against, while staying far tighter than the gap between+# an arm and the torso behind it. Tilted surfaces get more than this floor, see+# the slope-scaled bias in project_views_to_uv.DEPTH_TOLERANCE_FRAC = 0.01_WORLD_UP = np.array([0.0, 1.0, 0.0])@@ -280,6 +281,62 @@ def rasterize_uv(return pos_map, nrm_map, covered+def occlusion_buffer_size(view_size: int) -> int:+ """Resolution of the occlusion z-buffer for a view of `view_size` pixels.++ Deliberately coarser than the view. The occluders are surface samples taken+ at atlas texel density, and where the atlas is sparser than the view (any UV+ island scaled down relative to its screen area) one sample per pixel leaves+ the buffer full of holes: two surfaces then interleave into alternating+ pixels and neither ever sees the other. Binning several samples together is+ what lets the near surface win. The cost is precision at depth+ discontinuities, which the slope-scaled bias and the gap fill absorb.+ """+ return max(32, min(512, int(view_size) // 2))+++def view_depth_buffer(+ view: OrthographicView, points: np.ndarray, resolution: Optional[int] = None+) -> np.ndarray:+ """Nearest surface depth per buffer bin, z-buffered from `points`.++ Built here rather than read back from the render for one specific reason:+ pyrender converts its depth buffer with the perspective un-projection+ formula whatever camera drew it, so for an orthographic camera the numbers+ it returns are a nonlinear remap of the real depth. Comparing an analytic+ depth against them rejects almost every texel, and the symptom is not a+ wrong texture but a job that fails with "no view could see the surface".++ The occluders are the same rasterized surface samples being tested, so a+ sample is always its own nearest hit and the comparison degenerates to+ "is anything else in front of me". `inf` means no sample landed on that+ pixel, which is read as nothing occluding.+ """+ size = int(resolution or view.size)+ pixels, depth = view.project(points)+ u, v = pixels[:, 0], pixels[:, 1]+ scale = size / float(view.size)+ x = np.rint(u * scale).astype(np.int64)+ y = np.rint(v * scale).astype(np.int64)+ inside = (x >= 0) & (x < size) & (y >= 0) & (y < size) & (depth > 0)++ buffer = np.full(size * size, np.inf, dtype=np.float32)+ if inside.any():+ np.minimum.at(buffer, y[inside] * size + x[inside], depth[inside].astype(np.float32))+ buffer = buffer.reshape(size, size)++ # Spread each hit into its neighbouring bins. Sample density is uneven (a UV+ # island scaled down relative to its screen area contributes fewer samples+ # than it covers bins), so an occluder can miss a bin the surface behind it+ # does hit, and that one row of holes is enough to let a hidden strip take+ # colour from a view that cannot see it. Dilating makes the test err toward+ # refusing a texel near an occluder's edge, which the gap fill then paints+ # from its neighbours.+ from scipy.ndimage import minimum_filter++ return minimum_filter(buffer, size=3, mode="nearest")++def fill_gaps(canvas: np.ndarray, filled: np.ndarray) -> np.ndarray:"""Flood every unwritten texel with its nearest written neighbour.@@ -306,7 +363,7 @@ def project_views_to_uv(views: Sequence[OrthographicView],images: Sequence[np.ndarray],texture_size: int,- depth_buffers: Optional[Sequence[Optional[np.ndarray]]] = None,+ occlude: bool = True,) -> tuple[np.ndarray, np.ndarray, np.ndarray]:"""Back-project the generated views onto the UV atlas.@@ -315,18 +372,15 @@ def project_views_to_uv(facing the camera, nothing nearer along the ray) are averaged with weightcos(angle) ** FACING_EXPONENT.- `depth_buffers` are the rendered depth maps of the same views, in the same- order, in world units with 0 meaning "nothing hit". Passing them enables the- occlusion gate; passing None for a view (or for the whole sequence) keeps- only the facing gate, which is correct for a convex mesh and lets the- geometry be tested without a GPU rasterizer.+ `occlude` builds a z-buffer per view (see view_depth_buffer) so a texel on a+ surface hidden behind another part of the mesh takes no colour from the view+ that cannot actually see it. Turning it off is only correct for a convex+ mesh, where nothing can hide anything.Returns (atlas uint8 (S, S, 3), weight float32 (S, S), covered bool (S, S))."""if len(views) != len(images):raise ValueError("views and images must be the same length")- if depth_buffers is not None and len(depth_buffers) != len(views):- raise ValueError("depth_buffers must match the number of views")pos_map, nrm_map, covered = rasterize_uv(positions, normals, uv, faces, texture_size)if not covered.any():@@ -337,7 +391,7 @@ def project_views_to_uv(accum = np.zeros((flat_pos.shape[0], 3), dtype=np.float32)weight = np.zeros(flat_pos.shape[0], dtype=np.float32)- for idx, (view, image) in enumerate(zip(views, images)):+ for view, image in zip(views, images):img = np.asarray(image)if img.ndim == 2:img = np.stack([img] * 3, axis=-1)@@ -354,7 +408,8 @@ def project_views_to_uv(u = (u + 0.5) * (img_w / view.size) - 0.5v = (v + 0.5) * (img_h / view.size) - 0.5- confidence = np.clip(flat_nrm @ view.view_direction(), 0.0, 1.0) ** FACING_EXPONENT+ facing = np.clip(flat_nrm @ view.view_direction(), 0.0, 1.0)+ confidence = facing ** FACING_EXPONENTconfidence = np.where(confidence >= MIN_FACING, confidence, 0.0)# Half a pixel of slack at the frame border. A texel on the silhouette# projects exactly onto the edge pixel, and float error in the rasterized@@ -367,16 +422,28 @@ def project_views_to_uv(0.0,)- buffer = depth_buffers[idx] if depth_buffers is not None else None- if buffer is not None:- buf = np.asarray(buffer, dtype=np.float32)- scale_x = buf.shape[1] / float(view.size)- scale_y = buf.shape[0] / float(view.size)- bx = np.clip((u * scale_x).astype(np.int32), 0, buf.shape[1] - 1)- by = np.clip((v * scale_y).astype(np.int32), 0, buf.shape[0] - 1)+ if occlude:+ resolution = occlusion_buffer_size(view.size)+ buf = view_depth_buffer(view, flat_pos, resolution)+ scale = resolution / float(view.size)+ bx = np.clip(np.rint(pixels[:, 0] * scale).astype(np.int64), 0, resolution - 1)+ by = np.clip(np.rint(pixels[:, 1] * scale).astype(np.int64), 0, resolution - 1)nearest = buf[by, bx]- tol = max(view.radius * DEPTH_TOLERANCE_FRAC, 1e-6)- confidence = np.where((nearest > 0) & (depth <= nearest + tol), confidence, 0.0)+ # Slope-scaled bias. Within one bin a surface tilted away from the+ # camera spans bin_width * tan(angle) of depth, so a flat tolerance+ # makes the near edge of a bin reject its own far edge: the surface+ # shadows itself and the texture drops out in exactly the grazing+ # regions that already have the least coverage.+ cos_angle = np.clip(facing, MIN_FACING, 1.0)+ slope = np.sqrt(1.0 - cos_angle ** 2) / cos_angle+ bin_width = 2.0 * view.xmag / resolution+ # 4 bin widths: one for the spread inside a bin, one more for the+ # dilation above, and a factor of two so a surface never shadows+ # itself at the angles where coverage is already thinnest.+ bias = np.maximum(view.radius * DEPTH_TOLERANCE_FRAC, 4.0 * bin_width * slope)+ confidence = np.where(+ ~np.isfinite(nearest) | (depth <= nearest + bias), confidence, 0.0+ )if not confidence.any():continue