Files
Yanchen d1141b04c7 feat: 更新 IntoHole 的球体、滑槽和环境资产
- 为铁球、陶瓷球和木球制作风格化材质,归档 CC0 原始参考
- 更新方形球洞和实心滑槽,统一 90° 弯槽并兼容旧存档
- 用顺流泡沫表示水流方向,为冰块制作三种交错的裂纹
- 同步 Blender 源资产、Godot 加载、工坊和试玩预览
2026-11-19 16:18:41 +08:00

248 lines
11 KiB
Python

"""Run inside Blender: parameterized wooden chutes + an iron sphere.
Authoring axes: Z up. GLB export: (x, y, z) -> Godot (x, z, -y).
Dimensions and colliders originate here, never in the gameplay physics table.
"""
import bpy
import bmesh
import json
import math
from pathlib import Path
from mathutils import Vector
ROOT = Path(__file__).resolve().parents[4]
OUT = ROOT / 'assets/collections/baseline'
SOURCE = Path(__file__).resolve().parent
BALL_R = 0.3
FIT_CLEARANCE = 0.02
R = BALL_R + FIT_CLEARANCE
GOAL_R = BALL_R + FIT_CLEARANCE
GOAL_DEPTH = 0.55
SIDES = 64
OUT.mkdir(parents=True, exist_ok=True)
SOURCE.mkdir(parents=True, exist_ok=True)
(ROOT/'playtest/artifacts/baseline').mkdir(parents=True, exist_ok=True)
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
bpy.context.preferences.filepaths.save_version = 0
bpy.context.scene.unit_settings.system = 'METRIC'
bpy.context.scene.unit_settings.scale_length = 1.0
def material(name, color, roughness, metallic=0):
m = bpy.data.materials.new(name)
m.diffuse_color = (*color, 1)
m.use_nodes = True
node = m.node_tree.nodes.get('Principled BSDF')
node.inputs['Base Color'].default_value = (*color, 1)
node.inputs['Roughness'].default_value = roughness
node.inputs['Metallic'].default_value = metallic
return m
wood = material('Painted wood - warm ochre', (0.48, 0.29, 0.12), .48)
channel = material('Painted wood - satin groove', (0.78, 0.59, 0.33), .40)
iron = material('Iron - brushed', (.24, .29, .33), .24, .96)
mark = material('Iron ball - orientation stripe', (.04, .075, .10), .46, .60)
goal_material = material('Goal rim - green', (.063, .26, .17), .4, .25)
def mesh_obj(name, verts, faces):
mesh = bpy.data.meshes.new(name)
mesh.from_pydata(verts, [], faces)
mesh.validate()
mesh.update()
obj = bpy.data.objects.new(name, mesh)
bpy.context.collection.objects.link(obj)
bm = bmesh.new()
bm.from_mesh(mesh)
bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
bm.to_mesh(mesh)
bm.free()
return obj
def top_height(x, rise):
return 1 if rise == 0 else .5 + rise * (x + .5)
def block(name, rise):
half = 1.0 if name == 'y_merge' else .5
verts = [(x, y, z) for z in [0, 1] for y in [-half, half] for x in [-half, half]]
verts = [(x, y, top_height(x, rise) if z else 0) for x, y, z in verts]
faces = [(0,2,3,1),(4,5,7,6),(0,1,5,4),(2,6,7,3),(0,4,6,2),(1,3,7,5)]
obj = mesh_obj(name, verts, faces)
obj.data.materials.append(wood)
obj.data.materials.append(channel)
return obj
def tube(name, points, radius, mat):
# Vertical semicircle section maintained along authoring path.
vertices = []
for i, point in enumerate(points):
tangent = Vector(points[min(i+1,len(points)-1)]) - Vector(points[max(0,i-1)])
side = Vector((-tangent.y, tangent.x, 0)).normalized()
for j in range(SIDES):
a = j * math.tau / SIDES
v = Vector(point) + radius * math.cos(a) * side + Vector((0,0,radius*math.sin(a)))
vertices.append(tuple(v))
faces = []
for i in range(len(points)-1):
for j in range(SIDES):
k=i*SIDES+j; n=i*SIDES+(j+1)%SIDES
faces.append((k,n,n+SIDES,k+SIDES))
faces += [tuple(reversed(range(SIDES))),tuple((len(points)-1)*SIDES+j for j in range(SIDES))]
obj=mesh_obj(name,vertices,faces)
obj.data.materials.append(wood)
obj.data.materials.append(mat)
for face in obj.data.polygons:
face.material_index=1
return obj
def cut(body, cutter):
bpy.context.view_layer.objects.active=body
mod=body.modifiers.new('Actual channel void','BOOLEAN')
mod.operation='DIFFERENCE'
mod.solver='EXACT'
mod.object=cutter
bpy.ops.object.modifier_apply(modifier=mod.name)
bpy.data.objects.remove(cutter,do_unlink=True)
def extend(points, amount=.18):
p=[Vector(v) for v in points]
first=(p[1]-p[0]); first/=math.hypot(first.x,first.y)
last=(p[-1]-p[-2]); last/=math.hypot(last.x,last.y)
return [tuple(p[0]-first*amount)]+points+[tuple(p[-1]+last*amount)]
def paths(kind,rise):
if kind in ('straight','gentle','steep'):
return [[(x,0,top_height(x,rise)) for x in [-.5+i/24 for i in range(25)]]]
if kind=='turn_90':
sign=-1
return [[(-.5+.5*math.sin(t),sign*(.5-.5*math.cos(t)),1) for t in [i*math.pi/2/48 for i in range(49)]]]
# 2x2 Y connector: adjacent 1m lanes on the -X face, both at the same height.
# Lane A continues straight; lane B merges through a tangent-continuous S.
direct=[(-1+i/64*2,-.5,1) for i in range(65)]
# Spread the lateral shift over the whole 2m length so the merging ball
# retains forward momentum instead of striking the far wall sideways.
branch=[]
for i in range(129):
t=i/128
blend=3*t*t-2*t*t*t
branch.append((-1+2*t,.5-blend,1))
return [direct,branch]
def asset_dir(kind):
category = 'balls' if kind == 'iron_ball' else 'goals' if kind == 'goal_hole' else 'blocks' if kind in ('wall','directional_boost') else 'chutes'
return ROOT / 'assets' / category / kind
def export_objects(objects, name):
if globals().get('EXPORT_KINDS') is not None and name not in EXPORT_KINDS:
return
export_path = asset_dir(name) / 'baseline/model.glb'
export_path.parent.mkdir(parents=True, exist_ok=True)
bpy.ops.object.select_all(action='DESELECT')
for obj in objects: obj.select_set(True)
bpy.context.view_layer.objects.active=objects[0]
bpy.ops.export_scene.gltf(filepath=str(export_path),export_format='GLB',use_selection=True,export_yup=True,export_extras=True,export_apply=True)
def godot(v): return [round(v[0],6),round(v[2],6),round(-v[1],6)]
catalog={'schemaVersion':1,'geometryRevision':'solid_base_v1','unitsPerMeter':1,'authoringUp':'Z','runtimeUp':'Y','models':{}}
report={'generator':'Blender Python','geometryRevision':'solid_base_v1','ball_radius_m':BALL_R,'groove_radius_m':R,'assets':[],
'fit_clearance_m':FIT_CLEARANCE,'goal_radius_m':GOAL_R,
'important':['All five chutes have solid bases; only the upper rolling grooves are cut into the body.',
'The steep ramp preserves 1m rise; its retained 1.5m prototype envelope remains explicitly flagged.']}
showcase=[]
for kind,rise in [('straight',0),('turn_90',0),('gentle',.5),('steep',1),('y_merge',0)]:
body=block(kind,rise)
upper_paths=paths(kind,rise)
for n,path in enumerate(upper_paths):
cut(body,tube(f'{kind}_upper_{n}',extend(path),R,channel))
for face in body.data.polygons:
face.use_smooth=(face.material_index==1)
body['asset_id']=kind
body['groove_radius_m']=R
body['solid_base']=True
declared_size=[2.0,2.0,1.0] if kind=='y_merge' else [1.0,1.0,1.0]
body['declared_size_m']=declared_size
body['rise_m']=rise
bpy.context.view_layer.update()
coords=[body.matrix_world @ v.co for v in body.data.vertices]
low=[min(v[i] for v in coords) for i in range(3)]
high=[max(v[i] for v in coords) for i in range(3)]
bounds=[round(high[i]-low[i],6) for i in range(3)]
manifold=bmesh.new();manifold.from_mesh(body.data)
bad_edges=sum(not e.is_manifold for e in manifold.edges);manifold.free()
upper_ports=[]
for path in upper_paths:
for idx in [0,-1]:
v=Vector(path[idx]);v.z-=R
tangent=Vector(path[1])-Vector(path[0]) if idx==0 else Vector(path[-1])-Vector(path[-2])
tangent.normalize()
if kind=='y_merge':
tangent=Vector((1,0,0)) # parallel interfaces on the opposite X faces
entry={'surface':godot(v),'travel':godot(tangent)}
if not any(p['surface']==entry['surface'] for p in upper_ports):upper_ports.append(entry)
meta={'path':'res://'+str((asset_dir(kind)/'baseline/model.glb').relative_to(ROOT)),'radius':None,'rise':rise,'grooveRadius':R,'solidBase':True,
'upperPaths':[[godot(p) for p in path] for path in upper_paths],
'ports':upper_ports,
'boundsBlender':{'min':low,'max':high,'size':bounds},'nominalCellFits':all(d<=1.001 for d in bounds),
'cellFootprint':[int(declared_size[0]),int(declared_size[1])],
'declaredSize':declared_size,'declaredBoundsFits':all(bounds[i]<=declared_size[i]+.001 for i in range(3)),
'prototypeNotes':[] if rise!=1 else ['Full semicircle plus 1m rise exceeds the nominal 1m cell height.']}
body['single_cell_compliant']=meta['nominalCellFits']
body['declared_size_compliant']=meta['declaredBoundsFits']
export_objects([body],kind)
catalog['models'][kind]=meta
report['assets'].append({'id':kind,'size_m':bounds,'single_cell_compliant':meta['nominalCellFits'],
'declared_size_m':declared_size,'declared_size_compliant':meta['declaredBoundsFits'],
'mesh_vertices':len(body.data.vertices),'mesh_faces':len(body.data.polygons),'non_manifold_edges':bad_edges,
'solid_base':True})
showcase.append(body)
if kind=='y_merge':
report['y_connections']={'inlet_surface_positions':[godot((-1,-.5,1-R)),godot((-1,.5,1-R))],
'outlet_surface_position':godot((1,-.5,1-R)),'inlet_center_spacing_m':1.0,'inlet_height_difference_m':0.0,
'solid_base':True}
bpy.ops.mesh.primitive_uv_sphere_add(segments=64,ring_count=32,radius=BALL_R,location=(0,0,0))
ball=bpy.context.object;ball.name='iron_ball';ball.data.materials.append(iron);ball.data.materials.append(mark)
for face in ball.data.polygons:
face.use_smooth=True
# A narrow painted orientation band makes true rotation visible.
center=sum((ball.data.vertices[i].co for i in face.vertices),Vector())/len(face.vertices)
if abs(center.y)<.025:face.material_index=1
ball['asset_id']='iron_ball';ball['radius_m']=BALL_R
export_objects([ball],'iron_ball')
catalog['models']['iron_ball']={'path':'res://assets/balls/iron_ball/baseline/model.glb','radius':BALL_R,'boundsBlender':{'size':[2*BALL_R]*3}}
report['measured_ball_radius_m']=max(v.co.length for v in ball.data.vertices)
# A true narrow goal aperture: both entrance and throat have the same radius.
goal_vertices=[]
for z,rad in [(0,GOAL_R),(0,GOAL_R+.04),(-GOAL_DEPTH,GOAL_R),(-GOAL_DEPTH,GOAL_R+.04)]:
for i in range(96):
a=i*math.tau/96
goal_vertices.append((rad*math.cos(a),rad*math.sin(a),z))
goal_faces=[]
for i in range(96):
j=(i+1)%96
goal_faces += [(i,j,96+j,96+i),(192+i,288+i,288+j,192+j),(i,192+i,192+j,j),(96+i,96+j,288+j,288+i)]
goal=mesh_obj('goal_hole',goal_vertices,goal_faces)
goal.data.materials.append(goal_material)
goal['asset_id']='goal_hole';goal['opening_radius_m']=GOAL_R
export_objects([goal],'goal_hole')
catalog['models']['goal_hole']={'path':'res://assets/goals/goal_hole/baseline/model.glb','role':'goal','openingRadius':GOAL_R,'depth':GOAL_DEPTH,'rimThickness':.04}
(OUT/'catalog.json').write_text(json.dumps(catalog,indent=2,ensure_ascii=False))
(ROOT/'playtest/artifacts/baseline/geometry_report.json').write_text(json.dumps(report,indent=2,ensure_ascii=False))
for i,obj in enumerate(showcase):obj.location=(i%3*1.6,i//3*1.8,0)
ball.location=(5.5,.5,BALL_R)
goal.location=(6.5,.5,GOAL_DEPTH)
bpy.ops.wm.save_as_mainfile(filepath=str(SOURCE/'collection.blend'))
print('INTOHOLE_ASSETS_READY',OUT)