mlse-player-3d / app /visualization.py
Jake Reardon
Initial implementation of MLSE Player 3D Generator with SAM 3D Body integration
f0c79f8
import os
import numpy as np
import json
from typing import Dict, Any
def convert_mesh_to_threejs(mesh_data: Dict[str, Any], output_path: str):
"""
Convert mesh data to THREE.js compatible JSON format.
Args:
mesh_data: Mesh data from SAM 3D Body
output_path: Path to save the THREE.js compatible JSON
"""
try:
# Convert mesh data to THREE.js format
threejs_data = {
"metadata": {
"version": 4.5,
"type": "Object",
"generator": "MLSE Player 3D Generator"
},
"geometries": [
{
"uuid": "player-mesh",
"type": "BufferGeometry",
"data": {
"attributes": {
"position": {
"itemSize": 3,
"type": "Float32Array",
"array": mesh_data["vertices"].flatten().tolist()
},
"normal": {
"itemSize": 3,
"type": "Float32Array",
"array": mesh_data.get("normals", np.zeros_like(mesh_data["vertices"])).flatten().tolist()
},
"uv": {
"itemSize": 2,
"type": "Float32Array",
"array": mesh_data.get("uvs", np.zeros((len(mesh_data["vertices"]), 2))).flatten().tolist()
}
},
"index": {
"type": "Uint16Array",
"array": mesh_data["faces"].flatten().tolist()
}
}
}
],
"materials": [
{
"uuid": "player-material",
"type": "MeshStandardMaterial",
"color": 0x8888ff,
"roughness": 0.5,
"metalness": 0.2,
"emissive": 0x000000,
"side": 2
}
],
"object": {
"uuid": "player-object",
"type": "Mesh",
"name": "PlayerMesh",
"geometry": "player-mesh",
"material": "player-material",
"position": [0, 0, 0],
"quaternion": [0, 0, 0, 1],
"scale": [1, 1, 1]
}
}
# Write to file
with open(output_path, 'w') as f:
json.dump(threejs_data, f)
return output_path
except Exception as e:
print(f"Error converting mesh to THREE.js format: {str(e)}")
raise RuntimeError(f"Failed to convert mesh: {str(e)}")