This commit is contained in:
listik committed 2026-11-29 15:49:17 +03:00
commit a85391509d
211 files changed
+28903

No files matched your search

+168
View File
@@ -0,0 +1,168 @@
"""Export the V4 sniper rifle (no hands) as a Roblox-ready GLB with embedded PBR textures.
Run inside Blender with sniper_reference_v12_hands_natural.blend open:
exec(open(r'C:\\roblox\\hunter\\blender\\export_sniper_roblox.py', encoding='utf-8').read())
The source scene is not modified: evaluated copies of the rifle parts (bevels applied) go
into a temporary scene, are joined into one mesh per material (Roblox MeshPart limit is
20k triangles each), get small baked base-colour and metal/roughness PNGs, and are exported.
The pivot is moved to the pistol grip so the mesh drops straight into a Tool Handle.
"""
import json
import os
import struct
import bpy
import bmesh
from mathutils import Matrix, Vector
OUT_DIR = r'C:\roblox\hunter\3D models\sniper\export'
GRIP = Vector((-2.75, 0.0, -0.85)) # middle of the pistol grip in rifle space
TEX = 32
# Optional settings, set before exec() to export another part (e.g. a sight) with the same
# pivot, so it lines up with the rifle when both get the same CFrame in Roblox:
# EXPORT_COLLECTION = 'Sight Scope'; EXPORT_GLB = 'sight_scope.glb'; EXPORT_PREFIX = 'Scope_'
_g = globals()
GLB = os.path.join(OUT_DIR, _g.get('EXPORT_GLB', 'sniper_rifle.glb'))
PREFIX = _g.get('EXPORT_PREFIX', 'Rifle_')
os.makedirs(os.path.join(OUT_DIR, 'textures'), exist_ok=True)
src = bpy.data.collections[_g.get('EXPORT_COLLECTION', 'Rifle V4')]
dg = bpy.context.evaluated_depsgraph_get()
# ------------------------------------------------ gather triangles per material
per_mat = {}
for o in list(src.all_objects): # snapshot: creating meshes invalidates the live iterator
if o.type != 'MESH' or o.hide_render:
continue
oe = o.evaluated_get(dg)
me = bpy.data.meshes.new_from_object(oe, preserve_all_data_layers=False, depsgraph=dg)
me.transform(Matrix.Translation(-GRIP) @ o.matrix_world)
for i, slot in enumerate(o.material_slots):
mat = slot.material
if mat is None:
continue
bm = bmesh.new()
bm.from_mesh(me)
bmesh.ops.delete(bm, geom=[f for f in bm.faces if f.material_index != i], context='FACES')
if bm.faces:
per_mat.setdefault(mat, []).append(bm)
else:
bm.free()
bpy.data.meshes.remove(me)
# ------------------------------------------------ build export objects (only they get selected)
scene = bpy.context.scene
created_images, created_mats, created_objs = [], [], []
def solid_image(name, rgba, path):
im = bpy.data.images.new(name, TEX, TEX, alpha=True)
im.pixels[:] = list(rgba) * (TEX * TEX)
im.filepath_raw = path
im.file_format = 'PNG'
im.save()
im.pack()
created_images.append(im)
return im
def export_material(src_mat):
"""Copy of the material driven by image textures, which glTF/Roblox read as SurfaceAppearance."""
p = next(n for n in src_mat.node_tree.nodes if n.type == 'BSDF_PRINCIPLED')
color = list(p.inputs['Base Color'].default_value)
emit = p.inputs['Emission Strength'].default_value
if emit > 0: # glowing channels: bake the emission colour so it reads bright without lighting
color = list(p.inputs['Emission Color'].default_value)
metal = p.inputs['Metallic'].default_value
rough = p.inputs['Roughness'].default_value
slug = src_mat.name.lower().replace(' ', '_')
tex_dir = os.path.join(OUT_DIR, 'textures')
base = solid_image(f'{slug}_color', color[:3] + [1.0], os.path.join(tex_dir, f'{slug}_color.png'))
orm = solid_image(f'{slug}_mr', (1.0, rough, metal, 1.0), os.path.join(tex_dir, f'{slug}_metalrough.png'))
orm.colorspace_settings.name = 'Non-Color'
m = bpy.data.materials.new(src_mat.name)
created_mats.append(m)
nt = m.node_tree
nt.nodes.clear()
bsdf = nt.nodes.new('ShaderNodeBsdfPrincipled')
out = nt.nodes.new('ShaderNodeOutputMaterial')
nt.links.new(bsdf.outputs['BSDF'], out.inputs['Surface'])
t1 = nt.nodes.new('ShaderNodeTexImage'); t1.image = base
t2 = nt.nodes.new('ShaderNodeTexImage'); t2.image = orm
sep = nt.nodes.new('ShaderNodeSeparateColor')
nt.links.new(t1.outputs['Color'], bsdf.inputs['Base Color'])
nt.links.new(t2.outputs['Color'], sep.inputs['Color'])
nt.links.new(sep.outputs['Green'], bsdf.inputs['Roughness'])
nt.links.new(sep.outputs['Blue'], bsdf.inputs['Metallic'])
if emit > 0:
nt.links.new(t1.outputs['Color'], bsdf.inputs['Emission Color'])
bsdf.inputs['Emission Strength'].default_value = 1.0
return m, {'color': [round(c, 3) for c in color[:3]], 'metal': round(metal, 2),
'rough': round(rough, 2), 'emissive': emit > 0}
report = {'parts': []}
for src_mat, bms in sorted(per_mat.items(), key=lambda kv: kv[0].name):
joined = bmesh.new()
for bm in bms:
tmp = bpy.data.meshes.new('tmp')
bm.to_mesh(tmp)
bm.free()
joined.from_mesh(tmp)
bpy.data.meshes.remove(tmp)
bmesh.ops.triangulate(joined, faces=joined.faces)
name = PREFIX + src_mat.name.title().replace(' ', '')
me = bpy.data.meshes.new(name)
joined.to_mesh(me)
joined.free()
for uv in list(me.uv_layers):
me.uv_layers.remove(uv)
me.uv_layers.new(name='UVMap') # solid textures: any UV layout samples the same colour
mat, info = export_material(src_mat)
me.materials.clear()
me.materials.append(mat)
for poly in me.polygons:
poly.material_index = 0
ob = bpy.data.objects.new(name, me)
scene.collection.objects.link(ob)
created_objs.append(ob)
info.update(name=name, triangles=len(me.polygons))
report['parts'].append(info)
# ------------------------------------------------ export
prev_sel = [o for o in scene.objects if o.select_get()]
for o in scene.objects:
o.select_set(o in created_objs)
bpy.ops.export_scene.gltf(filepath=GLB, export_format='GLB', use_selection=True, use_active_scene=True,
export_apply=True, export_animations=False, export_yup=True,
export_texcoords=True, export_normals=True, export_materials='EXPORT',
export_image_format='AUTO')
for o in prev_sel:
o.select_set(True)
# ------------------------------------------------ clean up the temporary data
for o in created_objs:
me = o.data
bpy.data.objects.remove(o)
bpy.data.meshes.remove(me)
for m in created_mats:
bpy.data.materials.remove(m)
for im in created_images:
bpy.data.images.remove(im)
# ------------------------------------------------ verify the GLB contents
with open(GLB, 'rb') as f:
magic, _, total = struct.unpack('<4sII', f.read(12))
jlen, _ = struct.unpack('<II', f.read(8))
gltf = json.loads(f.read(jlen))
xs = [v for a in gltf['accessors'] if a.get('type') == 'VEC3' and 'min' in a for v in (a['min'], a['max'])]
lo = [min(v[i] for v in xs) for i in range(3)]
hi = [max(v[i] for v in xs) for i in range(3)]
report.update(file=GLB, bytes=total, magic=magic.decode(), meshes=len(gltf['meshes']),
materials=len(gltf['materials']), images=len(gltf.get('images', [])),
size_yup=[round(h - l, 2) for l, h in zip(lo, hi)],
triangles=sum(p['triangles'] for p in report['parts']))
EXPORT_REPORT = report
print(json.dumps(report))