# Export map_reference_pines_split (saved copy: map/roblox/export_source.blend) for Roblox. # Run: blender -b export_source.blend --python export_map_v2.py # # Output: map/roblox/map_v2/ # *.glb + manifest.json meshes, one material each (Roblox MeshPart = one material), <= MAX_TRIS triangles # clone = "zones" content of player zone 1 (fence, lights, fence snow); Studio clones it for all 10 zones # (manifest.zone_angles = Blender angle of every zone, zone 1 = 90 deg) # Zone_Fence_Wood.png the procedural cedar wood baked into a texture (Cycles diffuse colour) # terrain_columns.json ground (island snow, cliff, paths, plaza, drifts, curb snow) sampled for Roblox Terrain # Left out on purpose: zone name signs (collections below), hidden objects. import bpy, bmesh, json, math, os from collections import Counter from mathutils import Vector, Matrix from mathutils.bvhtree import BVHTree HERE = os.path.dirname(bpy.data.filepath) OUT = os.path.join(HERE, "map_v2") os.makedirs(OUT, exist_ok=True) MAX_TRIS = 18000 ZONE1_ANGLE, ZONE_HALF = 90.0, 17.0 EXCLUDE = {"Festive_Nameplate_Details", "Sign_Fence_Style_Supports", "Zone_Player_Nameplates", "Studio"} GROUND = {"Terrain", "Landscape_Snowdrifts", "Asphalt_Edge_Snowdrifts", "Continuous_Curb_Snow"} ZONE_COLLS = {"Fences", "Snow_Draped_Reference", "Snow_Organic_Domes"} CELL = 4.0 BAKE_SIZE = 1024 export_coll = bpy.data.collections.new("RobloxExport") bpy.context.scene.collection.children.link(export_coll) manifest = [] def obj_center(o): cs = [o.matrix_world @ Vector(c) for c in o.bound_box] return sum(cs, Vector()) / 8 def angle_of(o): c = obj_center(o) return math.degrees(math.atan2(c.y, c.x)) def in_zone1(o): return abs(((angle_of(o) - ZONE1_ANGLE + 180) % 360) - 180) <= ZONE_HALF def coll_of(o): return o.users_collection[0].name if o.users_collection else "" def lin_to_srgb255(c): f = lambda v: 12.92 * v if v <= 0.0031308 else 1.055 * v ** (1 / 2.4) - 0.055 return [max(0, min(255, round(f(max(0.0, v)) * 255))) for v in c] def bsdf(mat): return next((n for n in mat.node_tree.nodes if n.type == "BSDF_PRINCIPLED"), None) if mat and mat.node_tree else None def mat_props(mname): m = bpy.data.materials.get(mname) b = bsdf(m) col = [0.8, 0.8, 0.8] glow = False metal = 0.0 if b: col = list(b.inputs["Base Color"].default_value[:3]) metal = b.inputs["Metallic"].default_value es = b.inputs["Emission Strength"].default_value if es >= 0.5: glow = True ec = b.inputs["Emission Color"].default_value col = list(ec[:3]) if max(ec[:3]) > 0.05 else col low = mname.lower() if "bulb" in low or "glass" in low: glow = True if "snow" in low: rb = "Snow" elif glow: rb = "Neon" elif "wood" in low or "cedar" in low or "trunk" in low: rb = "Wood" elif metal > 0.5 or "bronze" in low or "gold" in low: rb = "Metal" else: rb = "SmoothPlastic" return {"material": rb, "color": lin_to_srgb255(col), "glow": glow} def evaluated_mesh(o): dg = bpy.context.evaluated_depsgraph_get() me = bpy.data.meshes.new_from_object(o.evaluated_get(dg)) me.transform(o.matrix_world) return me def faces_by_material(o, me): names = [s.material.name if s.material else "" for s in o.material_slots] or [""] out = Counter() for p in me.polygons: out[names[min(p.material_index, len(names) - 1)]] += len(p.vertices) - 2 return out, names def finish(name, bm, info, smooth=True): bmesh.ops.triangulate(bm, faces=bm.faces[:]) me = bpy.data.meshes.new(name) bm.to_mesh(me) bm.free() ob = bpy.data.objects.new(name, me) export_coll.objects.link(ob) tris = len(me.polygons) if tris > MAX_TRIS: dec = ob.modifiers.new("Dec", "DECIMATE") dec.ratio = MAX_TRIS / tris * 0.97 dg = bpy.context.evaluated_depsgraph_get() dg.update() nm = bpy.data.meshes.new_from_object(ob.evaluated_get(dg)) ob.modifiers.clear() ob.data = nm bpy.data.meshes.remove(me) me = nm cs = [v.co for v in me.vertices] lo = Vector((min(c.x for c in cs), min(c.y for c in cs), min(c.z for c in cs))) hi = Vector((max(c.x for c in cs), max(c.y for c in cs), max(c.z for c in cs))) ctr = (lo + hi) / 2 me.transform(Matrix.Translation(-ctr)) for p in me.polygons: p.use_smooth = smooth info.update({"name": name, "center": [round(v, 4) for v in ctr], "size": [round(v, 3) for v in hi - lo], "tris": len(me.polygons), "file": name + ".glb"}) manifest.append(info) return ob def export_group(prefix, objs, clone, raw_chunk=MAX_TRIS): """Merge objs per material (world space) into chunks of <= raw_chunk source triangles; chunks above MAX_TRIS are decimated down to it in finish().""" per_mat = {} for o in objs: me = evaluated_mesh(o) counts, names = faces_by_material(o, me) bpy.data.meshes.remove(me) for mname, n in counts.items(): per_mat.setdefault(mname, []).append((o, n)) for mname, items in sorted(per_mat.items()): if not mname: continue items.sort(key=lambda t: angle_of(t[0])) # spatially coherent chunks chunks, cur, cur_n = [], [], 0 for o, n in items: if cur and cur_n + n > raw_chunk: chunks.append(cur); cur, cur_n = [], 0 cur.append(o); cur_n += n if cur: chunks.append(cur) props = mat_props(mname) for k, chunk in enumerate(chunks): bm = bmesh.new() for o in chunk: me = evaluated_mesh(o) tmp = bmesh.new() tmp.from_mesh(me) names = [s.material.name if s.material else "" for s in o.material_slots] or [""] bmesh.ops.delete(tmp, geom=[f for f in tmp.faces if names[min(f.material_index, len(names) - 1)] != mname], context="FACES") tmp.to_mesh(me) tmp.free() bm.from_mesh(me) bpy.data.meshes.remove(me) if not bm.faces: bm.free(); continue name = "%s_%s_%d" % (prefix, mname, k) info = dict(props) info["clone"] = clone info["source_material"] = mname finish(name, bm, info, smooth=(props["material"] in ("Snow",)) or "Snow" in mname) # ------------------------------------------------------------------ classify visible objects visible = [o for o in bpy.data.objects if o.type in ("MESH", "CURVE") and o.visible_get()] zone_objs, global_objs, skipped = [], [], Counter() for o in visible: c = coll_of(o) if c in EXCLUDE: skipped[c] += 1 elif c in GROUND: continue elif c in ZONE_COLLS: if in_zone1(o): zone_objs.append(o) else: skipped["other zones"] += 1 else: global_objs.append(o) print("CLASSIFY zone1:", len(zone_objs), "global:", len(global_objs), "skipped:", dict(skipped)) # ------------------------------------------------------------------ zone 1: fence with baked wood fence = next(o for o in zone_objs if o.name.startswith("Zone_01_Fence")) wood_mat = fence.material_slots[0].material me = evaluated_mesh(fence) fob = bpy.data.objects.new("Zone_Fence", me) export_coll.objects.link(fob) bake_uv = me.uv_layers.new(name="BakeUV") for l in me.uv_layers: l.active_render = (l.name == "UVMap") me.uv_layers.active = bake_uv bpy.ops.object.select_all(action="DESELECT") fob.select_set(True) bpy.context.view_layer.objects.active = fob bpy.ops.object.mode_set(mode="EDIT") bpy.ops.mesh.select_all(action="SELECT") bpy.ops.uv.smart_project(angle_limit=math.radians(66), island_margin=0.004, scale_to_bounds=True) bpy.ops.object.mode_set(mode="OBJECT") img = bpy.data.images.new("Zone_Fence_Wood", BAKE_SIZE, BAKE_SIZE, alpha=False) bake_mat = wood_mat.copy() tex = bake_mat.node_tree.nodes.new("ShaderNodeTexImage") tex.image = img bake_mat.node_tree.nodes.active = tex me.materials.clear() me.materials.append(bake_mat) sc = bpy.context.scene sc.render.engine = "CYCLES" sc.cycles.samples = 4 sc.cycles.device = "CPU" sc.render.bake.use_pass_direct = False sc.render.bake.use_pass_indirect = False sc.render.bake.use_pass_color = True sc.render.bake.margin = 6 bpy.ops.object.bake(type="DIFFUSE", pass_filter={"COLOR"}, use_clear=True) img.filepath_raw = os.path.join(OUT, "Zone_Fence_Wood.png") img.file_format = "PNG" img.save() for l in [l for l in me.uv_layers if l.name != "BakeUV"]: me.uv_layers.remove(l) exp_mat = bpy.data.materials.new("Zone_Fence_Wood_Mat") try: exp_mat.use_nodes = True except Exception: pass nt = exp_mat.node_tree b = next(n for n in nt.nodes if n.type == "BSDF_PRINCIPLED") t2 = nt.nodes.new("ShaderNodeTexImage") t2.image = img nt.links.new(t2.outputs["Color"], b.inputs["Base Color"]) me.materials.clear() me.materials.append(exp_mat) cs = [v.co for v in me.vertices] lo = Vector((min(c.x for c in cs), min(c.y for c in cs), min(c.z for c in cs))) hi = Vector((max(c.x for c in cs), max(c.y for c in cs), max(c.z for c in cs))) ctr = (lo + hi) / 2 me.transform(Matrix.Translation(-ctr)) manifest.append({"name": "Zone_Fence", "clone": "zones", "material": "Wood", "texture": "Zone_Fence_Wood.png", "color": [255, 255, 255], "glow": False, "center": [round(v, 4) for v in ctr], "size": [round(v, 3) for v in hi - lo], "tris": sum(len(p.vertices) - 2 for p in me.polygons), "file": "Zone_Fence.glb"}) if manifest[-1]["tris"] > MAX_TRIS: print("WARNING fence tris", manifest[-1]["tris"]) sc.render.engine = "BLENDER_EEVEE" # ------------------------------------------------------------------ zone 1: lights + snow; global parts export_group("Zone", [o for o in zone_objs if o is not fence], "zones", raw_chunk=45000) export_group("Map", global_objs, None) # ------------------------------------------------------------------ export every part as its own GLB for info in manifest: o = bpy.data.objects[info["name"]] bpy.ops.object.select_all(action="DESELECT") o.select_set(True) bpy.context.view_layer.objects.active = o bpy.ops.export_scene.gltf(filepath=os.path.join(OUT, info["file"]), export_format="GLB", use_selection=True, export_yup=True, export_apply=True) zone_angles = [] for k in range(1, 11): z = bpy.data.objects.get("Zone_%02d_Fence" % k) if z: zone_angles.append(round(angle_of(z), 3)) lamps = [[round(v, 3) for v in obj_center(o)] for o in visible if o.name.startswith("Warm_Lantern") or (coll_of(o) == "Plaza_Benches_And_Lanterns" and "Glass" in o.name)] # ------------------------------------------------------------------ terrain columns dg = bpy.context.evaluated_depsgraph_get() trees = [] tlo = Vector((1e9, 1e9, 1e9)); thi = -tlo for o in visible: if coll_of(o) not in GROUND or o.type != "MESH": continue ev = o.evaluated_get(dg) tm = ev.to_mesh() tm.transform(o.matrix_world) verts = [v.co.copy() for v in tm.vertices] polys = [tuple(p.vertices) for p in tm.polygons] mats = [(o.material_slots[p.material_index].material.name if o.material_slots and o.material_slots[p.material_index].material else "") for p in tm.polygons] ev.to_mesh_clear() trees.append((BVHTree.FromPolygons(verts, polys), mats, o.name)) for v in verts: tlo = Vector(map(min, tlo, v)); thi = Vector(map(max, thi, v)) def code_for(obj, mat): m, n = mat.lower(), obj.lower() if "rock" in m or "cliff" in m: return "R" if "curb" in m and "snow" not in m: return "C" if "asphalt" in m: return "P" if "plaza" in n else "A" return "S" x0 = (int(tlo.x // CELL) - 1) * CELL y0 = (int(tlo.y // CELL) - 1) * CELL nx = int((thi.x - x0) // CELL) + 2 ny = int((thi.y - y0) // CELL) + 2 top, bot, mat = [], [], [] for j in range(ny): for i in range(nx): x = x0 + (i + 0.5) * CELL y = y0 + (j + 0.5) * CELL best_t, best_c, best_b = None, ".", None for bvh, mats, name in trees: hit = bvh.ray_cast(Vector((x, y, thi.z + 10)), Vector((0, 0, -1))) if hit[0] is not None and (best_t is None or hit[0].z > best_t): best_t = hit[0].z best_c = code_for(name, mats[hit[2]]) hb = bvh.ray_cast(Vector((x, y, tlo.z - 10)), Vector((0, 0, 1))) if hb[0] is not None and (best_b is None or hb[0].z < best_b): best_b = hb[0].z top.append(round(best_t, 2) if best_t is not None else None) bot.append(round(best_b, 2) if best_b is not None else None) mat.append(best_c) json.dump({"cell": CELL, "x0": x0, "y0": y0, "nx": nx, "ny": ny, "top": top, "bot": bot, "mat": "".join(mat), "zmin": tlo.z, "zmax": thi.z}, open(os.path.join(OUT, "terrain_columns.json"), "w")) json.dump({"zone_angles": zone_angles, "zone1_angle": ZONE1_ANGLE, "parts": manifest, "lantern_lights": lamps}, open(os.path.join(OUT, "manifest.json"), "w"), indent=1) total = 0 for m in manifest: mult = len(zone_angles) if m["clone"] == "zones" else 1 total += m["tris"] * mult print("PART", m["name"], m["tris"], m["material"], m["color"], m["clone"]) print("TERRAIN", nx, ny, dict(Counter(mat))) print("TOTAL_PARTS", len(manifest), "IN_GAME_TRIS", total, "ZONES", zone_angles, "LAMPS", len(lamps))