Files
Hunter/blender/prepare_monolith_import.py
T
2026-11-29 15:49:17 +03:00

131 lines
6.9 KiB
Python

import bpy, bmesh, os, json, re, io, contextlib, math, struct, shutil
from mathutils import Vector, Matrix
from mathutils.bvhtree import BVHTree
ROOT=r"C:\roblox\hunter"
OUT=ROOT+r"\3D models\game_zone\Roblox_Import"
os.makedirs(OUT,exist_ok=True)
source=bpy.context.scene
assert source.name.startswith("Hunter | Monolith arena"),source.name
temp=bpy.data.scenes.new("TEMP | Roblox export")
deps=bpy.context.evaluated_depsgraph_get()
manifest={"size_studs":[896,120,896],"stud_to_meter":.28,"axis":"Blender (x,y,z) -> Roblox (x,z,-y)","meshes":[],"lights":[]}
def rvec(p):return [round(p[0],6),round(p[2],6),round(-p[1],6)]
def srgb(c):return 12.92*c if c<=.0031308 else 1.055*(max(c,0)**(1/2.4))-.055
def plain_color(mat):
p=next(n for n in mat.node_tree.nodes if n.type=="BSDF_PRINCIPLED")
return [round(srgb(c),6) for c in p.inputs["Base Color"].default_value[:3]]
all_points=[]
for i,ob in enumerate(sorted([o for o in source.objects if o.type=="MESH"],key=lambda o:o.name),1):
lighting=any(c.name.startswith("Atmosphere") for c in ob.users_collection)
code=("L" if lighting else "A")+str(i).zfill(4)
name=code+"_"+re.sub(r"[^a-zA-Z0-9]+","_",ob.name).strip("_")
mats=[m for m in ob.data.materials if m]
material=mats[0]
p=next(n for n in material.node_tree.nodes if n.type=="BSDF_PRINCIPLED")
emission=float(p.inputs["Emission Strength"].default_value)
shape="decor" if lighting else ("wedge" if len(ob.data.vertices)==6 else "box" if len(ob.data.vertices)==8 else "gate")
entry={"id":code,"name":name,"source":ob.name,"shape":shape,"neon":emission>0,
"color":plain_color(material),"material":material.name,"colliders":[]}
# Gate voids are preserved by explicit invisible box colliders, not a hull.
if shape=="gate":
verts=[ob.matrix_world@v.co for v in ob.data.vertices]
tree=BVHTree.FromPolygons(verts,[tuple(p.vertices) for p in ob.data.polygons])
axes=[sorted(set(round(v[a],5) for v in verts)) for a in range(3)]
direction=Vector((.731,.417,.541)).normalized()
for ix in range(len(axes[0])-1):
for iy in range(len(axes[1])-1):
for iz in range(len(axes[2])-1):
lows=Vector((axes[0][ix],axes[1][iy],axes[2][iz]))
highs=Vector((axes[0][ix+1],axes[1][iy+1],axes[2][iz+1]))
size=highs-lows
if min(size)<.001:continue
center=(lows+highs)/2
loc,normal,_,_=tree.ray_cast(center,direction,2000)
if loc is not None and normal.dot(direction)>0:
entry["colliders"].append({"position":rvec(center),"size":[size.x,size.z,size.y]})
assert entry["colliders"],"No gate colliders: "+ob.name
evaluated=ob.evaluated_get(deps)
mesh=bpy.data.meshes.new_from_object(evaluated,preserve_all_data_layers=True,depsgraph=deps)
mesh.transform(ob.matrix_world)
bm=bmesh.new();bm.from_mesh(mesh)
assert all(e.is_manifold for e in bm.edges),"Non-manifold: "+ob.name
bmesh.ops.triangulate(bm,faces=list(bm.faces));bm.to_mesh(mesh);bm.free()
mesh.update()
tri=len(mesh.polygons)
assert tri<=20000,(ob.name,tri)
entry["triangles"]=tri
mesh.name=name
copy=bpy.data.objects.new(name,mesh);temp.collection.objects.link(copy)
# Keep copied geometry in studs for the mandatory intersection review.
entry["bounds"]=[[min(v.co[a] for v in mesh.vertices) for a in range(3)],
[max(v.co[a] for v in mesh.vertices) for a in range(3)]]
for v in mesh.vertices:all_points.append(tuple(v.co))
manifest["meshes"].append(entry)
for ob in source.objects:
if ob.type=="LIGHT" and ob.data.type=="AREA":
pos=ob.matrix_world.translation
direction=ob.matrix_world.to_quaternion()@Vector((0,0,-1))
manifest["lights"].append({"name":ob.name,"position":rvec(pos),"direction":rvec(direction),
"color":list(ob.data.color),"brightness":2.5,"range":48})
manifest["size_studs"]=[max(v[a] for v in all_points)-min(v[a] for v in all_points) for a in [0,2,1]]
bpy.context.window.scene=temp
check={}
code=open(ROOT+r"\blender\check_collisions.py",encoding="utf8").read()
exec(compile(code,"check_collisions.py","exec"),check)
log=io.StringIO()
with contextlib.redirect_stdout(log):status=check["main"]()
textlog=log.getvalue()
open(os.path.join(OUT,"collision_check.txt"),"w",encoding="utf8").write(textlog)
# Full hit list is retained, with expected structural contacts classified below.
byname={e["name"]:e for e in manifest["meshes"]}
reviews=[]
unexpected=[]
for ln in textlog.splitlines():
if "INTERSECTION: " not in ln:continue
left,right=ln.split("INTERSECTION: ",1)[1].split(" <-> ")
a,b=byname[left],byname[right]
overlap=[min(a["bounds"][1][k],b["bounds"][1][k])-max(a["bounds"][0][k],b["bounds"][0][k]) for k in range(3)]
if a["shape"]=="decor" or b["shape"]=="decor":
reason="Fixture housing/lens mounting contact; visual fixtures are non-colliding."
elif min(overlap)<.001:
reason="Intentional structural face/edge contact."
elif ("Citadel" in a["source"] or "Citadel" in b["source"]) and ("ascent" in a["source"] or "ascent" in b["source"]):
reason="Solid ramp supported by roof/bridge; walkable top is unobstructed."
else:
reason="REVIEW";unexpected.append([left,right,overlap])
reviews.append({"left":left,"right":right,"classification":reason,"overlap":overlap})
manifest["contact_review"]=reviews
manifest["unreviewed_intersections"]=unexpected
json.dump(manifest,open(os.path.join(OUT,"manifest.json"),"w",encoding="utf8"),indent=2)
if unexpected:
bpy.context.window.scene=source
result={"blocked_by_contact_review":unexpected,"temp_scene":temp.name}
else:
for ob in temp.objects:
ob.data.transform(Matrix.Scale(.28,4))
bpy.ops.object.select_all(action="SELECT")
target=os.path.join(OUT,"Hunter_Monolith_Arena.glb")
bpy.ops.export_scene.gltf(filepath=target,export_format="GLB",use_selection=True,use_active_scene=True,
export_apply=False,export_animations=False,export_yup=True,
export_texcoords=True,export_normals=True,export_materials="EXPORT",export_cameras=False,export_lights=False)
with open(target,"rb") as f:
head=f.read(12);length,kind=struct.unpack("<II",f.read(8));glb=json.loads(f.read(length))
assert len(glb.get("meshes",[]))==len(manifest["meshes"])
assert not glb.get("cameras")
assert len(glb.get("images",[]))==3
assert all("bufferView" in im for im in glb["images"])
manifest["export"]={"bytes":os.path.getsize(target),"meshes":len(glb["meshes"]),
"embedded_images":len(glb["images"]),"triangles":sum(e["triangles"] for e in manifest["meshes"]),
"max_triangles":max(e["triangles"] for e in manifest["meshes"])}
json.dump(manifest,open(os.path.join(OUT,"manifest.json"),"w",encoding="utf8"),indent=2)
texdir=os.path.join(OUT,"textures");os.makedirs(texdir,exist_ok=True)
for fn in ("HD_navy.png","HD_amber.png","HD_floor.png"):
shutil.copy2(ROOT+r"\3D models\game_zone\textures"+"/"+fn,texdir)
bpy.context.window.scene=source
for ob in list(temp.objects):
mesh=ob.data;bpy.data.objects.remove(ob,do_unlink=True)
if mesh.users==0:bpy.data.meshes.remove(mesh)
bpy.data.scenes.remove(temp)
result={"export":manifest["export"],"contacts_reviewed":len(reviews),"output":OUT}