@babylonjs-toolkit/agent 1.1.99 → 1.2.1
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.
- package/README.md +3 -2
- package/package.json +1 -1
- package/skills/bt-atlas/SKILL.md +22 -5
- package/skills/bt-design/references/3d-hero-docs.md +10 -3
- package/skills/bt-design/references/3d-hero-scroll.md +30 -5
- package/skills/bt-gauntlet/SKILL.md +4 -4
- package/skills/bt-gauntlet/references/spec-composition.md +4 -2
- package/skills/bt-gauntlet/references/target-images.md +28 -4
- package/skills/bt-gauntlet/references/unity-pipeline.md +30 -8
- package/skills/bt-hero/SKILL.md +3 -3
- package/skills/bt-landing/SKILL.md +1 -1
- package/skills/bt-prototype/SKILL.md +3 -3
- package/skills/bt-unwrap/SKILL.md +396 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/bt_unwrap.py +678 -0
- package/skills/bt-unwrap/scripts/blender/image_utils.py +264 -0
- package/skills/bt-unwrap/scripts/blender/mesh_tools.py +508 -0
- package/skills/bt-unwrap/scripts/blender/model_io.py +135 -0
- package/skills/bt-unwrap/scripts/blender/previews.py +205 -0
- package/skills/bt-unwrap/scripts/blender/rasterizer.py +217 -0
- package/skills/bt-unwrap/scripts/blender/reference_views.py +945 -0
- package/skills/bt-unwrap/scripts/blender/reference_warp.py +571 -0
- package/skills/bt-unwrap/scripts/blender/texture_bake.py +390 -0
- package/skills/bt-unwrap/scripts/blender/texture_compose.py +596 -0
- package/skills/bt-unwrap/scripts/blender/uv_layout.py +605 -0
- package/skills/bt-unwrap/scripts/bt-unwrap.mjs +165 -0
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Visual proof for bt-unwrap: before / after renders from fixed views, a side-by-side comparison sheet,
|
|
3
|
+
UV island maps (the island map is the uv-layout input bt-atlas expects), and reference alignment overlays.
|
|
4
|
+
|
|
5
|
+
Renders use Workbench with flat lighting and texture color only, so what you see is the texture itself —
|
|
6
|
+
no lighting can hide a smeared or stretched texture.
|
|
7
|
+
"""
|
|
8
|
+
import os
|
|
9
|
+
|
|
10
|
+
import bpy
|
|
11
|
+
import numpy as np
|
|
12
|
+
from mathutils import Matrix, Vector
|
|
13
|
+
|
|
14
|
+
import image_utils
|
|
15
|
+
import mesh_tools
|
|
16
|
+
import uv_layout
|
|
17
|
+
|
|
18
|
+
PREVIEW_VIEWS = {
|
|
19
|
+
"front": (0.0, -1.0, 0.0),
|
|
20
|
+
"left": (1.0, 0.0, 0.0),
|
|
21
|
+
"rear": (0.0, 1.0, 0.0),
|
|
22
|
+
"right": (-1.0, 0.0, 0.0),
|
|
23
|
+
"top": (0.0, 0.0, 1.0),
|
|
24
|
+
"three_quarter_front": (0.8, -1.0, 0.6),
|
|
25
|
+
"three_quarter_rear": (-0.8, 1.0, 0.6),
|
|
26
|
+
}
|
|
27
|
+
FRAME_MARGIN = 1.08
|
|
28
|
+
BACKDROP_COLOR = (0.82, 0.82, 0.82)
|
|
29
|
+
OUTLINE_COLOR = np.array((1.0, 0.1, 0.1, 1.0), dtype=np.float32)
|
|
30
|
+
SHEET_GAP_PIXELS = 8
|
|
31
|
+
LAYOUT_PREVIEW_MAX = 2048
|
|
32
|
+
OVERLAY_MAX = 1400
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def render_with_texture(objects: list, texture_path: str, output_dir: str, prefix: str, resolution: int) -> dict:
|
|
36
|
+
"""
|
|
37
|
+
Renders the objects with a different base color texture on the same UV layout (e.g. the reference
|
|
38
|
+
coverage map), restoring the real texture afterwards.
|
|
39
|
+
|
|
40
|
+
:param objects: Mesh objects whose material shows its base color through the active image node.
|
|
41
|
+
:param texture_path: Image to show instead.
|
|
42
|
+
:param output_dir: Folder for the PNG files.
|
|
43
|
+
:param prefix: File name prefix.
|
|
44
|
+
:param resolution: Square image size in pixels.
|
|
45
|
+
:returns: view name -> written file path.
|
|
46
|
+
"""
|
|
47
|
+
replacement = bpy.data.images.load(texture_path, check_existing=False)
|
|
48
|
+
swapped = []
|
|
49
|
+
for obj in mesh_tools.mesh_objects(objects):
|
|
50
|
+
for slot in obj.material_slots:
|
|
51
|
+
material = slot.material
|
|
52
|
+
node = material.node_tree.nodes.active if material and material.use_nodes else None
|
|
53
|
+
if node is not None and node.type == "TEX_IMAGE":
|
|
54
|
+
swapped.append((node, node.image))
|
|
55
|
+
node.image = replacement
|
|
56
|
+
try:
|
|
57
|
+
return render_views(objects, output_dir, prefix, resolution)
|
|
58
|
+
finally:
|
|
59
|
+
for node, original in swapped:
|
|
60
|
+
node.image = original
|
|
61
|
+
bpy.data.images.remove(replacement)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def render_views(objects: list, output_dir: str, prefix: str, resolution: int) -> dict:
|
|
65
|
+
"""
|
|
66
|
+
Renders the given objects (everything else hidden) from every preview view.
|
|
67
|
+
|
|
68
|
+
:param objects: Objects to show.
|
|
69
|
+
:param output_dir: Folder for the PNG files.
|
|
70
|
+
:param prefix: File name prefix, e.g. 'before' or 'after'.
|
|
71
|
+
:param resolution: Square image size in pixels.
|
|
72
|
+
:returns: view name -> written file path.
|
|
73
|
+
"""
|
|
74
|
+
scene = bpy.context.scene
|
|
75
|
+
visible = set(objects)
|
|
76
|
+
hidden_state = {}
|
|
77
|
+
for obj in scene.objects:
|
|
78
|
+
hidden_state[obj.name] = obj.hide_render
|
|
79
|
+
obj.hide_render = obj not in visible
|
|
80
|
+
|
|
81
|
+
previous_engine = scene.render.engine
|
|
82
|
+
scene.render.engine = "BLENDER_WORKBENCH"
|
|
83
|
+
scene.display.shading.light = "FLAT"
|
|
84
|
+
scene.display.shading.color_type = "TEXTURE"
|
|
85
|
+
scene.render.resolution_x = resolution
|
|
86
|
+
scene.render.resolution_y = resolution
|
|
87
|
+
scene.render.resolution_percentage = 100
|
|
88
|
+
scene.render.film_transparent = False
|
|
89
|
+
scene.render.image_settings.file_format = "PNG"
|
|
90
|
+
scene.view_settings.view_transform = "Standard"
|
|
91
|
+
world = scene.world or bpy.data.worlds.new("PreviewBackdrop")
|
|
92
|
+
world.color = BACKDROP_COLOR
|
|
93
|
+
scene.world = world
|
|
94
|
+
|
|
95
|
+
camera_data = bpy.data.cameras.new("BtUnwrapPreviewCamera")
|
|
96
|
+
camera_data.type = "ORTHO"
|
|
97
|
+
camera = bpy.data.objects.new("BtUnwrapPreviewCamera", camera_data)
|
|
98
|
+
scene.collection.objects.link(camera)
|
|
99
|
+
previous_camera = scene.camera
|
|
100
|
+
scene.camera = camera
|
|
101
|
+
|
|
102
|
+
positions = mesh_tools.world_vertex_positions(mesh_tools.mesh_objects(objects))
|
|
103
|
+
center = (positions.min(axis=0) + positions.max(axis=0)) / 2.0
|
|
104
|
+
radius = float(np.linalg.norm(positions.max(axis=0) - positions.min(axis=0)))
|
|
105
|
+
written = {}
|
|
106
|
+
os.makedirs(output_dir, exist_ok=True)
|
|
107
|
+
for view_name, raw_direction in PREVIEW_VIEWS.items():
|
|
108
|
+
direction = np.array(raw_direction) / np.linalg.norm(raw_direction)
|
|
109
|
+
right, up = uv_layout.view_axes(direction)
|
|
110
|
+
relative = positions - center
|
|
111
|
+
extent_across = np.ptp(relative @ right)
|
|
112
|
+
extent_up = np.ptp(relative @ up)
|
|
113
|
+
camera_data.ortho_scale = max(extent_across, extent_up) * FRAME_MARGIN
|
|
114
|
+
camera_data.clip_start = radius * 0.01
|
|
115
|
+
camera_data.clip_end = radius * 4.0
|
|
116
|
+
offset_center = center + right * ((relative @ right).max() + (relative @ right).min()) / 2.0 + \
|
|
117
|
+
up * ((relative @ up).max() + (relative @ up).min()) / 2.0
|
|
118
|
+
camera.matrix_world = Matrix.Translation(Vector(offset_center + direction * radius * 2.0)) @ \
|
|
119
|
+
Matrix((right.tolist(), up.tolist(), direction.tolist())).transposed().to_4x4()
|
|
120
|
+
scene.render.filepath = os.path.join(output_dir, f"{prefix}_{view_name}.png")
|
|
121
|
+
bpy.ops.render.render(write_still=True)
|
|
122
|
+
written[view_name] = scene.render.filepath
|
|
123
|
+
|
|
124
|
+
scene.camera = previous_camera
|
|
125
|
+
bpy.data.objects.remove(camera, do_unlink=True)
|
|
126
|
+
bpy.data.cameras.remove(camera_data)
|
|
127
|
+
scene.render.engine = previous_engine
|
|
128
|
+
for obj in scene.objects:
|
|
129
|
+
if obj.name in hidden_state:
|
|
130
|
+
obj.hide_render = hidden_state[obj.name]
|
|
131
|
+
return written
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def comparison_sheet(before: dict, after: dict, output_path: str) -> str:
|
|
135
|
+
"""
|
|
136
|
+
Stacks before (left column) and after (right column) renders, one row per view, top to bottom in the
|
|
137
|
+
order of PREVIEW_VIEWS.
|
|
138
|
+
|
|
139
|
+
:param before: view -> file path of the 'before' renders.
|
|
140
|
+
:param after: view -> file path of the 'after' renders.
|
|
141
|
+
:param output_path: PNG file to write.
|
|
142
|
+
:returns: The path written.
|
|
143
|
+
"""
|
|
144
|
+
rows = []
|
|
145
|
+
for view_name in PREVIEW_VIEWS:
|
|
146
|
+
if view_name not in before or view_name not in after:
|
|
147
|
+
continue
|
|
148
|
+
left = image_utils.load_image_array(before[view_name])
|
|
149
|
+
right = image_utils.load_image_array(after[view_name])
|
|
150
|
+
gap = np.ones((left.shape[0], SHEET_GAP_PIXELS, 4), dtype=np.float32)
|
|
151
|
+
rows.append(np.concatenate((left, gap, right), axis=1))
|
|
152
|
+
if not rows:
|
|
153
|
+
return ""
|
|
154
|
+
row_gap = np.ones((SHEET_GAP_PIXELS, rows[0].shape[1], 4), dtype=np.float32)
|
|
155
|
+
stacked = []
|
|
156
|
+
for row in reversed(rows): # arrays are bottom-up, so the first view goes last
|
|
157
|
+
stacked.extend((row, row_gap))
|
|
158
|
+
return image_utils.save_image_array(np.concatenate(stacked[:-1], axis=0), output_path)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def uv_layout_images(color: np.ndarray, covered: np.ndarray, output_dir: str, stem: str) -> dict:
|
|
162
|
+
"""
|
|
163
|
+
Writes the island map (white islands on black — bt-atlas's uv-layout input) and an outline overlay on
|
|
164
|
+
the final base color for people to read.
|
|
165
|
+
|
|
166
|
+
:param color: float32 (size, size, 4) final base color.
|
|
167
|
+
:param covered: Boolean (size, size) texels on the model.
|
|
168
|
+
:param output_dir: Folder to write into.
|
|
169
|
+
:param stem: File name stem.
|
|
170
|
+
:returns: {'islands': path, 'overlay': path}.
|
|
171
|
+
"""
|
|
172
|
+
size = covered.shape[0]
|
|
173
|
+
preview_size = min(size, LAYOUT_PREVIEW_MAX)
|
|
174
|
+
islands = np.repeat(covered[:, :, None].astype(np.float32), 3, axis=2)
|
|
175
|
+
islands_path = image_utils.save_image_array(
|
|
176
|
+
image_utils.resize_image(islands, preview_size, preview_size) if preview_size != size else islands,
|
|
177
|
+
os.path.join(output_dir, f"{stem}_uv_islands.png"))
|
|
178
|
+
outline = covered & ~image_utils.erode_mask(covered, max(1, size // 1024))
|
|
179
|
+
overlay = color.copy()
|
|
180
|
+
overlay[outline] = OUTLINE_COLOR
|
|
181
|
+
if preview_size != size:
|
|
182
|
+
overlay = image_utils.resize_image(overlay, preview_size, preview_size)
|
|
183
|
+
overlay_path = image_utils.save_image_array(overlay, os.path.join(output_dir, f"{stem}_uv_layout.png"))
|
|
184
|
+
return {"islands": islands_path, "overlay": overlay_path}
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def alignment_overlay(reference, output_dir: str) -> str:
|
|
188
|
+
"""
|
|
189
|
+
Draws the fitted mesh silhouette in red over a reference image, to check the alignment by eye.
|
|
190
|
+
|
|
191
|
+
:param reference: An aligned reference with a depth buffer.
|
|
192
|
+
:param output_dir: Folder to write into.
|
|
193
|
+
:returns: The path written.
|
|
194
|
+
"""
|
|
195
|
+
image = reference.pixels.copy()
|
|
196
|
+
covered = np.isfinite(reference.depth)
|
|
197
|
+
thickness = max(1, image.shape[1] // 700)
|
|
198
|
+
outline = covered & ~image_utils.erode_mask(covered, thickness)
|
|
199
|
+
image[covered & ~outline, :3] = image[covered & ~outline, :3] * 0.85 + np.array((0.15, 0.0, 0.0))
|
|
200
|
+
image[outline] = OUTLINE_COLOR
|
|
201
|
+
height, width = image.shape[:2]
|
|
202
|
+
scale = min(1.0, OVERLAY_MAX / max(width, height))
|
|
203
|
+
if scale < 1.0:
|
|
204
|
+
image = image_utils.resize_image(image, int(width * scale), int(height * scale))
|
|
205
|
+
return image_utils.save_image_array(image, os.path.join(output_dir, f"align_{reference.view}.png"))
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""
|
|
2
|
+
A small vectorised triangle rasterizer in numpy, used to find which triangle covers each texel of the new
|
|
3
|
+
UV layout and to build depth buffers for reference-image visibility.
|
|
4
|
+
|
|
5
|
+
Triangles are grouped by the size of their pixel bounding box, so each group is evaluated as one broadcast
|
|
6
|
+
array operation instead of a Python loop per triangle.
|
|
7
|
+
"""
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Iterator, Optional
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
# Bounding-box sizes are rounded up to these values so triangles of similar size share one batch.
|
|
14
|
+
BOX_SIZE_BUCKETS = np.array([1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
|
|
15
|
+
1024, 1536, 2048, 3072, 4096, 6144, 8192, 16384], dtype=np.int64)
|
|
16
|
+
|
|
17
|
+
# Upper bound on candidate pixels evaluated in one broadcast batch; keeps memory use around a few hundred MB.
|
|
18
|
+
DEFAULT_BATCH_PIXEL_BUDGET = 6_000_000
|
|
19
|
+
|
|
20
|
+
# Barycentric tolerance: a slightly negative value closes hairline cracks between neighbouring triangles.
|
|
21
|
+
EDGE_TOLERANCE = 1e-4
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class Fragments:
|
|
26
|
+
"""Pixels covered by one batch of triangles."""
|
|
27
|
+
|
|
28
|
+
pixel_index: np.ndarray # int64 flat index row * width + column
|
|
29
|
+
triangle_index: np.ndarray # int64 index into the triangle array that was rasterized
|
|
30
|
+
barycentric: np.ndarray # float32 (count, 3) weights of the triangle's three corners
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _bucket_size(sizes: np.ndarray) -> np.ndarray:
|
|
34
|
+
"""Rounds each bounding-box size up to the nearest bucket value."""
|
|
35
|
+
positions = np.searchsorted(BOX_SIZE_BUCKETS, sizes, side="left")
|
|
36
|
+
positions = np.minimum(positions, len(BOX_SIZE_BUCKETS) - 1)
|
|
37
|
+
return np.maximum(BOX_SIZE_BUCKETS[positions], sizes)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def rasterize(
|
|
41
|
+
triangle_points: np.ndarray,
|
|
42
|
+
width: int,
|
|
43
|
+
height: int,
|
|
44
|
+
edge_tolerance: float = EDGE_TOLERANCE,
|
|
45
|
+
batch_pixel_budget: int = DEFAULT_BATCH_PIXEL_BUDGET,
|
|
46
|
+
) -> Iterator[Fragments]:
|
|
47
|
+
"""
|
|
48
|
+
Rasterizes 2D triangles and yields the covered pixels batch by batch. A pixel is covered when its center
|
|
49
|
+
lies inside the triangle.
|
|
50
|
+
|
|
51
|
+
:param triangle_points: float array (triangle_count, 3, 2) of corner positions in pixel units; x to the
|
|
52
|
+
right, y measured from row 0.
|
|
53
|
+
:param width: Raster width in pixels.
|
|
54
|
+
:param height: Raster height in pixels.
|
|
55
|
+
:param edge_tolerance: Barycentric slack. Positive values grow triangles slightly (no cracks); a negative
|
|
56
|
+
value keeps only strict interiors (used for overlap detection).
|
|
57
|
+
:param batch_pixel_budget: Maximum candidate pixels evaluated at once.
|
|
58
|
+
:returns: An iterator of Fragments; a pixel may appear in several batches when triangles overlap.
|
|
59
|
+
"""
|
|
60
|
+
points = np.asarray(triangle_points, dtype=np.float64)
|
|
61
|
+
if points.shape[0] == 0:
|
|
62
|
+
return
|
|
63
|
+
minimum_x = np.clip(np.floor(points[:, :, 0].min(axis=1) - 0.5).astype(np.int64), 0, width - 1)
|
|
64
|
+
maximum_x = np.clip(np.ceil(points[:, :, 0].max(axis=1) - 0.5).astype(np.int64), 0, width - 1)
|
|
65
|
+
minimum_y = np.clip(np.floor(points[:, :, 1].min(axis=1) - 0.5).astype(np.int64), 0, height - 1)
|
|
66
|
+
maximum_y = np.clip(np.ceil(points[:, :, 1].max(axis=1) - 0.5).astype(np.int64), 0, height - 1)
|
|
67
|
+
outside = (points[:, :, 0].max(axis=1) < 0) | (points[:, :, 0].min(axis=1) > width) | \
|
|
68
|
+
(points[:, :, 1].max(axis=1) < 0) | (points[:, :, 1].min(axis=1) > height)
|
|
69
|
+
|
|
70
|
+
box_width = _bucket_size(maximum_x - minimum_x + 1)
|
|
71
|
+
box_height = _bucket_size(maximum_y - minimum_y + 1)
|
|
72
|
+
candidates = np.nonzero(~outside)[0]
|
|
73
|
+
if candidates.size == 0:
|
|
74
|
+
return
|
|
75
|
+
group_keys = box_width[candidates] * 100_000 + box_height[candidates]
|
|
76
|
+
order = np.argsort(group_keys, kind="stable")
|
|
77
|
+
sorted_candidates = candidates[order]
|
|
78
|
+
sorted_keys = group_keys[order]
|
|
79
|
+
group_starts = np.flatnonzero(np.r_[True, sorted_keys[1:] != sorted_keys[:-1]])
|
|
80
|
+
group_ends = np.r_[group_starts[1:], sorted_keys.size]
|
|
81
|
+
|
|
82
|
+
for group_start, group_end in zip(group_starts, group_ends):
|
|
83
|
+
group = sorted_candidates[group_start:group_end]
|
|
84
|
+
cell_width = int(box_width[group[0]])
|
|
85
|
+
cell_height = int(box_height[group[0]])
|
|
86
|
+
cells_per_triangle = cell_width * cell_height
|
|
87
|
+
chunk_size = max(1, batch_pixel_budget // cells_per_triangle)
|
|
88
|
+
offset_x = np.tile(np.arange(cell_width), cell_height)
|
|
89
|
+
offset_y = np.repeat(np.arange(cell_height), cell_width)
|
|
90
|
+
for chunk_start in range(0, group.size, chunk_size):
|
|
91
|
+
chunk = group[chunk_start:chunk_start + chunk_size]
|
|
92
|
+
fragments = _rasterize_chunk(points, chunk, minimum_x, minimum_y, offset_x, offset_y,
|
|
93
|
+
width, height, edge_tolerance)
|
|
94
|
+
if fragments is not None:
|
|
95
|
+
yield fragments
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _rasterize_chunk(points, chunk, minimum_x, minimum_y, offset_x, offset_y, width, height, edge_tolerance):
|
|
99
|
+
"""Evaluates every candidate pixel of a chunk of same-size triangles in one broadcast."""
|
|
100
|
+
corner_a = points[chunk, 0]
|
|
101
|
+
corner_b = points[chunk, 1]
|
|
102
|
+
corner_c = points[chunk, 2]
|
|
103
|
+
denominator = (corner_b[:, 1] - corner_c[:, 1]) * (corner_a[:, 0] - corner_c[:, 0]) + \
|
|
104
|
+
(corner_c[:, 0] - corner_b[:, 0]) * (corner_a[:, 1] - corner_c[:, 1])
|
|
105
|
+
valid = np.abs(denominator) > 1e-12
|
|
106
|
+
if not valid.any():
|
|
107
|
+
return None
|
|
108
|
+
chunk = chunk[valid]
|
|
109
|
+
corner_a, corner_b, corner_c, denominator = corner_a[valid], corner_b[valid], corner_c[valid], denominator[valid]
|
|
110
|
+
|
|
111
|
+
pixel_column = minimum_x[chunk][:, None] + offset_x[None, :]
|
|
112
|
+
pixel_row = minimum_y[chunk][:, None] + offset_y[None, :]
|
|
113
|
+
center_x = pixel_column + 0.5
|
|
114
|
+
center_y = pixel_row + 0.5
|
|
115
|
+
weight_a = ((corner_b[:, 1:2] - corner_c[:, 1:2]) * (center_x - corner_c[:, 0:1]) +
|
|
116
|
+
(corner_c[:, 0:1] - corner_b[:, 0:1]) * (center_y - corner_c[:, 1:2])) / denominator[:, None]
|
|
117
|
+
weight_b = ((corner_c[:, 1:2] - corner_a[:, 1:2]) * (center_x - corner_c[:, 0:1]) +
|
|
118
|
+
(corner_a[:, 0:1] - corner_c[:, 0:1]) * (center_y - corner_c[:, 1:2])) / denominator[:, None]
|
|
119
|
+
weight_c = 1.0 - weight_a - weight_b
|
|
120
|
+
inside = (weight_a >= -edge_tolerance) & (weight_b >= -edge_tolerance) & (weight_c >= -edge_tolerance)
|
|
121
|
+
inside &= (pixel_column < width) & (pixel_row < height)
|
|
122
|
+
triangle_slot, cell = np.nonzero(inside)
|
|
123
|
+
if triangle_slot.size == 0:
|
|
124
|
+
return None
|
|
125
|
+
barycentric = np.stack(
|
|
126
|
+
(weight_a[triangle_slot, cell], weight_b[triangle_slot, cell], weight_c[triangle_slot, cell]), axis=1
|
|
127
|
+
)
|
|
128
|
+
barycentric = np.clip(barycentric, 0.0, 1.0)
|
|
129
|
+
barycentric /= barycentric.sum(axis=1, keepdims=True)
|
|
130
|
+
return Fragments(
|
|
131
|
+
pixel_index=pixel_row[triangle_slot, cell] * width + pixel_column[triangle_slot, cell],
|
|
132
|
+
triangle_index=chunk[triangle_slot].astype(np.int64),
|
|
133
|
+
barycentric=barycentric.astype(np.float32),
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def rasterize_ids(triangle_points: np.ndarray, width: int, height: int) -> tuple:
|
|
138
|
+
"""
|
|
139
|
+
Builds a per-pixel triangle id buffer plus barycentric weights. Where triangles overlap, the last one
|
|
140
|
+
written wins.
|
|
141
|
+
|
|
142
|
+
:param triangle_points: float array (triangle_count, 3, 2) in pixel units.
|
|
143
|
+
:param width: Raster width in pixels.
|
|
144
|
+
:param height: Raster height in pixels.
|
|
145
|
+
:returns: (triangle_id int64 (height*width) with -1 for empty pixels,
|
|
146
|
+
barycentric float32 (height*width, 3)).
|
|
147
|
+
"""
|
|
148
|
+
triangle_id = np.full(width * height, -1, dtype=np.int64)
|
|
149
|
+
barycentric = np.zeros((width * height, 3), dtype=np.float32)
|
|
150
|
+
for fragments in rasterize(triangle_points, width, height):
|
|
151
|
+
triangle_id[fragments.pixel_index] = fragments.triangle_index
|
|
152
|
+
barycentric[fragments.pixel_index] = fragments.barycentric
|
|
153
|
+
return triangle_id, barycentric
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def rasterize_coverage_count(triangle_points: np.ndarray, width: int, height: int,
|
|
157
|
+
triangle_group: Optional[np.ndarray] = None) -> tuple:
|
|
158
|
+
"""
|
|
159
|
+
Counts, per pixel, how many triangle interiors cover it, to detect overlapping UV islands. Shared edges
|
|
160
|
+
are not counted twice because only strict interiors are rasterized.
|
|
161
|
+
|
|
162
|
+
:param triangle_points: float array (triangle_count, 3, 2) in pixel units.
|
|
163
|
+
:param width: Raster width in pixels.
|
|
164
|
+
:param height: Raster height in pixels.
|
|
165
|
+
:param triangle_group: Optional island id per triangle; when given, the returned set lists the islands
|
|
166
|
+
that take part in an overlap.
|
|
167
|
+
:returns: (count int32 (height*width), set of overlapping island ids).
|
|
168
|
+
"""
|
|
169
|
+
count = np.zeros(width * height, dtype=np.int32)
|
|
170
|
+
first_group = np.full(width * height, -1, dtype=np.int64)
|
|
171
|
+
overlapping_groups = set()
|
|
172
|
+
for fragments in rasterize(triangle_points, width, height, edge_tolerance=-1e-3):
|
|
173
|
+
np.add.at(count, fragments.pixel_index, 1)
|
|
174
|
+
if triangle_group is None:
|
|
175
|
+
continue
|
|
176
|
+
groups = triangle_group[fragments.triangle_index]
|
|
177
|
+
previous = first_group[fragments.pixel_index]
|
|
178
|
+
clash = (previous >= 0) & (previous != groups)
|
|
179
|
+
if clash.any():
|
|
180
|
+
overlapping_groups.update(np.unique(groups[clash]).tolist())
|
|
181
|
+
overlapping_groups.update(np.unique(previous[clash]).tolist())
|
|
182
|
+
unset = previous < 0
|
|
183
|
+
first_group[fragments.pixel_index[unset]] = groups[unset]
|
|
184
|
+
return count, overlapping_groups
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def rasterize_depth(triangle_points: np.ndarray, triangle_depth: np.ndarray, width: int, height: int) -> np.ndarray:
|
|
188
|
+
"""
|
|
189
|
+
Builds a depth buffer that keeps the NEAREST surface per pixel, where larger depth means closer to the
|
|
190
|
+
camera.
|
|
191
|
+
|
|
192
|
+
:param triangle_points: float array (triangle_count, 3, 2) of projected corners in pixel units.
|
|
193
|
+
:param triangle_depth: float array (triangle_count, 3) of corner depths.
|
|
194
|
+
:param width: Raster width in pixels.
|
|
195
|
+
:param height: Raster height in pixels.
|
|
196
|
+
:returns: float32 array (height, width); -inf where nothing is drawn.
|
|
197
|
+
"""
|
|
198
|
+
depth = np.full(width * height, -np.inf, dtype=np.float32)
|
|
199
|
+
for fragments in rasterize(triangle_points, width, height):
|
|
200
|
+
fragment_depth = (triangle_depth[fragments.triangle_index] * fragments.barycentric).sum(axis=1)
|
|
201
|
+
np.maximum.at(depth, fragments.pixel_index, fragment_depth.astype(np.float32))
|
|
202
|
+
return depth.reshape(height, width)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def rasterize_mask(triangle_points: np.ndarray, width: int, height: int) -> np.ndarray:
|
|
206
|
+
"""
|
|
207
|
+
Draws the filled silhouette of a set of triangles.
|
|
208
|
+
|
|
209
|
+
:param triangle_points: float array (triangle_count, 3, 2) in pixel units.
|
|
210
|
+
:param width: Raster width in pixels.
|
|
211
|
+
:param height: Raster height in pixels.
|
|
212
|
+
:returns: Boolean array (height, width).
|
|
213
|
+
"""
|
|
214
|
+
mask = np.zeros(width * height, dtype=bool)
|
|
215
|
+
for fragments in rasterize(triangle_points, width, height):
|
|
216
|
+
mask[fragments.pixel_index] = True
|
|
217
|
+
return mask.reshape(height, width)
|