Merge pull request #2 from Yusarina/main

PMX AND PMD Import
This commit is contained in:
Yusarina
2024-06-18 02:04:49 +00:00
committed by GitHub
13 changed files with 1422 additions and 35 deletions
+2
View File
@@ -0,0 +1,2 @@
*.pyc
+21 -4
View File
@@ -1,15 +1,32 @@
if "bpy" not in locals():
import bpy
from . import ui
from .core.register import order_classes
from . import core
from .core import register
from .core.register import __bl_ordered_classes
else:
import importlib
importlib.reload(ui)
importlib.reload(core)
def register():
print("Registering Avatar Toolkit")
# Order the classes before registration
order_classes()
core.register.order_classes()
# Register the UI classes
ui.register()
# Iterate over the classes to register and register them
for cls in __bl_ordered_classes:
print("registering" + str(cls))
bpy.utils.register_class(cls)
def unregister():
print("Unregistering Avatar Toolkit")
# Unregister the UI classes
ui.unregister()
# Iterate over the classes to unregister in reverse order and unregister them
for cls in reversed(list(__bl_ordered_classes)):
bpy.utils.unregister_class(cls)
print("unregistering" + str(cls))
+2 -2
View File
@@ -3,10 +3,10 @@
schema_version = "1.0.0"
id = "avatar_toolkit"
version = "0.0.1"
version = "4.3.1"
name = "Avatar Toolkit"
tagline = "A modern tool for importing and optimizing models for VRChat, Resonite, and other similar games."
maintainer = "Your Name <your.email@example.com>"
maintainer = "Team NekoNeo"
type = "add-on"
blender_version_min = "4.3.0"
+18
View File
@@ -1,3 +1,21 @@
# core/__init__.py
from .register import register_wrap
from . import pmx
#to reload all things in this directory and import them properly - @989onan
if "bpy" not in locals():
import bpy
import glob
import os
from os.path import dirname, basename, isfile, join
modules = glob.glob(join(dirname(__file__), "*.py"))
for module_name in [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]:
exec("from . import "+module_name)
print("importing " +module_name)
else:
import importlib
modules = glob.glob(join(dirname(__file__), "*.py"))
for module_name in [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]:
exec("importlib.reload("+module_name+")")
print("reloading " +module_name)
+225
View File
@@ -0,0 +1,225 @@
import bpy
import struct
import mathutils
import traceback
def read_pmd_header(file):
# Read PMD header information
magic = file.read(3)
if magic != b'Pmd':
raise ValueError("Invalid PMD file")
version = struct.unpack('<f', file.read(4))[0]
# Read additional header fields
model_name = file.read(20).decode('shift-jis').rstrip('\0')
comment = file.read(256).decode('shift-jis').rstrip('\0')
return version, model_name, comment
def read_pmd_vertex(file):
# Read PMD vertex information
position = struct.unpack('<3f', file.read(12))
normal = struct.unpack('<3f', file.read(12))
uv = struct.unpack('<2f', file.read(8))
bone_indices = list(struct.unpack('<2H', file.read(4)))
bone_weights = struct.unpack('<b', file.read(1))[0] / 100
edge_flag = struct.unpack('<b', file.read(1))[0]
return position, normal, uv, bone_indices, bone_weights, edge_flag
def read_pmd_material(file):
# Read PMD material information
diffuse_color = struct.unpack('<4f', file.read(16))
specular_color = struct.unpack('<3f', file.read(12))
specular_intensity = struct.unpack('<f', file.read(4))[0]
ambient_color = struct.unpack('<3f', file.read(12))
toon_index = struct.unpack('<b', file.read(1))[0]
edge_flag = struct.unpack('<b', file.read(1))[0]
vertex_count = struct.unpack('<i', file.read(4))[0]
texture_file_name = file.read(20).decode('shift-jis').rstrip('\0')
return diffuse_color, specular_color, specular_intensity, ambient_color, toon_index, edge_flag, vertex_count, texture_file_name
def read_pmd_bone(file):
# Read PMD bone information
bone_name = file.read(20).decode('shift-jis').rstrip('\0')
parent_bone_index = struct.unpack('<h', file.read(2))[0]
tail_pos_bone_index = struct.unpack('<h', file.read(2))[0]
bone_type = struct.unpack('<b', file.read(1))[0]
ik_parent_bone_index = struct.unpack('<h', file.read(2))[0]
bone_head_pos = struct.unpack('<3f', file.read(12))
return bone_name, parent_bone_index, tail_pos_bone_index, bone_type, ik_parent_bone_index, bone_head_pos
def read_pmd_ik(file):
# Read PMD IK information
ik_bone_index = struct.unpack('<h', file.read(2))[0]
ik_target_bone_index = struct.unpack('<h', file.read(2))[0]
ik_chain_length = struct.unpack('<b', file.read(1))[0]
iterations = struct.unpack('<h', file.read(2))[0]
limit_angle = struct.unpack('<f', file.read(4))[0]
ik_child_bone_indices = []
for _ in range(ik_chain_length):
ik_child_bone_index = struct.unpack('<h', file.read(2))[0]
ik_child_bone_indices.append(ik_child_bone_index)
return ik_bone_index, ik_target_bone_index, ik_chain_length, iterations, limit_angle, ik_child_bone_indices
def read_pmd_morph(file):
# Read PMD morph information
morph_name = file.read(20).decode('shift-jis').rstrip('\0')
morph_vertex_count = struct.unpack('<i', file.read(4))[0]
morph_type = struct.unpack('<b', file.read(1))[0]
morph_vertices = []
for _ in range(morph_vertex_count):
morph_vertex_index = struct.unpack('<i', file.read(4))[0]
morph_vertex_pos = struct.unpack('<3f', file.read(12))
morph_vertices.append((morph_vertex_index, morph_vertex_pos))
return morph_name, morph_vertex_count, morph_type, morph_vertices
def import_pmd(filepath):
try:
with open(filepath, 'rb') as file:
version, model_name, comment = read_pmd_header(file)
# Read vertices
vertex_count = struct.unpack('<i', file.read(4))[0]
vertices = []
for _ in range(vertex_count):
position, normal, uv, bone_indices, bone_weights, edge_flag = read_pmd_vertex(file)
vertices.append((position, normal, uv, bone_indices, bone_weights, edge_flag))
# Read faces
face_count = struct.unpack('<i', file.read(4))[0]
faces = []
for _ in range(face_count // 3):
face_indices = struct.unpack('<3i', file.read(12))
faces.append(face_indices)
# Read materials
material_count = struct.unpack('<i', file.read(4))[0]
materials = []
for _ in range(material_count):
diffuse_color, specular_color, specular_intensity, ambient_color, toon_index, edge_flag, vertex_count, texture_file_name = read_pmd_material(file)
materials.append((diffuse_color, specular_color, specular_intensity, ambient_color, toon_index, edge_flag, vertex_count, texture_file_name))
# Read bones
bone_count = struct.unpack('<h', file.read(2))[0]
bones = []
for _ in range(bone_count):
bone_name, parent_bone_index, tail_pos_bone_index, bone_type, ik_parent_bone_index, bone_head_pos = read_pmd_bone(file)
bones.append((bone_name, parent_bone_index, tail_pos_bone_index, bone_type, ik_parent_bone_index, bone_head_pos))
# Read IKs
ik_count = struct.unpack('<h', file.read(2))[0]
iks = []
for _ in range(ik_count):
ik_bone_index, ik_target_bone_index, ik_chain_length, iterations, limit_angle, ik_child_bone_indices = read_pmd_ik(file)
iks.append((ik_bone_index, ik_target_bone_index, ik_chain_length, iterations, limit_angle, ik_child_bone_indices))
# Read morphs
morph_count = struct.unpack('<h', file.read(2))[0]
morphs = []
for _ in range(morph_count):
morph_name, morph_vertex_count, morph_type, morph_vertices = read_pmd_morph(file)
morphs.append((morph_name, morph_vertex_count, morph_type, morph_vertices))
# Create Blender objects and assign PMD data
mesh = bpy.data.meshes.new(model_name)
mesh.from_pydata([v[0] for v in vertices], [], faces)
mesh.update()
obj = bpy.data.objects.new(model_name, mesh)
bpy.context.collection.objects.link(obj)
# Assign vertex normals
for i, vertex in enumerate(vertices):
mesh.vertices[i].normal = vertex[1]
# Assign UV coordinates
uv_layer = mesh.uv_layers.new()
for i, vertex in enumerate(vertices):
uv_layer.data[i].uv = vertex[2]
# Assign materials
for material_data in materials:
material = bpy.data.materials.new(f"Material_{len(mesh.materials)}")
material.diffuse_color = material_data[0]
material.specular_color = material_data[1]
material.specular_intensity = material_data[2]
material.ambient = material_data[3]
# Set other material properties based on the PMD data
mesh.materials.append(material)
# Create armature and assign bones
armature = bpy.data.armatures.new(model_name + "_Armature")
armature_obj = bpy.data.objects.new(model_name + "_Armature", armature)
bpy.context.collection.objects.link(armature_obj)
bpy.context.view_layer.objects.active = armature_obj
bpy.ops.object.mode_set(mode='EDIT')
for bone_data in bones:
bone = armature.edit_bones.new(bone_data[0])
bone.head = bone_data[5]
if bone_data[1] != -1:
parent_bone = armature.edit_bones[bone_data[1]]
bone.parent = parent_bone
bone.tail = parent_bone.head
else:
bone.tail = bone.head + mathutils.Vector((0, 0.1, 0))
# Set other bone properties based on the PMD data
bpy.ops.object.mode_set(mode='OBJECT')
# Assign bone weights to the mesh
for i, vertex in enumerate(vertices):
for j in range(2):
if vertex[3][j] != 65535:
bone_name = bones[vertex[3][j]][0]
weight = vertex[4] if j == 0 else 1 - vertex[4]
vertex_group = obj.vertex_groups.get(bone_name)
if not vertex_group:
vertex_group = obj.vertex_groups.new(name=bone_name)
vertex_group.add([i], weight, 'REPLACE')
# Assign IK constraints to bones
for ik_data in iks:
ik_bone = armature.bones[bones[ik_data[0]][0]]
ik_target_bone = armature.bones[bones[ik_data[1]][0]]
ik_constraint = ik_bone.constraints.new('IK')
ik_constraint.target = armature_obj
ik_constraint.subtarget = ik_target_bone.name
ik_constraint.chain_count = ik_data[2]
ik_constraint.iterations = ik_data[3]
ik_constraint.limit_mode = 'LIMITDIST_INSIDE'
ik_constraint.limit_mode_max_x = ik_data[4]
# Assign morphs to the mesh
for morph_data in morphs:
morph_name = morph_data[0]
morph_type = morph_data[2]
if morph_type == 0: # Vertex morph
shape_key = obj.shape_key_add(name=morph_name)
for vertex_data in morph_data[3]:
vertex_index = vertex_data[0]
vertex_offset = vertex_data[1]
shape_key.data[vertex_index].co += mathutils.Vector(vertex_offset)
print(f"Successfully imported PMD file: {filepath}")
print(f"Model Name: {model_name}")
print(f"Comment: {comment}")
except Exception:
print(f"Error importing PMD file: {filepath}")
print(f"Error details: {traceback.format_exc()}")
+483
View File
@@ -0,0 +1,483 @@
import bpy
import struct
import traceback
import mathutils
from mathutils import Matrix, Vector
def replace_char(string, index, character):
temp = list(string)
temp[index] = character
return "".join(temp)
def read_pmx_header(file):
# Read PMX header information
magic = file.read(4)
if magic != b'PMX ':
raise ValueError("Invalid PMX file")
version = struct.unpack('<f', file.read(4))[0]
# Read additional header fields
data_size = struct.unpack('<b', file.read(1))[0]
encoding = struct.unpack('<b', file.read(1))[0]
additional_uvs = struct.unpack('<b', file.read(1))[0]
vertex_index_size = struct.unpack('<b', file.read(1))[0]
texture_index_size = struct.unpack('<b', file.read(1))[0]
material_index_size = struct.unpack('<b', file.read(1))[0]
bone_index_size = struct.unpack('<b', file.read(1))[0]
morph_index_size = struct.unpack('<b', file.read(1))[0]
rigid_body_index_size = struct.unpack('<b', file.read(1))[0]
print(rigid_body_index_size)
# Read model name and comments
model_name = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace')
model_english_name = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace')
model_comment = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace')
print(model_name)
print(model_english_name)
print(model_comment)
model_english_comment = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace')
print(model_english_comment)
return version, encoding, additional_uvs, vertex_index_size, texture_index_size, material_index_size, bone_index_size, morph_index_size, rigid_body_index_size, model_name, model_english_name, model_comment, model_english_comment
def read_vertex(file, string_build, byte_size, additional_uvs):
position = struct.unpack('<3f', file.read(12))
normal = struct.unpack('<3f', file.read(12))
uv = struct.unpack('<2f', file.read(8))
additional_uv_read = []
for i in range(0,additional_uvs):
additional_uv_read.append(struct.unpack('<4f', file.read(16)))
weight_deform_type = struct.unpack('<B', file.read(1))[0]
C_num = []
R0_num = []
R1_num = []
#in the if-else chain, multiplying byte_size by a number should reflect the string_build's 1st (not 0th) character which is how many bone indices there are.
if weight_deform_type == 0: #BDEF 1
string_build = replace_char(string_build,1,'1') #how many bone indices there are
bone_indices = list(struct.unpack(string_build, file.read(byte_size*1)))
bone_weights = [1.0]
elif weight_deform_type == 1: #BDEF2
string_build = replace_char(string_build,1,'2') #how many bone indices there are
bone_indices = list(struct.unpack(string_build, file.read(byte_size*2)))
bone_1_weight = struct.unpack('<f', file.read(4))[0]
bone_weights = [bone_1_weight, 1.0-bone_1_weight]
elif weight_deform_type == 2: #BDEF4
string_build = replace_char(string_build,1,'4') #how many bone indices there are
bone_indices = list(struct.unpack(string_build, file.read(byte_size*4)))
bone_weights = list(struct.unpack('<4f', file.read(4*4)))
elif weight_deform_type == 3: #SDEF
string_build = replace_char(string_build,1,'2') #how many bone indices there are
bone_indices = list(struct.unpack(string_build, file.read(byte_size*2)))
bone_1_weight = struct.unpack('<f', file.read(4))[0]
bone_weights = [bone_1_weight, 1.0-bone_1_weight]
C_num = struct.unpack('<3f', file.read(12))
R0_num = struct.unpack('<3f', file.read(12))
R1_num = struct.unpack('<3f', file.read(12))
elif weight_deform_type == 4: #QDEF
string_build = replace_char(string_build,1,'4') #how many bone indices there are
bone_indices = list(struct.unpack(string_build, file.read(byte_size*4)))
bone_weights = list(struct.unpack('<4f', file.read(4*4)))
else:
raise IOError("Unsupported weight deform type \""+str(weight_deform_type)+"\" for file!")
edge_scale = struct.unpack('<f', file.read(4))[0]
return position, normal, uv, bone_indices, bone_weights, edge_scale, additional_uv_read
def read_material(file, string_build, byte_size):
material_name = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace')
material_english_name = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace')
diffuse_color = struct.unpack('<4f', file.read(16))
specular_color = struct.unpack('<3f', file.read(12))
specular_strength = struct.unpack('<f', file.read(4))[0]
ambient_color = struct.unpack('<3f', file.read(12))
flag = struct.unpack('<b', file.read(1))[0]
edge_color = struct.unpack('<4f', file.read(16))
edge_size = struct.unpack('<f', file.read(4))[0]
#this is bad don't do this, replaced it.. - @989onan
#texture_index = struct.unpack(f'<{texture_index_size}B', file.read(texture_index_size))[0]
texture_index = struct.unpack(replace_char(string_build, 1, '1'), file.read(byte_size))[0]
sphere_texture_index = struct.unpack(replace_char(string_build, 1, '1'), file.read(byte_size))[0]
sphere_mode = struct.unpack('<b', file.read(1))[0]
toon_sharing_flag = struct.unpack('<b', file.read(1))[0]
if toon_sharing_flag == 0:
toon_texture_index = struct.unpack(replace_char(string_build, 1, '1'), file.read(byte_size))[0]
else:
toon_texture_index = struct.unpack('<b', file.read(1))[0]
comment = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace')
surface_count = struct.unpack('<i', file.read(4))[0]/3
return material_name, material_english_name, diffuse_color, specular_color, specular_strength, ambient_color, flag, edge_color, edge_size, texture_index, sphere_texture_index, sphere_mode, toon_sharing_flag, toon_texture_index, comment, surface_count
def read_bone(file, string_build, byte_size):
bone_name = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace')
bone_english_name = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace')
position = struct.unpack('<3f', file.read(12))
parent_bone_index = struct.unpack(replace_char(string_build, 1, '1'), file.read(byte_size))[0]
layer = struct.unpack('<i', file.read(4))[0]
flag = struct.unpack('<H', file.read(2))[0]
tail_position = [None,None,None]
tail_index = 0.0
inherit_bone_parent_index = 0
inherit_bone_parent_influence = 0.0
fixed_axis = [0.0,0.0,0.0]
local_x_vector = [0.0,0.0,0.0]
local_z_vector = [0.0,0.0,0.0]
external_key = 0
ik_target_bone_index = 0.0
ik_loop_count = -1
ik_limit_radian = 0.0
ik_link_count = -1
if not (flag & 0x0001):
tail_position = struct.unpack('<3f', file.read(12))
else:
tail_index = struct.unpack(replace_char(string_build, 1, '1'), file.read(byte_size))[0]
if flag & 0x0100 or flag & 0x0200:
inherit_bone_parent_index = struct.unpack(replace_char(string_build, 1, '1'), file.read(byte_size))[0]
inherit_bone_parent_influence = struct.unpack('<f', file.read(4))[0]
if flag & 0x0400:
fixed_axis = struct.unpack('<3f', file.read(12))
if flag & 0x0800:
local_x_vector = struct.unpack('<3f', file.read(12))
local_z_vector = struct.unpack('<3f', file.read(12))
if flag & 0x2000:
external_key = struct.unpack('<i', file.read(4))[0]
ik_links = []
if flag & 0x0020:
ik_target_bone_index = struct.unpack(replace_char(string_build, 1, '1'), file.read(byte_size))[0]
ik_loop_count = struct.unpack('<i', file.read(4))[0]
ik_limit_radian = struct.unpack('<f', file.read(4))[0]
ik_link_count = struct.unpack('<i', file.read(4))[0]
for _ in range(ik_link_count):
ik_link_bone_index = struct.unpack(replace_char(string_build, 1, '1'), file.read(byte_size))[0]
ik_link_limit_min = struct.unpack('<3f', file.read(12))
ik_link_limit_max = struct.unpack('<3f', file.read(12))
ik_links.append((ik_link_bone_index, ik_link_limit_min, ik_link_limit_max))
return bone_name, bone_english_name, position, parent_bone_index, layer, flag, tail_position, inherit_bone_parent_index, inherit_bone_parent_influence, fixed_axis, local_x_vector, local_z_vector, external_key, ik_target_bone_index, ik_loop_count, ik_limit_radian, ik_links
def read_morph(file, morph_struct, morph_bytesize, vertex_struct, vertex_size, bone_struct, bone_size, material_struct, material_size, rigid_struct, rigid_size):
morph_name = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace')
morph_english_name = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace')
panel = struct.unpack('<b', file.read(1))[0]
morph_type = struct.unpack('<b', file.read(1))[0]
offset_size = struct.unpack('<i', file.read(4))[0]
morph_data = []
for _ in range(offset_size):
if morph_type == 0: # Group
morph_index = struct.unpack(replace_char(morph_struct, 1, '1'), file.read(morph_bytesize))[0]
morph_value = struct.unpack('<f', file.read(4))[0]
morph_data.append((morph_index, morph_value))
elif morph_type == 1: # Vertex
vertex_index = struct.unpack(replace_char(vertex_struct, 1, '1'), file.read(vertex_size))[0]
position_offset = struct.unpack('<3f', file.read(12))
morph_data.append((vertex_index, position_offset))
elif morph_type == 2: # Bone
bone_index = struct.unpack(bone_struct, file.read(bone_size))[0]
position_offset = struct.unpack('<3f', file.read(12))
rotation_offset = struct.unpack('<4f', file.read(16))
morph_data.append((bone_index, position_offset, rotation_offset))
elif morph_type == 3: # UV
vertex_index = struct.unpack(replace_char(vertex_struct, 1, '1'), file.read(vertex_size))[0]
uv_offset = struct.unpack('<4f', file.read(16))
morph_data.append((vertex_index, uv_offset))
elif morph_type == 4: # UV extended1
vertex_index = struct.unpack(replace_char(vertex_struct, 1, '1'), file.read(vertex_size))[0]
uv_offset = struct.unpack('<4f', file.read(16))
morph_data.append((vertex_index, uv_offset))
elif morph_type == 5: # UV extended2
vertex_index = struct.unpack(replace_char(vertex_struct, 1, '1'), file.read(vertex_size))[0]
uv_offset = struct.unpack('<4f', file.read(16))
morph_data.append((vertex_index, uv_offset))
elif morph_type == 6: # UV extended3
vertex_index = struct.unpack(replace_char(vertex_struct, 1, '1'), file.read(vertex_size))[0]
uv_offset = struct.unpack('<4f', file.read(16))
morph_data.append((vertex_index, uv_offset))
elif morph_type == 7: # UV extended4
vertex_index = struct.unpack(replace_char(vertex_struct, 1, '1'), file.read(vertex_size))[0]
uv_offset = struct.unpack('<4f', file.read(16))
morph_data.append((vertex_index, uv_offset))
elif morph_type == 8: # Material
material_index = struct.unpack(replace_char(material_struct, 1, '1'), file.read(material_size))[0]
offset_type = struct.unpack('<b', file.read(1))[0]
diffuse_offset = struct.unpack('<4f', file.read(16))
specular_offset = struct.unpack('<3f', file.read(12))
specular_factor_offset = struct.unpack('<f', file.read(4))[0]
ambient_offset = struct.unpack('<3f', file.read(12))
edge_color_offset = struct.unpack('<4f', file.read(16))
edge_size_offset = struct.unpack('<f', file.read(4))[0]
texture_factor_offset = struct.unpack('<4f', file.read(16))
sphere_texture_factor_offset = struct.unpack('<4f', file.read(16))
toon_texture_factor_offset = struct.unpack('<4f', file.read(16))
morph_data.append((material_index, offset_type, diffuse_offset, specular_offset, specular_factor_offset, ambient_offset, edge_color_offset, edge_size_offset, texture_factor_offset, sphere_texture_factor_offset, toon_texture_factor_offset))
elif morph_type == 9: # Flip
morph_index = struct.unpack(replace_char(morph_struct, 1, '1'), file.read(morph_bytesize))[0]
morph_value = struct.unpack('<f', file.read(4))[0]
morph_data.append((morph_index, morph_value))
elif morph_type == 10: # Impulse
morph_index = struct.unpack(replace_char(rigid_struct, 1, '1'), file.read(rigid_size))[0]
local_flag = struct.unpack('<b', file.read(1))[0]
movement_speed = struct.unpack('<3f', file.read(12))
rotation_torque = struct.unpack('<3f', file.read(12))
morph_data.append((morph_index, local_flag, movement_speed, rotation_torque))
return morph_name, morph_english_name, panel, morph_type, morph_data
def read_index_size(index, types):
struct = "<??"
byte_size = 0
if index == 1:
struct = replace_char(struct, 2, types[0])
byte_size = 1
elif index == 2:
struct = replace_char(struct,2,types[1])
byte_size = 2
else:
struct = replace_char(struct,2,types[2])
byte_size = 4
return struct, byte_size
def import_pmx(filepath):
try:
faces = []
vertices = []
textures = []
materials = []
bones = []
morphs = []
try:
with open(filepath, mode='rb') as file:
print("stage 1")
version, encoding, additional_uvs, vertex_index_size, texture_index_size, material_index_size, bone_index_size, morph_index_size, rigid_body_index_size, model_name, model_english_name, model_comment, model_english_comment = read_pmx_header(file)
print("stage 2")
# Read vertices
print("fix 3")
vertex_count = struct.unpack('<i', file.read(4))[0]
print("stage 3")
print(vertex_count)
#====== Start reading index sizes and create helper prebuilts =====
morph_struct, morph_size = read_index_size(morph_index_size, 'bhi')
vertex_struct, vertex_size = read_index_size(vertex_index_size, 'BHi')
bone_struct, bone_size = read_index_size(bone_index_size, 'bhi')
material_struct, material_size = read_index_size(material_index_size, 'bhi')
texture_struct, texture_size = read_index_size(texture_index_size, 'bhi')
rigid_struct, rigid_size = read_index_size(rigid_body_index_size, 'bhi')
#====== End of reading index sizes and create helper prebuilts =====
for _ in range(vertex_count):
position, normal, uv, bone_indices, bone_weights, edge_scale, additional_uv_read = read_vertex(file, bone_struct, bone_size, additional_uvs)
vertices.append((position, normal, uv, bone_indices, bone_weights, edge_scale))
# Read faces
print("stage 4")
face_count = struct.unpack('<i', file.read(4))[0]
print("stage 5")
def read_data(data, length):
return list(struct.unpack(data, file.read(length)))
#storing function to use in for-loop to prevent checking the same thing a bajillion times - @989onan
face_funct = lambda: print("invalid face funct")
if vertex_index_size == 1:
face_funct = lambda: read_data('<3B',3)
elif vertex_index_size == 2:
face_funct = lambda: read_data('<3H',6)
else:
face_funct = lambda: read_data('<3i',12)
for _ in range(face_count // 3):
faces.append(face_funct())
print("stage 6")
# Read textures
texture_count = struct.unpack('<i', file.read(4))[0]
for _ in range(texture_count):
texture_path = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace')
textures.append(texture_path)
print("stage 7")
# Read materials
material_count = struct.unpack('<i', file.read(4))[0]
print("material count "+str(material_count))
for _ in range(material_count):
material_name, material_english_name, diffuse_color, specular_color, specular_strength, ambient_color, flag, edge_color, edge_size, texture_index, sphere_texture_index, sphere_mode, toon_sharing_flag, toon_texture_index, comment, surface_count = read_material(file, texture_struct, texture_size)
materials.append((material_name, material_english_name, diffuse_color, specular_color, specular_strength, ambient_color, flag, edge_color, edge_size, texture_index, sphere_texture_index, sphere_mode, toon_sharing_flag, toon_texture_index, comment, surface_count))
print("stage 8")
# Read bones
bone_count = struct.unpack('<i', file.read(4))[0]
print("bone count: "+str(bone_count))
for _ in range(bone_count):
bone_name, bone_english_name, position, parent_bone_index, layer, flag, tail_position, inherit_bone_parent_index, inherit_bone_parent_influence, fixed_axis, local_x_vector, local_z_vector, external_key, ik_target_bone_index, ik_loop_count, ik_limit_radian, ik_links = read_bone(file, bone_struct, bone_size)
bones.append((bone_name, bone_english_name, position, parent_bone_index, layer, flag, tail_position, inherit_bone_parent_index, inherit_bone_parent_influence, fixed_axis, local_x_vector, local_z_vector, external_key, ik_target_bone_index, ik_loop_count, ik_limit_radian, ik_links))
# Read morphs
morph_count = struct.unpack('<i', file.read(4))[0]
print("morph count: "+str(morph_count))
for _ in range(morph_count):
morph_name, morph_english_name, panel, morph_type, morph_data = read_morph(file, morph_struct, morph_size, vertex_struct, vertex_size, bone_struct, bone_size, material_struct, material_size, rigid_struct, rigid_size)
morphs.append((morph_name, morph_english_name, panel, morph_type, morph_data))
print("finished reading file!")
except Exception as e:
print(str(e))
#pass
#raise IOError("Could not read PMX file") from e
# Create Blender objects and assign PMX data
mesh = bpy.data.meshes.new(model_name)
mesh.from_pydata([v[0] for v in vertices], [], faces)
mesh.update()
obj = bpy.data.objects.new(model_name, mesh)
bpy.context.collection.objects.link(obj)
# Assign vertex normals
custom_normals = [(Vector(i[1]).xzy).normalized() for i in vertices]
mesh.normals_split_custom_set_from_vertices(custom_normals)
# Assign UV coordinates
uv_layer = mesh.uv_layers.new()
for i, vertex in enumerate(vertices):
uv_layer.data[i].uv = vertex[2]
# Assign materials
for material_data in materials:
material = bpy.data.materials.new(material_data[0])
material.diffuse_color = material_data[2]
material.specular_color = material_data[3]
material.specular_intensity = material_data[4]
#material.ambient = material_data[5] #TODO: this doesn't exist
# Set other material properties based on the PMX data
mesh.materials.append(material)
# Create armature and assign bones
armature = bpy.data.armatures.new(model_name + "_Armature")
armature_obj = bpy.data.objects.new(model_name + "_Armature", armature)
bpy.context.collection.objects.link(armature_obj)
obj.parent = armature_obj
modifier = obj.modifiers.new("Armature", 'ARMATURE')
modifier.object = armature_obj
bpy.context.view_layer.objects.active = armature_obj
bpy.ops.object.mode_set(mode='EDIT')
for bone_data in bones:
bone = armature.edit_bones.new(bone_data[0])
bone.head = bone_data[2]
if bone_data[6][0] != None:
bone.tail = bone_data[6]
else:
bone.tail = [bone.head[0],bone.head[1],bone.head[2]+1]
#print("fire2!")
#print(bone_data)
if bone_data[3] != -1 or bone_data[3] != -1:
#print("parent bone index: " + str(bone_data[3]))
#print("parent bone name: \""+bones[bone_data[3]][0]+"\"")
#print("parent edit bone name: \""+armature.edit_bones[bones[bone_data[3]][0]].name+"\"")
#print("fire1!")
parent_bone = armature.edit_bones[bones[bone_data[3]][0]]
parent_bone.tail = bone.head.xyz
bone.parent = parent_bone
# Set other bone properties based on the PMX data
bpy.ops.object.mode_set(mode='OBJECT')
# Assign bone weights to the mesh
for i, vertex in enumerate(vertices):
for j in range(0,len(vertex[3])):
if vertex[3][j] != -1:
bone_name = bones[vertex[3][j]][0]
weight = vertex[4][j]
vertex_group = obj.vertex_groups.get(bone_name)
if not vertex_group:
vertex_group = obj.vertex_groups.new(name=bone_name)
vertex_group.add([i], weight, 'REPLACE')
# Assign morphs to the mesh
for morph_data in morphs:
morph_name = morph_data[0]
morph_type = morph_data[3]
if morph_type == 1: # Vertex morph
shape_key = obj.shape_key_add(name=morph_name)
for offset_data in morph_data[4]:
vertex_index = offset_data[0]
offset = offset_data[1]
shape_key.data[vertex_index].co += mathutils.Vector(offset)
# Handle other morph types based on the PMX specification
#ROTATE LAST!
armature_obj.rotation_euler[0] = 1.5708
armature_obj.rotation_euler[2] = 3.14159
armature_obj.select_set(True)
obj.select_set(True)
bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
print(f"Successfully imported PMX file: {filepath}")
print(f"Model Name: {model_name}")
print(f"Model English Name: {model_english_name}")
print(f"Model Comment: {model_comment}")
print(f"Model English Comment: {model_english_comment}")
except Exception as e:
print(f"Error importing PMX file: {filepath}")
print(f"Error details hhh: {traceback.format_exc()}")
+224
View File
@@ -0,0 +1,224 @@
import bpy
import struct
import mathutils
def read_pmd_header(file):
# Read PMD header information
magic = file.read(3)
if magic != b'Pmd':
raise ValueError("Invalid PMD file")
version = struct.unpack('<f', file.read(4))[0]
# Read additional header fields
model_name = file.read(20).decode('shift-jis').rstrip('\0')
comment = file.read(256).decode('shift-jis').rstrip('\0')
return version, model_name, comment
def read_pmd_vertex(file):
# Read PMD vertex information
position = struct.unpack('<3f', file.read(12))
normal = struct.unpack('<3f', file.read(12))
uv = struct.unpack('<2f', file.read(8))
bone_indices = list(struct.unpack('<2H', file.read(4)))
bone_weights = struct.unpack('<b', file.read(1))[0] / 100
edge_flag = struct.unpack('<b', file.read(1))[0]
return position, normal, uv, bone_indices, bone_weights, edge_flag
def read_pmd_material(file):
# Read PMD material information
diffuse_color = struct.unpack('<4f', file.read(16))
specular_color = struct.unpack('<3f', file.read(12))
specular_intensity = struct.unpack('<f', file.read(4))[0]
ambient_color = struct.unpack('<3f', file.read(12))
toon_index = struct.unpack('<b', file.read(1))[0]
edge_flag = struct.unpack('<b', file.read(1))[0]
vertex_count = struct.unpack('<i', file.read(4))[0]
texture_file_name = file.read(20).decode('shift-jis').rstrip('\0')
return diffuse_color, specular_color, specular_intensity, ambient_color, toon_index, edge_flag, vertex_count, texture_file_name
def read_pmd_bone(file):
# Read PMD bone information
bone_name = file.read(20).decode('shift-jis').rstrip('\0')
parent_bone_index = struct.unpack('<h', file.read(2))[0]
tail_pos_bone_index = struct.unpack('<h', file.read(2))[0]
bone_type = struct.unpack('<b', file.read(1))[0]
ik_parent_bone_index = struct.unpack('<h', file.read(2))[0]
bone_head_pos = struct.unpack('<3f', file.read(12))
return bone_name, parent_bone_index, tail_pos_bone_index, bone_type, ik_parent_bone_index, bone_head_pos
def read_pmd_ik(file):
# Read PMD IK information
ik_bone_index = struct.unpack('<h', file.read(2))[0]
ik_target_bone_index = struct.unpack('<h', file.read(2))[0]
ik_chain_length = struct.unpack('<b', file.read(1))[0]
iterations = struct.unpack('<h', file.read(2))[0]
limit_angle = struct.unpack('<f', file.read(4))[0]
ik_child_bone_indices = []
for _ in range(ik_chain_length):
ik_child_bone_index = struct.unpack('<h', file.read(2))[0]
ik_child_bone_indices.append(ik_child_bone_index)
return ik_bone_index, ik_target_bone_index, ik_chain_length, iterations, limit_angle, ik_child_bone_indices
def read_pmd_morph(file):
# Read PMD morph information
morph_name = file.read(20).decode('shift-jis').rstrip('\0')
morph_vertex_count = struct.unpack('<i', file.read(4))[0]
morph_type = struct.unpack('<b', file.read(1))[0]
morph_vertices = []
for _ in range(morph_vertex_count):
morph_vertex_index = struct.unpack('<i', file.read(4))[0]
morph_vertex_pos = struct.unpack('<3f', file.read(12))
morph_vertices.append((morph_vertex_index, morph_vertex_pos))
return morph_name, morph_vertex_count, morph_type, morph_vertices
def import_pmd(filepath):
try:
with open(filepath, 'rb') as file:
version, model_name, comment = read_pmd_header(file)
# Read vertices
vertex_count = struct.unpack('<i', file.read(4))[0]
vertices = []
for _ in range(vertex_count):
position, normal, uv, bone_indices, bone_weights, edge_flag = read_pmd_vertex(file)
vertices.append((position, normal, uv, bone_indices, bone_weights, edge_flag))
# Read faces
face_count = struct.unpack('<i', file.read(4))[0]
faces = []
for _ in range(face_count // 3):
face_indices = struct.unpack('<3i', file.read(12))
faces.append(face_indices)
# Read materials
material_count = struct.unpack('<i', file.read(4))[0]
materials = []
for _ in range(material_count):
diffuse_color, specular_color, specular_intensity, ambient_color, toon_index, edge_flag, vertex_count, texture_file_name = read_pmd_material(file)
materials.append((diffuse_color, specular_color, specular_intensity, ambient_color, toon_index, edge_flag, vertex_count, texture_file_name))
# Read bones
bone_count = struct.unpack('<h', file.read(2))[0]
bones = []
for _ in range(bone_count):
bone_name, parent_bone_index, tail_pos_bone_index, bone_type, ik_parent_bone_index, bone_head_pos = read_pmd_bone(file)
bones.append((bone_name, parent_bone_index, tail_pos_bone_index, bone_type, ik_parent_bone_index, bone_head_pos))
# Read IKs
ik_count = struct.unpack('<h', file.read(2))[0]
iks = []
for _ in range(ik_count):
ik_bone_index, ik_target_bone_index, ik_chain_length, iterations, limit_angle, ik_child_bone_indices = read_pmd_ik(file)
iks.append((ik_bone_index, ik_target_bone_index, ik_chain_length, iterations, limit_angle, ik_child_bone_indices))
# Read morphs
morph_count = struct.unpack('<h', file.read(2))[0]
morphs = []
for _ in range(morph_count):
morph_name, morph_vertex_count, morph_type, morph_vertices = read_pmd_morph(file)
morphs.append((morph_name, morph_vertex_count, morph_type, morph_vertices))
# Create Blender objects and assign PMD data
mesh = bpy.data.meshes.new(model_name)
mesh.from_pydata([v[0] for v in vertices], [], faces)
mesh.update()
obj = bpy.data.objects.new(model_name, mesh)
bpy.context.collection.objects.link(obj)
# Assign vertex normals
for i, vertex in enumerate(vertices):
mesh.vertices[i].normal = vertex[1]
# Assign UV coordinates
uv_layer = mesh.uv_layers.new()
for i, vertex in enumerate(vertices):
uv_layer.data[i].uv = vertex[2]
# Assign materials
for material_data in materials:
material = bpy.data.materials.new(f"Material_{len(mesh.materials)}")
material.diffuse_color = material_data[0]
material.specular_color = material_data[1]
material.specular_intensity = material_data[2]
material.ambient = material_data[3]
# Set other material properties based on the PMD data
mesh.materials.append(material)
# Create armature and assign bones
armature = bpy.data.armatures.new(model_name + "_Armature")
armature_obj = bpy.data.objects.new(model_name + "_Armature", armature)
bpy.context.collection.objects.link(armature_obj)
bpy.context.view_layer.objects.active = armature_obj
bpy.ops.object.mode_set(mode='EDIT')
for bone_data in bones:
bone = armature.edit_bones.new(bone_data[0])
bone.head = bone_data[5]
if bone_data[1] != -1:
parent_bone = armature.edit_bones[bone_data[1]]
bone.parent = parent_bone
bone.tail = parent_bone.head
else:
bone.tail = bone.head + mathutils.Vector((0, 0.1, 0))
# Set other bone properties based on the PMD data
bpy.ops.object.mode_set(mode='OBJECT')
# Assign bone weights to the mesh
for i, vertex in enumerate(vertices):
for j in range(2):
if vertex[3][j] != 65535:
bone_name = bones[vertex[3][j]][0]
weight = vertex[4] if j == 0 else 1 - vertex[4]
vertex_group = obj.vertex_groups.get(bone_name)
if not vertex_group:
vertex_group = obj.vertex_groups.new(name=bone_name)
vertex_group.add([i], weight, 'REPLACE')
# Assign IK constraints to bones
for ik_data in iks:
ik_bone = armature.bones[bones[ik_data[0]][0]]
ik_target_bone = armature.bones[bones[ik_data[1]][0]]
ik_constraint = ik_bone.constraints.new('IK')
ik_constraint.target = armature_obj
ik_constraint.subtarget = ik_target_bone.name
ik_constraint.chain_count = ik_data[2]
ik_constraint.iterations = ik_data[3]
ik_constraint.limit_mode = 'LIMITDIST_INSIDE'
ik_constraint.limit_mode_max_x = ik_data[4]
# Assign morphs to the mesh
for morph_data in morphs:
morph_name = morph_data[0]
morph_type = morph_data[2]
if morph_type == 0: # Vertex morph
shape_key = obj.shape_key_add(name=morph_name)
for vertex_data in morph_data[3]:
vertex_index = vertex_data[0]
vertex_offset = vertex_data[1]
shape_key.data[vertex_index].co += mathutils.Vector(vertex_offset)
print(f"Successfully imported PMD file: {filepath}")
print(f"Model Name: {model_name}")
print(f"Comment: {comment}")
except Exception as e:
print(f"Error importing PMD file: {filepath}")
print(f"Error details: {str(e)}")
+307
View File
@@ -0,0 +1,307 @@
import bpy
import struct
def read_pmx_header(file):
# Read PMX header information
magic = file.read(4) # Read magic bytes (should be "PMX ")
if magic != b'PMX ':
raise ValueError("Invalid PMX file")
version = struct.unpack('<f', file.read(4))[0] # Read version number (float, 4 bytes)
# Read additional header fields
data_size = struct.unpack('<i', file.read(4))[0] # Read size of remaining header data (int, 4 bytes)
encoding = struct.unpack('<b', file.read(1))[0] # Read encoding type (byte, 1 byte)
additional_uvs = struct.unpack('<b', file.read(1))[0] # Read number of additional UV layers (byte, 1 byte)
vertex_index_size = struct.unpack('<b', file.read(1))[0] # Read vertex index size (byte, 1 byte)
texture_index_size = struct.unpack('<b', file.read(1))[0] # Read texture index size (byte, 1 byte)
material_index_size = struct.unpack('<b', file.read(1))[0] # Read material index size (byte, 1 byte)
bone_index_size = struct.unpack('<b', file.read(1))[0] # Read bone index size (byte, 1 byte)
morph_index_size = struct.unpack('<b', file.read(1))[0] # Read morph index size (byte, 1 byte)
rigid_body_index_size = struct.unpack('<b', file.read(1))[0] # Read rigid body index size (byte, 1 byte)
# Read model name and comments
model_name = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace') # Read model name (string, variable length)
model_english_name = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace') # Read model English name (string, variable length)
model_comment = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace') # Read model comment (string, variable length)
model_english_comment = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace') # Read model English comment (string, variable length)
return version, encoding, additional_uvs, vertex_index_size, texture_index_size, material_index_size, bone_index_size, morph_index_size, rigid_body_index_size, model_name, model_english_name, model_comment, model_english_comment
def read_vertex(file, vertex_index_size):
position = struct.unpack('<3f', file.read(12)) # Read vertex position (float, 3 * 4 bytes)
normal = struct.unpack('<3f', file.read(12)) # Read vertex normal (float, 3 * 4 bytes)
uv = struct.unpack('<2f', file.read(8)) # Read vertex UV coordinates (float, 2 * 4 bytes)
if vertex_index_size == 1:
bone_indices = list(struct.unpack('<4B', file.read(4))) # Read bone indices (byte, 4 * 1 byte)
elif vertex_index_size == 2:
bone_indices = list(struct.unpack('<4H', file.read(8))) # Read bone indices (short, 4 * 2 bytes)
else:
bone_indices = list(struct.unpack('<4I', file.read(16))) # Read bone indices (int, 4 * 4 bytes)
bone_weights = list(struct.unpack('<4f', file.read(16))) # Read bone weights (float, 4 * 4 bytes)
edge_scale = struct.unpack('<f', file.read(4))[0] # Read edge scale (float, 4 bytes)
return position, normal, uv, bone_indices, bone_weights, edge_scale
def read_material(file, texture_index_size):
material_name = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace') # Read material name (string, variable length)
material_english_name = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace') # Read material English name (string, variable length)
diffuse_color = struct.unpack('<4f', file.read(16)) # Read diffuse color (float, 4 * 4 bytes)
specular_color = struct.unpack('<3f', file.read(12)) # Read specular color (float, 3 * 4 bytes)
specular_strength = struct.unpack('<f', file.read(4))[0] # Read specular strength (float, 4 bytes)
ambient_color = struct.unpack('<3f', file.read(12)) # Read ambient color (float, 3 * 4 bytes)
flag = struct.unpack('<b', file.read(1))[0] # Read flag (byte, 1 byte)
edge_color = struct.unpack('<4f', file.read(16)) # Read edge color (float, 4 * 4 bytes)
edge_size = struct.unpack('<f', file.read(4))[0] # Read edge size (float, 4 bytes)
texture_index = struct.unpack(f'<{texture_index_size}B', file.read(texture_index_size))[0] # Read texture index (byte, texture_index_size bytes)
sphere_texture_index = struct.unpack(f'<{texture_index_size}B', file.read(texture_index_size))[0] # Read sphere texture index (byte, texture_index_size bytes)
sphere_mode = struct.unpack('<b', file.read(1))[0] # Read sphere mode (byte, 1 byte)
toon_sharing_flag = struct.unpack('<b', file.read(1))[0] # Read toon sharing flag (byte, 1 byte)
if toon_sharing_flag == 0:
toon_texture_index = struct.unpack(f'<{texture_index_size}B', file.read(texture_index_size))[0] # Read toon texture index (byte, texture_index_size bytes)
else:
toon_texture_index = struct.unpack('<b', file.read(1))[0] # Read shared toon texture index (byte, 1 byte)
comment = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace') # Read material comment (string, variable length)
return material_name, material_english_name, diffuse_color, specular_color, specular_strength, ambient_color, flag, edge_color, edge_size, texture_index, sphere_texture_index, sphere_mode, toon_sharing_flag, toon_texture_index, comment
def read_bone(file, bone_index_size):
bone_name = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace') # Read bone name (string, variable length)
bone_english_name = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace') # Read bone English name (string, variable length)
position = struct.unpack('<3f', file.read(12)) # Read bone position (float, 3 * 4 bytes)
parent_bone_index = struct.unpack(f'<{bone_index_size}B', file.read(bone_index_size))[0] # Read parent bone index (byte, bone_index_size bytes)
layer = struct.unpack('<i', file.read(4))[0] # Read bone layer (int, 4 bytes)
flag = struct.unpack('<H', file.read(2))[0] # Read bone flag (short, 2 bytes)
if flag & 0x0001:
tail_position = struct.unpack('<3f', file.read(12)) # Read bone tail position (float, 3 * 4 bytes)
else:
tail_index = struct.unpack(f'<{bone_index_size}B', file.read(bone_index_size))[0] # Read bone tail index (byte, bone_index_size bytes)
if flag & 0x0100 or flag & 0x0200:
inherit_bone_parent_index = struct.unpack(f'<{bone_index_size}B', file.read(bone_index_size))[0] # Read inherit bone parent index (byte, bone_index_size bytes)
inherit_bone_parent_influence = struct.unpack('<f', file.read(4))[0] # Read inherit bone parent influence (float, 4 bytes)
if flag & 0x0400:
fixed_axis = struct.unpack('<3f', file.read(12)) # Read fixed axis (float, 3 * 4 bytes)
if flag & 0x0800:
local_x_vector = struct.unpack('<3f', file.read(12)) # Read local X-axis vector (float, 3 * 4 bytes)
local_z_vector = struct.unpack('<3f', file.read(12)) # Read local Z-axis vector (float, 3 * 4 bytes)
if flag & 0x2000:
external_key = struct.unpack('<i', file.read(4))[0] # Read external key (int, 4 bytes)
if flag & 0x0020:
ik_target_bone_index = struct.unpack(f'<{bone_index_size}B', file.read(bone_index_size))[0] # Read IK target bone index (byte, bone_index_size bytes)
ik_loop_count = struct.unpack('<i', file.read(4))[0] # Read IK loop count (int, 4 bytes)
ik_limit_radian = struct.unpack('<f', file.read(4))[0] # Read IK limit angle (float, 4 bytes)
ik_link_count = struct.unpack('<i', file.read(4))[0] # Read IK link count (int, 4 bytes)
ik_links = []
for _ in range(ik_link_count):
ik_link_bone_index = struct.unpack(f'<{bone_index_size}B', file.read(bone_index_size))[0] # Read IK link bone index (byte, bone_index_size bytes)
ik_link_limit_min = struct.unpack('<3f', file.read(12)) # Read IK link limit minimum (float, 3 * 4 bytes)
ik_link_limit_max = struct.unpack('<3f', file.read(12)) # Read IK link limit maximum (float, 3 * 4 bytes)
ik_links.append((ik_link_bone_index, ik_link_limit_min, ik_link_limit_max))
return bone_name, bone_english_name, position, parent_bone_index, layer, flag, tail_position, inherit_bone_parent_index, inherit_bone_parent_influence, fixed_axis, local_x_vector, local_z_vector, external_key, ik_target_bone_index, ik_loop_count, ik_limit_radian, ik_links
def read_morph(file, morph_index_size):
morph_name = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace') # Read morph name (string, variable length)
morph_english_name = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace') # Read morph English name (string, variable length)
panel = struct.unpack('<b', file.read(1))[0] # Read panel type (byte, 1 byte)
morph_type = struct.unpack('<b', file.read(1))[0] # Read morph type (byte, 1 byte)
offset_size = struct.unpack('<i', file.read(4))[0] # Read offset size (int, 4 bytes)
morph_data = []
for _ in range(offset_size):
if morph_type == 0: # Group
morph_index = struct.unpack(f'<{morph_index_size}B', file.read(morph_index_size))[0] # Read morph index (byte, morph_index_size bytes)
morph_value = struct.unpack('<f', file.read(4))[0] # Read morph value (float, 4 bytes)
morph_data.append((morph_index, morph_value))
elif morph_type == 1: # Vertex
vertex_index = struct.unpack('<i', file.read(4))[0] # Read vertex index (int, 4 bytes)
position_offset = struct.unpack('<3f', file.read(12)) # Read position offset (float, 3 * 4 bytes)
morph_data.append((vertex_index, position_offset))
elif morph_type == 2: # Bone
bone_index = struct.unpack(f'<{morph_index_size}B', file.read(morph_index_size))[0] # Read bone index (byte, morph_index_size bytes)
position_offset = struct.unpack('<3f', file.read(12)) # Read position offset (float, 3 * 4 bytes)
rotation_offset = struct.unpack('<4f', file.read(16)) # Read rotation offset (float, 4 * 4 bytes)
morph_data.append((bone_index, position_offset, rotation_offset))
elif morph_type == 3: # UV
vertex_index = struct.unpack('<i', file.read(4))[0] # Read vertex index (int, 4 bytes)
uv_offset = struct.unpack('<4f', file.read(16)) # Read UV offset (float, 4 * 4 bytes)
morph_data.append((vertex_index, uv_offset))
elif morph_type == 4: # UV extended1
vertex_index = struct.unpack('<i', file.read(4))[0] # Read vertex index (int, 4 bytes)
uv_offset = struct.unpack('<4f', file.read(16)) # Read UV offset (float, 4 * 4 bytes)
morph_data.append((vertex_index, uv_offset))
elif morph_type == 5: # UV extended2
vertex_index = struct.unpack('<i', file.read(4))[0] # Read vertex index (int, 4 bytes)
uv_offset = struct.unpack('<4f', file.read(16)) # Read UV offset (float, 4 * 4 bytes)
morph_data.append((vertex_index, uv_offset))
elif morph_type == 6: # UV extended3
vertex_index = struct.unpack('<i', file.read(4))[0] # Read vertex index (int, 4 bytes)
uv_offset = struct.unpack('<4f', file.read(16)) # Read UV offset (float, 4 * 4 bytes)
morph_data.append((vertex_index, uv_offset))
elif morph_type == 7: # UV extended4
vertex_index = struct.unpack('<i', file.read(4))[0] # Read vertex index (int, 4 bytes)
uv_offset = struct.unpack('<4f', file.read(16)) # Read UV offset (float, 4 * 4 bytes)
morph_data.append((vertex_index, uv_offset))
elif morph_type == 8: # Material
material_index = struct.unpack('<i', file.read(4))[0] # Read material index (int, 4 bytes)
offset_type = struct.unpack('<b', file.read(1))[0] # Read offset type (byte, 1 byte)
diffuse_offset = struct.unpack('<4f', file.read(16)) # Read diffuse color offset (float, 4 * 4 bytes)
specular_offset = struct.unpack('<3f', file.read(12)) # Read specular color offset (float, 3 * 4 bytes)
specular_factor_offset = struct.unpack('<f', file.read(4))[0] # Read specular factor offset (float, 4 bytes)
ambient_offset = struct.unpack('<3f', file.read(12)) # Read ambient color offset (float, 3 * 4 bytes)
edge_color_offset = struct.unpack('<4f', file.read(16)) # Read edge color offset (float, 4 * 4 bytes)
edge_size_offset = struct.unpack('<f', file.read(4))[0] # Read edge size offset (float, 4 bytes)
texture_factor_offset = struct.unpack('<4f', file.read(16)) # Read texture factor offset (float, 4 * 4 bytes)
sphere_texture_factor_offset = struct.unpack('<4f', file.read(16)) # Read sphere texture factor offset (float, 4 * 4 bytes)
toon_texture_factor_offset = struct.unpack('<4f', file.read(16)) # Read toon texture factor offset (float, 4 * 4 bytes)
morph_data.append((material_index, offset_type, diffuse_offset, specular_offset, specular_factor_offset, ambient_offset, edge_color_offset, edge_size_offset, texture_factor_offset, sphere_texture_factor_offset, toon_texture_factor_offset))
return morph_name, morph_english_name, panel, morph_type, morph_data
def import_pmx(filepath):
try:
with open(filepath, 'rb') as file:
version, encoding, additional_uvs, vertex_index_size, texture_index_size, material_index_size, bone_index_size, morph_index_size, rigid_body_index_size, model_name, model_english_name, model_comment, model_english_comment = read_pmx_header(file)
# Read vertices
vertex_count = struct.unpack('<i', file.read(4))[0] # Read vertex count (int, 4 bytes)
vertices = []
for _ in range(vertex_count):
position, normal, uv, bone_indices, bone_weights, edge_scale = read_vertex(file, vertex_index_size)
vertices.append((position, normal, uv, bone_indices, bone_weights, edge_scale))
# Read faces
face_count = struct.unpack('<i', file.read(4))[0] # Read face count (int, 4 bytes)
faces = []
for _ in range(face_count // 3):
face_indices = struct.unpack('<3i', file.read(12)) # Read face indices (int, 3 * 4 bytes)
faces.append(face_indices)
# Read textures
texture_count = struct.unpack('<i', file.read(4))[0] # Read texture count (int, 4 bytes)
textures = []
for _ in range(texture_count):
texture_path = str(file.read(struct.unpack('<i', file.read(4))[0]), 'utf-16-le', errors='replace') # Read texture path (string, variable length)
textures.append(texture_path)
# Read materials
material_count = struct.unpack('<i', file.read(4))[0] # Read material count (int, 4 bytes)
materials = []
for _ in range(material_count):
material_name, material_english_name, diffuse_color, specular_color, specular_strength, ambient_color, flag, edge_color, edge_size, texture_index, sphere_texture_index, sphere_mode, toon_sharing_flag, toon_texture_index, comment = read_material(file, texture_index_size)
materials.append((material_name, material_english_name, diffuse_color, specular_color, specular_strength, ambient_color, flag, edge_color, edge_size, texture_index, sphere_texture_index, sphere_mode, toon_sharing_flag, toon_texture_index, comment))
# Read bones
bone_count = struct.unpack('<i', file.read(4))[0] # Read bone count (int, 4 bytes)
bones = []
for _ in range(bone_count):
bone_name, bone_english_name, position, parent_bone_index, layer, flag, tail_position, inherit_bone_parent_index, inherit_bone_parent_influence, fixed_axis, local_x_vector, local_z_vector, external_key, ik_target_bone_index, ik_loop_count, ik_limit_radian, ik_links = read_bone(file, bone_index_size)
bones.append((bone_name, bone_english_name, position, parent_bone_index, layer, flag, tail_position, inherit_bone_parent_index, inherit_bone_parent_influence, fixed_axis, local_x_vector, local_z_vector, external_key, ik_target_bone_index, ik_loop_count, ik_limit_radian, ik_links))
# Read morphs
morph_count = struct.unpack('<i', file.read(4))[0] # Read morph count (int, 4 bytes)
morphs = []
for _ in range(morph_count):
morph_name, morph_english_name, panel, morph_type, morph_data = read_morph(file, morph_index_size)
morphs.append((morph_name, morph_english_name, panel, morph_type, morph_data))
# Create Blender objects and assign PMX data
mesh = bpy.data.meshes.new(model_name)
mesh.from_pydata([v[0] for v in vertices], [], faces)
mesh.update()
obj = bpy.data.objects.new(model_name, mesh)
bpy.context.collection.objects.link(obj)
# Assign vertex normals
for i, vertex in enumerate(vertices):
mesh.vertices[i].normal = vertex[1]
# Assign UV coordinates
uv_layer = mesh.uv_layers.new()
for i, vertex in enumerate(vertices):
uv_layer.data[i].uv = vertex[2]
# Assign materials
for material_data in materials:
material = bpy.data.materials.new(material_data[0])
material.diffuse_color = material_data[2]
material.specular_color = material_data[3]
material.specular_intensity = material_data[4]
material.ambient = material_data[5]
# Set other material properties based on the PMX data
mesh.materials.append(material)
# Create armature and assign bones
armature = bpy.data.armatures.new(model_name + "_Armature")
armature_obj = bpy.data.objects.new(model_name + "_Armature", armature)
bpy.context.collection.objects.link(armature_obj)
bpy.context.view_layer.objects.active = armature_obj
bpy.ops.object.mode_set(mode='EDIT')
for bone_data in bones:
bone = armature.edit_bones.new(bone_data[0])
bone.head = bone_data[2]
bone.tail = bone_data[6]
if bone_data[3] != -1:
parent_bone = armature.edit_bones[bone_data[3]]
bone.parent = parent_bone
# Set other bone properties based on the PMX data
bpy.ops.object.mode_set(mode='OBJECT')
# Assign bone weights to the mesh
for i, vertex in enumerate(vertices):
for j in range(4):
if vertex[3][j] != -1:
bone_name = bones[vertex[3][j]][0]
weight = vertex[4][j]
vertex_group = obj.vertex_groups.get(bone_name)
if not vertex_group:
vertex_group = obj.vertex_groups.new(name=bone_name)
vertex_group.add([i], weight, 'REPLACE')
# Assign morphs to the mesh
for morph_data in morphs:
morph_name = morph_data[0]
morph_type = morph_data[3]
if morph_type == 1: # Vertex morph
shape_key = obj.shape_key_add(name=morph_name)
for offset_data in morph_data[4]:
vertex_index = offset_data[0]
offset = offset_data[1]
shape_key.data[vertex_index].co += mathutils.Vector(offset)
# Handle other morph types based on the PMX specification
print(f"Successfully imported PMX file: {filepath}")
print(f"Model Name: {model_name}")
print(f"Model English Name: {model_english_name}")
print(f"Model Comment: {model_comment}")
print(f"Model English Comment: {model_english_comment}")
except Exception as e:
print(f"Error importing PMX file: {filepath}")
print(f"Error details: {str(e)}")
+81 -6
View File
@@ -13,12 +13,87 @@ def register_wrap(cls):
__bl_classes.append(cls)
return cls
#- @989onan had to add this from Cats. This is extremely important else you will be screamed at by register order issues!
# Find order to register to solve dependencies
#################################################
def toposort(deps_dict):
sorted_list = []
sorted_values = set()
while len(deps_dict) > 0:
unsorted = []
for value, deps in deps_dict.items():
if len(deps) == 0:
sorted_list.append(value)
sorted_values.add(value)
else:
unsorted.append(value)
deps_dict = {value : deps_dict[value] - sorted_values for value in unsorted}
sort_order(sorted_list) #to sort by 'bl_order' so we can choose how things may appear in the ui
return sorted_list
def order_classes():
global __bl_ordered_classes
# Create a copy of the classes list to store the ordered classes
__bl_ordered_classes = __bl_classes.copy()
deps_dict = {}
classes_to_register = set(iter_classes_to_register())
for class_obj in classes_to_register:
deps_dict[class_obj] = set(iter_own_register_deps(class_obj, classes_to_register))
__bl_ordered_classes.clear()
# Then put everything else sorted into the list
for class_obj in toposort(deps_dict):
__bl_ordered_classes.append(class_obj)
print(__bl_ordered_classes)
__bl_classes.clear()
def iter_classes_to_register():
# Iterate over the ordered classes and yield each class for registration
for cls in __bl_ordered_classes:
yield cls
for class_obj in __bl_classes:
yield class_obj
def iter_own_register_deps(class_obj, own_classes):
yield from (dep for dep in iter_register_deps(class_obj) if dep in own_classes)
def iter_register_deps(class_obj):
for value in typing.get_type_hints(class_obj, {}, {}, True).values():
dependency = get_dependency_from_annotation(value)
if dependency is not None:
yield dependency
if hasattr(class_obj, "bl_parent_id"):
if class_obj.bl_parent_id != "":
for dependency in __bl_classes:
if dependency.bl_idname == class_obj.bl_parent_id:
yield dependency
def get_dependency_from_annotation(value):
if isinstance(value, tuple) and len(value) == 2:
if value[0] in (bpy.props.PointerProperty, bpy.props.CollectionProperty):
return value[1]["type"]
return None
# Find order to register to solve dependencies
#################################################
def toposort(deps_dict):
sorted_list = []
sorted_values = set()
while len(deps_dict) > 0:
unsorted = []
for value, deps in deps_dict.items():
if len(deps) == 0:
sorted_list.append(value)
sorted_values.add(value)
else:
unsorted.append(value)
deps_dict = {value : deps_dict[value] - sorted_values for value in unsorted}
return sorted_list
+13 -17
View File
@@ -1,23 +1,19 @@
if "bpy" not in locals():
import bpy
from . import panel, quick_access, optimization
import glob
import os
from os.path import dirname, basename, isfile, join
modules = glob.glob(join(dirname(__file__), "*.py"))
for module_name in [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]:
exec("from . import "+module_name)
print("importing " +module_name)
else:
import importlib
# Reload the modules to reflect changes during development
importlib.reload(panel)
importlib.reload(quick_access)
importlib.reload(optimization)
modules = glob.glob(join(dirname(__file__), "*.py"))
for module_name in [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]:
print("reloading " +module_name)
exec("importlib.reload("+module_name+")")
def register():
print("UI register called")
from ..core.register import iter_classes_to_register
# Iterate over the classes to register and register them
for cls in iter_classes_to_register():
bpy.utils.register_class(cls)
def unregister():
print("UI unregister called")
from ..core.register import iter_classes_to_register
# Iterate over the classes to unregister in reverse order and unregister them
for cls in reversed(list(iter_classes_to_register())):
bpy.utils.unregister_class(cls)
+1
View File
@@ -1,5 +1,6 @@
import bpy
from ..core.register import register_wrap
from .panel import AvatarToolkitPanel
@register_wrap
class AvatarToolkitOptimizationPanel(bpy.types.Panel):
+2 -1
View File
@@ -12,4 +12,5 @@ class AvatarToolkitPanel(bpy.types.Panel):
def draw(self, context):
layout = self.layout
layout.label(text="Welcome to Avatar Toolkit!")
print("Avatar Toolkit Panel is being drawn")
#print("Avatar Toolkit Panel is being drawn")
+39 -1
View File
@@ -1,5 +1,9 @@
import bpy
from ..core.register import register_wrap
from .panel import AvatarToolkitPanel
from ..core.import_pmx import import_pmx
from ..core.import_pmd import import_pmd
@register_wrap
class AvatarToolkitQuickAccessPanel(bpy.types.Panel):
@@ -13,4 +17,38 @@ class AvatarToolkitQuickAccessPanel(bpy.types.Panel):
def draw(self, context):
layout = self.layout
layout.label(text="Quick Access Options")
# Add quick access options here
# Add import buttons
row = layout.row()
row.operator("avatar_toolkit.import_pmx", text="Import PMX")
row.operator("avatar_toolkit.import_pmd", text="Import PMD")
@register_wrap
class AVATAR_TOOLKIT_OT_import_pmx(bpy.types.Operator):
bl_idname = "avatar_toolkit.import_pmx"
bl_label = "Import PMX"
filepath: bpy.props.StringProperty(subtype="FILE_PATH")
def execute(self, context):
import_pmx(self.filepath)
return {'FINISHED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
@register_wrap
class AVATAR_TOOLKIT_OT_import_pmd(bpy.types.Operator):
bl_idname = "avatar_toolkit.import_pmd"
bl_label = "Import PMD"
filepath: bpy.props.StringProperty(subtype="FILE_PATH")
def execute(self, context):
import_pmd(self.filepath)
return {'FINISHED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}