Compare commits

...

29 Commits

Author SHA1 Message Date
Colin Basnett
e704069763 Initial commit for work to fix the multi-armature workflow 2025-10-28 23:13:34 -07:00
Colin Basnett
8ed985263c Fix for bad class inclusion 2025-10-06 17:57:55 -07:00
Colin Basnett
d91408ecab Incremented version to 8.2.2 2025-10-06 17:52:59 -07:00
Colin Basnett
dd1ea683bb Added bone mapping option to ignore trailing whitespace
Some very old PSKs and PSAs have trailing spaces in the bone names instead of padding the buffer with null bytes.

Trailing whitespace will now be ignored by default to maximize compatibility.
2025-10-06 17:48:51 -07:00
Colin Basnett
240b79d374 Fixed a number of PEP warnings
Most of these are just assert statements to silence the warnings for accessing optionals
2025-09-20 12:34:35 -07:00
Colin Basnett
33e7862288 Converted __init__ module initialisation to new pattern
Thanks to Dr. Sybren for the BCON25 presentation that tipped me off to the existence of `register_classes_factory`.
2025-09-18 23:29:14 -07:00
Colin Basnett
b4eefaba6f Increased the minimum Blender version to 4.4 2025-08-17 17:20:07 -07:00
Colin Basnett
ca869731e7 Incremented version to 8.2.1 2025-08-17 13:20:16 -07:00
Colin Basnett
20c8a39f23 Fixed is_action_for_object failing when action had multiple slots 2025-08-17 13:19:47 -07:00
Colin Basnett
8d2f46c2b1 Split axis selection functionality from TransformMixin 2025-08-10 22:12:46 -07:00
Colin Basnett
84863d9de4 Fixed same invalid faces bug, but for the Extra UVs channel 2025-08-09 17:48:55 -07:00
Colin Basnett
ef38b896a6 Added unit test for import PSKs with invalid faces 2025-08-03 01:50:31 -07:00
Colin Basnett
3e54378a57 Incremented version to 8.2.0 2025-08-03 01:43:47 -07:00
Colin Basnett
75cee40604 Merge branch '8.2.0' 2025-08-03 01:43:15 -07:00
Colin Basnett
7cc36d427e Minor formatting fix 2025-08-03 01:42:54 -07:00
Colin Basnett
5c50e76771 Moved get_collection_*from_context functions to helpers.py 2025-08-03 01:42:44 -07:00
Colin Basnett
bd3ea76109 Fixed a bug where meshes with invalid faces could not be imported 2025-08-03 01:41:29 -07:00
Colin Basnett
f4b20e4e0f Reverted to old "is action for armature" functionality
The current Blender 4.4 functionality is still very wishy washy (not able to inspect channel bags), and the solution that was created was broken.

In addition, newly created actions will be given an appropriately named slot instead of it being a "Legacy Slot".
2025-08-03 01:40:38 -07:00
Colin Basnett
921efe97aa Minor fixes 2025-07-23 10:26:56 -07:00
Colin Basnett
4767081bc4 Update README.md 2025-06-19 18:41:24 +00:00
Colin Basnett
ff4cbc8871 Update README.md 2025-06-19 18:40:07 +00:00
Colin Basnett
7d0c520019 Update README.md 2025-06-19 18:39:33 +00:00
Colin Basnett
e7ce934383 Improve empty material slot error message 2025-06-07 19:29:59 -07:00
Colin Basnett
a48fcbd6e3 Ignore empty armature modifiers on PSK export 2025-06-07 19:20:29 -07:00
Colin Basnett
253566576e Fix PSK export with no armatures while using ARMATURE export space 2025-06-07 19:19:54 -07:00
Colin Basnett
660a196002 Fix "Advanced" panel being open by default in PSA export 2025-06-07 19:18:02 -07:00
Colin Basnett
98968a8623 Fix error when attempting to export mesh with no UV layers
The fallback behaviour is now to just output zeroes for the UVs if a mesh has no UV layers.
2025-06-07 19:17:39 -07:00
Colin Basnett
29831d7f09 Improved performance of PSK importer by ~40% for large meshes 2025-05-18 01:16:20 -07:00
Colin Basnett
00d9e3996c Fixed an issue where ACTIVE_ACTION sequence source was not working
Also added a scene-level transform source.
2025-05-18 00:46:50 -07:00
30 changed files with 771 additions and 407 deletions

View File

@@ -7,6 +7,11 @@ This Blender addon allows you to import and export meshes and animations to and
This software is licensed under the [GPLv3](https://www.gnu.org/licenses/gpl-3.0.html) license.
# Installation
For Blender 4.2 and higher, download the latest version from the [Blender Extensions](https://extensions.blender.org/add-ons/io-scene-psk-psa/) platform.
For Blender 4.1 and lower, see [Legacy Compatibility](#legacy-compatibility).
# Features
* Full PSK/PSA import and export capabilities.
* Non-standard file section data (.pskx) is supported for import only (vertex normals, extra UV channels, vertex colors, shape keys).
@@ -18,11 +23,6 @@ This software is licensed under the [GPLv3](https://www.gnu.org/licenses/gpl-3.0
* Multiple armature objects can be exported to a single PSK or PSA file, allowing seamless use of [action slots](https://docs.blender.org/manual/en/latest/animation/actions.html#action-slots).
* Support for exporting instance collections.
# Installation
For Blender 4.2 and higher, download the latest version from the [Blender Extensions](https://extensions.blender.org/add-ons/io-scene-psk-psa/) platform.
For Blender 4.1 and lower, see [Legacy Compatibility](#legacy-compatibility).
# Usage
## Exporting a PSK
1. Select the mesh objects you wish to export.
@@ -71,15 +71,12 @@ There is a [pull request](https://github.com/gildor2/UEViewer/pull/277) to add s
# Legacy Compatibility
Below is a table of the latest addon versions that are compatible with older versions of Blender. These versions are no longer maintained and may contain bugs that have been fixed in newer versions. It is recommended to use the latest version of the addon for the best experience.
Critical bug fixes may be issued for legacy addon versions that are under [Blender's LTS maintenance period](https://www.blender.org/download/lts/). Once the LTS period has ended, legacy addon versions will no longer be supported by the maintainers of this repository, although the releases will still be available for download.
| Blender Version| Addon Version | Long Term Support |
|-|--------------------------------------------------------------------------------|-----------------|
| [4.1](https://www.blender.org/download/releases/4-1/) | [7.0.0](https://github.com/DarklightGames/io_scene_psk_psa/releases/tag/7.0.0) | No |
| [4.0](https://www.blender.org/download/releases/4-0/) | [6.2.1](https://github.com/DarklightGames/io_scene_psk_psa/releases/tag/6.2.1) | No |
| [3.4 - 3.6](https://www.blender.org/download/lts/3-6/) | [5.0.6](https://github.com/DarklightGames/io_scene_psk_psa/releases/tag/5.0.6) | June 2025 |
| [2.93 - 3.3](https://www.blender.org/download/releases/3-3/) | [4.3.0](https://github.com/DarklightGames/io_scene_psk_psa/releases/tag/4.3.0) | ~~September 2024~~ |
| Blender Version| Addon Version |
|-|-|
| [4.1](https://www.blender.org/download/releases/4-1/) | [7.0.0](https://github.com/DarklightGames/io_scene_psk_psa/releases/tag/7.0.0) |
| [4.0](https://www.blender.org/download/releases/4-0/) | [6.2.1](https://github.com/DarklightGames/io_scene_psk_psa/releases/tag/6.2.1) |
| [3.4 - 3.6](https://www.blender.org/download/lts/3-6/) | [5.0.6](https://github.com/DarklightGames/io_scene_psk_psa/releases/tag/5.0.6) |
| [2.93 - 3.3](https://www.blender.org/download/releases/3-3/) | [4.3.0](https://github.com/DarklightGames/io_scene_psk_psa/releases/tag/4.3.0) |
# Testing
To execute the automated tests, run:

View File

@@ -1,6 +1,41 @@
from bpy.app.handlers import persistent
if 'bpy' in locals():
from .shared import data as shared_data, types as shared_types, helpers as shared_helpers
from .shared import dfs as shared_dfs, ui as shared_ui
from .psk import (
builder as psk_builder,
data as psk_data,
importer as psk_importer,
properties as psk_properties,
writer as psk_writer,
)
from .psk import reader as psk_reader, ui as psk_ui
from .psk.export import (
operators as psk_export_operators,
properties as psk_export_properties,
ui as psk_export_ui,
)
from .psk.import_ import operators as psk_import_operators
from .psa import (
config as psa_config,
data as psa_data,
writer as psa_writer,
reader as psa_reader,
builder as psa_builder,
importer as psa_importer,
)
from .psa.export import (
properties as psa_export_properties,
ui as psa_export_ui,
operators as psa_export_operators,
)
from .psa.import_ import operators as psa_import_operators
from .psa.import_ import ui as psa_import_ui, properties as psa_import_properties
_needs_reload = 'bpy' in locals()
if _needs_reload:
import importlib
importlib.reload(shared_data)
@@ -33,57 +68,10 @@ if 'bpy' in locals():
importlib.reload(psa_import_properties)
importlib.reload(psa_import_operators)
importlib.reload(psa_import_ui)
else:
from .shared import data as shared_data, types as shared_types, helpers as shared_helpers
from .shared import dfs as shared_dfs, ui as shared_ui
from .psk import (
builder as psk_builder,
data as psk_data,
importer as psk_importer,
properties as psk_properties,
writer as psk_writer,
)
from .psk import reader as psk_reader, ui as psk_ui
from .psk.export import (
operators as psk_export_operators,
properties as psk_export_properties,
ui as psk_export_ui,
)
from .psk.import_ import operators as psk_import_operators
from .psa import (
config as psa_config,
data as psa_data,
writer as psa_writer,
reader as psa_reader,
builder as psa_builder,
importer as psa_importer,
)
from .psa.export import (
properties as psa_export_properties,
ui as psa_export_ui,
operators as psa_export_operators,
)
from .psa.import_ import operators as psa_import_operators
from .psa.import_ import ui as psa_import_ui, properties as psa_import_properties
import bpy
from bpy.props import PointerProperty
classes = shared_types.classes + \
psk_properties.classes + \
psk_ui.classes + \
psk_import_operators.classes + \
psk_export_properties.classes + \
psk_export_operators.classes + \
psk_export_ui.classes + \
psa_export_properties.classes + \
psa_export_operators.classes + \
psa_export_ui.classes + \
psa_import_properties.classes + \
psa_import_operators.classes + \
psa_import_ui.classes
def psk_export_menu_func(self, context):
self.layout.operator(psk_export_operators.PSK_OT_export.bl_idname, text='Unreal PSK (.psk)')
@@ -101,22 +89,41 @@ def psa_import_menu_func(self, context):
self.layout.operator(psa_import_operators.PSA_OT_import.bl_idname, text='Unreal PSA (.psa)')
_modules = (
shared_types,
shared_ui,
psk_properties,
psk_ui,
psk_import_operators,
psk_export_properties,
psk_export_operators,
psk_export_ui,
psa_export_properties,
psa_export_operators,
psa_export_ui,
psa_import_properties,
psa_import_operators,
psa_import_ui
)
def register():
for cls in classes:
bpy.utils.register_class(cls)
for module in _modules:
module.register()
bpy.types.TOPBAR_MT_file_export.append(psk_export_menu_func)
bpy.types.TOPBAR_MT_file_import.append(psk_import_menu_func)
bpy.types.TOPBAR_MT_file_export.append(psa_export_menu_func)
bpy.types.TOPBAR_MT_file_import.append(psa_import_menu_func)
bpy.types.Material.psk = PointerProperty(type=psk_properties.PSX_PG_material)
bpy.types.Scene.psa_import = PointerProperty(type=psa_import_properties.PSA_PG_import)
bpy.types.Scene.psa_export = PointerProperty(type=psa_export_properties.PSA_PG_export)
bpy.types.Scene.psk_export = PointerProperty(type=psk_export_properties.PSK_PG_export)
bpy.types.Action.psa_export = PointerProperty(type=shared_types.PSX_PG_action_export)
bpy.types.Material.psk = PointerProperty(type=psk_properties.PSX_PG_material, options={'HIDDEN'})
bpy.types.Scene.psx_export = PointerProperty(type=shared_types.PSX_PG_scene_export, options={'HIDDEN'})
bpy.types.Scene.psa_import = PointerProperty(type=psa_import_properties.PSA_PG_import, options={'HIDDEN'})
bpy.types.Scene.psa_export = PointerProperty(type=psa_export_properties.PSA_PG_export, options={'HIDDEN'})
bpy.types.Scene.psk_export = PointerProperty(type=psk_export_properties.PSK_PG_export, options={'HIDDEN'})
bpy.types.Action.psa_export = PointerProperty(type=shared_types.PSX_PG_action_export, options={'HIDDEN'})
def unregister():
del bpy.types.Material.psk
del bpy.types.Scene.psx_export
del bpy.types.Scene.psa_import
del bpy.types.Scene.psa_export
del bpy.types.Scene.psk_export
@@ -125,8 +132,8 @@ def unregister():
bpy.types.TOPBAR_MT_file_import.remove(psk_import_menu_func)
bpy.types.TOPBAR_MT_file_export.remove(psa_export_menu_func)
bpy.types.TOPBAR_MT_file_import.remove(psa_import_menu_func)
for cls in reversed(classes):
bpy.utils.unregister_class(cls)
for module in reversed(_modules):
module.unregister()
if __name__ == '__main__':

View File

@@ -1,13 +1,13 @@
schema_version = "1.0.0"
id = "io_scene_psk_psa"
version = "8.1.2"
version = "8.2.2"
name = "Unreal PSK/PSA (.psk/.psa)"
tagline = "Import and export PSK and PSA files used in Unreal Engine"
maintainer = "Colin Basnett <cmbasnett@gmail.com>"
type = "add-on"
website = "https://github.com/DarklightGames/io_scene_psk_psa/"
tags = ["Game Engine", "Import-Export"]
blender_version_min = "4.2.0"
blender_version_min = "4.4.0"
# Optional: maximum supported Blender version
# blender_version_max = "5.1.0"
license = [

View File

@@ -1,10 +1,10 @@
from bpy.types import Action, AnimData, Context, Object, PoseBone
from .data import Psa
from typing import Dict, List, Optional, Tuple
from typing import Dict, List, Optional, Tuple, Iterable
from mathutils import Matrix, Quaternion, Vector
from ..shared.helpers import create_psx_bones, get_coordinate_system_transform
from ..shared.helpers import PsxBoneCollection, create_psx_bones, get_coordinate_system_transform
class PsaBuildSequence:
@@ -14,8 +14,8 @@ class PsaBuildSequence:
self.frame_start: int = 0
self.frame_end: int = 0
def __init__(self, armature_object: Object, anim_data: AnimData):
self.armature_object = armature_object
def __init__(self, armature_objects: Iterable[Object], anim_data: AnimData):
self.armature_objects = list(armature_objects)
self.anim_data = anim_data
self.name: str = ''
self.nla_state: PsaBuildSequence.NlaState = PsaBuildSequence.NlaState()
@@ -27,10 +27,9 @@ class PsaBuildSequence:
class PsaBuildOptions:
def __init__(self):
self.armature_objects: List[Object] = []
self.animation_data: Optional[AnimData] = None
self.sequences: List[PsaBuildSequence] = []
self.bone_filter_mode: str = 'ALL'
self.bone_collection_indices: List[Tuple[str, int]] = []
self.bone_collection_indices: List[PsxBoneCollection] = []
self.sequence_name_prefix: str = ''
self.sequence_name_suffix: str = ''
self.scale = 1.0
@@ -39,6 +38,11 @@ class PsaBuildOptions:
self.forward_axis = 'X'
self.up_axis = 'Z'
self.root_bone_name = 'ROOT'
self.sequence_source = 'ACTIONS' # One of ('ACTIONS', 'TIMELINE_MARKERS', 'NLA_STRIPS')
@property
def bone_collection_primary_key(self) -> str:
return 'DATA' if self.sequence_source == 'ACTIVE_ACTION' else 'OBJECT'
def _get_pose_bone_location_and_rotation(
@@ -53,7 +57,7 @@ def _get_pose_bone_location_and_rotation(
if is_false_root_bone:
pose_bone_matrix = coordinate_system_transform
elif pose_bone.parent is not None:
elif pose_bone is not None and pose_bone.parent is not None:
pose_bone_matrix = pose_bone.matrix
pose_bone_parent_matrix = pose_bone.parent.matrix
pose_bone_matrix = pose_bone_parent_matrix.inverted() @ pose_bone_matrix
@@ -98,10 +102,22 @@ def _get_pose_bone_location_and_rotation(
def build_psa(context: Context, options: PsaBuildOptions) -> Psa:
assert context.scene
assert context.window_manager
psa = Psa()
# TODO: move this OUT!
armature_objects_for_bones = options.armature_objects
if options.sequence_source == 'ACTIVE_ACTION' and len(options.armature_objects) >= 2:
# Make sure that the data-block for all the selected armature objects is the same.
if any(map(lambda o: o.data != options.armature_objects[0].data, options.armature_objects[1:])):
raise RuntimeError('All armature objects must share the same data-block when exporting from the active action')
armature_objects_for_bones = [options.armature_objects[0]]
psx_bone_create_result = create_psx_bones(
armature_objects=options.armature_objects,
armature_objects=armature_objects_for_bones,
export_space=options.export_space,
root_bone_name=options.root_bone_name,
forward_axis=options.forward_axis,
@@ -109,6 +125,7 @@ def build_psa(context: Context, options: PsaBuildOptions) -> Psa:
scale=options.scale,
bone_filter_mode=options.bone_filter_mode,
bone_collection_indices=options.bone_collection_indices,
bone_collection_primary_key=options.bone_collection_primary_key,
)
# Build list of PSA bones.
@@ -126,7 +143,7 @@ def build_psa(context: Context, options: PsaBuildOptions) -> Psa:
export_sequence.name = export_sequence.name.strip()
# Save each armature object's current action and frame so that we can restore the state once we are done.
saved_armature_object_actions = {o: o.animation_data.action for o in options.armature_objects}
saved_armature_object_actions = {o: o.animation_data.action if o.animation_data else None for o in options.armature_objects}
saved_frame_current = context.scene.frame_current
# Now build the PSA sequences.
@@ -145,11 +162,7 @@ def build_psa(context: Context, options: PsaBuildOptions) -> Psa:
frame_extents = abs(frame_end - frame_start)
frame_count_raw = frame_extents + 1
frame_count = max(1, max(export_sequence.key_quota, int(frame_count_raw * export_sequence.compression_ratio)))
try:
frame_step = frame_extents / (frame_count - 1)
except ZeroDivisionError:
frame_step = 0.0
frame_step = frame_extents / (frame_count - 1) if frame_count > 1 else 0.0
# If this is a reverse sequence, we need to reverse the frame step.
if frame_start > frame_end:
@@ -172,10 +185,9 @@ def build_psa(context: Context, options: PsaBuildOptions) -> Psa:
frame = float(frame_start)
# Link the action to the animation data and update view layer.
for armature_object in options.armature_objects:
armature_object.animation_data.action = export_sequence.nla_state.action
export_sequence.anim_data.action = export_sequence.nla_state.action
assert context.view_layer
context.view_layer.update()
def add_key(location: Vector, rotation: Quaternion):
@@ -199,7 +211,7 @@ def build_psa(context: Context, options: PsaBuildOptions) -> Psa:
armature_scales: Dict[Object, Vector] = {}
# Extract the scale from the world matrix of the evaluated armature object.
for armature_object in options.armature_objects:
for armature_object in export_sequence.armature_objects:
evaluated_armature_object = armature_object.evaluated_get(context.evaluated_depsgraph_get())
_, _, scale = evaluated_armature_object.matrix_world.decompose()
scale *= options.scale
@@ -210,18 +222,17 @@ def build_psa(context: Context, options: PsaBuildOptions) -> Psa:
# locations.
export_bones: List[PsaExportBone] = []
# TODO: we need different behavior here if it's ACTIVE_ACTION
for psx_bone, armature_object in psx_bone_create_result.bones:
if armature_object is None:
export_bones.append(PsaExportBone(None, None, Vector((1.0, 1.0, 1.0))))
continue
assert armature_object.pose
pose_bone = armature_object.pose.bones[psx_bone.name.decode('windows-1252')]
export_bones.append(PsaExportBone(pose_bone, armature_object, armature_scales[armature_object]))
for export_bone in export_bones:
print(export_bone.pose_bone, export_bone.armature_object, export_bone.scale)
match options.sampling_mode:
case 'INTERPOLATED':
# Used as a store for the last frame's pose bone locations and rotations.
@@ -315,6 +326,7 @@ def build_psa(context: Context, options: PsaBuildOptions) -> Psa:
# Restore the previous actions & frame.
for armature_object, action in saved_armature_object_actions.items():
assert armature_object.animation_data
armature_object.animation_data.action = action
context.scene.frame_set(saved_frame_current)

View File

@@ -56,6 +56,8 @@ def read_psa_config(psa_sequence_names: List[str], file_path: str) -> PsaConfig:
if config.has_section('RemoveTracks'):
for key, value in config.items('RemoveTracks'):
match = re.match(f'^(.+)\.(\d+)$', key)
if not match:
continue
sequence_name = match.group(1)
# Map the sequence name onto the actual sequence name in the PSA file.

View File

@@ -1,9 +1,10 @@
from collections import Counter
from typing import List, Iterable, Dict, Tuple, Optional
from typing import List, Iterable, Dict, Tuple, cast as typing_cast
import bpy
import re
from bpy.props import StringProperty
from bpy.types import Context, Action, Object, AnimData, TimelineMarker, Operator
from bpy.types import Context, Action, Object, AnimData, TimelineMarker, Operator, Armature
from bpy_extras.io_utils import ExportHelper
from .properties import (
@@ -12,14 +13,14 @@ from .properties import (
filter_sequences,
get_sequences_from_name_and_frame_range,
)
from .ui import PSA_UL_export_sequences
from ..builder import build_psa, PsaBuildSequence, PsaBuildOptions
from ..writer import write_psa
from ...shared.helpers import populate_bone_collection_list, get_nla_strips_in_frame_range
from ...shared.semver import SemanticVersion
from ...shared.helpers import populate_bone_collection_list, get_nla_strips_in_frame_range, PsxBoneCollection
from ...shared.ui import draw_bone_filter_mode
def get_sequences_propnames_from_source(sequence_source: str) -> Optional[Tuple[str, str]]:
def get_sequences_propnames_from_source(sequence_source: str) -> Tuple[str, str]:
match sequence_source:
case 'ACTIONS':
return 'action_list', 'action_list_index'
@@ -34,35 +35,28 @@ def get_sequences_propnames_from_source(sequence_source: str) -> Optional[Tuple[
def is_action_for_object(obj: Object, action: Action):
if action is None or len(action.fcurves) == 0:
if len(action.fcurves) == 0:
return False
if obj is None or obj.animation_data is None or obj.type != 'ARMATURE':
return False
version = SemanticVersion(bpy.app.version)
armature_data = typing_cast(Armature, obj.data)
bone_names = set([x.name for x in armature_data.bones])
def is_action_for_object_legacy(action: Action, obj: Object):
"""
This is the legacy behavior before slotted actions were introduced in Blender 4.4.
It would simply check if it had any f-curves that corresponded to any bones in the armature.
"""
import re
armature_data = obj.data
bone_names = set([x.name for x in armature_data.bones])
for fcurve in action.fcurves:
match = re.match(r'pose\.bones\[\"([^\"]+)\"](\[\"([^\"]+)\"])?', fcurve.data_path)
if not match:
continue
bone_name = match.group(1)
if bone_name in bone_names:
return True
# The nesting here is absolutely bonkers.
for layer in action.layers:
for strip in layer.strips:
for channelbag in strip.channelbags:
for fcurve in channelbag.fcurves:
match = re.match(r'pose\.bones\[\"([^\"]+)\"](\[\"([^\"]+)\"])?', fcurve.data_path)
if not match:
continue
bone_name = match.group(1)
if bone_name in bone_names:
return True
if version < SemanticVersion((4, 4, 0)):
return is_action_for_object_legacy(action, obj)
# If the object is a part of the slot's user list, then it is a valid action for the object.
return any(obj in slot.users() for slot in action.slots)
return False
def update_actions_and_timeline_markers(context: Context, armature_objects: Iterable[Object]):
@@ -178,7 +172,7 @@ def get_animation_data_object(context: Context) -> Object:
active_object = context.view_layer.objects.active
if active_object.type != 'ARMATURE':
if active_object is None or active_object.type != 'ARMATURE':
raise RuntimeError('Active object must be an Armature')
if pg.sequence_source != 'ACTIONS' and pg.should_override_animation_data:
@@ -335,8 +329,6 @@ class PSA_OT_export(Operator, ExportHelper):
row.operator(PSA_OT_export_actions_select_all.bl_idname, text='All', icon='CHECKBOX_HLT')
row.operator(PSA_OT_export_actions_deselect_all.bl_idname, text='None', icon='CHECKBOX_DEHLT')
from .ui import PSA_UL_export_sequences
propname, active_propname = get_sequences_propnames_from_source(pg.sequence_source)
sequences_panel.template_list(PSA_UL_export_sequences.bl_idname, '', pg, propname, pg, active_propname,
rows=max(3, min(len(getattr(pg, propname)), 10)))
@@ -400,7 +392,7 @@ class PSA_OT_export(Operator, ExportHelper):
rows=rows
)
bones_advanced_header, bones_advanced_panel = layout.panel('Advanced', default_closed=False)
bones_advanced_header, bones_advanced_panel = layout.panel('Bones Advanced', default_closed=True)
bones_advanced_header.label(text='Advanced')
if bones_advanced_panel:
flow = bones_advanced_panel.grid_flow()
@@ -450,7 +442,11 @@ class PSA_OT_export(Operator, ExportHelper):
armature_object.animation_data_create()
update_actions_and_timeline_markers(context, self.armature_objects)
populate_bone_collection_list(self.armature_objects, pg.bone_collection_list)
populate_bone_collection_list(
pg.bone_collection_list,
self.armature_objects,
primary_key='DATA' if pg.sequence_source == 'ACTIVE_ACTION' else 'OBJECT',
)
context.window_manager.fileselect_add(self)
@@ -459,16 +455,6 @@ class PSA_OT_export(Operator, ExportHelper):
def execute(self, context):
pg = getattr(context.scene, 'psa_export')
# Ensure that we actually have items that we are going to be exporting.
if pg.sequence_source == 'ACTIONS' and len(pg.action_list) == 0:
raise RuntimeError('No actions were selected for export')
if pg.sequence_source == 'TIMELINE_MARKERS' and len(pg.marker_list) == 0:
raise RuntimeError('No timeline markers were selected for export')
if pg.sequence_source == 'NLA_TRACK_STRIPS' and len(pg.nla_strip_list) == 0:
raise RuntimeError('No NLA track strips were selected for export')
# Populate the export sequence list.
animation_data_object = get_animation_data_object(context)
animation_data = animation_data_object.animation_data
@@ -476,6 +462,9 @@ class PSA_OT_export(Operator, ExportHelper):
if animation_data is None:
raise RuntimeError(f'No animation data for object \'{animation_data_object.name}\'')
if context.active_object is None:
raise RuntimeError('No active object')
export_sequences: List[PsaBuildSequence] = []
match pg.sequence_source:
@@ -483,7 +472,7 @@ class PSA_OT_export(Operator, ExportHelper):
for action_item in filter(lambda x: x.is_selected, pg.action_list):
if len(action_item.action.fcurves) == 0:
continue
export_sequence = PsaBuildSequence(context.active_object, animation_data)
export_sequence = PsaBuildSequence(self.armature_objects, animation_data)
export_sequence.name = action_item.name
export_sequence.nla_state.action = action_item.action
export_sequence.nla_state.frame_start = action_item.frame_start
@@ -494,7 +483,7 @@ class PSA_OT_export(Operator, ExportHelper):
export_sequences.append(export_sequence)
case 'TIMELINE_MARKERS':
for marker_item in filter(lambda x: x.is_selected, pg.marker_list):
export_sequence = PsaBuildSequence(context.active_object, animation_data)
export_sequence = PsaBuildSequence(self.armature_objects, animation_data)
export_sequence.name = marker_item.name
export_sequence.nla_state.frame_start = marker_item.frame_start
export_sequence.nla_state.frame_end = marker_item.frame_end
@@ -505,7 +494,7 @@ class PSA_OT_export(Operator, ExportHelper):
export_sequences.append(export_sequence)
case 'NLA_TRACK_STRIPS':
for nla_strip_item in filter(lambda x: x.is_selected, pg.nla_strip_list):
export_sequence = PsaBuildSequence(context.active_object, animation_data)
export_sequence = PsaBuildSequence(self.armature_objects, animation_data)
export_sequence.name = nla_strip_item.name
export_sequence.nla_state.frame_start = nla_strip_item.frame_start
export_sequence.nla_state.frame_end = nla_strip_item.frame_end
@@ -515,7 +504,7 @@ class PSA_OT_export(Operator, ExportHelper):
export_sequences.append(export_sequence)
case 'ACTIVE_ACTION':
for active_action_item in filter(lambda x: x.is_selected, pg.active_action_list):
export_sequence = PsaBuildSequence(active_action_item.armature_object, active_action_item.armature_object.animation_data)
export_sequence = PsaBuildSequence([active_action_item.armature_object], active_action_item.armature_object.animation_data)
action = active_action_item.action
export_sequence.name = action.name
export_sequence.nla_state.action = action
@@ -533,19 +522,18 @@ class PSA_OT_export(Operator, ExportHelper):
return {'CANCELLED'}
options = PsaBuildOptions()
options.armature_objects = self.armature_objects
options.animation_data = animation_data
options.sequences = export_sequences
options.bone_filter_mode = pg.bone_filter_mode
options.bone_collection_indices = [(x.armature_object_name, x.index) for x in pg.bone_collection_list if x.is_selected]
options.bone_collection_indices = [PsxBoneCollection(x.armature_object_name, x.armature_data_name, x.index) for x in pg.bone_collection_list if x.is_selected]
options.sequence_name_prefix = pg.sequence_name_prefix
options.sequence_name_suffix = pg.sequence_name_suffix
options.scale = pg.scale
options.sampling_mode = pg.sampling_mode
options.export_space = pg.export_space
options.scale = pg.scale
options.forward_axis = pg.forward_axis
options.up_axis = pg.up_axis
options.root_bone_name = pg.root_bone_name
options.sequence_source = pg.sequence_source
try:
psa = build_psa(context, options)
@@ -671,10 +659,14 @@ class PSA_OT_export_bone_collections_deselect_all(Operator):
return {'FINISHED'}
classes = (
_classes = (
PSA_OT_export,
PSA_OT_export_actions_select_all,
PSA_OT_export_actions_deselect_all,
PSA_OT_export_bone_collections_select_all,
PSA_OT_export_bone_collections_deselect_all,
)
from bpy.utils import register_classes_factory
register, unregister = register_classes_factory(_classes)

View File

@@ -12,7 +12,10 @@ from bpy.props import (
StringProperty,
)
from bpy.types import PropertyGroup, Object, Action, AnimData, Context
from ...shared.types import ForwardUpAxisMixin, ExportSpaceMixin, PsxBoneExportMixin
from ...shared.dfs import dfs_view_layer_objects
from ...shared.helpers import populate_bone_collection_list
from ...shared.types import TransformMixin, ExportSpaceMixin, PsxBoneExportMixin
def psa_export_property_group_animation_data_override_poll(_context, obj):
@@ -103,7 +106,44 @@ def animation_data_override_update_cb(self: 'PSA_PG_export', context: Context):
self.nla_track = ''
class PSA_PG_export(PropertyGroup, ForwardUpAxisMixin, ExportSpaceMixin, PsxBoneExportMixin):
sequence_source_items = (
('ACTIONS', 'Actions', 'Sequences will be exported using actions', 'ACTION', 0),
('TIMELINE_MARKERS', 'Timeline Markers', 'Sequences are delineated by scene timeline markers', 'MARKER_HLT', 1),
('NLA_TRACK_STRIPS', 'NLA Track Strips', 'Sequences are delineated by the start & end times of strips on the selected NLA track', 'NLA', 2),
('ACTIVE_ACTION', 'Active Action', 'The active action will be exported for each selected armature', 'ACTION', 3),
)
fps_source_items = (
('SCENE', 'Scene', '', 'SCENE_DATA', 0),
('ACTION_METADATA', 'Action Metadata', 'The frame rate will be determined by action\'s FPS property found in the PSA Export panel.\n\nIf the Sequence Source is Timeline Markers, the lowest value of all contributing actions will be used', 'ACTION', 1),
('CUSTOM', 'Custom', '', 2)
)
compression_ratio_source_items = (
('ACTION_METADATA', 'Action Metadata', 'The compression ratio will be determined by action\'s Compression Ratio property found in the PSA Export panel.\n\nIf the Sequence Source is Timeline Markers, the lowest value of all contributing actions will be used', 'ACTION', 1),
('CUSTOM', 'Custom', '', 2)
)
sampling_mode_items = (
('INTERPOLATED', 'Interpolated', 'Sampling is performed by interpolating the evaluated bone poses from the adjacent whole frames.', 'INTERPOLATED', 0),
('SUBFRAME', 'Subframe', 'Sampling is performed by evaluating the bone poses at the subframe time.\n\nNot recommended unless you are also animating with subframes enabled.', 'SUBFRAME', 1),
)
def sequence_source_update_cb(self: 'PSA_PG_export', context: Context) -> None:
armature_objects = []
assert context.view_layer
for dfs_object in dfs_view_layer_objects(context.view_layer):
if dfs_object.obj.type == 'ARMATURE' and dfs_object.is_selected:
armature_objects.append(dfs_object.obj)
populate_bone_collection_list(
self.bone_collection_list,
armature_objects,
primary_key='DATA' if self.sequence_source == 'ACTIVE_ACTION' else 'OBJECT')
class PSA_PG_export(PropertyGroup, TransformMixin, ExportSpaceMixin, PsxBoneExportMixin):
should_override_animation_data: BoolProperty(
name='Override Animation Data',
options=set(),
@@ -120,12 +160,8 @@ class PSA_PG_export(PropertyGroup, ForwardUpAxisMixin, ExportSpaceMixin, PsxBone
name='Source',
options=set(),
description='',
items=(
('ACTIONS', 'Actions', 'Sequences will be exported using actions', 'ACTION', 0),
('TIMELINE_MARKERS', 'Timeline Markers', 'Sequences are delineated by scene timeline markers', 'MARKER_HLT', 1),
('NLA_TRACK_STRIPS', 'NLA Track Strips', 'Sequences are delineated by the start & end times of strips on the selected NLA track', 'NLA', 2),
('ACTIVE_ACTION', 'Active Action', 'The active action will be exported for each selected armature', 'ACTION', 3),
)
items=sequence_source_items,
update=sequence_source_update_cb,
)
nla_track: StringProperty(
name='NLA Track',
@@ -139,22 +175,14 @@ class PSA_PG_export(PropertyGroup, ForwardUpAxisMixin, ExportSpaceMixin, PsxBone
name='FPS Source',
options=set(),
description='',
items=(
('SCENE', 'Scene', '', 'SCENE_DATA', 0),
('ACTION_METADATA', 'Action Metadata', 'The frame rate will be determined by action\'s FPS property found in the PSA Export panel.\n\nIf the Sequence Source is Timeline Markers, the lowest value of all contributing actions will be used', 'ACTION', 1),
('CUSTOM', 'Custom', '', 2)
)
items=fps_source_items,
)
fps_custom: FloatProperty(default=30.0, min=sys.float_info.epsilon, soft_min=1.0, options=set(), step=100,
soft_max=60.0)
fps_custom: FloatProperty(default=30.0, min=sys.float_info.epsilon, soft_min=1.0, options=set(), step=100, soft_max=60.0)
compression_ratio_source: EnumProperty(
name='Compression Ratio Source',
options=set(),
description='',
items=(
('ACTION_METADATA', 'Action Metadata', 'The compression ratio will be determined by action\'s Compression Ratio property found in the PSA Export panel.\n\nIf the Sequence Source is Timeline Markers, the lowest value of all contributing actions will be used', 'ACTION', 1),
('CUSTOM', 'Custom', '', 2)
)
items=compression_ratio_source_items,
)
compression_ratio_custom: FloatProperty(default=1.0, min=0.0, max=1.0, subtype='FACTOR', description='The key sampling ratio of the exported sequence.\n\nA compression ratio of 1.0 will export all frames, while a compression ratio of 0.5 will export half of the frames')
action_list: CollectionProperty(type=PSA_PG_export_action_list_item)
@@ -193,21 +221,11 @@ class PSA_PG_export(PropertyGroup, ForwardUpAxisMixin, ExportSpaceMixin, PsxBone
name='Show Reversed',
description='Show reversed sequences'
)
scale: FloatProperty(
name='Scale',
default=1.0,
description='Scale factor to apply to the bone translations. Use this if you are exporting animations for a scaled PSK mesh',
min=0.0,
soft_max=100.0
)
sampling_mode: EnumProperty(
name='Sampling Mode',
options=set(),
description='The method by which frames are sampled',
items=(
('INTERPOLATED', 'Interpolated', 'Sampling is performed by interpolating the evaluated bone poses from the adjacent whole frames.', 'INTERPOLATED', 0),
('SUBFRAME', 'Subframe', 'Sampling is performed by evaluating the bone poses at the subframe time.\n\nNot recommended unless you are also animating with subframes enabled.', 'SUBFRAME', 1),
),
items=sampling_mode_items,
default='INTERPOLATED'
)
@@ -245,10 +263,14 @@ def filter_sequences(pg: PSA_PG_export, sequences) -> List[int]:
return flt_flags
classes = (
_classes = (
PSA_PG_export_action_list_item,
PSA_PG_export_timeline_markers,
PSA_PG_export_nla_strip_list_item,
PSA_PG_export_active_action_list_item,
PSA_PG_export,
)
from bpy.utils import register_classes_factory
register, unregister = register_classes_factory(_classes)

View File

@@ -13,7 +13,7 @@ class PSA_UL_export_sequences(UIList):
# Show the filtering options by default.
self.use_filter_show = True
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):
def draw_item(self, context, layout, data, item, icon, active_data, active_property, index, flt_flag):
item = typing_cast(PSA_PG_export_action_list_item, item)
is_pose_marker = hasattr(item, 'is_pose_marker') and item.is_pose_marker
@@ -44,7 +44,7 @@ class PSA_UL_export_sequences(UIList):
subrow.prop(pg, 'sequence_filter_pose_marker', icon_only=True, icon='PMARKER')
subrow.prop(pg, 'sequence_filter_reversed', text='', icon='FRAME_PREV')
def filter_items(self, context, data, prop):
def filter_items(self, context, data, property):
pg = getattr(context.scene, 'psa_export')
actions = getattr(data, prop)
flt_flags = filter_sequences(pg, actions)
@@ -52,6 +52,10 @@ class PSA_UL_export_sequences(UIList):
return flt_flags, flt_neworder
classes = (
_classes = (
PSA_UL_export_sequences,
)
from bpy.utils import register_classes_factory
register, unregister = register_classes_factory(_classes)

View File

@@ -8,11 +8,12 @@ from bpy_extras.io_utils import ImportHelper
from .properties import PsaImportMixin, get_visible_sequences
from ..config import read_psa_config
from ..importer import PsaImportOptions, import_psa
from ..importer import BoneMapping, PsaImportOptions, import_psa
from ..reader import PsaReader
def psa_import_poll(cls, context: Context):
assert context.view_layer and context.view_layer.objects.active
active_object = context.view_layer.objects.active
if active_object is None or active_object.type != 'ARMATURE':
cls.poll_message_set('The active object must be an armature')
@@ -32,10 +33,12 @@ class PSA_OT_import_sequences_select_from_text(Operator):
return len(pg.sequence_list) > 0
def invoke(self, context, event):
assert context.window_manager
return context.window_manager.invoke_props_dialog(self, width=256)
def draw(self, context):
layout = self.layout
assert layout
pg = getattr(context.scene, 'psa_import')
layout.label(icon='INFO', text='Each sequence name should be on a new line.')
layout.prop(pg, 'select_text', text='')
@@ -134,6 +137,8 @@ class PSA_OT_import_drag_and_drop(Operator, PsaImportMixin):
warnings = []
sequences_count = 0
assert context.view_layer and context.view_layer.objects.active
for file in self.files:
psa_path = str(os.path.join(self.directory, file.name))
psa_reader = PsaReader(psa_path)
@@ -157,12 +162,14 @@ class PSA_OT_import_drag_and_drop(Operator, PsaImportMixin):
def invoke(self, context: Context, event):
# Make sure the selected object is an obj.
assert context.view_layer and context.view_layer.objects.active
active_object = context.view_layer.objects.active
if active_object is None or active_object.type != 'ARMATURE':
self.report({'ERROR_INVALID_CONTEXT'}, 'The active object must be an armature')
return {'CANCELLED'}
# Show the import operator properties in a pop-up dialog (do not use the file selector).
assert context.window_manager
context.window_manager.invoke_props_dialog(self)
return {'RUNNING_MODAL'}
@@ -181,7 +188,10 @@ def psa_import_options_from_property_group(pg: PsaImportMixin, sequence_names: I
options.should_write_metadata = pg.should_write_metadata
options.should_write_keyframes = pg.should_write_keyframes
options.should_convert_to_samples = pg.should_convert_to_samples
options.bone_mapping_mode = pg.bone_mapping_mode
options.bone_mapping = BoneMapping(
is_case_sensitive=pg.bone_mapping_is_case_sensitive,
should_ignore_trailing_whitespace=pg.bone_mapping_should_ignore_trailing_whitespace
)
options.fps_source = pg.fps_source
options.fps_custom = pg.fps_custom
options.translation_scale = pg.translation_scale
@@ -236,7 +246,10 @@ class PSA_OT_import_all(Operator, PsaImportMixin):
options = PsaImportOptions(
action_name_prefix=self.action_name_prefix,
bone_mapping_mode=self.bone_mapping_mode,
bone_mapping=BoneMapping(
is_case_sensitive=self.bone_mapping_is_case_sensitive,
should_ignore_trailing_whitespace=self.bone_mapping_should_ignore_trailing_whitespace
),
fps_custom=self.fps_custom,
fps_source=self.fps_source,
sequence_names=sequence_names,
@@ -250,6 +263,8 @@ class PSA_OT_import_all(Operator, PsaImportMixin):
translation_scale=self.translation_scale
)
assert context.view_layer
assert context.view_layer.objects.active
result = _import_psa(context, options, self.filepath, context.view_layer.objects.active)
if len(result.warnings) > 0:
@@ -308,12 +323,13 @@ class PSA_OT_import(Operator, ImportHelper, PsaImportMixin):
def invoke(self, context: Context, event: Event):
# Attempt to load the PSA file for the pre-selected file.
load_psa_file(context, self.filepath)
assert context.window_manager
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
def draw(self, context: Context):
layout = self.layout
assert layout
pg = getattr(context.scene, 'psa_import')
sequences_header, sequences_panel = layout.panel('sequences_panel_id', default_closed=False)
@@ -370,10 +386,14 @@ class PSA_OT_import(Operator, ImportHelper, PsaImportMixin):
advanced_header.label(text='Advanced')
if advanced_panel:
col = advanced_panel.column()
col.use_property_split = True
col.use_property_decorate = False
col.prop(self, 'bone_mapping_mode')
bone_mapping_header, bone_mapping_panel = layout.panel('bone_mapping_id', default_closed=False)
bone_mapping_header.label(text='Bone Mapping')
if bone_mapping_panel:
col = bone_mapping_panel.column()
col.use_property_split = True
col.use_property_decorate = False
col.prop(self, 'bone_mapping_is_case_sensitive')
col.prop(self, 'bone_mapping_should_ignore_trailing_whitespace')
col = advanced_panel.column()
col.use_property_split = True
@@ -412,10 +432,15 @@ def draw_psa_import_options_no_panels(layout, pg: PsaImportMixin):
col.use_property_decorate = False
col.prop(pg, 'should_convert_to_samples')
col = layout.column(heading='Bone Mapping')
col.use_property_split = True
col.use_property_decorate = False
col.prop(pg, 'bone_mapping_is_case_sensitive')
col.prop(pg, 'bone_mapping_should_ignore_trailing_whitespace')
col = layout.column()
col.use_property_split = True
col.use_property_decorate = False
col.prop(pg, 'bone_mapping_mode')
col.prop(pg, 'translation_scale')
col = layout.column(heading='Options')
@@ -434,11 +459,11 @@ class PSA_FH_import(FileHandler): # TODO: rename and add handling for PSA expor
bl_file_extensions = '.psa'
@classmethod
def poll_drop(cls, context: Context):
return context.area and context.area.type == 'VIEW_3D'
def poll_drop(cls, context: Context) -> bool:
return context.area is not None and context.area.type == 'VIEW_3D'
classes = (
_classes = (
PSA_OT_import_sequences_select_all,
PSA_OT_import_sequences_deselect_all,
PSA_OT_import_sequences_select_from_text,
@@ -447,3 +472,6 @@ classes = (
PSA_OT_import_drag_and_drop,
PSA_FH_import,
)
from bpy.utils import register_classes_factory
register, unregister = register_classes_factory(_classes)

View File

@@ -80,12 +80,13 @@ class PsaImportMixin:
description='Convert keyframes to read-only samples. '
'Recommended if you do not plan on editing the actions directly'
)
bone_mapping_mode: EnumProperty(
name='Bone Mapping',
options=set(),
description='The method by which bones from the incoming PSA file are mapped to the armature',
items=bone_mapping_items,
default='CASE_INSENSITIVE'
bone_mapping_is_case_sensitive: BoolProperty(
default=False,
name='Case Sensitive'
)
bone_mapping_should_ignore_trailing_whitespace: BoolProperty(
default=True,
name='Ignore Trailing Whitespace'
)
fps_source: EnumProperty(name='FPS Source', items=fps_source_items)
fps_custom: FloatProperty(
@@ -175,9 +176,12 @@ def get_visible_sequences(pg: PSA_PG_import, sequences) -> List[PSA_PG_import_ac
return visible_sequences
classes = (
_classes = (
PSA_PG_import_action_list_item,
PSA_PG_bone,
PSA_PG_data,
PSA_PG_import,
)
from bpy.utils import register_classes_factory
register, unregister = register_classes_factory(_classes)

View File

@@ -42,8 +42,11 @@ class PSA_UL_import_actions(PSA_UL_sequences_mixin):
pass
classes = (
_classes = (
PSA_UL_sequences,
PSA_UL_import_sequences,
PSA_UL_import_actions,
)
from bpy.utils import register_classes_factory
register, unregister = register_classes_factory(_classes)

View File

@@ -1,24 +1,35 @@
import typing
from typing import Iterable, List, Optional, cast as typing_cast
from typing import Sequence, Iterable, List, Optional, cast as typing_cast
import bpy
import numpy as np
from bpy.types import Armature, Context, FCurve, Object
import re
from bpy.types import Armature, Context, FCurve, Object, Bone, PoseBone
from mathutils import Vector, Quaternion
from .config import PsaConfig, REMOVE_TRACK_LOCATION, REMOVE_TRACK_ROTATION
from .reader import PsaReader
from ..shared.data import PsxBone
class BoneMapping:
def __init__(self,
is_case_sensitive: bool = False,
should_ignore_trailing_whitespace: bool = True
):
self.is_case_sensitive = is_case_sensitive
# Ancient PSK and PSA exporters would, for some reason, pad the bone names with spaces
# instead of just writing null bytes, probably because the programmers were lazy.
# By default, we will ignore trailing whitespace when doing comparisons.
self.should_ignore_trailing_whitespace = should_ignore_trailing_whitespace
class PsaImportOptions(object):
def __init__(self,
action_name_prefix: str = '',
bone_mapping_mode: str = 'CASE_INSENSITIVE',
bone_mapping: BoneMapping = BoneMapping(),
fps_custom: float = 30.0,
fps_source: str = 'SEQUENCE',
psa_config: PsaConfig = PsaConfig(),
sequence_names: List[str] = None,
sequence_names: Optional[List[str]] = None,
should_convert_to_samples: bool = False,
should_overwrite: bool = False,
should_stash: bool = False,
@@ -29,7 +40,7 @@ class PsaImportOptions(object):
translation_scale: float = 1.0
):
self.action_name_prefix = action_name_prefix
self.bone_mapping_mode = bone_mapping_mode
self.bone_mapping = bone_mapping
self.fps_custom = fps_custom
self.fps_source = fps_source
self.psa_config = psa_config
@@ -48,15 +59,15 @@ class ImportBone(object):
def __init__(self, psa_bone: PsxBone):
self.psa_bone: PsxBone = psa_bone
self.parent: Optional[ImportBone] = None
self.armature_bone = None
self.pose_bone = None
self.armature_bone: Optional[Bone] = None
self.pose_bone: Optional[PoseBone] = None
self.original_location: Vector = Vector()
self.original_rotation: Quaternion = Quaternion()
self.post_rotation: Quaternion = Quaternion()
self.fcurves: List[FCurve] = []
def _calculate_fcurve_data(import_bone: ImportBone, key_data: Iterable[float]):
def _calculate_fcurve_data(import_bone: ImportBone, key_data: Sequence[float]):
# Convert world-space transforms to local-space transforms.
key_rotation = Quaternion(key_data[0:4])
key_location = Vector(key_data[4:])
@@ -79,20 +90,30 @@ class PsaImportResult:
self.warnings: List[str] = []
def _get_armature_bone_index_for_psa_bone(psa_bone_name: str, armature_bone_names: List[str], bone_mapping_mode: str = 'EXACT') -> Optional[int]:
def _get_armature_bone_index_for_psa_bone(psa_bone_name: str, armature_bone_names: List[str], bone_mapping: BoneMapping) -> Optional[int]:
"""
@param psa_bone_name: The name of the PSA bone.
@param armature_bone_names: The names of the bones in the armature.
@param bone_mapping_mode: One of `['EXACT', 'CASE_INSENSITIVE']`.
@param bone_mapping: Bone mapping information.
@return: The index of the armature bone that corresponds to the given PSA bone, or None if no such bone exists.
"""
# Use regular expressions for bone name matching.
pattern = psa_bone_name
flags = 0
if bone_mapping.should_ignore_trailing_whitespace:
psa_bone_name = psa_bone_name.rstrip()
pattern += r'\s*'
if not bone_mapping.is_case_sensitive:
flags = re.IGNORECASE
pattern = re.compile(pattern, flags)
for armature_bone_index, armature_bone_name in enumerate(armature_bone_names):
if bone_mapping_mode == 'CASE_INSENSITIVE':
if armature_bone_name.lower() == psa_bone_name.lower():
return armature_bone_index
else:
if armature_bone_name == psa_bone_name:
return armature_bone_index
if re.fullmatch(pattern, armature_bone_name):
return armature_bone_index
return None
@@ -146,6 +167,9 @@ def _resample_sequence_data_matrix(sequence_data_matrix: np.ndarray, frame_step:
def import_psa(context: Context, psa_reader: PsaReader, armature_object: Object, options: PsaImportOptions) -> PsaImportResult:
assert context.window_manager
result = PsaImportResult()
sequences = [psa_reader.sequences[x] for x in options.sequence_names]
armature_data = typing_cast(Armature, armature_object.data)
@@ -159,7 +183,7 @@ def import_psa(context: Context, psa_reader: PsaReader, armature_object: Object,
for psa_bone_index, psa_bone in enumerate(psa_reader.bones):
psa_bone_name: str = psa_bone.name.decode('windows-1252')
armature_bone_index = _get_armature_bone_index_for_psa_bone(psa_bone_name, armature_bone_names, options.bone_mapping_mode)
armature_bone_index = _get_armature_bone_index_for_psa_bone(psa_bone_name, armature_bone_names, options.bone_mapping)
if armature_bone_index is not None:
# Ensure that no other PSA bone has been mapped to this armature bone yet.
if armature_bone_index not in armature_to_psa_bone_indices:
@@ -253,12 +277,14 @@ def import_psa(context: Context, psa_reader: PsaReader, armature_object: Object,
action = bpy.data.actions[action_name]
else:
action = bpy.data.actions.new(name=action_name)
action.slots.new('OBJECT', armature_object.name)
# Calculate the target FPS.
match options.fps_source:
case 'CUSTOM':
target_fps = options.fps_custom
case 'SCENE':
assert context.scene
target_fps = context.scene.render.fps
case 'SEQUENCE':
target_fps = sequence.fps
@@ -345,10 +371,11 @@ def import_psa(context: Context, psa_reader: PsaReader, armature_object: Object,
# If the user specifies, store the new animations as strips on a non-contributing NLA track.
if options.should_stash:
if armature_object.animation_data is None:
armature_object.animation_data_create()
animation_data = armature_object.animation_data
if animation_data is None:
animation_data = armature_object.animation_data_create()
for action in actions:
nla_track = armature_object.animation_data.nla_tracks.new()
nla_track = animation_data.nla_tracks.new()
nla_track.name = action.name
nla_track.mute = True
nla_track.strips.new(name=action.name, start=0, action=action)

View File

@@ -17,7 +17,7 @@ def _try_fix_cue4parse_issue_103(sequences) -> bool:
# Manually set the frame_start_index for each sequence. This assumes that the sequences are in order with
# no shared frames between sequences (all exporters that I know of do this, so it's a safe assumption).
frame_start_index = 0
for i, sequence in enumerate(sequences):
for sequence in sequences:
sequence.frame_start_index = frame_start_index
frame_start_index += sequence.frame_count
return True

View File

@@ -1,11 +1,11 @@
from ctypes import Structure, sizeof
from typing import Type
from typing import Optional, Type, Collection
from .data import Psa
from ..shared.data import PsxBone, Section
def write_section(fp, name: bytes, data_type: Type[Structure] = None, data: list = None):
def write_section(fp, name: bytes, data_type: Optional[Type[Structure]] = None, data: Optional[Collection] = None):
section = Section()
section.name = name
if data_type is not None and data is not None:

View File

@@ -1,16 +1,18 @@
import bmesh
import bpy
import numpy as np
from bpy.types import Armature, Collection, Context, Depsgraph, Object
from bpy.types import Armature, Collection, Context, Depsgraph, Object, ArmatureModifier, Mesh
from mathutils import Matrix
from typing import Dict, Generator, Iterable, List, Optional, Set, Tuple, cast as typing_cast
from typing import Dict, Iterable, List, Optional, Set, cast as typing_cast
from .data import Psk
from .properties import triangle_type_and_bit_flags_to_poly_flags
from ..shared.data import Vector3
from ..shared.dfs import DfsObject, dfs_collection_objects, dfs_view_layer_objects
from ..shared.helpers import (
PsxBoneCollection,
convert_string_to_cp1252_bytes,
create_psx_bones,
get_armatures_for_mesh_objects,
get_coordinate_system_transform,
)
@@ -24,7 +26,7 @@ class PskInputObjects(object):
class PskBuildOptions(object):
def __init__(self):
self.bone_filter_mode = 'ALL'
self.bone_collection_indices: List[Tuple[str, int]] = []
self.bone_collection_indices: List[PsxBoneCollection] = []
self.object_eval_state = 'EVALUATED'
self.material_order_mode = 'AUTOMATIC'
self.material_name_list: List[str] = []
@@ -42,7 +44,7 @@ def get_materials_for_mesh_objects(depsgraph: Depsgraph, mesh_objects: Iterable[
for i, material_slot in enumerate(evaluated_mesh_object.material_slots):
material = material_slot.material
if material is None:
raise RuntimeError('Material slot cannot be empty (index ' + str(i) + ')')
raise RuntimeError(f'Material slots cannot be empty. ({mesh_object.name}, index {i})')
if material not in yielded_materials:
yielded_materials.add(material)
yield material
@@ -53,40 +55,31 @@ def get_mesh_objects_for_collection(collection: Collection) -> Iterable[DfsObjec
def get_mesh_objects_for_context(context: Context) -> Iterable[DfsObject]:
if context.view_layer is None:
return
for dfs_object in dfs_view_layer_objects(context.view_layer):
if dfs_object.obj.type == 'MESH' and dfs_object.is_selected:
yield dfs_object
def get_armature_for_mesh_object(mesh_object: Object) -> Optional[Object]:
for modifier in mesh_object.modifiers:
if modifier.type == 'ARMATURE':
return modifier.object
if mesh_object.type != 'MESH':
return None
# Get the first armature modifier with a non-empty armature object.
for modifier in filter(lambda x: x.type == 'ARMATURE', mesh_object.modifiers):
armature_modifier = typing_cast(ArmatureModifier, modifier)
if armature_modifier.object is not None:
return armature_modifier.object
return None
def get_armatures_for_mesh_objects(mesh_objects: Iterable[Object]) -> Generator[Object, None, None]:
# Ensure that there are either no armature modifiers (static mesh) or that there is exactly one armature modifier
# object shared between all meshes.
armature_objects = set()
for mesh_object in mesh_objects:
modifiers = [x for x in mesh_object.modifiers if x.type == 'ARMATURE']
if len(modifiers) == 0:
continue
if modifiers[0].object in armature_objects:
continue
yield modifiers[0].object
def _get_psk_input_objects(mesh_dfs_objects: Iterable[DfsObject]) -> PskInputObjects:
mesh_dfs_objects = list(mesh_dfs_objects)
if len(mesh_dfs_objects) == 0:
raise RuntimeError('At least one mesh must be selected')
input_objects = PskInputObjects()
input_objects.mesh_dfs_objects = mesh_dfs_objects
input_objects.armature_objects |= set(get_armatures_for_mesh_objects(map(lambda x: x.obj, mesh_dfs_objects)))
return input_objects
@@ -95,17 +88,15 @@ def get_psk_input_objects_for_context(context: Context) -> PskInputObjects:
return _get_psk_input_objects(mesh_objects)
def get_psk_input_objects_for_collection(collection: Collection, should_exclude_hidden_meshes: bool = True) -> PskInputObjects:
def get_psk_input_objects_for_collection(collection: Collection) -> PskInputObjects:
mesh_objects = get_mesh_objects_for_collection(collection)
if should_exclude_hidden_meshes:
mesh_objects = filter(lambda x: x.is_visible, mesh_objects)
return _get_psk_input_objects(mesh_objects)
class PskBuildResult(object):
def __init__(self):
self.psk = None
self.warnings: List[str] = []
def __init__(self, psk: Psk, warnings: list[str]):
self.psk: Psk = psk
self.warnings: List[str] = warnings
def _get_mesh_export_space_matrix(armature_object: Optional[Object], export_space: str) -> Matrix:
@@ -146,9 +137,12 @@ def _get_material_name_indices(obj: Object, material_names: List[str]) -> Iterab
def build_psk(context: Context, input_objects: PskInputObjects, options: PskBuildOptions) -> PskBuildResult:
assert context.window_manager
armature_objects = list(input_objects.armature_objects)
result = PskBuildResult()
warnings: list[str] = []
psk = Psk()
psx_bone_create_result = create_psx_bones(
@@ -173,7 +167,7 @@ def build_psk(context: Context, input_objects: PskInputObjects, options: PskBuil
# The material name list may contain materials that are not on the mesh objects.
# Therefore, we can take the material_name_list as gospel and simply use it as a lookup table.
# If a look-up fails, replace it with an empty material.
materials = [bpy.data.materials.get(x.material_name, None) for x in options.material_name_list]
materials = [bpy.data.materials.get(x, None) for x in options.material_name_list]
case _:
assert False, f'Invalid material order mode: {options.material_order_mode}'
@@ -181,8 +175,9 @@ def build_psk(context: Context, input_objects: PskInputObjects, options: PskBuil
psk_material = Psk.Material()
psk_material.name = convert_string_to_cp1252_bytes(material.name if material else 'None')
psk_material.texture_index = len(psk.materials)
psk_material.poly_flags = triangle_type_and_bit_flags_to_poly_flags(material.psk.mesh_triangle_type,
material.psk.mesh_triangle_bit_flags)
if material is not None:
psk_material.poly_flags = triangle_type_and_bit_flags_to_poly_flags(material.psk.mesh_triangle_type,
material.psk.mesh_triangle_bit_flags)
psk.materials.append(psk_material)
# TODO: This wasn't left in a good state. We should detect if we need to add a "default" material.
@@ -203,6 +198,9 @@ def build_psk(context: Context, input_objects: PskInputObjects, options: PskBuil
# Calculate the export spaces for the armature objects.
# This is used later to transform the mesh object geometry into the export space.
armature_mesh_export_space_matrices: Dict[Optional[Object], Matrix] = {None: Matrix.Identity(4)}
if options.export_space == 'ARMATURE':
# For meshes without an armature modifier, we need to set the export space to the armature object.
armature_mesh_export_space_matrices[None] = _get_mesh_export_space_matrix(next(iter(input_objects.armature_objects), None), options.export_space)
for armature_object in armature_objects:
armature_mesh_export_space_matrices[armature_object] = _get_mesh_export_space_matrix(armature_object, options.export_space)
@@ -213,15 +211,14 @@ def build_psk(context: Context, input_objects: PskInputObjects, options: PskBuil
# Temporarily force the armature into the rest position.
# We will undo this later.
for armature_object in armature_objects:
armature_object.data.pose_position = 'REST'
armature_data = typing_cast(Armature, armature_object.data)
armature_data.pose_position = 'REST'
material_names = [m.name for m in materials]
material_names = [m.name if m is not None else 'None' for m in materials]
for object_index, input_mesh_object in enumerate(input_objects.mesh_dfs_objects):
obj, matrix_world = input_mesh_object.obj, input_mesh_object.matrix_world
armature_object = get_armature_for_mesh_object(obj)
should_flip_normals = False
# Material indices
@@ -239,7 +236,7 @@ def build_psk(context: Context, input_objects: PskInputObjects, options: PskBuil
match options.object_eval_state:
case 'ORIGINAL':
mesh_object = obj
mesh_data = obj.data
mesh_data = typing_cast(Mesh, obj.data)
case 'EVALUATED':
# Create a copy of the mesh object after non-armature modifiers are applied.
depsgraph = context.evaluated_depsgraph_get()
@@ -281,7 +278,14 @@ def build_psk(context: Context, input_objects: PskInputObjects, options: PskBuil
case _:
assert False, f'Invalid object evaluation state: {options.object_eval_state}'
mesh_export_space_matrix = armature_mesh_export_space_matrices[armature_object]
match options.export_space:
case 'ARMATURE' | 'ROOT':
mesh_export_space_matrix = armature_mesh_export_space_matrices[armature_object]
case 'WORLD':
mesh_export_space_matrix = armature_mesh_export_space_matrices[armature_object]
case _:
assert False, f'Invalid export space: {options.export_space}'
vertex_transform_matrix = scale_matrix @ coordinate_system_matrix @ mesh_export_space_matrix
point_transform_matrix = vertex_transform_matrix @ mesh_object.matrix_world
@@ -295,19 +299,25 @@ def build_psk(context: Context, input_objects: PskInputObjects, options: PskBuil
point.z = v.z
psk.points.append(point)
uv_layer = mesh_data.uv_layers.active.data
# Wedges
mesh_data.calc_loop_triangles()
if mesh_data.uv_layers.active is None:
warnings.append(f'"{mesh_object.name}" has no active UV Map')
# Build a list of non-unique wedges.
wedges = []
for loop_index, loop in enumerate(mesh_data.loops):
wedges.append(Psk.Wedge(
point_index=loop.vertex_index + vertex_offset,
u=uv_layer[loop_index].uv[0],
v=1.0 - uv_layer[loop_index].uv[1]
))
if mesh_data.uv_layers.active:
uv_layer = mesh_data.uv_layers.active.data
for loop_index, loop in enumerate(mesh_data.loops):
wedges.append(Psk.Wedge(
point_index=loop.vertex_index + vertex_offset,
u=uv_layer[loop_index].uv[0],
v=1.0 - uv_layer[loop_index].uv[1]
))
else:
for loop_index, loop in enumerate(mesh_data.loops):
wedges.append(Psk.Wedge(point_index=loop.vertex_index + vertex_offset, u=0.0, v=0.0))
# Assign material indices to the wedges.
for triangle in mesh_data.loop_triangles:
@@ -417,13 +427,12 @@ def build_psk(context: Context, input_objects: PskInputObjects, options: PskBuil
# Restore the original pose position of the armature objects.
for armature_object, pose_position in original_armature_object_pose_positions.items():
armature_object.data.pose_position = pose_position
context.window_manager.progress_end()
armature_data = typing_cast(Armature, armature_object.data)
armature_data.pose_position = pose_position
# https://github.com/DarklightGames/io_scene_psk_psa/issues/129.
psk.sort_and_normalize_weights()
result.psk = psk
context.window_manager.progress_end()
return result
return PskBuildResult(psk, warnings)

View File

@@ -3,7 +3,7 @@ from typing import Iterable, List, Optional, cast as typing_cast
import bpy
from bpy.props import BoolProperty, StringProperty
from bpy.types import Collection, Context, Depsgraph, Material, Object, Operator, SpaceProperties
from bpy.types import Context, Depsgraph, Material, Object, Operator, Scene
from bpy_extras.io_utils import ExportHelper
from .properties import PskExportMixin
@@ -15,7 +15,7 @@ from ..builder import (
get_psk_input_objects_for_context,
)
from ..writer import write_psk
from ...shared.helpers import populate_bone_collection_list
from ...shared.helpers import PsxBoneCollection, get_collection_export_operator_from_context, populate_bone_collection_list
from ...shared.ui import draw_bone_filter_mode
@@ -35,29 +35,6 @@ def populate_material_name_list(depsgraph: Depsgraph, mesh_objects: Iterable[Obj
def get_collection_from_context(context: Context) -> Optional[Collection]:
if context.space_data.type != 'PROPERTIES':
return None
space_data = typing_cast(SpaceProperties, context.space_data)
if space_data.use_pin_id:
return typing_cast(Collection, space_data.pin_id)
else:
return context.collection
def get_collection_export_operator_from_context(context: Context) -> Optional[object]:
collection = get_collection_from_context(context)
if collection is None:
return None
if 0 > collection.active_exporter_index >= len(collection.exporters):
return None
exporter = collection.exporters[collection.active_exporter_index]
# TODO: make sure this is actually an ASE exporter.
return exporter.export_properties
class PSK_OT_bone_collection_list_populate(Operator):
bl_idname = 'psk.bone_collection_list_populate'
bl_label = 'Populate Bone Collection List'
@@ -69,6 +46,9 @@ class PSK_OT_bone_collection_list_populate(Operator):
if export_operator is None:
self.report({'ERROR_INVALID_CONTEXT'}, 'No valid export operator found in context')
return {'CANCELLED'}
if context.collection is None:
self.report({'ERROR_INVALID_CONTEXT'}, 'No active collection')
return {'CANCELLED'}
try:
input_objects = get_psk_input_objects_for_collection(context.collection)
except RuntimeError as e:
@@ -77,7 +57,7 @@ class PSK_OT_bone_collection_list_populate(Operator):
if not input_objects.armature_objects:
self.report({'ERROR_INVALID_CONTEXT'}, 'No armature modifiers found on mesh objects')
return {'CANCELLED'}
populate_bone_collection_list(input_objects.armature_objects, export_operator.bone_collection_list)
populate_bone_collection_list(export_operator.bone_collection_list, input_objects.armature_objects)
return {'FINISHED'}
@@ -111,6 +91,7 @@ class PSK_OT_populate_material_name_list(Operator):
self.report({'ERROR_INVALID_CONTEXT'}, 'No valid export operator found in context')
return {'CANCELLED'}
depsgraph = context.evaluated_depsgraph_get()
assert context.collection
input_objects = get_psk_input_objects_for_collection(context.collection)
try:
populate_material_name_list(depsgraph, [x.obj for x in input_objects.mesh_dfs_objects], export_operator.material_name_list)
@@ -135,6 +116,7 @@ class PSK_OT_material_list_name_add(Operator):
name: StringProperty(search=material_list_names_search_cb, name='Material Name', default='None')
def invoke(self, context, event):
assert context.window_manager
return context.window_manager.invoke_props_dialog(self)
def execute(self, context):
@@ -246,18 +228,28 @@ def get_sorted_materials_by_names(materials: Iterable[Material], material_names:
return materials_in_collection + materials_not_in_collection
def get_psk_build_options_from_property_group(pg: PskExportMixin) -> PskBuildOptions:
def get_psk_build_options_from_property_group(scene: Scene, pg: PskExportMixin) -> PskBuildOptions:
options = PskBuildOptions()
options.object_eval_state = pg.object_eval_state
options.export_space = pg.export_space
options.bone_filter_mode = pg.bone_filter_mode
options.bone_collection_indices = [(x.armature_object_name, x.index) for x in pg.bone_collection_list if x.is_selected]
options.scale = pg.scale
options.forward_axis = pg.forward_axis
options.up_axis = pg.up_axis
options.bone_collection_indices = [PsxBoneCollection(x.armature_object_name, x.armature_data_name, x.index) for x in pg.bone_collection_list if x.is_selected]
options.root_bone_name = pg.root_bone_name
options.material_order_mode = pg.material_order_mode
options.material_name_list = pg.material_name_list
options.material_name_list = [x.material_name for x in pg.material_name_list]
match pg.transform_source:
case 'SCENE':
transform_source = getattr(scene, 'psx_export')
case 'SELF':
transform_source = pg
case _:
assert False, f'Invalid transform source: {pg.transform_source}'
options.scale = transform_source.scale
options.forward_axis = transform_source.forward_axis
options.up_axis = transform_source.up_axis
return options
@@ -276,15 +268,18 @@ class PSK_OT_export_collection(Operator, ExportHelper, PskExportMixin):
collection: StringProperty(options={'HIDDEN'})
def execute(self, context):
collection = bpy.data.collections.get(self.collection)
collection = bpy.data.collections.get(self.collection, None)
if collection is not None:
return {'CANCELLED'}
try:
input_objects = get_psk_input_objects_for_collection(collection, self.should_exclude_hidden_meshes)
input_objects = get_psk_input_objects_for_collection(collection)
except RuntimeError as e:
self.report({'ERROR_INVALID_CONTEXT'}, str(e))
return {'CANCELLED'}
options = get_psk_build_options_from_property_group(self)
options = get_psk_build_options_from_property_group(context.scene, self)
filepath = str(Path(self.filepath).resolve())
try:
@@ -305,6 +300,8 @@ class PSK_OT_export_collection(Operator, ExportHelper, PskExportMixin):
def draw(self, context: Context):
layout = self.layout
assert layout is not None
flow = layout.grid_flow(row_major=True)
flow.use_property_split = True
flow.use_property_decorate = False
@@ -317,7 +314,6 @@ class PSK_OT_export_collection(Operator, ExportHelper, PskExportMixin):
flow.use_property_split = True
flow.use_property_decorate = False
flow.prop(self, 'object_eval_state', text='Data')
flow.prop(self, 'should_exclude_hidden_meshes')
# Bones
bones_header, bones_panel = layout.panel('Bones', default_closed=False)
@@ -375,10 +371,24 @@ class PSK_OT_export_collection(Operator, ExportHelper, PskExportMixin):
flow.use_property_split = True
flow.use_property_decorate = False
flow.prop(self, 'export_space')
flow.prop(self, 'scale')
flow.prop(self, 'forward_axis')
flow.prop(self, 'up_axis')
flow.prop(self, 'transform_source')
flow = transform_panel.grid_flow(row_major=True)
flow.use_property_split = True
flow.use_property_decorate = False
match self.transform_source:
case 'SCENE':
transform_source = getattr(context.scene, 'psx_export')
flow.enabled = False
case 'CUSTOM':
transform_source = self
case _:
assert False, f'Invalid transform source: {self.transform_source}'
flow.prop(transform_source, 'scale')
flow.prop(transform_source, 'forward_axis')
flow.prop(transform_source, 'up_axis')
class PSK_OT_export(Operator, ExportHelper):
@@ -403,7 +413,7 @@ class PSK_OT_export(Operator, ExportHelper):
pg = getattr(context.scene, 'psk_export')
populate_bone_collection_list(input_objects.armature_objects, pg.bone_collection_list)
populate_bone_collection_list(pg.bone_collection_list, input_objects.armature_objects)
depsgraph = context.evaluated_depsgraph_get()
@@ -413,6 +423,7 @@ class PSK_OT_export(Operator, ExportHelper):
self.report({'ERROR_INVALID_CONTEXT'}, str(e))
return {'CANCELLED'}
assert context.window_manager
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
@@ -420,6 +431,8 @@ class PSK_OT_export(Operator, ExportHelper):
def draw(self, context):
layout = self.layout
assert layout
pg = getattr(context.scene, 'psk_export')
# Mesh
@@ -477,11 +490,22 @@ class PSK_OT_export(Operator, ExportHelper):
flow.prop(pg, 'forward_axis')
flow.prop(pg, 'up_axis')
# Extended Format
extended_format_header, extended_format_panel = layout.panel('Extended Format', default_closed=False)
extended_format_header.label(text='Extended Format')
if extended_format_panel:
flow = extended_format_panel.grid_flow(row_major=True)
flow.use_property_split = True
flow.use_property_decorate = False
flow.prop(pg, 'should_export_vertex_normals', text='Vertex Normals')
def execute(self, context):
pg = getattr(context.scene, 'psk_export')
assert context.scene
input_objects = get_psk_input_objects_for_context(context)
options = get_psk_build_options_from_property_group(pg)
options = get_psk_build_options_from_property_group(context.scene, pg)
try:
result = build_psk(context, input_objects, options)
@@ -499,7 +523,7 @@ class PSK_OT_export(Operator, ExportHelper):
return {'FINISHED'}
classes = (
_classes = (
PSK_OT_material_list_move_up,
PSK_OT_material_list_move_down,
PSK_OT_export,
@@ -511,3 +535,6 @@ classes = (
PSK_OT_material_list_name_move_down,
PSK_OT_material_list_name_add,
)
from bpy.utils import register_classes_factory
register, unregister = register_classes_factory(_classes)

View File

@@ -1,14 +1,16 @@
from bpy.types import Context
from bpy.props import (
BoolProperty,
CollectionProperty,
EnumProperty,
FloatProperty,
IntProperty,
PointerProperty,
StringProperty,
)
from bpy.types import Material, PropertyGroup
from ...shared.types import ExportSpaceMixin, ForwardUpAxisMixin, PsxBoneExportMixin
from ...shared.helpers import get_collection_export_operator_from_context
from ...shared.types import ExportSpaceMixin, TransformMixin, PsxBoneExportMixin
object_eval_state_items = (
('EVALUATED', 'Evaluated', 'Use data from fully evaluated object'),
@@ -20,33 +22,27 @@ material_order_mode_items = (
('MANUAL', 'Manual', 'Manually arrange the materials'),
)
transform_source_items = (
('SCENE', 'Scene', 'Use the scene transform settings'),
('CUSTOM', 'Custom', 'Use custom transform settings'),
)
class PSK_PG_material_list_item(PropertyGroup):
material: PointerProperty(type=Material)
index: IntProperty()
class PSK_PG_material_name_list_item(PropertyGroup):
material_name: StringProperty()
index: IntProperty()
class PskExportMixin(ExportSpaceMixin, ForwardUpAxisMixin, PsxBoneExportMixin):
class PskExportMixin(ExportSpaceMixin, TransformMixin, PsxBoneExportMixin):
object_eval_state: EnumProperty(
items=object_eval_state_items,
name='Object Evaluation State',
default='EVALUATED'
)
should_exclude_hidden_meshes: BoolProperty(
default=False,
name='Visible Only',
description='Export only visible meshes'
)
scale: FloatProperty(
name='Scale',
default=1.0,
description='Scale factor to apply to the exported mesh and armature',
min=0.0001,
soft_max=100.0
)
material_order_mode: EnumProperty(
name='Material Order',
description='The order in which to export the materials',
@@ -55,14 +51,28 @@ class PskExportMixin(ExportSpaceMixin, ForwardUpAxisMixin, PsxBoneExportMixin):
)
material_name_list: CollectionProperty(type=PSK_PG_material_name_list_item)
material_name_list_index: IntProperty(default=0)
should_export_vertex_normals: BoolProperty(
name='Export Vertex Normals',
default=False,
description='Export VTXNORMS section.'
)
transform_source: EnumProperty(
items=transform_source_items,
name='Transform Source',
default='SCENE'
)
class PSK_PG_export(PropertyGroup, PskExportMixin):
pass
classes = (
_classes = (
PSK_PG_material_list_item,
PSK_PG_material_name_list_item,
PSK_PG_export,
)
from bpy.utils import register_classes_factory
register, unregister = register_classes_factory(_classes)

View File

@@ -10,6 +10,9 @@ class PSK_UL_material_names(UIList):
row.prop(item, 'material_name', text='', emboss=False, icon_value=icon_value, icon='BLANK1' if icon_value == 0 else 'NONE')
classes = (
_classes = (
PSK_UL_material_names,
)
from bpy.utils import register_classes_factory
register, unregister = register_classes_factory(_classes)

View File

@@ -1,14 +1,19 @@
import os
from pathlib import Path
from bpy.props import CollectionProperty, StringProperty
from bpy.types import Context, FileHandler, Operator, OperatorFileListElement, UILayout
from typing import cast as typing_cast
from bpy.props import CollectionProperty, StringProperty, FloatProperty, EnumProperty
from bpy.types import Armature, Context, FileHandler, Operator, OperatorFileListElement, UILayout
from bpy_extras.io_utils import ImportHelper
from ...shared.helpers import get_coordinate_system_transform
from ...shared.types import AxisMixin
from ..importer import PskImportOptions, import_psk
from ..properties import PskImportMixin
from ..reader import read_psk
def get_psk_import_options_from_properties(property_group: PskImportMixin):
options = PskImportOptions()
options.should_import_mesh = property_group.should_import_mesh
@@ -109,6 +114,7 @@ class PSK_OT_import(Operator, ImportHelper, PskImportMixin):
return {'FINISHED'}
def draw(self, context):
assert self.layout
psk_import_draw(self.layout, self)
@@ -122,13 +128,15 @@ class PSK_OT_import_drag_and_drop(Operator, PskImportMixin):
files: CollectionProperty(type=OperatorFileListElement, options={'SKIP_SAVE', 'HIDDEN'})
@classmethod
def poll(cls, context):
return context.area and context.area.type == 'VIEW_3D'
def poll(cls, context) -> bool:
return context.area is not None and context.area.type == 'VIEW_3D'
def draw(self, context):
assert self.layout
psk_import_draw(self.layout, self)
def invoke(self, context, event):
assert context.window_manager
context.window_manager.invoke_props_dialog(self)
return {'RUNNING_MODAL'}
@@ -158,6 +166,46 @@ class PSK_OT_import_drag_and_drop(Operator, PskImportMixin):
return {'FINISHED'}
class PSK_OT_create_bones_from_selected_objects(Operator, AxisMixin):
bl_idname = 'psk.create_bones_from_selected_objects'
bl_label = 'Create Bones from Selected Objects'
bl_options = {'UNDO'}
length: FloatProperty(name='Length', subtype='DISTANCE', default=0.01)
@classmethod
def poll(cls, context: Context) -> bool:
return context.active_object is not None and context.active_object.type == 'ARMATURE'
def invoke(self, context, event):
assert context.window_manager
return context.window_manager.invoke_props_dialog(self)
def execute(self, context: Context):
armature_object = context.active_object
assert armature_object
armature_data = typing_cast(Armature, armature_object.data)
axis_transform = get_coordinate_system_transform(self.forward_axis, self.up_axis)
import bpy
bpy.ops.object.mode_set(mode='EDIT')
for index, obj in enumerate(context.selected_objects):
if obj == armature_object:
continue
edit_bone_matrix = armature_object.matrix_world.inverted() @ obj.matrix_world
edit_bone = armature_data.edit_bones.new(f'{obj.name}_{index}')
# translation, rotation, _ = edit_bone_matrix.decompose()
edit_bone.length = self.length
edit_bone.matrix = edit_bone_matrix @ axis_transform
bpy.ops.object.mode_set(mode='OBJECT')
return {'FINISHED'}
# TODO: move to another file
class PSK_FH_import(FileHandler):
bl_idname = 'PSK_FH_import'
@@ -167,12 +215,15 @@ class PSK_FH_import(FileHandler):
bl_file_extensions = '.psk;.pskx'
@classmethod
def poll_drop(cls, context: Context):
return context.area and context.area.type == 'VIEW_3D'
def poll_drop(cls, context: Context) -> bool:
return context.area is not None and context.area.type == 'VIEW_3D'
classes = (
_classes = (
PSK_OT_import,
PSK_OT_import_drag_and_drop,
PSK_FH_import,
)
from bpy.utils import register_classes_factory
register, unregister = register_classes_factory(_classes)

View File

@@ -53,7 +53,7 @@ class PskImportResult:
self.mesh_object: Optional[Object] = None
@property
def root_object(self) -> Object:
def root_object(self) -> Optional[Object]:
return self.armature_object if self.armature_object is not None else self.mesh_object
@@ -62,6 +62,9 @@ def import_psk(psk: Psk, context: Context, name: str, options: PskImportOptions)
armature_object = None
mesh_object = None
assert context.scene
assert bpy.context.view_layer
if options.should_import_armature:
# Armature
armature_data = bpy.data.armatures.new(name)
@@ -163,8 +166,11 @@ def import_psk(psk: Psk, context: Context, name: str, options: PskImportOptions)
# Faces
invalid_face_indices = set()
for face_index, face in enumerate(psk.faces):
point_indices = map(lambda i: psk.wedges[i].point_index, reversed(face.wedge_indices))
points = [bm.verts[i] for i in point_indices]
points = (
bm.verts[psk.wedges[face.wedge_indices[2]].point_index],
bm.verts[psk.wedges[face.wedge_indices[1]].point_index],
bm.verts[psk.wedges[face.wedge_indices[0]].point_index],
)
try:
bm_face = bm.faces.new(points)
bm_face.material_index = face.material_index
@@ -178,44 +184,49 @@ def import_psk(psk: Psk, context: Context, name: str, options: PskImportOptions)
if len(invalid_face_indices) > 0:
result.warnings.append(f'Discarded {len(invalid_face_indices)} invalid face(s).')
face_count = len(bm.faces)
bm.to_mesh(mesh_data)
# Texture Coordinates
uv_layer_data_index = 0
uv_layer = mesh_data.uv_layers.new(name='UVMap')
uv_layer_data = np.zeros((face_count * 3, 2), dtype=np.float32)
for face_index, face in enumerate(psk.faces):
if face_index in invalid_face_indices:
continue
face_wedges = [psk.wedges[i] for i in reversed(face.wedge_indices)]
for wedge in face_wedges:
uv_layer.data[uv_layer_data_index].uv = wedge.u, 1.0 - wedge.v
for wedge in map(lambda i: psk.wedges[i], reversed(face.wedge_indices)):
uv_layer_data[uv_layer_data_index] = wedge.u, 1.0 - wedge.v
uv_layer_data_index += 1
uv_layer = mesh_data.uv_layers.new(name='UVMap')
uv_layer.uv.foreach_set('vector', uv_layer_data.ravel())
# Extra UVs
if psk.has_extra_uvs and options.should_import_extra_uvs:
extra_uv_channel_count = int(len(psk.extra_uvs) / len(psk.wedges))
wedge_index_offset = 0
uv_layer_data = np.zeros((face_count * 3, 2), dtype=np.float32)
for extra_uv_index in range(extra_uv_channel_count):
uv_layer_data_index = 0
uv_layer = mesh_data.uv_layers.new(name=f'EXTRAUV{extra_uv_index}')
for face_index, face in enumerate(psk.faces):
if face_index in invalid_face_indices:
continue
for wedge_index in reversed(face.wedge_indices):
u, v = psk.extra_uvs[wedge_index_offset + wedge_index]
uv_layer.data[uv_layer_data_index].uv = u, 1.0 - v
for wedge in map(lambda i: psk.wedges[i], reversed(face.wedge_indices)):
uv_layer_data[uv_layer_data_index] = wedge.u, 1.0 - wedge.v
uv_layer_data_index += 1
wedge_index_offset += len(psk.wedges)
uv_layer = mesh_data.uv_layers.new(name=f'EXTRAUV{extra_uv_index}')
uv_layer.uv.foreach_set('vector', uv_layer_data.ravel())
# Vertex Colors
if psk.has_vertex_colors and options.should_import_vertex_colors:
# Convert vertex colors to sRGB if necessary.
psk_vertex_colors = np.zeros((len(psk.vertex_colors), 4))
for vertex_color_index in range(len(psk.vertex_colors)):
psk_vertex_colors[vertex_color_index,:] = psk.vertex_colors[vertex_color_index].normalized()
psk_vertex_colors[vertex_color_index] = tuple(psk.vertex_colors[vertex_color_index])
psk_vertex_colors /= 255.0
# Convert vertex colors to sRGB if necessary.
if options.vertex_color_space == 'SRGBA':
for i in range(psk_vertex_colors.shape[0]):
psk_vertex_colors[i, :3] = tuple(map(lambda x: rgb_to_srgb(x), psk_vertex_colors[i, :3]))
psk_vertex_colors[:, :3] = np.vectorize(rgb_to_srgb)(psk_vertex_colors[:, :3])
# Map the PSK vertex colors to the face corners.
face_count = len(psk.faces) - len(invalid_face_indices)
@@ -230,7 +241,7 @@ def import_psk(psk: Psk, context: Context, name: str, options: PskImportOptions)
# Create the vertex color attribute.
face_corner_color_attribute = mesh_data.attributes.new(name='VERTEXCOLOR', type='FLOAT_COLOR', domain='CORNER')
face_corner_color_attribute.data.foreach_set('color', face_corner_colors.flatten())
face_corner_color_attribute.data.foreach_set('color', face_corner_colors.ravel())
# Vertex Normals
if psk.has_vertex_normals and options.should_import_vertex_normals:

View File

@@ -20,9 +20,15 @@ mesh_triangle_bit_flags_items = (
)
class PSX_PG_material(PropertyGroup):
mesh_triangle_type: EnumProperty(items=mesh_triangle_types_items, name='Triangle Type')
mesh_triangle_bit_flags: EnumProperty(items=mesh_triangle_bit_flags_items, name='Triangle Bit Flags',
options={'ENUM_FLAG'})
mesh_triangle_type: EnumProperty(
name='Triangle Type',
items=mesh_triangle_types_items
)
mesh_triangle_bit_flags: EnumProperty(
name='Triangle Bit Flags',
items=mesh_triangle_bit_flags_items,
options={'ENUM_FLAG'}
)
mesh_triangle_types_items_dict = {item[0]: item[3] for item in mesh_triangle_types_items}
mesh_triangle_bit_flags_items_dict = {item[0]: item[3] for item in mesh_triangle_bit_flags_items}
@@ -36,7 +42,7 @@ def triangle_type_and_bit_flags_to_poly_flags(mesh_triangle_type: str, mesh_tria
return poly_flags
def poly_flags_to_triangle_type_and_bit_flags(poly_flags: int) -> (str, set[str]):
def poly_flags_to_triangle_type_and_bit_flags(poly_flags: int) -> tuple[str, set[str]]:
try:
triangle_type = next(item[0] for item in mesh_triangle_types_items if item[3] == (poly_flags & 15))
except StopIteration:
@@ -53,6 +59,17 @@ def should_import_skleton_get(self):
return self.components in {'ALL', 'ARMATURE'}
vertex_color_space_items = (
('LINEAR', 'Linear', ''),
('SRGBA', 'sRGBA', ''),
)
psk_import_components_items = (
('ALL', 'Mesh & Armature', 'Import mesh and armature'),
('MESH', 'Mesh Only', 'Import mesh only'),
('ARMATURE', 'Armature Only', 'Import armature only'),
)
class PskImportMixin:
should_import_vertex_colors: BoolProperty(
default=True,
@@ -65,10 +82,7 @@ class PskImportMixin:
options=set(),
description='The source vertex color space',
default='SRGBA',
items=(
('LINEAR', 'Linear', ''),
('SRGBA', 'sRGBA', ''),
)
items=vertex_color_space_items
)
should_import_vertex_normals: BoolProperty(
default=True,
@@ -86,11 +100,7 @@ class PskImportMixin:
name='Components',
options=set(),
description='Which components to import',
items=(
('ALL', 'Mesh & Armature', 'Import mesh and armature'),
('MESH', 'Mesh Only', 'Import mesh only'),
('ARMATURE', 'Armature Only', 'Import armature only'),
),
items=psk_import_components_items,
default='ALL'
)
should_import_mesh: BoolProperty(
@@ -135,6 +145,10 @@ class PskImportMixin:
)
classes = (
_classes = (
PSX_PG_material,
)
from bpy.utils import register_classes_factory
register, unregister = register_classes_factory(_classes)

View File

@@ -15,6 +15,7 @@ class PSK_PT_material(Panel):
def draw(self, context):
layout = self.layout
assert layout is not None
layout.use_property_split = True
layout.use_property_decorate = False
material = context.material
@@ -23,6 +24,10 @@ class PSK_PT_material(Panel):
col.prop(material.psk, 'mesh_triangle_bit_flags', expand=True, text='Flags')
classes = (
_classes = (
PSK_PT_material,
)
from bpy.utils import register_classes_factory
register, unregister = register_classes_factory(_classes)

View File

@@ -17,13 +17,18 @@ class Color(Structure):
yield self.a
def __eq__(self, other):
return all(map(lambda x: x[0] == x[1], zip(self, other)))
return self.r == other.r and self.g == other.g and self.b == other.b and self.a == other.a
def __repr__(self):
return repr(tuple(self))
def normalized(self) -> Tuple:
return tuple(map(lambda x: x / 255.0, iter(self)))
return (
self.r / 255.0,
self.g / 255.0,
self.b / 255.0,
self.a / 255.0
)
class Vector2(Structure):

View File

@@ -146,16 +146,3 @@ def dfs_view_layer_objects(view_layer: ViewLayer) -> Iterable[DfsObject]:
yield from _dfs_collection_objects_recursive(layer_collection.collection, visited=visited)
yield from layer_collection_objects_recursive(view_layer.layer_collection)
def _is_dfs_object_visible(obj: Object, instance_objects: List[Object]) -> bool:
"""
Check if a DFS object is visible.
@param obj: The object.
@param instance_objects: The instance objects.
@return: True if the object is visible, False otherwise.
"""
if instance_objects:
return instance_objects[-1].visible_get()
return obj.visible_get()

View File

@@ -1,18 +1,16 @@
import bpy
from collections import Counter
from typing import List, Iterable, Optional, Dict, Tuple, cast as typing_cast
from bpy.props import CollectionProperty
from bpy.types import Armature, AnimData, Object
from bpy.types import Armature, AnimData, Collection, Context, Object, ArmatureModifier, SpaceProperties
from mathutils import Matrix, Vector, Quaternion as BpyQuaternion
from .data import Vector3, Quaternion
from ..shared.data import PsxBone
def rgb_to_srgb(c: float):
def rgb_to_srgb(c: float) -> float:
if c > 0.0031308:
return 1.055 * (pow(c, (1.0 / 2.4))) - 0.055
else:
return 12.92 * c
return 12.92 * c
def get_nla_strips_in_frame_range(animation_data: AnimData, frame_min: float, frame_max: float):
@@ -28,16 +26,27 @@ def get_nla_strips_in_frame_range(animation_data: AnimData, frame_min: float, fr
yield strip
def populate_bone_collection_list(armature_objects: Iterable[Object], bone_collection_list: CollectionProperty) -> None:
def populate_bone_collection_list(bone_collection_list, armature_objects: Iterable[Object], primary_key: str = 'OBJECT'):
"""
Updates the bone collections collection.
Updates the bone collection list.
Bone collection selections are preserved between updates unless none of the groups were previously selected;
otherwise, all collections are selected by default.
Selection is preserved between updates unless none of the groups were previously selected.
Otherwise, all collections are selected by default.
The primary key is used to determine how to group the armature objects. For example, if the primary key is
'DATA', then all bone collections with the same armature data-block will be under one entry.
:param bone_collection_list: The list to update.
:param armature_objects: The armature objects to populate the collection with.
:param primary_key: The primary key to use for the collection (one of 'OBJECT' or 'DATA').
:return: None
"""
has_selected_collections = any([g.is_selected for g in bone_collection_list])
unassigned_collection_is_selected, selected_assigned_collection_names = True, []
if primary_key not in ('OBJECT', 'DATA'):
assert False, f'Invalid primary key: {primary_key}'
if not armature_objects:
return
@@ -51,16 +60,26 @@ def populate_bone_collection_list(armature_objects: Iterable[Object], bone_colle
selected_assigned_collection_names = [
g.name for i, g in enumerate(bone_collection_list) if i != unassigned_collection_idx and g.is_selected]
bone_collection_list.clear()
unique_armature_data = set()
for armature_object in armature_objects:
armature = typing_cast(Armature, armature_object.data)
if armature is None:
return
continue
if primary_key == 'DATA' and armature_object.data in unique_armature_data:
# Skip this armature since we have already added an entry for it and we are using the data as the key.
continue
unique_armature_data.add(armature_object.data)
item = bone_collection_list.add()
item.armature_object_name = armature_object.name
item.armature_data_name = armature_object.data.name if armature_object.data else ''
item.name = 'Unassigned' # TODO: localize
item.index = -1
# Count the number of bones without an assigned bone collection
@@ -70,6 +89,7 @@ def populate_bone_collection_list(armature_objects: Iterable[Object], bone_colle
for bone_collection_index, bone_collection in enumerate(armature.collections_all):
item = bone_collection_list.add()
item.armature_object_name = armature_object.name
item.armature_data_name = armature_object.data.name if armature_object.data else ''
item.name = bone_collection.name
item.index = bone_collection_index
item.count = len(bone_collection.bones)
@@ -286,6 +306,16 @@ def convert_bpy_quaternion_to_psx_quaternion(other: BpyQuaternion) -> Quaternion
return quaternion
class PsxBoneCollection:
"""
Stores the armature's object name, data-block name and bone collection index.
"""
def __init__(self, armature_object_name: str, armature_data_name: str, index: int):
self.armature_object_name = armature_object_name
self.armature_data_name = armature_data_name
self.index = index
def create_psx_bones(
armature_objects: List[Object],
export_space: str = 'WORLD',
@@ -294,7 +324,8 @@ def create_psx_bones(
up_axis: str = 'Z',
scale: float = 1.0,
bone_filter_mode: str = 'ALL',
bone_collection_indices: Optional[List[Tuple[str, int]]] = None,
bone_collection_indices: Optional[List[PsxBoneCollection]] = None,
bone_collection_primary_key: str = 'OBJECT',
) -> PsxBoneCreateResult:
"""
Creates a list of PSX bones from the given armature objects and options.
@@ -306,20 +337,27 @@ def create_psx_bones(
bones: List[Tuple[PsxBone, Optional[Object]]] = []
if export_space != 'WORLD' and len(armature_objects) > 1:
if export_space != 'WORLD' and len(armature_objects) >= 2:
armature_object_names = [armature_object.name for armature_object in armature_objects]
raise RuntimeError(f'When exporting multiple armatures, the Export Space must be World. The following armatures are attempting to be exported: {armature_object_names}')
raise RuntimeError(f'When exporting multiple armatures, the Export Space must be World.\n' \
f'The following armatures are attempting to be exported: {armature_object_names}')
coordinate_system_matrix = get_coordinate_system_transform(forward_axis, up_axis)
coordinate_system_default_rotation = coordinate_system_matrix.to_quaternion()
total_bone_count = sum(len(armature_object.data.bones) for armature_object in armature_objects)
# Store the bone names to be exported for each armature object.
armature_object_bone_names: Dict[Object, List[str]] = dict()
for armature_object in armature_objects:
armature_bone_collection_indices = [x[1] for x in bone_collection_indices if x[0] == armature_object.name]
armature_bone_collection_indices: List[int] = []
match bone_collection_primary_key:
case 'OBJECT':
armature_bone_collection_indices.extend([x.index for x in bone_collection_indices if x.armature_object_name == armature_object.name])
case 'DATA':
armature_bone_collection_indices.extend([x.index for x in bone_collection_indices if armature_object.data and x.armature_data_name == armature_object.data.name])
case _:
assert False, f'Invalid primary key: {bone_collection_primary_key}'
bone_names = get_export_bone_names(armature_object, bone_filter_mode, armature_bone_collection_indices)
armature_object_bone_names[armature_object] = bone_names
@@ -429,3 +467,36 @@ def get_coordinate_system_transform(forward_axis: str = 'X', up_axis: str = 'Z')
(up.x, up.y, up.z, 0.0),
(0.0, 0.0, 0.0, 1.0)
))
def get_armatures_for_mesh_objects(mesh_objects: Iterable[Object]):
"""
Returns a generator of unique armature objects that are used by the given mesh objects.
"""
armature_objects: set[Object] = set()
for mesh_object in mesh_objects:
armature_modifiers = [typing_cast(ArmatureModifier, x) for x in mesh_object.modifiers if x.type == 'ARMATURE']
for armature_object in map(lambda x: x.object, armature_modifiers):
if armature_object is not None:
armature_objects.add(armature_object)
yield from armature_objects
def get_collection_from_context(context: Context) -> Optional[Collection]:
if context.space_data is None or context.space_data.type != 'PROPERTIES':
return None
space_data = typing_cast(SpaceProperties, context.space_data)
if space_data.use_pin_id:
return typing_cast(Collection, space_data.pin_id)
else:
return context.collection
def get_collection_export_operator_from_context(context: Context) -> Optional[object]:
collection = get_collection_from_context(context)
if collection is None or collection.active_exporter_index is None:
return None
if 0 > collection.active_exporter_index >= len(collection.exporters):
return None
exporter = collection.exporters[collection.active_exporter_index]
return exporter.export_properties

View File

@@ -21,6 +21,7 @@ class PSX_UL_bone_collection_list(UIList):
class PSX_PG_bone_collection_list_item(PropertyGroup):
armature_object_name: StringProperty()
armature_data_name: StringProperty()
name: StringProperty()
index: IntProperty()
count: IntProperty()
@@ -93,7 +94,7 @@ def up_axis_update(self, __context):
self.forward_axis = next((axis for axis in axis_identifiers if axis != self.up_axis), 'X')
class ForwardUpAxisMixin:
class AxisMixin:
forward_axis: EnumProperty(
name='Forward',
items=forward_items,
@@ -108,6 +109,16 @@ class ForwardUpAxisMixin:
)
class TransformMixin(AxisMixin):
scale: FloatProperty(
name='Scale',
default=1.0,
description='Scale factor to apply to all location data',
soft_min=0.0,
soft_max=100.0
)
export_space_items = [
('WORLD', 'World', 'Export in world space'),
('ARMATURE', 'Armature', 'Export the local space of the armature object'),
@@ -139,9 +150,17 @@ class PsxBoneExportMixin:
)
classes = (
class PSX_PG_scene_export(PropertyGroup, TransformMixin):
pass
_classes = (
PSX_PG_scene_export,
PSX_PG_action_export,
PSX_PG_bone_collection_list_item,
PSX_UL_bone_collection_list,
PSX_PT_action,
)
from bpy.utils import register_classes_factory
register, unregister = register_classes_factory(_classes)

View File

@@ -1,4 +1,5 @@
from bpy.types import UILayout
import bpy
from bpy.types import Context, UILayout, Panel
from .types import bone_filter_mode_items
@@ -16,3 +17,43 @@ def draw_bone_filter_mode(layout: UILayout, pg, should_always_show_bone_collecti
item_layout = row.row(align=True)
item_layout.prop_enum(pg, 'bone_filter_mode', item_identifier)
item_layout.enabled = should_always_show_bone_collections or is_bone_filter_mode_item_available(pg, identifier)
class PSX_PT_scene(Panel):
bl_idname = 'PSX_PT_scene'
bl_label = 'PSK Export'
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = 'scene'
bl_category = 'PSK/PSA'
@classmethod
def poll(cls, context):
return context.scene is not None
def draw(self, context: Context):
layout = self.layout
scene = bpy.context.scene
psx_export = getattr(scene, 'psx_export', None)
if psx_export is None:
return
# Transform
transform_header, transform_panel = layout.panel('Transform', default_closed=False)
transform_header.label(text='Transform')
if transform_panel:
flow = layout.grid_flow(columns=1)
flow.use_property_split = True
flow.use_property_decorate = False
flow.prop(psx_export, 'scale')
flow.prop(psx_export, 'forward_axis')
flow.prop(psx_export, 'up_axis')
_classes = (
PSX_PT_scene,
)
from bpy.utils import register_classes_factory
register, unregister = register_classes_factory(_classes)

View File

@@ -10,3 +10,6 @@ branch = true
[tool.coverage.report]
ignore_errors = true
[tool.pyright]
reportInvalidTypeForm = false

BIN
tests/data/Bat.psk LFS Normal file

Binary file not shown.

View File

@@ -4,6 +4,7 @@ import pytest
SUZANNE_FILEPATH = 'tests/data/Suzanne.psk'
SARGE_FILEPATH = 'tests/data/CS_Sarge_S0_Skelmesh.pskx'
SLURP_MONSTER_AXE_FILEPATH = 'tests/data/Slurp_Monster_Axe_LOD0.psk'
BAT_FILEPATH = 'tests/data/Bat.psk'
@pytest.fixture(autouse=True)
@@ -280,3 +281,9 @@ def test_psk_import_without_shape_keys():
assert mesh_object.type == 'MESH', "Mesh object type should be MESH"
assert mesh_object.data.shape_keys is None, "Mesh object should not have shape keys"
def test_psk_import_with_invalid_faces():
assert bpy.ops.psk.import_file(
filepath=BAT_FILEPATH,
components='MESH'
) == {'FINISHED'}