mrPlow58/Scripts/build_kamaz_cr_chaos_rig_from_blender_socket.py
2026-07-03 07:06:16 +03:00

217 lines
8.1 KiB
Python

import json
import os
import socket
BLEND_OUT = r"C:\Users\post\Documents\mrPlow\in\KAMAZ_CR_chaos_rig_53605.blend"
FBX_OUT = r"C:\Users\post\Documents\mrPlow\mrPlow58\VehicleExports\KAMAZ_CR\FBX\SK_KAMAZ_CR_ChaosRig_53605.fbx"
REPORT_OUT = r"C:\Users\post\Documents\mrPlow\mrPlow58\VehicleExports\KAMAZ_CR\kamaz_cr_chaos_rig_53605_export_report.json"
BLENDER_CODE = r'''
import bpy
import json
import os
from mathutils import Vector
source_blend = r"C:\Users\post\Documents\mrPlow\in\KAMAZ_CR_plusX_previous_modules_fitcheck1.blend"
blend_out = r"C:\Users\post\Documents\mrPlow\in\KAMAZ_CR_chaos_rig_53605.blend"
fbx_out = r"C:\Users\post\Documents\mrPlow\mrPlow58\VehicleExports\KAMAZ_CR\FBX\SK_KAMAZ_CR_ChaosRig_53605.fbx"
report_out = r"C:\Users\post\Documents\mrPlow\mrPlow58\VehicleExports\KAMAZ_CR\kamaz_cr_chaos_rig_53605_export_report.json"
bpy.ops.wm.open_mainfile(filepath=source_blend)
include_collections = {
"Collection",
"KAMAZ_CR_Base_Static",
"KAMAZ_CR_Blinkers_Migalki_SplitParts",
"KAMAZ_CR_Drivetrain_OtherSplitParts",
"KAMAZ_CR_FrontAxle_SplitParts",
"KAMAZ_CR_RearAxle_SplitParts",
}
exclude_names = {"CISTERN1", "tyre004", "disk"} # spare wheel is visual cargo, not a Chaos wheel.
wheel_groups = {
"Phys_Wheel_FL": {"names": ["tyre008", "disk007", "kolpak003", "bolt005"], "center": (1.738, -1.160, 0.537)},
"Phys_Wheel_FR": {"names": ["tyre001", "disk001", "kolpak001", "bolt001"], "center": (1.738, 0.996, 0.537)},
"Phys_Wheel_RL": {"names": ["tyre007", "disk006", "tyre006", "disk005", "bolt004"], "center": (-2.181, -1.003, 0.537)},
"Phys_Wheel_RR": {"names": ["tyre002", "disk002", "tyre003", "disk003", "bolt002"], "center": (-2.181, 0.842, 0.537)},
}
wheel_name_to_bone = {}
for bone_name, data in wheel_groups.items():
for object_name in data["names"]:
wheel_name_to_bone[object_name] = bone_name
bpy.ops.object.mode_set(mode='OBJECT') if bpy.ops.object.mode_set.poll() else None
bpy.ops.object.select_all(action='DESELECT')
selected = []
skipped = []
source_assignment = []
for obj in bpy.context.scene.objects:
if obj.type != "MESH":
continue
collections = {c.name for c in obj.users_collection}
if obj.name in exclude_names:
skipped.append({"name": obj.name, "reason": "excluded"})
continue
if not collections.intersection(include_collections):
skipped.append({"name": obj.name, "reason": "collection", "collections": sorted(collections)})
continue
if obj.hide_get():
skipped.append({"name": obj.name, "reason": "hidden"})
continue
target_group = wheel_name_to_bone.get(obj.name, "Body")
for vg in list(obj.vertex_groups):
obj.vertex_groups.remove(vg)
vg = obj.vertex_groups.new(name=target_group)
vg.add([v.index for v in obj.data.vertices], 1.0, 'ADD')
source_assignment.append({"object": obj.name, "vertexGroup": target_group, "vertices": len(obj.data.vertices)})
obj.select_set(True)
selected.append(obj)
if not selected:
raise RuntimeError("No mesh objects selected for KAMAZ_CR rig.")
bpy.context.view_layer.objects.active = selected[0]
for obj in selected:
bpy.ops.object.select_all(action='DESELECT')
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)
# Join to one mesh so Unreal receives a clean one-skeleton/one-mesh asset.
bpy.ops.object.select_all(action='DESELECT')
for obj in selected:
obj.select_set(True)
bpy.context.view_layer.objects.active = selected[0]
with bpy.context.temp_override(
active_object=selected[0],
object=selected[0],
selected_objects=selected,
selected_editable_objects=selected,
):
bpy.ops.object.join()
mesh_obj = bpy.context.view_layer.objects.active
mesh_obj.name = "SK_KAMAZ_CR_53605_Mesh"
mesh_obj.data.name = "SK_KAMAZ_CR_53605_MeshData"
vertex_weights = {vg.name: 0 for vg in mesh_obj.vertex_groups}
for vertex in mesh_obj.data.vertices:
for group in vertex.groups:
name = mesh_obj.vertex_groups[group.group].name
vertex_weights[name] = vertex_weights.get(name, 0) + 1
# Create armature with UE-friendly names and simple hierarchy.
arm_data = bpy.data.armatures.new("SK_KAMAZ_CR_53605_ArmatureData")
arm_obj = bpy.data.objects.new("SK_KAMAZ_CR_53605_Armature", arm_data)
bpy.context.scene.collection.objects.link(arm_obj)
bpy.context.view_layer.objects.active = arm_obj
arm_obj.select_set(True)
with bpy.context.temp_override(active_object=arm_obj, object=arm_obj, selected_objects=[arm_obj], selected_editable_objects=[arm_obj]):
bpy.ops.object.mode_set(mode='EDIT')
root = arm_data.edit_bones.new("Root")
root.head = (0.0, 0.0, 0.0)
root.tail = (0.35, 0.0, 0.0)
body = arm_data.edit_bones.new("Body")
body.head = (-0.20, 0.0, 1.22)
body.tail = (0.45, 0.0, 1.22)
body.parent = root
for bone_name, data in wheel_groups.items():
x, y, z = data["center"]
bone = arm_data.edit_bones.new(bone_name)
bone.head = (x, y, z)
bone.tail = (x + 0.35, y, z)
bone.parent = root
with bpy.context.temp_override(active_object=arm_obj, object=arm_obj, selected_objects=[arm_obj], selected_editable_objects=[arm_obj]):
bpy.ops.object.mode_set(mode='OBJECT')
mod = mesh_obj.modifiers.new("Armature_KAMAZ_CR_53605", "ARMATURE")
mod.object = arm_obj
mesh_obj.parent = arm_obj
mesh_obj.matrix_parent_inverse = arm_obj.matrix_world.inverted()
# Unit/orientation contract for the source file.
bpy.context.scene.unit_settings.system = 'METRIC'
bpy.context.scene.unit_settings.scale_length = 1.0
bpy.ops.object.select_all(action='DESELECT')
arm_obj.select_set(True)
mesh_obj.select_set(True)
bpy.context.view_layer.objects.active = arm_obj
os.makedirs(os.path.dirname(fbx_out), exist_ok=True)
with bpy.context.temp_override(
active_object=arm_obj,
object=arm_obj,
selected_objects=[arm_obj, mesh_obj],
selected_editable_objects=[arm_obj, mesh_obj],
):
bpy.ops.export_scene.fbx(
filepath=fbx_out,
use_selection=True,
object_types={'ARMATURE', 'MESH'},
apply_unit_scale=True,
apply_scale_options='FBX_SCALE_UNITS',
bake_space_transform=False,
add_leaf_bones=False,
primary_bone_axis='X',
secondary_bone_axis='-Y',
mesh_smooth_type='FACE',
use_mesh_modifiers=True,
path_mode='AUTO'
)
bpy.ops.wm.save_as_mainfile(filepath=blend_out)
report = {
"ok": True,
"blend": blend_out,
"fbx": fbx_out,
"sourceFile": source_blend,
"vehicle": "KAMAZ-53605-3950-48(A5)",
"orientation": { "forward": "+X", "up": "+Z", "units": "meters" },
"wheelbaseMeters": round(wheel_groups["Phys_Wheel_FL"]["center"][0] - wheel_groups["Phys_Wheel_RL"]["center"][0], 3),
"wheelRadiusMeters": 0.538,
"bones": ["Root", "Body"] + list(wheel_groups.keys()),
"wheelCentersMeters": {k: list(v["center"]) for k, v in wheel_groups.items()},
"vertexWeights": vertex_weights,
"sourceAssignmentSample": source_assignment[:80],
"skippedCount": len(skipped),
"skippedSample": skipped[:40],
"notes": [
"New Chaos rig built for the KAMAZ_CR mesh, not reused from the old KAMAZ.",
"Vertex groups are assigned per original object before join; body panels never get wheel weights by proximity.",
"Rear dual wheels are weighted to one Chaos wheel bone per side.",
"CISTERN1 is excluded from the base vehicle and remains an attachment."
]
}
os.makedirs(os.path.dirname(report_out), exist_ok=True)
with open(report_out, "w", encoding="utf-8") as f:
json.dump(report, f, ensure_ascii=False, indent=2)
print(json.dumps(report, ensure_ascii=False))
'''
def main():
os.makedirs(os.path.dirname(FBX_OUT), exist_ok=True)
message = json.dumps({"type": "execute", "strict_json": False, "code": BLENDER_CODE}).encode("utf-8") + b"\0"
with socket.create_connection(("127.0.0.1", 9876), timeout=5) as sock:
sock.sendall(message)
data = b""
while True:
chunk = sock.recv(65536)
if not chunk:
break
data += chunk
if b"\0" in data:
break
print(data.split(b"\0")[0].decode("utf-8", "replace"))
if __name__ == "__main__":
main()