-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcampfire.py
More file actions
1523 lines (1396 loc) · 53.5 KB
/
Copy pathcampfire.py
File metadata and controls
1523 lines (1396 loc) · 53.5 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 campfire — a showcase piece, not an example.
Asserts budget conformance of a procedural campfire (two-course
wedge-stone ring stacked on a shared plane, pit-floor cobbles and ash,
a kissing log tripod, and resting firewood) after composing shipped
pipeline pieces: bmesh construction, UVs, three materials, high-to-low
normal bake, LOD chain, convex collider, Unity glTF export.
The old piece was two floating courses of identical boxes with a
daylight mortar gap, a 12-gon teepee whose tips occupied the same
point, and an empty pit.
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-stones`` named
bottom-course supports, ``--float-logs`` teepee kiss, ``--gap-courses``
the stacked-course seat.
Fixed seed 17 for stone-width jitter. 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 campfire.py --
blender --background --python campfire.py -- --skip-decimate
blender --background --python campfire.py -- --output campfire.png
"""
import argparse
import math
import os
import random
import sys
import tempfile
import traceback
import bmesh
import bpy
from mathutils import 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
N_AROUND = 14
N_ROWS = 2
R_INNER = 0.26
R_OUTER = 0.39
R_MID = 0.5 * (R_INNER + R_OUTER)
STONE_H = 0.078
STONE_SEED = 17
STONE_JITTER = 0.22
# Each ring stone is a lofted chamfered section, not a curved brick: a
# seeded belly and radial offset, rounded ends pinched to END_PINCH, and
# (upper course only) a domed crown. Beds stay flat so the courses seat.
STONE_R_JITTER = 0.012
STONE_BULGE = 0.14
STONE_WOBBLE = 0.05
STONE_DOME = 0.020
END_PINCH = 0.62
STONE_CHAMFER = 0.28
STONE_VARY_MIN = 0.006
GAP_ANG = 0.004
N_COBBLES = 12
COBBLE_H = 0.016
ASH_H = 0.010
ASH_R = 0.20
N_STICKS = 3
STICK_R = 0.028
STICK_SEGS = 12
LOG_R = 0.030
LOG_LEN = 0.28
Z_APEX = 0.365
R_BASE = 0.20
COURSE_GAP = 0.022
FLOAT_LOG = 0.055
SHORT_STONES_LIFT = 0.040
LIFT_Z = 0.05
KISS_MAX = 0.008
COURSE_SEAT_MAX = 0.004
STAVE_ZMIN_MAX = 0.001
AREA_EPS = 1e-10
DOUBLES_EPS = 1e-5
ZMIN_EPS = 1e-4
ZFIGHT_EPS = 1e-4
ZFIGHT_COS = 0.998
BODY_TOL = 0.04
RING_DIA = 0.807
RING_H = 0.176
BBOX_TOL = 0.015
OUTER_SIZE = (0.807, 0.808, 0.404)
BASE_TRIS_MIN = 1400
BASE_TRIS_MAX = 3600
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 = 3
WOOD_FACES_MIN = 80
ASH_FACES_MIN = 24
STONE_FACES_MIN = 200
UV_EPS = 1e-4
UV_OVERLAP_MAX = 1e-5
COLLIDER_TRIS_MAX = 360
BAKE_RES = 256
CAGE_EXTRUSION = 0.06
BOTTOM_COUNT = N_AROUND
STONE_IDX = 0
WOOD_IDX = 1
ASH_IDX = 2
# Per-piece tone jitter and wood grain frequency, as in shipping-crate.
PLANK_TONE_JITTER = 0.25
TONE_SEED = 29
WOOD_GRAIN_SCALE = 45.0
def eevee_engine_id():
return "BLENDER_EEVEE" if bpy.app.version >= (5, 0, 0) else "BLENDER_EEVEE_NEXT"
def fail(msg, code):
print(f"ERROR: {msg}", file=sys.stderr)
return code
def triangle_count(mesh):
mesh.calc_loop_triangles()
return len(mesh.loop_triangles)
def evaluated_triangle_count(obj):
depsgraph = bpy.context.evaluated_depsgraph_get()
eval_obj = obj.evaluated_get(depsgraph)
eval_mesh = eval_obj.to_mesh()
try:
eval_mesh.calc_loop_triangles()
return len(eval_mesh.loop_triangles)
finally:
eval_obj.to_mesh_clear()
def stone_spans(n, gap_ang, jitter, seed):
rng = random.Random(seed)
weights = [1.0 + rng.uniform(-jitter, jitter) for _ in range(n)]
total = sum(weights)
usable = 2.0 * math.pi - n * gap_ang
spans = []
a = 0.0
for w in weights:
width = usable * (w / total)
spans.append((a, a + width))
a += width + gap_ang
return spans
def add_stone(bm, a0, a1, z0, z1, rng, crown, stations, mat_idx):
"""One ring stone: a chamfered octagon section lofted from a0 to a1.
The section's width swells to a seeded belly mid-stone and pinches to
END_PINCH at the ends, which are capped, so each stone is a rounded
lump rather than a curved brick. The bed (z0) is flat on every stone.
The crown is flat at z1 on the lower course, which the upper course
sits on, and domed by a seeded ``crown`` on the upper course.
"""
r_in = R_INNER + rng.uniform(-STONE_R_JITTER, STONE_R_JITTER)
r_out = R_OUTER + rng.uniform(-STONE_R_JITTER, STONE_R_JITTER)
bulge = rng.uniform(0.3, 1.0) * STONE_BULGE
phase = rng.uniform(0.0, 2.0 * math.pi)
top = z1 + crown
rings = []
for k in range(stations):
t = k / (stations - 1)
ang = a0 + (a1 - a0) * t
sw = math.sin(math.pi * t)
pinch = END_PINCH + (1.0 - END_PINCH) * math.sqrt(sw)
cr = 0.5 * (r_in + r_out)
hw = 0.5 * (r_out - r_in) * pinch * (1.0 + bulge * sw)
lo = cr - hw
hi = cr + hw * (1.0 + STONE_WOBBLE * math.sin(phase + 3.0 * math.pi * t))
zt = z0 + (top - z0) * (0.80 + 0.20 * sw)
c = STONE_CHAMFER * min(hi - lo, zt - z0) * 0.5
section = (
(lo + c, z0), (hi - c, z0), (hi, z0 + c), (hi, zt - c),
(hi - c, zt), (lo + c, zt), (lo, zt - c), (lo, z0 + c),
)
ca, sa = math.cos(ang), math.sin(ang)
rings.append([bm.verts.new((r * ca, r * sa, z)) for r, z in section])
n = len(rings[0])
for k in range(stations - 1):
a, b = rings[k], rings[k + 1]
for i in range(n):
j = (i + 1) % n
f = bm.faces.new((a[i], a[j], b[j], b[i]))
f.material_index = mat_idx
for ring, flip in ((rings[0], False), (rings[-1], True)):
hub = bm.verts.new(sum((v.co for v in ring), Vector()) / n)
for i in range(n):
vs = (hub, ring[(i + 1) % n], ring[i])
f = bm.faces.new(tuple(reversed(vs)) if flip else vs)
f.material_index = mat_idx
return [v for ring in rings for v in ring]
def add_cyl_between(bm, a, b, r0, r1, segs, mat_idx):
a = Vector(a)
b = Vector(b)
delta = b - a
length = delta.length
if length < 1e-8:
return []
geo = bmesh.ops.create_cone(
bm,
cap_ends=True,
cap_tris=True,
segments=segs,
radius1=r0,
radius2=r1,
depth=length,
)
verts = list(geo["verts"])
quat = Vector((0.0, 0.0, 1.0)).rotation_difference(delta.normalized())
rot = quat.to_matrix()
mid = (a + b) * 0.5
for v in verts:
v.co = rot @ v.co + mid
faces = {f for v in verts for f in v.link_faces}
for f in faces:
f.material_index = mat_idx
return verts
def add_ash_disk(bm, radius, height, segs, mat_idx):
geo = bmesh.ops.create_cone(
bm,
cap_ends=True,
cap_tris=True,
segments=segs,
radius1=radius,
radius2=radius * 0.92,
depth=height,
)
verts = list(geo["verts"])
for v in verts:
v.co.z += height * 0.5
faces = {f for v in verts for f in v.link_faces}
for f in faces:
f.material_index = mat_idx
return verts
def triangulate_ngons(bm):
faces = [f for f in bm.faces if len(f.verts) > 4]
if faces:
bmesh.ops.triangulate(bm, faces=faces)
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 = abs(nrm.x)
ay = abs(nrm.y)
az = 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 build_campfire_mesh(
name,
bevel_offset,
bevel_segments,
short_stones=False,
float_logs=False,
gap_courses=False,
uniform_stones=False,
):
bm = bmesh.new()
spans = stone_spans(N_AROUND, GAP_ANG, STONE_JITTER, STONE_SEED)
z_ground = SHORT_STONES_LIFT if short_stones else 0.0
extra = COURSE_GAP if gap_courses else 0.0
stone_verts = []
try:
# --uniform-stones gives every stone the same draw: each jitter at its
# upper bound, so the stones are identical but the ring keeps the
# envelope of its widest seeded stone.
class _Flat:
def uniform(self, a, b):
return b
stations = 3 + bevel_segments
for row in range(N_ROWS):
z0 = z_ground + row * STONE_H + (extra if row else 0.0)
z1 = z0 + STONE_H
rot_off = (row % 2) * (math.pi / N_AROUND)
for idx, (a0, a1) in enumerate(spans):
rng = _Flat() if uniform_stones else random.Random(STONE_SEED * 31 + row * 101 + idx)
crown = STONE_DOME * rng.uniform(0.35, 1.0) if row == N_ROWS - 1 else 0.0
stone_verts.extend(
add_stone(
bm, a0 + rot_off, a1 + rot_off, z0, z1, rng, crown,
stations, STONE_IDX,
)
)
add_ash_disk(bm, ASH_R, ASH_H, 16, ASH_IDX)
rng = random.Random(STONE_SEED)
for i in range(N_COBBLES):
ang = 2.0 * math.pi * i / N_COBBLES + 0.18
r = 0.07 + 0.05 * ((i % 3) / 2.0)
sz = 0.028 + 0.010 * (i % 2)
loc = Vector((r * math.cos(ang), r * math.sin(ang), COBBLE_H * 0.5))
geo = bmesh.ops.create_cube(bm, size=1.0)
verts = geo["verts"]
for v in verts:
p = Vector((
v.co.x * (sz * 1.4),
v.co.y * sz,
v.co.z * COBBLE_H,
))
h = rng.uniform(-0.12, 0.12)
p = Vector((p.x * (1.0 + h), p.y * (1.0 - 0.5 * h), p.z))
rot_z = ang + rng.uniform(-0.2, 0.2)
c, s = math.cos(rot_z), math.sin(rot_z)
v.co = Vector((
p.x * c - p.y * s,
p.x * s + p.y * c,
p.z,
)) + loc
for f in {f for v in verts for f in v.link_faces}:
f.material_index = STONE_IDX
apex_ring = (STICK_R * 0.55) / math.sin(math.pi / N_STICKS)
if float_logs:
apex_ring *= 2.8
z_base = COBBLE_H + STICK_R * 0.35
overshoot = STICK_R * 1.15
for i in range(N_STICKS):
yaw = i * (2.0 * math.pi / N_STICKS) + math.pi / 6.0
base = Vector((
R_BASE * math.cos(yaw),
R_BASE * math.sin(yaw),
z_base,
))
apex = Vector((
apex_ring * math.cos(yaw),
apex_ring * math.sin(yaw),
Z_APEX - i * (STICK_R * 0.55),
))
direction = (apex - base).normalized()
end = apex + direction * overshoot
add_cyl_between(
bm, base, end, STICK_R, STICK_R * 0.78, STICK_SEGS, WOOD_IDX,
)
for i in range(2):
yaw = i * (math.pi / 2.0) + math.radians(22.0)
z = COBBLE_H + LOG_R + 0.010 * i
a = Vector((
0.5 * LOG_LEN * math.cos(yaw),
0.5 * LOG_LEN * math.sin(yaw),
z,
))
b = Vector((-a.x, -a.y, z))
add_cyl_between(bm, a, b, LOG_R * (1.0 - 0.06 * i), LOG_R * 0.86, 12, WOOD_IDX)
for i in range(6):
ang = 2.0 * math.pi * i / 6.0 + 0.4
r = 0.04 + 0.02 * (i % 2)
sz = 0.018 + 0.006 * (i % 3)
loc = (
r * math.cos(ang),
r * math.sin(ang),
ASH_H + sz * 0.45,
)
geo = bmesh.ops.create_cube(bm, size=1.0)
verts = geo["verts"]
for v in verts:
p = Vector((v.co.x * sz * 1.3, v.co.y * sz, v.co.z * sz * 0.7))
c, s = math.cos(ang), math.sin(ang)
v.co = Vector((p.x * c - p.y * s, p.x * s + p.y * c, p.z)) + Vector(loc)
for f in {f for v in verts for f in v.link_faces}:
f.material_index = WOOD_IDX
triangulate_ngons(bm)
bmesh.ops.remove_doubles(bm, verts=list(bm.verts), dist=1e-5)
bmesh.ops.dissolve_degenerate(bm, dist=1e-6)
pack_uvs(bm)
bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces))
for face in bm.faces:
face.smooth = face.material_index == WOOD_IDX
for edge in bm.edges:
mats = {f.material_index for f in edge.link_faces}
if WOOD_IDX in mats and STONE_IDX not in mats and ASH_IDX not in mats:
edge.smooth = True
if edge.is_manifold and len(edge.link_faces) == 2:
if edge.calc_face_angle() > math.radians(38.0):
edge.smooth = False
else:
edge.smooth = False
me = bpy.data.meshes.new(name)
bm.to_mesh(me)
me.update()
for poly in me.polygons:
poly.use_smooth = poly.material_index == WOOD_IDX
finally:
bm.free()
obj = bpy.data.objects.new(name, me)
bpy.context.collection.objects.link(obj)
return obj
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.16)
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 assign_slots(obj, stone, wood, ash):
mats = obj.data.materials
wanted = (stone, wood, ash)
for i, mat in enumerate(wanted):
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 face_area(me, poly):
verts = [me.vertices[i].co for i in poly.vertices]
if len(verts) < 3:
return 0.0
acc = Vector((0.0, 0.0, 0.0))
origin = verts[0]
for a, b in zip(verts[1:], verts[2:]):
acc += (a - origin).cross(b - origin)
return 0.5 * acc.length
def uv_stats(mesh):
uv = mesh.uv_layers.active
if uv is None:
return 0.0, 0.0, 1.0, 1.0, 0, 1.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)))
overlap = 0.0
for i in range(len(aabbs)):
a = aabbs[i]
for j in range(i + 1, len(aabbs)):
b = 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 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, "euler": nv - ne + nf,
}
def zfight_pairs(me):
data = [
(p.center.copy(), p.normal.copy(), frozenset(p.vertices))
for p in me.polygons
]
eps2 = ZFIGHT_EPS * ZFIGHT_EPS
count = 0
for i in range(len(data)):
ci, ni, vi = data[i]
for j in range(i + 1, len(data)):
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):
member = set(group)
for p in me.polygons:
if all(i in member for i in p.vertices):
return p.material_index
return None
def support_audit(me):
groups = shells(me)
bottoms = []
for g in groups:
if mat_of(me, g) != STONE_IDX:
continue
a = shell_aabb(me, g)
dz = a[5] - a[2]
r = 0.25 * ((a[3] - a[0]) + (a[4] - a[1]))
if dz > 0.05 and r > 0.04 and a[2] < 0.02:
bottoms.append(a)
zmin = min((a[2] for a in bottoms), default=99.0)
return {"stones": len(bottoms), "stone_z": zmin}
def course_seat(me):
groups = shells(me)
lower, upper = [], []
for g in groups:
if mat_of(me, g) != STONE_IDX:
continue
a = shell_aabb(me, g)
dz = a[5] - a[2]
r = 0.25 * ((a[3] - a[0]) + (a[4] - a[1]))
if dz < 0.05 or r < 0.04:
continue
mid = 0.5 * (a[2] + a[5])
if mid < STONE_H:
lower.append(a)
else:
upper.append(a)
if not lower or not upper:
return 99.0
return min(a[2] for a in upper) - max(a[5] for a in lower)
def teepee_kiss(me):
groups = shells(me)
sticks = []
for g in groups:
if mat_of(me, g) != WOOD_IDX:
continue
a = shell_aabb(me, g)
if a[5] < 0.25:
continue
sticks.append(g)
if len(sticks) < 2:
return 99.0
trees = []
for g in sticks:
bm_s = bmesh.new()
bm_s.from_mesh(me)
keep = set(g)
drop = [f for f in bm_s.faces if not all(v.index in keep for v in f.verts)]
if drop:
bmesh.ops.delete(bm_s, geom=drop, context="FACES")
if bm_s.faces:
trees.append((g, BVHTree.FromBMesh(bm_s), bm_s))
else:
bm_s.free()
best = 99.0
try:
for i in range(len(trees)):
g, _tree, _bm = trees[i]
zmax = max(me.vertices[k].co.z for k in g)
for j in range(i + 1, len(trees)):
tree = trees[j][1]
pair = 99.0
for k in g:
p = me.vertices[k].co
if p.z < zmax - 0.10:
continue
loc, _n, _idx, dist = tree.find_nearest(p)
if loc is None:
continue
pair = min(pair, dist)
best = min(best, pair)
return best
finally:
for _g, _t, bm_s in trees:
bm_s.free()
def stone_variation(me):
"""Spread of the ring stones' crowns and outer radii, in metres.
Identical stones read instantly as CG. Across the stones of each
course, the spread (max - min) of each stone's top and of its outer
radius is measured from the mesh; the smaller of the two spreads,
over both courses, must clear STONE_VARY_MIN.
"""
courses = {}
for g in shells(me):
if mat_of(me, g) != STONE_IDX:
continue
a = shell_aabb(me, g)
if a[5] - a[2] < 0.05:
continue
top = a[5]
r_out = max(math.hypot(me.vertices[i].co.x, me.vertices[i].co.y) for i in g)
row = 0 if 0.5 * (a[2] + a[5]) < STONE_H else 1
courses.setdefault(row, []).append((top, r_out))
spreads = []
for row, vals in courses.items():
tops = [v[0] for v in vals]
radii = [v[1] for v in vals]
if row == N_ROWS - 1:
spreads.append(max(tops) - min(tops))
spreads.append(max(radii) - min(radii))
return min(spreads, default=0.0)
def _long_axis(pts):
"""Principal axis of a point set, by power iteration on its covariance."""
c = sum(pts, Vector()) / len(pts)
cov = [[0.0] * 3 for _ in range(3)]
for p in pts:
d = p - c
for i in range(3):
for j in range(3):
cov[i][j] += d[i] * d[j]
v = Vector((1.0, 0.3, 0.1))
for _ in range(30):
w = Vector([sum(cov[i][j] * v[j] for j in range(3)) for i in range(3)])
if w.length < 1e-12:
break
v = w.normalized()
return v
def paint_pieces(me):
"""Per-shell ``PieceTone`` and ``GrainDir`` face attributes.
Every stone, stick and log is its own shell, so each gets one tone,
and the wood shader runs grain along each piece's own long axis.
"""
tone = [0.5] * len(me.polygons)
grain = [(0.0, 0.0, 1.0)] * len(me.polygons)
owner = {}
rng = random.Random(TONE_SEED)
for g in shells(me):
pts = [me.vertices[i].co.copy() for i in g]
d = _long_axis(pts) if len(pts) > 2 else Vector((0.0, 0.0, 1.0))
t = 0.5 + rng.uniform(-PLANK_TONE_JITTER, PLANK_TONE_JITTER)
for i in g:
owner[i] = (t, tuple(d))
for poly in me.polygons:
t, d = owner[poly.vertices[0]]
tone[poly.index] = t
grain[poly.index] = d
a = me.attributes.new("PieceTone", "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 _sock(sockets, identifier):
"""A Mix-node socket by identifier; its A/B/Result names repeat per type."""
return next(sk for sk in sockets if sk.identifier == identifier)
def wood_material(name):
"""Grain along each stick and log (``GrainDir``), tone per piece (``PieceTone``)."""
mat = bpy.data.materials.new(name)
mat.use_nodes = True
nt = mat.node_tree
bsdf = nt.nodes["Principled BSDF"]
coord = nt.nodes.new("ShaderNodeTexCoord")
gdir = nt.nodes.new("ShaderNodeAttribute")
gdir.attribute_name = "GrainDir"
tone = nt.nodes.new("ShaderNodeAttribute")
tone.attribute_name = "PieceTone"
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])
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 = WOOD_GRAIN_SCALE
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.12, 0.052, 0.018, 1.0)
ramp.color_ramp.elements[1].position = 0.72
ramp.color_ramp.elements[1].color = (0.38, 0.18, 0.065, 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.1
gain.inputs[2].default_value = 0.45
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"])
# Char: heat falls off with distance from the fire's core (the ash bed at
# the ring centre), so the tripod blackens toward the flames and keeps its
# bark colour at the far ends. Inside the char, cracked embers glow.
heat = _heat_field(nt, coord)
char = nt.nodes.new("ShaderNodeMapRange")
char.inputs["From Min"].default_value = 0.12
char.inputs["From Max"].default_value = 0.55
nt.links.new(heat, char.inputs["Value"])
cmix = nt.nodes.new("ShaderNodeMix")
cmix.data_type = "RGBA"
nt.links.new(char.outputs["Result"], _sock(cmix.inputs, "Factor_Float"))
nt.links.new(_sock(mix.outputs, "Result_Color"), _sock(cmix.inputs, "A_Color"))
_sock(cmix.inputs, "B_Color").default_value = (0.016, 0.013, 0.011, 1.0)
nt.links.new(_sock(cmix.outputs, "Result_Color"), bsdf.inputs["Base Color"])
crack = nt.nodes.new("ShaderNodeTexVoronoi")
crack.feature = "DISTANCE_TO_EDGE"
crack.inputs["Scale"].default_value = 42.0
nt.links.new(coord.outputs["Object"], crack.inputs["Vector"])
seam = nt.nodes.new("ShaderNodeMapRange")
seam.inputs["From Min"].default_value = 0.0
seam.inputs["From Max"].default_value = 0.035
seam.inputs["To Min"].default_value = 1.0
seam.inputs["To Max"].default_value = 0.0
nt.links.new(crack.outputs["Distance"], seam.inputs["Value"])
glow = nt.nodes.new("ShaderNodeMath")
glow.operation = "MULTIPLY"
nt.links.new(seam.outputs["Result"], glow.inputs[0])
hot = nt.nodes.new("ShaderNodeMapRange")
hot.inputs["From Min"].default_value = 0.70
hot.inputs["From Max"].default_value = 0.95
nt.links.new(heat, hot.inputs["Value"])
nt.links.new(hot.outputs["Result"], glow.inputs[1])
# only some of the cracks are live: a coarse noise mask breaks the net
live = nt.nodes.new("ShaderNodeTexNoise")
live.inputs["Scale"].default_value = 9.0
live.inputs["Detail"].default_value = 2.0
nt.links.new(coord.outputs["Object"], live.inputs["Vector"])
lmap = nt.nodes.new("ShaderNodeMapRange")
lmap.inputs["From Min"].default_value = 0.48
lmap.inputs["From Max"].default_value = 0.62
nt.links.new(live.outputs["Fac"], lmap.inputs["Value"])
masked = nt.nodes.new("ShaderNodeMath")
masked.operation = "MULTIPLY"
nt.links.new(glow.outputs["Value"], masked.inputs[0])
nt.links.new(lmap.outputs["Result"], masked.inputs[1])
bsdf.inputs["Emission Color"].default_value = (1.0, 0.30, 0.05, 1.0)
estr = nt.nodes.new("ShaderNodeMath")
estr.operation = "MULTIPLY"
estr.inputs[1].default_value = 3.5
nt.links.new(masked.outputs["Value"], estr.inputs[0])
nt.links.new(estr.outputs["Value"], bsdf.inputs["Emission Strength"])
return mat
def _heat_field(nt, coord):
"""0..1 heat: 1 at the fire's core just above the ash bed, 0 by ~0.34 m out."""
off = nt.nodes.new("ShaderNodeVectorMath")
off.operation = "SUBTRACT"
off.inputs[1].default_value = (0.0, 0.0, 0.06)
nt.links.new(coord.outputs["Object"], off.inputs[0])
dist = nt.nodes.new("ShaderNodeVectorMath")
dist.operation = "LENGTH"
nt.links.new(off.outputs["Vector"], dist.inputs[0])
heat = nt.nodes.new("ShaderNodeMapRange")
heat.inputs["From Min"].default_value = 0.34
heat.inputs["From Max"].default_value = 0.04
nt.links.new(dist.outputs["Value"], heat.inputs["Value"])
return heat.outputs["Result"]
def stone_material(name, light, dark, roughness, mottle, speck, bump, soot=0.0, spread=0.8):
"""Fieldstone: isotropic mottling, speckle and pitting, a tone per stone.
Copied from stone-archway, reading ``PieceTone`` for the per-stone
shade. Nothing in the pattern has a direction, so it cannot read as
wood grain the way stretched noise does.
"""
mat = bpy.data.materials.new(name)
mat.use_nodes = True
nt = mat.node_tree
bsdf = nt.nodes["Principled BSDF"]
coord = nt.nodes.new("ShaderNodeTexCoord")
mot = nt.nodes.new("ShaderNodeTexNoise")
mot.inputs["Scale"].default_value = mottle
mot.inputs["Detail"].default_value = 4.0
mot.inputs["Roughness"].default_value = 0.55
nt.links.new(coord.outputs["Object"], mot.inputs["Vector"])
ramp = nt.nodes.new("ShaderNodeValToRGB")
ramp.color_ramp.elements[0].position = 0.32
ramp.color_ramp.elements[0].color = dark
ramp.color_ramp.elements[1].position = 0.70
ramp.color_ramp.elements[1].color = light
nt.links.new(mot.outputs["Fac"], ramp.inputs["Fac"])
spk = nt.nodes.new("ShaderNodeTexNoise")
spk.inputs["Scale"].default_value = speck
spk.inputs["Detail"].default_value = 2.0
nt.links.new(coord.outputs["Object"], spk.inputs["Vector"])
gain = nt.nodes.new("ShaderNodeMapRange")
gain.inputs["To Min"].default_value = 0.82
gain.inputs["To Max"].default_value = 1.12
nt.links.new(spk.outputs["Fac"], gain.inputs["Value"])
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["Result"], _sock(mix.inputs, "B_Color"))
tone = nt.nodes.new("ShaderNodeAttribute")
tone.attribute_name = "PieceTone"
shade = nt.nodes.new("ShaderNodeMath")
shade.operation = "MULTIPLY_ADD"
shade.inputs[1].default_value = spread
shade.inputs[2].default_value = 1.0 - 0.5 * spread
nt.links.new(tone.outputs["Fac"], shade.inputs[0])
mix2 = nt.nodes.new("ShaderNodeMix")
mix2.data_type = "RGBA"
mix2.blend_type = "MULTIPLY"
_sock(mix2.inputs, "Factor_Float").default_value = 1.0
nt.links.new(_sock(mix.outputs, "Result_Color"), _sock(mix2.inputs, "A_Color"))
nt.links.new(shade.outputs["Value"], _sock(mix2.inputs, "B_Color"))
nt.links.new(_sock(mix2.outputs, "Result_Color"), bsdf.inputs["Base Color"])
if soot:
# smoke-blackened where the stones face the fire, patchy by mottle
heat = _heat_field(nt, coord)
smap = nt.nodes.new("ShaderNodeMapRange")
smap.inputs["From Min"].default_value = 0.05
smap.inputs["From Max"].default_value = 0.40
smap.inputs["To Max"].default_value = soot
nt.links.new(heat, smap.inputs["Value"])
patch = nt.nodes.new("ShaderNodeMath")
patch.operation = "MULTIPLY"
nt.links.new(smap.outputs["Result"], patch.inputs[0])
nt.links.new(mot.outputs["Fac"], patch.inputs[1])
pmul = nt.nodes.new("ShaderNodeMath")
pmul.operation = "MULTIPLY"
pmul.inputs[1].default_value = 1.6
pmul.use_clamp = True
nt.links.new(patch.outputs["Value"], pmul.inputs[0])
smix = nt.nodes.new("ShaderNodeMix")
smix.data_type = "RGBA"
nt.links.new(pmul.outputs["Value"], _sock(smix.inputs, "Factor_Float"))
nt.links.new(_sock(mix2.outputs, "Result_Color"), _sock(smix.inputs, "A_Color"))
_sock(smix.inputs, "B_Color").default_value = (0.022, 0.019, 0.017, 1.0)
nt.links.new(_sock(smix.outputs, "Result_Color"), bsdf.inputs["Base Color"])
rough = nt.nodes.new("ShaderNodeMapRange")
rough.inputs["To Min"].default_value = roughness - 0.06
rough.inputs["To Max"].default_value = min(1.0, roughness + 0.08)
nt.links.new(spk.outputs["Fac"], rough.inputs["Value"])
nt.links.new(rough.outputs["Result"], bsdf.inputs["Roughness"])
if bump > 0.0:
bmp = nt.nodes.new("ShaderNodeBump")
bmp.inputs["Strength"].default_value = bump
bmp.inputs["Distance"].default_value = 0.002
nt.links.new(spk.outputs["Fac"], bmp.inputs["Height"])
nt.links.new(bmp.outputs["Normal"], bsdf.inputs["Normal"])
return mat
def ash_material(name):