637 lines
19 KiB
Python
637 lines
19 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
MSH to glTF 2.0 converter.
|
|
Converts custom .msh XML mesh format to glTF 2.0 binary (.glb) format.
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import struct
|
|
import xml.etree.ElementTree as ET
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
from typing import Optional
|
|
|
|
|
|
@dataclass
|
|
class MeshData:
|
|
"""Parsed mesh data from MSH file."""
|
|
name: str
|
|
mesh_id: int
|
|
transformation_matrix: list[float] # 16 floats, row-major
|
|
vertices: list[tuple[float, float, float]]
|
|
texcoords: list[tuple[float, float]]
|
|
normals: list[tuple[float, float, float]]
|
|
faces: list[tuple[int, int, int]] # triangles
|
|
diffuse_color: tuple[float, float, float, float] = (1.0, 1.0, 1.0, 1.0)
|
|
emission_color: tuple[float, float, float, float] = (0.0, 0.0, 0.0, 0.0)
|
|
diffuse_texture: Optional[str] = None
|
|
bump_texture: Optional[str] = None
|
|
specular_texture: Optional[str] = None
|
|
mask_texture: Optional[str] = None
|
|
|
|
|
|
@dataclass
|
|
class MSHFile:
|
|
"""Complete MSH file with all meshes."""
|
|
meshes: list[MeshData] = field(default_factory=list)
|
|
|
|
|
|
def parse_float_list(text: str) -> list[float]:
|
|
"""Parse semicolon-separated float values."""
|
|
if not text or not text.strip():
|
|
return []
|
|
return [float(x) for x in text.strip().split(';') if x.strip()]
|
|
|
|
|
|
def parse_vertices(text: str) -> list[tuple[float, float, float]]:
|
|
"""Parse vertex positions from semicolon-separated values."""
|
|
values = parse_float_list(text)
|
|
return [(values[i], values[i+1], values[i+2]) for i in range(0, len(values), 3)]
|
|
|
|
|
|
def parse_texcoords(text: str) -> list[tuple[float, float]]:
|
|
"""Parse texture coordinates from semicolon-separated values."""
|
|
values = parse_float_list(text)
|
|
return [(values[i], values[i+1]) for i in range(0, len(values), 2)]
|
|
|
|
|
|
def parse_normals(text: str) -> list[tuple[float, float, float]]:
|
|
"""Parse normals from semicolon-separated values."""
|
|
values = parse_float_list(text)
|
|
return [(values[i], values[i+1], values[i+2]) for i in range(0, len(values), 3)]
|
|
|
|
|
|
def parse_faces(text: str) -> list[tuple[int, int, int]]:
|
|
"""Parse face indices from semicolon-separated values."""
|
|
if not text or not text.strip():
|
|
return []
|
|
values = [int(x) for x in text.strip().split(';') if x.strip()]
|
|
return [(values[i], values[i+1], values[i+2]) for i in range(0, len(values), 3)]
|
|
|
|
|
|
def parse_color(text: str) -> tuple[float, float, float, float]:
|
|
"""Parse color (RGBA) from semicolon-separated values."""
|
|
values = parse_float_list(text)
|
|
if len(values) >= 4:
|
|
return (values[0], values[1], values[2], values[3])
|
|
elif len(values) >= 3:
|
|
return (values[0], values[1], values[2], 1.0)
|
|
return (1.0, 1.0, 1.0, 1.0)
|
|
|
|
|
|
def parse_transformation_matrix(text: str) -> list[float]:
|
|
"""Parse 4x4 transformation matrix from semicolon-separated values."""
|
|
return parse_float_list(text)
|
|
|
|
|
|
def parse_mesh_element(mesh_elem: ET.Element) -> MeshData:
|
|
"""Parse a single MESH element."""
|
|
name = mesh_elem.get('NAME', 'unnamed')
|
|
mesh_id = int(mesh_elem.get('ID', '0'))
|
|
|
|
# Parse transformation matrix
|
|
trans_elem = mesh_elem.find('TRANSFORMATIONMATRIX')
|
|
transform = parse_transformation_matrix(trans_elem.text) if trans_elem is not None else [1.0] * 16
|
|
|
|
# Parse vertices
|
|
vertex_elem = mesh_elem.find('VERTEXES')
|
|
vertices = []
|
|
if vertex_elem is not None:
|
|
num = int(vertex_elem.get('NUMBER', '0'))
|
|
vertices = parse_vertices(vertex_elem.text)
|
|
|
|
# Parse texture coordinates
|
|
texcoord_elem = mesh_elem.find('TEXTURECOORDS')
|
|
texcoords = []
|
|
if texcoord_elem is not None:
|
|
texcoords = parse_texcoords(texcoord_elem.text)
|
|
|
|
# Parse normals
|
|
normal_elem = mesh_elem.find('NORMALS')
|
|
normals = []
|
|
if normal_elem is not None:
|
|
normals = parse_normals(normal_elem.text)
|
|
|
|
# Parse elements/faces
|
|
diffuse_color = (1.0, 1.0, 1.0, 1.0)
|
|
emission_color = (0.0, 0.0, 0.0, 0.0)
|
|
diffuse_texture = None
|
|
bump_texture = None
|
|
specular_texture = None
|
|
mask_texture = None
|
|
faces = []
|
|
|
|
elements_elem = mesh_elem.find('ELEMENTS')
|
|
if elements_elem is not None:
|
|
for elem in elements_elem.findall('ELEMENT'):
|
|
# Parse colors
|
|
diffuse_elem = elem.find('DIFFUSE_COLOR')
|
|
if diffuse_elem is not None:
|
|
diffuse_color = parse_color(diffuse_elem.text)
|
|
|
|
emission_elem = elem.find('EMISSION_COLOR')
|
|
if emission_elem is not None:
|
|
emission_color = parse_color(emission_elem.text)
|
|
|
|
# Parse textures
|
|
diff_tex = elem.find('DIFFUSE_TEXTURE/FILENAME')
|
|
if diff_tex is not None:
|
|
diffuse_texture = diff_tex.text
|
|
|
|
bump_tex = elem.find('BUMP_TEXTURE/FILENAME')
|
|
if bump_tex is not None:
|
|
bump_texture = bump_tex.text
|
|
|
|
spec_tex = elem.find('SPECULAR_TEXTURE/FILENAME')
|
|
if spec_tex is not None:
|
|
specular_texture = spec_tex.text
|
|
|
|
mask_tex = elem.find('MASK_TEXTURE/FILENAME')
|
|
if mask_tex is not None:
|
|
mask_texture = mask_tex.text
|
|
|
|
# Parse faces
|
|
faces_elem = elem.find('FACES')
|
|
if faces_elem is not None:
|
|
faces = parse_faces(faces_elem.text)
|
|
|
|
return MeshData(
|
|
name=name,
|
|
mesh_id=mesh_id,
|
|
transformation_matrix=transform,
|
|
vertices=vertices,
|
|
texcoords=texcoords,
|
|
normals=normals,
|
|
faces=faces,
|
|
diffuse_color=diffuse_color,
|
|
emission_color=emission_color,
|
|
diffuse_texture=diffuse_texture,
|
|
bump_texture=bump_texture,
|
|
specular_texture=specular_texture,
|
|
mask_texture=mask_texture,
|
|
)
|
|
|
|
|
|
def parse_msh_file(filepath: Path) -> MSHFile:
|
|
"""Parse MSH file and return all mesh data."""
|
|
tree = ET.parse(filepath)
|
|
root = tree.getroot()
|
|
|
|
msh_file = MSHFile()
|
|
|
|
for mesh_elem in root.findall('.//MESH'):
|
|
mesh_data = parse_mesh_element(mesh_elem)
|
|
# Skip empty meshes
|
|
if mesh_data.vertices and mesh_data.faces:
|
|
msh_file.meshes.append(mesh_data)
|
|
|
|
return msh_file
|
|
|
|
|
|
# glTF 2.0 binary format helpers
|
|
GLTF_MAGIC = 0x46546C67 # "glTF"
|
|
GLTF_VERSION = 2
|
|
|
|
|
|
def encode_gltf_json(gltf_data: dict) -> bytes:
|
|
"""Encode glTF JSON to UTF-8 bytes with padding."""
|
|
json_str = json.dumps(gltf_data, separators=(',', ':'))
|
|
json_bytes = json_str.encode('utf-8')
|
|
|
|
# Pad to 4-byte boundary
|
|
padding = (4 - (len(json_bytes) % 4)) % 4
|
|
json_bytes += b' ' * padding
|
|
|
|
return json_bytes
|
|
|
|
|
|
def create_glb(gltf_data: dict, bin_data: bytes) -> bytes:
|
|
"""Create a GLB binary file from glTF data and binary buffer."""
|
|
json_bytes = encode_gltf_json(gltf_data)
|
|
|
|
# GLB header: magic (4), version (4), length (4)
|
|
# Chunk header: chunkLength (4), chunkType (4)
|
|
|
|
json_chunk_length = len(json_bytes)
|
|
bin_chunk_length = len(bin_data)
|
|
|
|
total_length = 12 + 8 + json_chunk_length + 8 + bin_chunk_length
|
|
|
|
# Build GLB
|
|
glb = bytearray()
|
|
|
|
# Header
|
|
glb.extend(struct.pack('<I', GLTF_MAGIC))
|
|
glb.extend(struct.pack('<I', GLTF_VERSION))
|
|
glb.extend(struct.pack('<I', total_length))
|
|
|
|
# JSON chunk
|
|
glb.extend(struct.pack('<I', json_chunk_length))
|
|
glb.extend(struct.pack('<I', 0x4E4F534A) # "JSON"
|
|
)
|
|
glb.extend(json_bytes)
|
|
|
|
# Binary chunk
|
|
glb.extend(struct.pack('<I', bin_chunk_length))
|
|
glb.extend(struct.pack('<I', 0x004E4942) # "BIN\0"
|
|
)
|
|
glb.extend(bin_data)
|
|
|
|
return bytes(glb)
|
|
|
|
|
|
# Texture lookup cache
|
|
_texture_cache = {}
|
|
|
|
|
|
def find_textures(model_name: str, mesh_name: str, textures_dir: Path) -> dict:
|
|
"""
|
|
Find textures for a given model and mesh.
|
|
Returns dict with 'diffuse', 'bump', 'specular', 'mask' keys.
|
|
"""
|
|
cache_key = (str(model_name), str(mesh_name), str(textures_dir))
|
|
if cache_key in _texture_cache:
|
|
return _texture_cache[cache_key]
|
|
|
|
result = {
|
|
'diffuse': None,
|
|
'bump': None,
|
|
'specular': None,
|
|
'mask': None
|
|
}
|
|
|
|
extensions = ['.png', '.jpg', '.jpeg', '.dds', '.tga']
|
|
tex_types = {
|
|
'diffuse': '_d',
|
|
'bump': '_b',
|
|
'specular': '_s',
|
|
'mask': '_m',
|
|
}
|
|
|
|
# Try to find textures by looking for files that start with model_name
|
|
try:
|
|
all_textures = list(textures_dir.glob(f"{model_name}*{min(extensions, key=len)}"))
|
|
except Exception:
|
|
all_textures = []
|
|
|
|
# Also search in subdirectories like lp/
|
|
try:
|
|
for subdir in textures_dir.iterdir():
|
|
if subdir.is_dir():
|
|
all_textures.extend(subdir.glob(f"{model_name}*{min(extensions, key=len)}"))
|
|
except Exception:
|
|
pass
|
|
|
|
# Extract base names from found textures
|
|
for tex_path in all_textures:
|
|
tex_name = tex_path.name
|
|
# Remove extension
|
|
base = tex_name.rsplit('.', 1)[0]
|
|
|
|
# Try to match with mesh name
|
|
for tex_type, suffix in tex_types.items():
|
|
if result[tex_type]:
|
|
continue
|
|
|
|
# Check if texture matches: {model_name}_{mesh_name}{suffix}
|
|
if base.endswith(suffix):
|
|
# Get prefix without suffix
|
|
prefix = base[:-len(suffix)]
|
|
|
|
# Check if prefix matches model_name or model_name + mesh_name
|
|
if prefix == model_name or prefix == f"{model_name}_{mesh_name}":
|
|
result[tex_type] = tex_name
|
|
break
|
|
|
|
# Also check if mesh_name is a suffix of prefix
|
|
if mesh_name in prefix and prefix.startswith(model_name):
|
|
result[tex_type] = tex_name
|
|
break
|
|
|
|
# Fallback: try default textures
|
|
default_textures = {
|
|
'diffuse': 'default_diffuse.png',
|
|
'bump': 'default_bump.png',
|
|
'specular': 'default_specular.png',
|
|
'mask': 'default_mask.png',
|
|
}
|
|
|
|
for tex_type, default_tex in default_textures.items():
|
|
if not result[tex_type]:
|
|
tex_path = textures_dir / default_tex
|
|
if tex_path.exists():
|
|
result[tex_type] = default_tex
|
|
|
|
_texture_cache[cache_key] = result
|
|
return result
|
|
|
|
|
|
def convert_single_mesh(mesh: MeshData, model_name: str, mesh_idx: int, textures_dir: Path) -> tuple[dict, bytes]:
|
|
"""Convert a single mesh to glTF format."""
|
|
all_positions = []
|
|
all_normals = []
|
|
all_texcoords = []
|
|
all_indices = []
|
|
|
|
# Add vertices
|
|
for v in mesh.vertices:
|
|
all_positions.extend(v)
|
|
|
|
# Add normals (or generate if missing)
|
|
if mesh.normals:
|
|
for n in mesh.normals:
|
|
all_normals.extend(n)
|
|
else:
|
|
for _ in mesh.vertices:
|
|
all_normals.extend([0.0, 1.0, 0.0])
|
|
|
|
# Add texture coordinates (or generate if missing)
|
|
# Invert V coordinate (Y) for glTF
|
|
if mesh.texcoords:
|
|
for tc in mesh.texcoords:
|
|
all_texcoords.extend([tc[0], 1.0 - tc[1]])
|
|
else:
|
|
for _ in mesh.vertices:
|
|
all_texcoords.extend([0.0, 0.0])
|
|
|
|
# Add indices
|
|
for face in mesh.faces:
|
|
all_indices.extend([face[0], face[1], face[2]])
|
|
|
|
# Create binary buffer
|
|
bin_data = bytearray()
|
|
|
|
# Position buffer
|
|
position_offset = len(bin_data)
|
|
bin_data.extend(struct.pack(f'{len(all_positions)}f', *all_positions))
|
|
|
|
# Normal buffer
|
|
normal_offset = len(bin_data)
|
|
bin_data.extend(struct.pack(f'{len(all_normals)}f', *all_normals))
|
|
|
|
# Texcoord buffer
|
|
texcoord_offset = len(bin_data)
|
|
bin_data.extend(struct.pack(f'{len(all_texcoords)}f', *all_texcoords))
|
|
|
|
# Index buffer
|
|
index_offset = len(bin_data)
|
|
bin_data.extend(struct.pack(f'{len(all_indices)}I', *all_indices))
|
|
|
|
# Pad to 4 bytes
|
|
while len(bin_data) % 4:
|
|
bin_data.append(0)
|
|
|
|
# Calculate bounds
|
|
min_pos = (
|
|
min(v[0] for v in mesh.vertices),
|
|
min(v[1] for v in mesh.vertices),
|
|
min(v[2] for v in mesh.vertices)
|
|
) if mesh.vertices else (0, 0, 0)
|
|
max_pos = (
|
|
max(v[0] for v in mesh.vertices),
|
|
max(v[1] for v in mesh.vertices),
|
|
max(v[2] for v in mesh.vertices)
|
|
) if mesh.vertices else (0, 0, 0)
|
|
|
|
# Build glTF JSON for single mesh
|
|
gltf = {
|
|
"asset": {
|
|
"version": "2.0",
|
|
"generator": "MSH to glTF Converter"
|
|
},
|
|
"scene": 0,
|
|
"scenes": [{"name": "Scene", "nodes": [0]}],
|
|
"nodes": [{"name": mesh.name, "mesh": 0}],
|
|
"meshes": [],
|
|
"materials": [],
|
|
"accessors": [],
|
|
"bufferViews": [],
|
|
"buffers": [{"byteLength": len(bin_data)}]
|
|
}
|
|
|
|
# Find textures for this mesh
|
|
textures = find_textures(model_name, mesh.name, textures_dir)
|
|
|
|
# Initialize images, textures, samplers
|
|
image_map = {}
|
|
gltf["images"] = []
|
|
gltf["textures"] = []
|
|
gltf["samplers"] = [{
|
|
"magFilter": 9729,
|
|
"minFilter": 9987,
|
|
"wrapS": 10497,
|
|
"wrapT": 10497,
|
|
}]
|
|
|
|
def get_image_index(filename: str) -> int:
|
|
if filename not in image_map:
|
|
image_map[filename] = len(gltf["images"])
|
|
gltf["images"].append({"uri": f"../media/pic/{filename}"})
|
|
return image_map[filename]
|
|
|
|
# Create material for this mesh
|
|
pbr = {
|
|
"baseColorFactor": list(mesh.diffuse_color),
|
|
"metallicFactor": 0.0,
|
|
"roughnessFactor": 1.0
|
|
}
|
|
|
|
if textures['diffuse']:
|
|
img_idx = get_image_index(textures['diffuse'])
|
|
tex_idx = len(gltf["textures"])
|
|
gltf["textures"].append({"source": img_idx, "sampler": 0})
|
|
pbr["baseColorTexture"] = {"index": tex_idx, "texCoord": 0}
|
|
|
|
material = {
|
|
"name": f"{mesh.name}_material",
|
|
"pbrMetallicRoughness": pbr,
|
|
"emissiveFactor": list(mesh.emission_color[:3])
|
|
}
|
|
|
|
if textures['bump']:
|
|
img_idx = get_image_index(textures['bump'])
|
|
tex_idx = len(gltf["textures"])
|
|
gltf["textures"].append({"source": img_idx, "sampler": 0})
|
|
material["normalTexture"] = {"index": tex_idx, "texCoord": 0}
|
|
|
|
gltf["materials"].append(material)
|
|
|
|
# Create buffer views (single mesh = single buffer view each)
|
|
vertex_count = len(mesh.vertices)
|
|
index_count = len(mesh.faces) * 3
|
|
|
|
# Position buffer view
|
|
gltf["bufferViews"].append({
|
|
"buffer": 0,
|
|
"byteOffset": 0,
|
|
"byteLength": vertex_count * 12
|
|
})
|
|
|
|
# Position accessor
|
|
gltf["accessors"].append({
|
|
"bufferView": 0,
|
|
"byteOffset": 0,
|
|
"componentType": 5126,
|
|
"count": vertex_count,
|
|
"type": "VEC3",
|
|
"max": list(max_pos),
|
|
"min": list(min_pos)
|
|
})
|
|
|
|
# Normal buffer view
|
|
gltf["bufferViews"].append({
|
|
"buffer": 0,
|
|
"byteOffset": normal_offset,
|
|
"byteLength": vertex_count * 12
|
|
})
|
|
|
|
# Normal accessor
|
|
gltf["accessors"].append({
|
|
"bufferView": 1,
|
|
"byteOffset": 0,
|
|
"componentType": 5126,
|
|
"count": vertex_count,
|
|
"type": "VEC3"
|
|
})
|
|
|
|
# Texcoord buffer view
|
|
gltf["bufferViews"].append({
|
|
"buffer": 0,
|
|
"byteOffset": texcoord_offset,
|
|
"byteLength": vertex_count * 8
|
|
})
|
|
|
|
# Texcoord accessor
|
|
gltf["accessors"].append({
|
|
"bufferView": 2,
|
|
"byteOffset": 0,
|
|
"componentType": 5126,
|
|
"count": vertex_count,
|
|
"type": "VEC2"
|
|
})
|
|
|
|
# Index buffer view
|
|
gltf["bufferViews"].append({
|
|
"buffer": 0,
|
|
"byteOffset": index_offset,
|
|
"byteLength": index_count * 4
|
|
})
|
|
|
|
# Index accessor
|
|
gltf["accessors"].append({
|
|
"bufferView": 3,
|
|
"byteOffset": 0,
|
|
"componentType": 5125,
|
|
"count": index_count,
|
|
"type": "SCALAR"
|
|
})
|
|
|
|
# Primitive
|
|
gltf["meshes"].append({
|
|
"name": mesh.name,
|
|
"primitives": [{
|
|
"attributes": {
|
|
"POSITION": 0,
|
|
"NORMAL": 1,
|
|
"TEXCOORD_0": 2
|
|
},
|
|
"indices": 3,
|
|
"mode": 4,
|
|
"material": 0
|
|
}]
|
|
})
|
|
|
|
return gltf, bytes(bin_data)
|
|
|
|
|
|
def convert_file(input_path: Path, output_path: Optional[Path] = None, textures_dir: Path = None, split_meshes: bool = True) -> None:
|
|
"""Convert a single MSH file to GLB."""
|
|
print(f"Parsing {input_path}...")
|
|
msh_file = parse_msh_file(input_path)
|
|
print(f" Found {len(msh_file.meshes)} mesh(es)")
|
|
|
|
if not msh_file.meshes:
|
|
print(f" Warning: No meshes with vertices found in {input_path}")
|
|
return
|
|
|
|
for i, mesh in enumerate(msh_file.meshes):
|
|
print(f" Mesh {i}: {mesh.name} - {len(mesh.vertices)} vertices, {len(mesh.faces)} faces")
|
|
|
|
# Get model name from input file
|
|
model_name = input_path.stem
|
|
|
|
if split_meshes:
|
|
# Save each mesh to a separate file
|
|
for mesh_idx, mesh in enumerate(msh_file.meshes):
|
|
# Create output path: {model-name}-{mesh-name}.glb
|
|
mesh_name = mesh.name.replace(' ', '-').replace('/', '-')
|
|
output_file = f"{model_name}-{mesh_name}.glb"
|
|
|
|
if output_path:
|
|
# Use output directory
|
|
out_path = Path(output_path) / output_file
|
|
else:
|
|
out_path = Path(output_file)
|
|
|
|
print(f"Converting mesh '{mesh.name}' to {out_path}...")
|
|
gltf_json, bin_data = convert_single_mesh(mesh, model_name, mesh_idx, textures_dir)
|
|
|
|
glb_data = create_glb(gltf_json, bin_data)
|
|
out_path.write_bytes(glb_data)
|
|
print(f" Written {len(glb_data)} bytes")
|
|
else:
|
|
# Original behavior - single file with all meshes
|
|
print(f"Converting to glTF...")
|
|
gltf_json, bin_data = convert_mesh_to_gltf(msh_file, model_name, textures_dir)
|
|
|
|
if output_path is None:
|
|
output_path = input_path.with_suffix('.glb')
|
|
|
|
print(f"Writing {output_path}...")
|
|
glb_data = create_glb(gltf_json, bin_data)
|
|
output_path.write_bytes(glb_data)
|
|
print(f" Written {len(glb_data)} bytes")
|
|
|
|
|
|
def main():
|
|
import json
|
|
|
|
parser = argparse.ArgumentParser(description='Convert MSH mesh files to glTF 2.0')
|
|
parser.add_argument('input', nargs='+', help='Input MSH files')
|
|
parser.add_argument('-o', '--output', help='Output directory (for multiple files) or file (for single)')
|
|
parser.add_argument('-t', '--textures', default='media/pic', help='Textures directory')
|
|
|
|
args = parser.parse_args()
|
|
|
|
input_paths = [Path(p) for p in args.input]
|
|
textures_dir = Path(args.textures)
|
|
|
|
if len(input_paths) == 1 and args.output:
|
|
# Single file output
|
|
output_path = Path(args.output)
|
|
convert_file(input_paths[0], output_path, textures_dir)
|
|
elif len(input_paths) == 1:
|
|
# Single file, auto output name
|
|
convert_file(input_paths[0], textures_dir=textures_dir)
|
|
else:
|
|
# Multiple files
|
|
output_dir = Path(args.output) if args.output else Path('.')
|
|
output_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
for input_path in input_paths:
|
|
try:
|
|
output_path = output_dir / (input_path.stem + '.glb')
|
|
convert_file(input_path, output_path, textures_dir)
|
|
except Exception as e:
|
|
print(f"Error converting {input_path}: {e}")
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|