File size: 9,074 Bytes
6a8fb56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""Render protocol for Zer0pa key-visual cards.

Locked after the XR orientation diagnosis. Every lane goes through this module
so the conventions don't drift.

USAGE (in a per-lane script):
    from render_protocol import (
        clean_scene, load_hbm_object, center_and_orient,
        add_wireframe_material, setup_world, setup_camera, render_2x,
        verify_orientation, OUT_W, OUT_H, W2X, H2X,
    )
"""
import bpy
import math


# ----- canonical output -----
OUT_W, OUT_H = 572, 534
W2X, H2X = OUT_W * 2, OUT_H * 2   # 1144 x 1068

# ----- canonical colors -----
BG = (10/255, 10/255, 10/255, 1.0)       # near-black card background
WIRE_COLOR = (0.86, 0.87, 0.89, 1.0)     # off-white wires (matches v6 palette)
FILL_COLOR = (10/255, 10/255, 10/255, 1.0)  # same as BG; fill is occluder only


# ----- helpers -----
def clean_scene():
    bpy.ops.wm.read_factory_settings(use_empty=True)
    return bpy.context.scene


def load_hbm_collection(bundle_path, collection_name):
    """Load a whole collection (e.g., 'Skeleton - Realistic') from a Blender
    Studio bundle. Returns the linked collection and list of mesh objects."""
    with bpy.data.libraries.load(bundle_path, link=False) as (df, dt):
        if collection_name not in df.collections:
            raise RuntimeError(f"collection '{collection_name}' not in bundle\nAvailable: {df.collections}")
        dt.collections = [collection_name]
    col = dt.collections[0]
    bpy.context.scene.collection.children.link(col)
    mesh_objs = [o for o in col.all_objects if o.type == 'MESH']
    return col, mesh_objs


def collection_world_bbox(mesh_objs):
    """Compute world-space bbox over a list of mesh objects (post-deps eval)."""
    bpy.context.view_layer.update()
    deps = bpy.context.evaluated_depsgraph_get()
    mins = [float('inf')] * 3
    maxs = [float('-inf')] * 3
    for obj in mesh_objs:
        eo = obj.evaluated_get(deps)
        em = eo.to_mesh()
        for v in em.vertices:
            w = eo.matrix_world @ v.co
            for i, c in enumerate((w.x, w.y, w.z)):
                if c < mins[i]: mins[i] = c
                if c > maxs[i]: maxs[i] = c
        eo.to_mesh_clear()
    return tuple((mins[i], maxs[i]) for i in range(3))


def shift_collection(mesh_objs, dx, dy, dz):
    """Shift every mesh object in the collection by the same offset."""
    for o in mesh_objs:
        o.location.x += dx; o.location.y += dy; o.location.z += dz
    bpy.context.view_layer.update()


def load_hbm_object(bundle_path, object_name):
    """Load one object from a Blender Studio asset bundle.
    RESETS its source-bundle transform — bundle objects are pre-placed."""
    with bpy.data.libraries.load(bundle_path, link=False) as (df, dt):
        if object_name not in df.objects:
            raise RuntimeError(f"'{object_name}' not in {bundle_path}\nAvailable: {df.objects}")
        dt.objects = [object_name]
    obj = dt.objects[0]
    bpy.context.scene.collection.objects.link(obj)
    obj.location = (0, 0, 0)
    obj.rotation_euler = (0, 0, 0)
    obj.scale = (1, 1, 1)
    obj.hide_render = False
    obj.hide_viewport = False
    return obj


def center_and_orient(obj, x_flip=False, rotate_euler=(0, 0, 0)):
    """Shift mesh verts so centroid sits at object origin, then apply rotation.
    Returns world-space bbox AFTER the transforms (verified via depsgraph).

    `x_flip`: True for mirror-paired second instance (e.g. left vs right hand).
    `rotate_euler`: degrees, applied around object origin.
    """
    co = [v.co for v in obj.data.vertices]
    cx = (min(c.x for c in co) + max(c.x for c in co)) / 2
    cy = (min(c.y for c in co) + max(c.y for c in co)) / 2
    cz = (min(c.z for c in co) + max(c.z for c in co)) / 2
    for v in obj.data.vertices:
        v.co.x -= cx
        v.co.y -= cy
        v.co.z -= cz
    obj.data.update()

    obj.rotation_euler = tuple(math.radians(d) for d in rotate_euler)
    if x_flip:
        obj.scale = (-1, 1, 1)

    bpy.context.view_layer.update()
    deps = bpy.context.evaluated_depsgraph_get()
    eo = obj.evaluated_get(deps)
    em = eo.to_mesh()
    cw = [eo.matrix_world @ v.co for v in em.vertices]
    bbox = (
        (min(c.x for c in cw), max(c.x for c in cw)),
        (min(c.y for c in cw), max(c.y for c in cw)),
        (min(c.z for c in cw), max(c.z for c in cw)),
    )
    eo.to_mesh_clear()
    return bbox


def add_wireframe(obj, thickness_factor=0.004):
    """Duplicate obj, add Wireframe modifier with white emission. Returns the
    wire object. Inherits obj's world matrix so it works for parented objects."""
    # Force depsgraph update so obj.matrix_world reflects any just-set transform
    bpy.context.view_layer.update()
    wm = obj.data.copy()
    wire = bpy.data.objects.new(obj.name + "_wire", wm)
    bpy.context.scene.collection.objects.link(wire)
    # Mirror full world matrix so parented bones land correctly
    wire.matrix_world = obj.matrix_world.copy()

    # mesh span for thickness
    co = [v.co for v in wm.vertices]
    span = max(
        max(c.x for c in co) - min(c.x for c in co),
        max(c.y for c in co) - min(c.y for c in co),
        max(c.z for c in co) - min(c.z for c in co),
    )
    wf = wire.modifiers.new("WF", 'WIREFRAME')
    wf.thickness = span * thickness_factor
    wf.use_replace = True
    wf.use_even_offset = True
    wf.use_boundary = True
    wf.offset = 1.0   # push outward

    mat = bpy.data.materials.new(obj.name + "_wmat"); mat.use_nodes = True
    nt = mat.node_tree
    for n in list(nt.nodes): nt.nodes.remove(n)
    out = nt.nodes.new("ShaderNodeOutputMaterial")
    emi = nt.nodes.new("ShaderNodeEmission")
    emi.inputs["Color"].default_value = WIRE_COLOR
    emi.inputs["Strength"].default_value = 2.5
    nt.links.new(emi.outputs[0], out.inputs[0])
    wire.data.materials.clear(); wire.data.materials.append(mat)

    return wire


def hide_fill(obj):
    """Hide the fill mesh entirely. Used when wireframe is sufficient
    visual on its own (cleaner, no z-fighting risk)."""
    obj.hide_render = True


def set_fill_as_occluder(obj, shrink=0.985):
    """Configure the original mesh as a dark-fill occluder that hides
    back-of-mesh wireframe edges from showing through the front.

    Scales the fill slightly smaller than the wireframe so it sits just
    inside the wire tubes without z-fighting. shrink=0.985 = 1.5% smaller.
    """
    # Apply shrink as object scale (works regardless of fill's existing scale.x sign for mirror)
    sx, sy, sz = obj.scale.x, obj.scale.y, obj.scale.z
    obj.scale = (sx * shrink, sy * shrink, sz * shrink)

    mat = bpy.data.materials.new(obj.name + "_fmat"); mat.use_nodes = True
    nt = mat.node_tree
    for n in list(nt.nodes): nt.nodes.remove(n)
    out = nt.nodes.new("ShaderNodeOutputMaterial")
    emi = nt.nodes.new("ShaderNodeEmission")
    emi.inputs["Color"].default_value = BG
    emi.inputs["Strength"].default_value = 1.0
    nt.links.new(emi.outputs[0], out.inputs[0])
    obj.data.materials.clear(); obj.data.materials.append(mat)
    obj.hide_render = False
    obj.hide_viewport = False


def setup_world():
    w = bpy.data.worlds.new("CardWorld"); w.use_nodes = True
    nt = w.node_tree
    for n in list(nt.nodes): nt.nodes.remove(n)
    out = nt.nodes.new("ShaderNodeOutputWorld")
    bg = nt.nodes.new("ShaderNodeBackground")
    bg.inputs["Color"].default_value = BG
    bg.inputs["Strength"].default_value = 1.0
    nt.links.new(bg.outputs[0], out.inputs[0])
    bpy.context.scene.world = w


def setup_camera(target_xyz, distance, lens=50):
    scene = bpy.context.scene
    target = bpy.data.objects.new("Target", None)
    target.location = target_xyz
    scene.collection.objects.link(target)

    cam_data = bpy.data.cameras.new("Cam")
    cam_data.lens = lens
    cam_data.clip_start = 0.001
    cam_data.clip_end = 100
    cam = bpy.data.objects.new("Cam", cam_data)
    scene.collection.objects.link(cam)
    cam.location = (target_xyz[0], target_xyz[1] - distance, target_xyz[2])
    trk = cam.constraints.new('TRACK_TO')
    trk.target = target
    trk.track_axis = 'TRACK_NEGATIVE_Z'
    trk.up_axis = 'UP_Y'
    scene.camera = cam
    return cam, target


def frame_distance_for_width(width, lens=50, sensor=36, margin=1.20):
    """Camera Y-distance needed so a horizontal extent of `width` (m) fits in
    frame with `margin` (1.0 = exact fit, 1.20 = 20% margin)."""
    half_fov = math.atan((sensor/2) / lens)
    return (width / 2) / math.tan(half_fov) * margin


def render_2x(out_path):
    scene = bpy.context.scene
    scene.render.engine = 'BLENDER_EEVEE_NEXT'
    scene.render.resolution_x = W2X
    scene.render.resolution_y = H2X
    scene.render.image_settings.file_format = 'PNG'
    scene.render.image_settings.color_mode = 'RGB'
    scene.render.filepath = out_path
    scene.render.film_transparent = False
    scene.view_settings.view_transform = 'Raw'
    scene.view_settings.look = 'None'
    scene.view_settings.exposure = 0.0
    scene.view_settings.gamma = 1.0
    bpy.ops.render.render(write_still=True)