-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcrate_stack.py
More file actions
1751 lines (1602 loc) · 61.6 KB
/
Copy pathcrate_stack.py
File metadata and controls
1751 lines (1602 loc) · 61.6 KB
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Game-ready stack of three shipping crates — a showcase piece, not an example.
Asserts budget conformance of a procedural crate *stack*: one crate
generator invoked three times with a per-instance seed, each instance
yawed and seated on the lid of the one below, then run through the
shipped pipeline (bmesh construction, UVs, two materials, high-to-low
normal bake, LOD chain, convex collider, Unity glTF export).
What this piece is about is **reuse with variation**. The three crates
come out of a single ``build_crate`` call each, differing only by the
seed handed to it. That seed drives the yaw, the lean, and the plank
widths, so the crates read as three of the same design rather than one
model copied three times. True instancing (three objects sharing one
mesh datablock) and per-instance geometry variation are mutually
exclusive; this piece takes the variation and says so, and the shipped
asset is the flattened single mesh a game engine would receive.
Budgets are declared below and recomputed from the generated result.
They are not API-contract witnesses. Each falsifier violates one named
budget: ``--skip-decimate`` the LOD-ratio band, ``--stray-vert`` mesh
hygiene, ``--lift-z`` grounded zmin, ``--short-skids`` the named ground
supports, ``--float-stack`` the crate-to-crate seat, ``--same-seed`` the
per-instance variation budget, ``--float-nails`` the nail seat,
``--sharp-iron`` the edge-treatment budget.
Fixed seed 41. DECIMATE COLLAPSE triangle counts are not byte-identical
across Blender versions — the LOD gate is a ratio band, not an exact
count.
blender --background --python crate_stack.py --
blender --background --python crate_stack.py -- --same-seed
blender --background --python crate_stack.py -- --output stack.png
"""
import argparse
import math
import os
import random
import sys
import tempfile
import traceback
import bmesh
import bpy
from mathutils import Matrix, Vector
from mathutils.bvhtree import BVHTree
_REPO = os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, os.pardir)
)
sys.path.insert(0, os.path.join(_REPO, "examples"))
sys.dont_write_bytecode = True
import gallery_framing # noqa: E402
# One crate: 0.58 x 0.42 at the posts, 0.244 tall including skids and lid.
# Three stacked come to knee height, wider than they are tall.
CRATE_X = 0.58
CRATE_Y = 0.42
POST = 0.034
SKID_H = 0.024
SKID_W = 0.052
SLAT_T = 0.013
RAIL_H = 0.032
TENON = 0.008
IRON_T = 0.0035
IRON_WRAP = 0.052
# Straps bite into the timber and stop short of the rail top. Sitting them
# flush made the plate corner and the post corner the same point, which is
# a welded double, not a fixing.
IRON_BITE = 0.0012
IRON_DROP = 0.005
# The lid bites down onto the rails for the same reason: a lid resting
# exactly on the rail top shares that plane and those corner vertices.
LID_BITE = 0.004
# Iron is chamfered like the timber, only finer: a 3.5 mm plate with the
# timber's 1.8 mm bevel would have no flat left.
IRON_BEVEL = 0.0008
# Clout nails: two per plate, driven through the strap into the post. The
# shank end sits a named bite below the plate face so each head is seated,
# not parked on the surface; the head is a frustum so no visible edge of it
# is a right angle.
NAIL_R = 0.0050
NAIL_R_TOP = 0.0036
NAIL_H = 0.0024
NAIL_BITE = 0.0006
NAIL_SEGS = 6
NAIL_ZS = (0.18, 0.82)
NAIL_BITE_MIN = 0.0003
NAIL_BITE_MAX = 0.0010
NAIL_PROUD_MIN = 0.0010
# Nail versus plate is told apart by world-AABB extent. Derived from the
# strap, not the nail: a yawed 10 mm head has an AABB wider than 10 mm, and
# a fixed 10 mm threshold dropped 8 of 48 nails the moment the heads grew.
NAIL_EXTENT_MAX = IRON_WRAP * 0.5
FLOAT_NAIL_LIFT = 0.0015
# Edge treatment: no manifold edge on the finished mesh is a right angle.
# Every box edge is chamfered, so a 90-degree edge means a bevel pass was
# skipped.
RIGHT_ANGLE_TOL = math.radians(5.0)
PLANK_TONE_JITTER = 0.30
BODY_H = 0.205
N_SIDE = 3
N_END = 2
N_FLOOR = 3
N_LID = 3
SLAT_JITTER = 0.20
N_CRATES = 3
STACK_SEED = 41
# Each crate bites this far into the lid of the one below, so the seat is
# an overlap rather than two coincident faces (which would z-fight).
STACK_BITE = 0.005
YAW_MIN = 0.060
YAW_MAX = 0.170
# Crates also step sideways. Three boxes stacked dead-centre read as a
# filing cabinet however much they are yawed.
OFFSET_MAX = 0.030
YAW_SPREAD_MIN = 0.020
WIDTH_SPREAD_MIN = 0.0008
# Four corners, two plates per corner, one nail per plate per station.
N_NAILS = N_CRATES * 4 * 2 * len(NAIL_ZS)
CRATE_H = SKID_H + BODY_H + SLAT_T - LID_BITE
STACK_H = N_CRATES * CRATE_H - (N_CRATES - 1) * STACK_BITE
BBOX_TOL = 0.020
OUTER_SIZE = (0.658, 0.524, 0.704)
# The crate body over its corner iron and nail heads, in the crate's own frame.
# The strap stands IRON_T - IRON_BITE proud of the post, and each nail
# head a further NAIL_H - NAIL_BITE proud of the strap.
BODY_PROUD = IRON_T - IRON_BITE + NAIL_H - NAIL_BITE
BODY_X = CRATE_X + 2.0 * BODY_PROUD
BODY_Y = CRATE_Y + 2.0 * BODY_PROUD
CRATE_TOL = 0.015
BASE_TRIS_MIN = 5200
BASE_TRIS_MAX = 7000
LOD1_RATIO_MIN = 0.32
LOD1_RATIO_MAX = 0.62
LOD2_RATIO_MIN = 0.10
LOD2_RATIO_MAX = 0.35
LOD1_TARGET = 0.50
LOD2_TARGET = 0.22
MATERIAL_COUNT = 2
UV_EPS = 1e-4
UV_OVERLAP_MAX = 1e-5
COLLIDER_TRIS_MAX = 260
BAKE_RES = 256
CAGE_EXTRUSION = 0.08
METAL_FACES_MIN = 900
WOOD_FACES_MIN = 1800
ZMIN_EPS = 1e-4
DOUBLES_EPS = 1e-5
AREA_EPS = 1e-10
ZFIGHT_EPS = 1e-4
ZFIGHT_COS = 0.999
LIFT_Z = 0.05
SKID_Z_MAX = 1e-3
GROUND_SKIDS_MIN = 3
STACK_SEAT_MAX = 0.0015
FLOAT_LIFT = 0.009
SHORT_SKID_LIFT = 0.012
WOOD_IDX = 0
METAL_IDX = 1
def eevee_engine_id():
"""EEVEE id: 'BLENDER_EEVEE' on 5.0+, 'BLENDER_EEVEE_NEXT' on 4.2-4.5."""
return "BLENDER_EEVEE" if bpy.app.version >= (5, 0, 0) else "BLENDER_EEVEE_NEXT"
def fail(msg, code):
print(f"FAIL[{code}]: {msg}", file=sys.stderr)
return code
def triangle_count(mesh):
mesh.calc_loop_triangles()
return len(mesh.loop_triangles)
def evaluated_triangle_count(obj):
deps = bpy.context.evaluated_depsgraph_get()
ev = obj.evaluated_get(deps)
mesh = ev.to_mesh()
try:
mesh.calc_loop_triangles()
return len(mesh.loop_triangles)
finally:
ev.to_mesh_clear()
def add_box(bm, loc, scale, mat_idx, xform=None):
"""Axis-aligned box in the crate frame, optionally placed by *xform*."""
geo = bmesh.ops.create_cube(bm, size=1.0)
verts = geo["verts"]
for v in verts:
p = Vector(
(
v.co.x * scale[0] + loc[0],
v.co.y * scale[1] + loc[1],
v.co.z * scale[2] + loc[2],
)
)
v.co = xform @ p if xform is not None else p
faces = {f for v in verts for f in v.link_faces}
for f in faces:
f.material_index = mat_idx
return verts
def pack_uvs(bm, margin=0.08):
uv = bm.loops.layers.uv.new("UVMap")
faces = list(bm.faces)
n = len(faces)
cols = max(1, math.ceil(math.sqrt(n)))
rows = max(1, math.ceil(n / cols))
cell_w = 1.0 / cols
cell_h = 1.0 / rows
pad_u = margin * cell_w * 0.5
pad_v = margin * cell_h * 0.5
usable_w = cell_w - 2.0 * pad_u
usable_h = cell_h - 2.0 * pad_v
for i, face in enumerate(faces):
col = i % cols
row = i // cols
nrm = face.normal
ax, ay, az = abs(nrm.x), abs(nrm.y), abs(nrm.z)
coords = []
for loop in face.loops:
co = loop.vert.co
if az >= ax and az >= ay:
coords.append((co.x, co.y))
elif ax >= ay:
coords.append((co.y, co.z))
else:
coords.append((co.x, co.z))
xs = [c[0] for c in coords]
ys = [c[1] for c in coords]
minx, maxx = min(xs), max(xs)
miny, maxy = min(ys), max(ys)
dx = max(maxx - minx, 1e-8)
dy = max(maxy - miny, 1e-8)
origin_u = col * cell_w + pad_u
origin_v = row * cell_h + pad_v
for loop, (x, y) in zip(face.loops, coords):
loop[uv].uv = (
origin_u + (x - minx) / dx * usable_w,
origin_v + (y - miny) / dy * usable_h,
)
def _span_layout(count, span, rng, gap=0.009):
"""Uneven plank widths that still fill *span* with named gaps."""
raw = [1.0 + rng.uniform(-SLAT_JITTER, SLAT_JITTER) for _ in range(count)]
s = sum(raw)
usable = span - gap * (count + 1)
widths = [usable * r / s for r in raw]
pos = -span / 2.0 + gap
centres = []
for w in widths:
centres.append(pos + w / 2.0)
pos += w + gap
return centres, widths
def build_crate(
bm, base_z, yaw, rng, offset=(0.0, 0.0), short_skids=False, float_nails=False
):
"""One crate, placed with its skid underside at *base_z* and yawed.
Called once per stack level. Everything that differs between levels
comes out of *rng* and *yaw*; the geometry recipe itself is shared.
"""
xform = Matrix.Translation((offset[0], offset[1], 0.0)) @ Matrix.Rotation(
yaw, 4, "Z"
)
hx = CRATE_X / 2.0 - POST / 2.0
hy = CRATE_Y / 2.0 - POST / 2.0
skid_z0 = base_z + (SHORT_SKID_LIFT if short_skids else 0.0)
deck_z = base_z + SKID_H
top_z = deck_z + BODY_H
wood = []
# Two runners under the posts. These are the named ground supports on
# the bottom crate and the seat feet on the ones above.
# Three runners, not two: two leave a slot you can see daylight
# through between stacked crates, and a centre bearer is what a crate
# this wide would actually carry.
for si, sy in enumerate((-hy, 0.0, hy)):
z0 = skid_z0 if (short_skids and si == 0) else base_z
wood.extend(
add_box(
bm,
(0.0, sy, z0 + SKID_H / 2.0),
(CRATE_X, SKID_W, SKID_H),
WOOD_IDX,
xform,
)
)
# Corner posts, tenoned down into the skid line so no shared plane.
post_h = BODY_H + TENON
for sxn in (-1.0, 1.0):
for syn in (-1.0, 1.0):
wood.extend(
add_box(
bm,
(sxn * hx, syn * hy, deck_z - TENON + post_h / 2.0),
(POST, POST, post_h),
WOOD_IDX,
xform,
)
)
# Top rails and bottom sills, both tenoned into the posts.
for zc, h in ((top_z - RAIL_H / 2.0, RAIL_H),
(deck_z - TENON + (RAIL_H + TENON) / 2.0, RAIL_H + TENON)):
for syn in (-1.0, 1.0):
wood.extend(
add_box(
bm,
(0.0, syn * hy, zc),
(CRATE_X - POST + 2.0 * TENON, POST, h),
WOOD_IDX,
xform,
)
)
for sxn in (-1.0, 1.0):
wood.extend(
add_box(
bm,
(sxn * hx, 0.0, zc),
(POST, CRATE_Y - POST + 2.0 * TENON, h),
WOOD_IDX,
xform,
)
)
floor_c, floor_w = _span_layout(N_FLOOR, CRATE_X - POST, rng)
for c, w in zip(floor_c, floor_w):
wood.extend(
add_box(
bm,
(c, 0.0, deck_z + SLAT_T / 2.0),
(w, CRATE_Y - POST + TENON, SLAT_T),
WOOD_IDX,
xform,
)
)
lid_c, lid_w = _span_layout(N_LID, CRATE_X, rng)
for c, w in zip(lid_c, lid_w):
wood.extend(
add_box(
bm,
(c, 0.0, top_z + SLAT_T / 2.0 - LID_BITE),
(w, CRATE_Y, SLAT_T),
WOOD_IDX,
xform,
)
)
# Side and end boards. Their heights carry the per-instance jitter and
# are what the variation budget recomputes.
side_c, side_w = _span_layout(N_SIDE, BODY_H - RAIL_H * 1.6, rng)
band_z = deck_z + RAIL_H * 0.8 + (BODY_H - RAIL_H * 1.6) / 2.0
for syn in (-1.0, 1.0):
y = syn * (CRATE_Y / 2.0 - SLAT_T / 2.0 - 0.0012)
for c, w in zip(side_c, side_w):
wood.extend(
add_box(
bm,
(0.0, y, band_z + c),
(CRATE_X - POST + TENON, SLAT_T, w),
WOOD_IDX,
xform,
)
)
end_c, end_w = _span_layout(N_END, BODY_H - RAIL_H * 1.6, rng)
for sxn in (-1.0, 1.0):
x = sxn * (CRATE_X / 2.0 - SLAT_T / 2.0 - 0.0012)
for c, w in zip(end_c, end_w):
wood.extend(
add_box(
bm,
(x, 0.0, band_z + c),
(SLAT_T, CRATE_Y - POST + TENON, w),
WOOD_IDX,
xform,
)
)
# L-straps: two plates meeting at the vertical corner edge, proud of
# the post. Two plates, never three overlapping cubes.
strap_z0 = deck_z + 0.010
strap_h = top_z - IRON_DROP - strap_z0
zc = strap_z0 + strap_h / 2.0
# Outer face of each plate, after biting into the post.
px = CRATE_X / 2.0 + IRON_T - IRON_BITE
py = CRATE_Y / 2.0 + IRON_T - IRON_BITE
plates = []
for sxn in (-1.0, 1.0):
for syn in (-1.0, 1.0):
plates.extend(add_strap(bm, sxn, syn, px, py, strap_z0, strap_h, xform))
# Nails are placed from the plate's own outer face and normal, so they
# follow the strap if its thickness, bite or wrap ever changes.
nail_stations = []
for sxn in (-1.0, 1.0):
for syn in (-1.0, 1.0):
for fz in NAIL_ZS:
z = strap_z0 + strap_h * fz
nail_stations.append(
(Vector((sxn * px, syn * (py - IRON_WRAP * 0.5), z)),
Vector((sxn, 0.0, 0.0)))
)
nail_stations.append(
(Vector((sxn * (px - IRON_WRAP * 0.5), syn * py, z)),
Vector((0.0, syn, 0.0)))
)
for face_pt, nrm in nail_stations:
add_nail(bm, face_pt, nrm, xform, lift=FLOAT_NAIL_LIFT if float_nails else 0.0)
return wood, side_w, plates
def add_strap(bm, sxn, syn, px, py, z0, h, xform):
"""One L-section corner strap, a single closed shell.
Two overlapping boxes shared their outer corner edge, so once the iron
was chamfered both boxes put a strip on the same line: a coplanar pair
at every corner. An extruded L has one outer corner. Each cap is two
convex quads meeting on the inner-corner diagonal, so there is no n-gon.
"""
outline = [
(px, py - IRON_WRAP),
(px, py),
(px - IRON_WRAP, py),
(px - IRON_WRAP, py - IRON_T),
(px - IRON_T, py - IRON_T),
(px - IRON_T, py - IRON_WRAP),
]
rings = []
for z in (z0, z0 + h):
rings.append(
[bm.verts.new(xform @ Vector((sxn * x, syn * y, z))) for x, y in outline]
)
lo, hi = rings
faces = []
# Bottom cap wound opposite the top so the shell is consistently
# oriented; recalc_face_normals later points it outward.
for ring, flip in ((lo, True), (hi, False)):
for quad in ((0, 1, 4, 5), (1, 2, 3, 4)):
vs = [ring[k] for k in quad]
faces.append(bm.faces.new(vs[::-1] if flip else vs))
n = len(outline)
for i in range(n):
j = (i + 1) % n
faces.append(bm.faces.new((lo[i], lo[j], hi[j], hi[i])))
for f in faces:
f.material_index = METAL_IDX
return lo + hi
def add_nail(bm, face_pt, nrm, xform, lift=0.0):
"""A frustum nail head seated NAIL_BITE into the plate at *face_pt*."""
geo = bmesh.ops.create_cone(
bm,
cap_ends=True,
cap_tris=True,
segments=NAIL_SEGS,
radius1=NAIL_R,
radius2=NAIL_R_TOP,
depth=NAIL_H,
)
orient = nrm.to_track_quat("Z", "Y").to_matrix().to_4x4()
seat = Matrix.Translation(face_pt + nrm * lift) @ orient @ Matrix.Translation(
(0.0, 0.0, NAIL_H / 2.0 - NAIL_BITE)
)
verts = geo["verts"]
for v in verts:
v.co = xform @ (seat @ v.co)
for f in {f for v in verts for f in v.link_faces}:
f.material_index = METAL_IDX
def build_stack_mesh(
name,
same_seed=False,
short_skids=False,
float_stack=False,
float_nails=False,
sharp_iron=False,
):
bm = bmesh.new()
wood_verts = []
plate_verts = []
try:
base_z = 0.0
for i in range(N_CRATES):
# Two streams. The design stream is what --same-seed collapses:
# yaw and plank widths, the things that make each crate its own
# instance. The placement stream stays per-instance either way,
# so the falsified stack keeps the same footprint and fails on
# the variation budget rather than on the bounding box.
seed = STACK_SEED if same_seed else STACK_SEED + i * 7
rng = random.Random(seed)
place = random.Random(STACK_SEED * 31 + i)
sign = 1.0 if i % 2 == 0 else -1.0
yaw = sign * (YAW_MIN + rng.random() * (YAW_MAX - YAW_MIN - 0.02))
offset = (
0.0 if i == 0 else place.uniform(-OFFSET_MAX, OFFSET_MAX),
0.0 if i == 0 else place.uniform(-OFFSET_MAX, OFFSET_MAX),
)
lift = FLOAT_LIFT if (float_stack and i == N_CRATES - 1) else 0.0
verts, _widths, plates = build_crate(
bm,
base_z + lift,
yaw,
rng,
offset=offset,
short_skids=short_skids and i == 0,
float_nails=float_nails,
)
wood_verts.extend(verts)
plate_verts.extend(plates)
base_z += CRATE_H - STACK_BITE
# Iron first, at its own finer offset: the plates are only 3.5 mm
# thick. The nails are frustums and need no bevel.
# The flat diagonal inside each L cap is not an edge anyone sees,
# and chamfering it would crease a flat face.
if plate_verts and not sharp_iron:
edges = [
e for e in {e for v in plate_verts for e in v.link_edges}
if len(e.link_faces) == 2 and e.calc_face_angle(0.0) > 1e-3
]
# material= pins the chamfer faces to iron; left to default,
# bevel handed them slot 0 and the plates rendered as timber.
bmesh.ops.bevel(
bm,
geom=edges,
offset=IRON_BEVEL,
segments=1,
profile=0.5,
affect="EDGES",
clamp_overlap=True,
material=METAL_IDX,
)
if wood_verts:
edges = list({e for v in wood_verts for e in v.link_edges if v.is_valid})
if edges:
bmesh.ops.bevel(
bm,
geom=edges,
offset=0.0018,
segments=1,
profile=0.5,
affect="EDGES",
clamp_overlap=True,
)
pack_uvs(bm)
bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces))
for face in bm.faces:
face.smooth = True
for edge in bm.edges:
edge.smooth = True
if edge.is_manifold and len(edge.link_faces) == 2:
if edge.calc_face_angle() > math.radians(35.0):
edge.smooth = False
me = bpy.data.meshes.new(name)
bm.to_mesh(me)
me.update()
finally:
bm.free()
paint_planks(me)
obj = bpy.data.objects.new(name, me)
bpy.context.collection.objects.link(obj)
return obj
def paint_planks(me):
"""Per-plank tone and grain direction, as face attributes.
Every plank came out of one material, so every plank was the same
board. Each shell gets a seeded tone and the direction it runs in —
its long axis, recovered from its own vertices — which the wood shader
uses to stretch its grain along the board rather than along a world
axis that is 6 degrees off on a yawed crate.
"""
tone = [0.5] * len(me.polygons)
grain = [(1.0, 0.0, 0.0)] * len(me.polygons)
vf = vert_faces(me)
rng = random.Random(STACK_SEED * 13)
for g in shells(me):
pts = [me.vertices[i].co for i in g]
e1, _e2, theta = xy_principal(pts)
dz = max(p.z for p in pts) - min(p.z for p in pts)
d = (0.0, 0.0, 1.0) if dz > e1 else (math.cos(theta), math.sin(theta), 0.0)
t = 0.5 + rng.uniform(-PLANK_TONE_JITTER, PLANK_TONE_JITTER)
for fi in {fi for i in g for fi in vf[i]}:
tone[fi] = t
grain[fi] = d
a = me.attributes.new("PlankTone", "FLOAT", "FACE")
a.data.foreach_set("value", tone)
b = me.attributes.new("GrainDir", "FLOAT_VECTOR", "FACE")
b.data.foreach_set("vector", [c for v in grain for c in v])
def principled(name, color, metallic, roughness, noise_scale=0.0, wear=None):
mat = bpy.data.materials.new(name)
mat.use_nodes = True
nt = mat.node_tree
bsdf = nt.nodes["Principled BSDF"]
bsdf.inputs["Base Color"].default_value = color
bsdf.inputs["Metallic"].default_value = metallic
bsdf.inputs["Roughness"].default_value = roughness
if noise_scale > 0.0 and wear is not None:
tex = nt.nodes.new("ShaderNodeTexNoise")
tex.inputs["Scale"].default_value = noise_scale
tex.inputs["Detail"].default_value = 8.0
tex.inputs["Roughness"].default_value = 0.55
mix = nt.nodes.new("ShaderNodeMix")
mix.data_type = "RGBA"
mix.inputs["A"].default_value = color
mix.inputs["B"].default_value = wear
fac = mix.inputs.get("Factor") or mix.inputs.get("Fac")
nt.links.new(tex.outputs["Fac"], fac)
nt.links.new(mix.outputs["Result"], bsdf.inputs["Base Color"])
rmix = nt.nodes.new("ShaderNodeMix")
rmix.data_type = "FLOAT"
rmix.inputs["A"].default_value = roughness
rmix.inputs["B"].default_value = min(1.0, roughness + 0.18)
rfac = rmix.inputs.get("Factor") or rmix.inputs.get("Fac")
nt.links.new(tex.outputs["Fac"], rfac)
nt.links.new(rmix.outputs["Result"], bsdf.inputs["Roughness"])
return mat
def _sock(sockets, identifier):
"""A Mix-node socket by identifier; its A/B/Result names repeat per type."""
return next(s for s in sockets if s.identifier == identifier)
def wood_material(name):
"""Timber whose grain runs along each board and whose tone varies by plank.
Reads the ``PlankTone`` and ``GrainDir`` face attributes that
``paint_planks`` writes. The grain is noise sampled in object space with
the component along the board compressed, so its streaks are long in
the direction the plank runs whatever the crate's yaw.
"""
mat = bpy.data.materials.new(name)
mat.use_nodes = True
nt = mat.node_tree
bsdf = nt.nodes["Principled BSDF"]
bsdf.inputs["Metallic"].default_value = 0.0
coord = nt.nodes.new("ShaderNodeTexCoord")
gdir = nt.nodes.new("ShaderNodeAttribute")
gdir.attribute_name = "GrainDir"
tone = nt.nodes.new("ShaderNodeAttribute")
tone.attribute_name = "PlankTone"
dot = nt.nodes.new("ShaderNodeVectorMath")
dot.operation = "DOT_PRODUCT"
nt.links.new(coord.outputs["Object"], dot.inputs[0])
nt.links.new(gdir.outputs["Vector"], dot.inputs[1])
squash = nt.nodes.new("ShaderNodeMath")
squash.operation = "MULTIPLY"
squash.inputs[1].default_value = 0.94
nt.links.new(dot.outputs["Value"], squash.inputs[0])
along = nt.nodes.new("ShaderNodeVectorMath")
along.operation = "SCALE"
nt.links.new(gdir.outputs["Vector"], along.inputs[0])
nt.links.new(squash.outputs["Value"], along.inputs["Scale"])
grain_co = nt.nodes.new("ShaderNodeVectorMath")
grain_co.operation = "SUBTRACT"
nt.links.new(coord.outputs["Object"], grain_co.inputs[0])
nt.links.new(along.outputs["Vector"], grain_co.inputs[1])
# Plank tone also offsets the grain sample, so neighbouring boards do
# not show one continuous figure across the gap between them.
shift = nt.nodes.new("ShaderNodeVectorMath")
shift.operation = "ADD"
nt.links.new(grain_co.outputs["Vector"], shift.inputs[0])
nt.links.new(tone.outputs["Fac"], shift.inputs[1])
noise = nt.nodes.new("ShaderNodeTexNoise")
noise.inputs["Scale"].default_value = 34.0
noise.inputs["Detail"].default_value = 6.0
noise.inputs["Roughness"].default_value = 0.62
nt.links.new(shift.outputs["Vector"], noise.inputs["Vector"])
ramp = nt.nodes.new("ShaderNodeValToRGB")
ramp.color_ramp.elements[0].position = 0.30
ramp.color_ramp.elements[0].color = (0.105, 0.045, 0.016, 1.0)
ramp.color_ramp.elements[1].position = 0.72
ramp.color_ramp.elements[1].color = (0.34, 0.16, 0.060, 1.0)
nt.links.new(noise.outputs["Fac"], ramp.inputs["Fac"])
gain = nt.nodes.new("ShaderNodeMath")
gain.operation = "MULTIPLY_ADD"
gain.inputs[1].default_value = 1.2
gain.inputs[2].default_value = 0.40
nt.links.new(tone.outputs["Fac"], gain.inputs[0])
mix = nt.nodes.new("ShaderNodeMix")
mix.data_type = "RGBA"
mix.blend_type = "MULTIPLY"
_sock(mix.inputs, "Factor_Float").default_value = 1.0
nt.links.new(ramp.outputs["Color"], _sock(mix.inputs, "A_Color"))
nt.links.new(gain.outputs["Value"], _sock(mix.inputs, "B_Color"))
nt.links.new(_sock(mix.outputs, "Result_Color"), bsdf.inputs["Base Color"])
rough = nt.nodes.new("ShaderNodeMapRange")
rough.inputs["To Min"].default_value = 0.72
rough.inputs["To Max"].default_value = 0.52
nt.links.new(noise.outputs["Fac"], rough.inputs["Value"])
nt.links.new(rough.outputs["Result"], bsdf.inputs["Roughness"])
return mat
def stack_materials():
"""(wood, iron) — shared by the check path, the render and inspection."""
wood = wood_material("StackWood")
metal = principled(
"StackMetal", (0.17, 0.165, 0.155, 1.0), 0.80, 0.46,
noise_scale=18.0, wear=(0.20, 0.085, 0.032, 1.0),
)
return wood, metal
def assign_slots(obj, wood, metal):
mats = obj.data.materials
for i, mat in enumerate((wood, metal)):
if i < len(mats):
mats[i] = mat
else:
mats.append(mat)
def world_bbox(obj):
corners = [obj.matrix_world @ Vector(c) for c in obj.bound_box]
xs = [c.x for c in corners]
ys = [c.y for c in corners]
zs = [c.z for c in corners]
return (min(xs), min(ys), min(zs), max(xs), max(ys), max(zs))
def uv_stats(mesh):
"""UV bounds plus AABB overlap area, bucketed so this stays linear."""
uv = mesh.uv_layers.active
if uv is None:
return 0.0, 0.0, 1.0, 1.0, 0.0, 0
data = uv.data
us = [loop.uv[0] for loop in data]
vs = [loop.uv[1] for loop in data]
aabbs = []
for poly in mesh.polygons:
pu = [data[i].uv[0] for i in poly.loop_indices]
pv = [data[i].uv[1] for i in poly.loop_indices]
aabbs.append((min(pu), min(pv), max(pu), max(pv)))
# Bucket on a grid at least as coarse as the largest island, so any
# overlapping pair lands in a shared cell. O(n) instead of O(n^2).
span = max(
1e-6,
max((a[2] - a[0]) for a in aabbs),
max((a[3] - a[1]) for a in aabbs),
)
buckets = {}
for i, a in enumerate(aabbs):
c0 = int(math.floor(a[0] / span))
c1 = int(math.floor(a[2] / span))
r0 = int(math.floor(a[1] / span))
r1 = int(math.floor(a[3] / span))
for c in range(c0, c1 + 1):
for r in range(r0, r1 + 1):
buckets.setdefault((c, r), []).append(i)
overlap = 0.0
seen = set()
for members in buckets.values():
for ii in range(len(members)):
for jj in range(ii + 1, len(members)):
i, j = members[ii], members[jj]
key = (i, j) if i < j else (j, i)
if key in seen:
continue
seen.add(key)
a, b = aabbs[i], aabbs[j]
x0 = max(a[0], b[0])
y0 = max(a[1], b[1])
x1 = min(a[2], b[2])
y1 = min(a[3], b[3])
overlap += max(0.0, x1 - x0) * max(0.0, y1 - y0)
return min(us), min(vs), max(us), max(vs), overlap, len(aabbs)
def face_area(me, poly):
idxs = poly.vertices
if len(idxs) < 3:
return 0.0
v0 = me.vertices[idxs[0]].co
area = 0.0
for i in range(1, len(idxs) - 1):
vs = (me.vertices[idxs[i]].co, me.vertices[idxs[i + 1]].co)
area += (vs[0] - v0).cross(vs[1] - v0).length * 0.5
return area
def hygiene_audit(me):
nv, ne, nf = len(me.vertices), len(me.edges), len(me.polygons)
ngons = sum(1 for p in me.polygons if len(p.vertices) > 4)
zero_area = sum(1 for p in me.polygons if face_area(me, p) <= AREA_EPS)
bm = bmesh.new()
try:
bm.from_mesh(me)
bm.verts.ensure_lookup_table()
bm.edges.ensure_lookup_table()
loose_v = sum(1 for v in bm.verts if len(v.link_edges) == 0)
loose_e = sum(1 for e in bm.edges if len(e.link_faces) == 0)
nonman = sum(1 for e in bm.edges if not e.is_manifold)
ret = bmesh.ops.find_doubles(bm, verts=list(bm.verts), dist=DOUBLES_EPS)
doubles = len(ret.get("targetmap") or {})
finally:
bm.free()
return {
"nv": nv, "ne": ne, "nf": nf, "ngons": ngons,
"loose_v": loose_v, "loose_e": loose_e, "nonman": nonman,
"zero_area": zero_area, "doubles": doubles,
}
def zfight_pairs(me):
"""Coplanar, near-coincident face pairs that share no vertex.
Bucketed on a grid of ZFIGHT_EPS so a 2500-face stack does not cost
three million Python-level pair tests in smoke.
"""
data = [
(p.center.copy(), p.normal.copy(), frozenset(p.vertices))
for p in me.polygons
]
cell = ZFIGHT_EPS
buckets = {}
for i, (c, _n, _v) in enumerate(data):
key = (
int(math.floor(c.x / cell)),
int(math.floor(c.y / cell)),
int(math.floor(c.z / cell)),
)
buckets.setdefault(key, []).append(i)
eps2 = ZFIGHT_EPS * ZFIGHT_EPS
count = 0
checked = set()
for key, members in buckets.items():
kx, ky, kz = key
near = []
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
for dz in (-1, 0, 1):
near.extend(buckets.get((kx + dx, ky + dy, kz + dz), ()))
for i in members:
ci, ni, vi = data[i]
for j in near:
if j == i:
continue
pair = (i, j) if i < j else (j, i)
if pair in checked:
continue
checked.add(pair)
cj, nj, vj = data[j]
if (cj - ci).length_squared > eps2:
continue
if abs(ni.dot(nj)) <= ZFIGHT_COS:
continue
if vi & vj:
continue
count += 1
return count
def shells(me):
neighbors = [[] for _ in range(len(me.vertices))]
for edge in me.edges:
a, b = edge.vertices
neighbors[a].append(b)
neighbors[b].append(a)
seen = [False] * len(me.vertices)
groups = []
for start in range(len(me.vertices)):
if seen[start]:
continue
seen[start] = True
stack = [start]
group = []
while stack:
current = stack.pop()
group.append(current)
for nxt in neighbors[current]:
if not seen[nxt]:
seen[nxt] = True
stack.append(nxt)
groups.append(group)
return groups
def shell_aabb(me, group):
pts = [me.vertices[i].co for i in group]
return (
min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts),
max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts),
)
def mat_of(me, group, face_of_vert):
member = set(group)
for i in group:
for fi in face_of_vert[i]:
poly = me.polygons[fi]
if all(v in member for v in poly.vertices):
return poly.material_index
return None
def vert_faces(me):
table = [[] for _ in range(len(me.vertices))]
for fi, poly in enumerate(me.polygons):
for vi in poly.vertices:
table[vi].append(fi)
return table
def xy_principal(pts):
"""Long/short XY extent and orientation of a shell, free of world yaw.
Every part is an axis-aligned box in its crate's frame, then rotated
about Z. A world-AABB test therefore measures the rotated bounding
box, not the part: a 0.554 m board yawed 0.09 rad reports 0.061 m of
depth instead of its 0.013 m thickness, and every shape filter keyed
to thickness silently matches nothing. Recovering the box's own axes
by principal components makes the classification yaw-invariant, and
hands back the yaw as a by-product.
"""
n = len(pts)
cx = sum(p.x for p in pts) / n
cy = sum(p.y for p in pts) / n
sxx = syy = sxy = 0.0
for p in pts:
dx, dy = p.x - cx, p.y - cy
sxx += dx * dx
syy += dy * dy
sxy += dx * dy
theta = 0.5 * math.atan2(2.0 * sxy, sxx - syy)
c, s = math.cos(theta), math.sin(theta)
us = [(p.x - cx) * c + (p.y - cy) * s for p in pts]
vs = [-(p.x - cx) * s + (p.y - cy) * c for p in pts]
e1 = max(us) - min(us)
e2 = max(vs) - min(vs)
if e1 < e2:
e1, e2 = e2, e1
theta += math.pi / 2.0
while theta > math.pi / 2.0:
theta -= math.pi
while theta <= -math.pi / 2.0:
theta += math.pi
return e1, e2, theta
def _levels_from_runners(cands):
"""Stack bases, clustered from the runners the mesh actually has.
Binning against the declared pitch put a lid — which sits 8 mm below
the next crate's base — on the wrong level the moment a falsifier
shifted a crate, and the seat budget then compared a crate against
itself. Clustering the measured runner heights instead makes the
bands follow the geometry, including when a falsifier moves it.
"""
bases = []
for z in sorted(cands):
if not bases or z - bases[-1] > CRATE_H * 0.5:
bases.append(z)
else:
bases[-1] = min(bases[-1], z)
return bases
def classify(me):
"""Bin every wood shell to a stack level and name the parts.
Two passes: find the runners, cluster their heights into stack bases,
then assign every shell to the highest base at or below it. Only the
identification uses the layout; every number a budget later asserts
on — heights, gaps, yaws, footprints — is measured from vertices.
"""
vf = vert_faces(me)
wood = []
for g in shells(me):
if mat_of(me, g, vf) != WOOD_IDX:
continue
pts = [me.vertices[i].co for i in g]
zmin = min(p.z for p in pts)
zmax = max(p.z for p in pts)
e1, e2, theta = xy_principal(pts)
wood.append(
{
"g": g, "zmin": zmin, "dz": zmax - zmin,
"e1": e1, "e2": e2, "yaw": theta,
}