diff --git a/CLAUDE.md b/CLAUDE.md index 97b30e2..c85d532 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,7 +12,7 @@ Generic な `.anim`(シェイプキー・表示の切り替え・オブジェクトの Transform)は、ミュートした NLA トラックの Action にする(`core/animation.py`。#209)。 値が変わらないか 0.1 秒以下で終わる、状態を切り替えるだけのクリップ(Animator のステート用)は読み込まない。 FBX の中のテイクは、.meta の clipAnimations どおりのクリップにして同じく NLA に並べ、同じ骨格のモーションだけのモデルは - レストの違いを変換して 1 体のアーマチュアにまとめる(`blender/fbx_motion.py`。#276)。オプションは Animation(Muted / Active / None)。 + レストの違いを変換して 1 体のアーマチュアにまとめる(`blender/fbx_motion.py` と `rig_merge.py`。NLA への置き方は両方で `nla.py`。#276)。オプションは Animation(Muted / Active / None)。 ## 設計の要点(詳細は DESIGN.md) @@ -51,7 +51,7 @@ ``` unitypackage_loader/ Extension 本体(blender_manifest.toml、Blender 4.5 以降の Extension 形式) core/ bpy 非依存。単体テスト可能。bpy を import しないこと - blender/ bpy 依存(importer / options / log / prepare / model_import / session_materials / scene_placement / scene_objects / terrain / unity_meshes / animation / fbx_motion / materials / nodes / textures / toon_group / outline) + blender/ bpy 依存(importer / options / log / prepare / model_import / session_materials / scene_placement / scene_objects / terrain / unity_meshes / animation / fbx_motion / rig_merge / nla / materials / nodes / textures / toon_group / outline) operators/ File > Import、モデル選択ダイアログ、再構築、アウトライン ui/ Preferences、サイドバー "UPI" タブ tests/ unittest(bpy 不要)+ Blender 上の統合テスト+合成パッケージ生成 diff --git a/DESIGN.md b/DESIGN.md index 8d86882..203e7ab 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -663,7 +663,9 @@ unitypackage_loader/ │ ├─ terrain.py # Terrain のメッシュと塗り分けのマテリアル(SessionTerrains。#205) │ ├─ unity_meshes.py # Unity の Mesh アセットから作るメッシュ(SessionMeshes。#216) │ ├─ animation.py # クリップの Action と NLA トラック(ClipImporter。#209) -│ ├─ fbx_motion.py # モデルのテイクのクリップへの分割、モーションだけのアーマチュアのまとめ(MotionBuilder。#276) +│ ├─ fbx_motion.py # モデルのテイクのクリップへの分割(MotionBuilder。#276) +│ ├─ rig_merge.py # モーションだけのアーマチュアのまとめとレストの違いの変換(merge_motion_rigs。#276) +│ ├─ nla.py # クリップを NLA のトラックに置く共通処理(Active のときのミュート・ループ。#281) │ ├─ log.py # 捕まえて続けた例外のログ(Verbose Console Log はオペレーターが渡す) │ ├─ scene_objects.py # シーンの Empty・ライト・カメラ・複製・行列の当てはめ(計算は core/model_space.py)・非表示 │ ├─ materials.py # ノード生成 @@ -1096,8 +1098,8 @@ def run(ctx, filepath, opts) -> Report: どのオブジェクトのものか決められないので付けない(Medieval Village の風車など。Animator Controller から引けば決められるが、今は読まない)。 - **Action と NLA**(`blender/animation.py`): クリップごとに Action を 1 つ作り(`unity_clip_guid` / `unity_clip_path`)、対象のデータブロック (オブジェクトかシェイプキーの Key)ごとにスロットを作る(Blender 4.4 以降のスロット付き Action)。対象ごとにクリップの名前の NLA トラックを - ミュートで足すので、読み込んだ直後の見た目は変わらない。キーはクリップの開始からの秒 × シーンのフレームレートで、ストリップはシーンの開始フレームに置く。 - ループするクリップ(`m_LoopTime`)は、ストリップの繰り返し(`repeat`)をシーンのフレーム範囲の終わりまでにする(`fbx_motion.loop_strip`)。 + ミュートで足すので(`nla.add_track`。モデルのテイクと共通)、読み込んだ直後の見た目は変わらない。キーはクリップの開始からの秒 × シーンのフレームレートで、ストリップはシーンの開始フレームに置く。 + ループするクリップ(`m_LoopTime`)は、ストリップの繰り返し(`repeat`)をシーンのフレーム範囲の終わりまでにする(`nla.loop_strip`)。 NLA はストリップの範囲の外を評価しないので、F カーブの Cycles モディファイアー(これも付ける。Action を直接再生するとき用)だけではループしない。 - シェイプキー: 値を 1/100 にしてキーと接線をそのままベジェにする。100 を超える重みは `slider_max` を広げる。 - 表示: `hide_viewport` / `hide_render` を階段(CONSTANT)で、値が 0.5 未満なら隠す。`m_IsActive` は Unity の階層での子孫にも当てる @@ -1131,7 +1133,7 @@ Blender の FBX インポーターはテイクごとにテイクの名前の Act ときと同じにする)。Action には `unity_take` / `unity_take_model` を残す。 - **使い回し**: シーンで同じモデルを配置ごとに読み直すときは、最初に読んだときの Action を使い、新しく作られた分は消す。 前の読み込みが失敗して Action が消えていたら作り直す。 -- **アーマチュアのまとめ**(`merge_motion_rigs`。Models 単位): メッシュが無く、アーマチュアが 1 体で、トラックを持つモデルを +- **アーマチュアのまとめ**(`blender/rig_merge.py` の `merge_motion_rigs`。Models 単位): メッシュが無く、アーマチュアが 1 体で、トラックを持つモデルを モーションだけのモデルとし、骨格(ボーンの名前と親の組)が含まれる関係にあり、置き場所(親のワールドの行列)が同じものを 1 体にまとめる。残すのはボーンがいちばん多く、その中で先に読んだもの。 - スキンの無い FBX はファイルの既定の姿勢をレストにするので、レストはファイルごとに違う(32 RPG Animations では指のボーンで @@ -1146,7 +1148,7 @@ Blender の FBX インポーターはテイクごとにテイクの名前の Act アーマチュアの数を `clip_notes` に出す。 - FBX インポーターは、アニメーションを読むかどうかによらずシーンのフレームレートをファイルのものにする(今までと同じ)。 フレームレートの違う FBX を続けて読むと、先に読んだ FBX のモーションの速さがずれる(未対応)。 -- ループ(`loopTime`)は、`.anim` と同じくストリップの繰り返しにする(`loop_strip`。まとめたアーマチュアに写すときも回数を引き継ぐ)。 +- ループ(`loopTime`)は、`.anim` と同じくストリップの繰り返しにする(`nla.loop_strip`。まとめたアーマチュアに写すときも回数を引き継ぐ。`nla.copy_track`)。 ### 4.8 `blender/textures.py` diff --git a/tests/expectations_synthetic_anim_active.json b/tests/expectations_synthetic_anim_active.json new file mode 100644 index 0000000..43c2715 --- /dev/null +++ b/tests/expectations_synthetic_anim_active.json @@ -0,0 +1,24 @@ +{ + "options": { + "unit": "MODELS", + "animation": "ACTIVE" + }, + "errors": 0, + "clips": { + "count": 4, + "unmuted": { + "Face": ["Smile"], + "Hat": ["HatOff"], + "Door": ["DoorOpen"], + "Knob": ["DoorOpen"], + "Body": ["Wave"] + }, + "tracks": { + "Face": ["Smile"], + "Hat": ["HatOff"], + "Door": ["DoorOpen"], + "Knob": ["DoorOpen"], + "Body": ["Wave"] + } + } +} diff --git a/tests/integration_runs.json b/tests/integration_runs.json index cb53ba1..f4251f7 100644 --- a/tests/integration_runs.json +++ b/tests/integration_runs.json @@ -46,6 +46,7 @@ { "package": "synthetic_mesh.unitypackage", "expectations": "expectations_synthetic_mesh_models.json", "note": "FBX のマテリアルの画像が作者の PC のパスを指すモデル" }, { "package": "synthetic_anim.unitypackage", "expectations": "expectations_synthetic_anim.json", "note": ".anim の Action(シェイプキー・表示の切り替え・Transform)と、読み込まないクリップの内訳" }, { "package": "synthetic_anim.unitypackage", "expectations": "expectations_synthetic_anim_scene.json", "note": "シーンに 2 か所置いたモデルの両方にクリップを付ける" }, + { "package": "synthetic_anim.unitypackage", "expectations": "expectations_synthetic_anim_active.json", "note": "Animation が Active なら、.anim のトラックもオブジェクトごとに最初の 1 本だけミュートを外す" }, { "package": "synthetic_anim.unitypackage", "expectations": "expectations_synthetic_anim_off.json", "note": "Animation を None にすると Action を作らない" }, { "package": "synthetic_motion.unitypackage", "expectations": "expectations_synthetic_motion.json", "note": "モデルのテイクを .meta のクリップで分け、同じ骨格のモーションだけのアーマチュアをレストを変換してまとめる" }, { "package": "synthetic_motion.unitypackage", "expectations": "expectations_synthetic_motion_active.json", "note": "Animation が Active なら、オブジェクトごとに最初のトラックだけミュートを外す" }, diff --git a/unitypackage_loader/blender/animation.py b/unitypackage_loader/blender/animation.py index 53fd656..9b745c8 100644 --- a/unitypackage_loader/blender/animation.py +++ b/unitypackage_loader/blender/animation.py @@ -7,7 +7,7 @@ そのままベジェ(階段は CONSTANT)にする。GameObject の非アクティブは、Unity の階層での子孫にも当てる。 - Transform は Unity のローカルの値をフレームごとに求め、オブジェクトの行列にしてから位置・回転・スケールのキーにする (行列の対応は ``core/model_space.local_basis``)。ボーンを対象にしたカーブは読み込まない(#270)。 -- 対象ごとに、クリップの名前の NLA トラックをミュートで足す。読み込んだ直後の見た目は変わらない。 +- 対象ごとに、クリップの名前の NLA トラックを足す(``nla.add_track``)。既定はミュートで、読み込んだ直後の見た目は変わらない。 """ from __future__ import annotations @@ -34,9 +34,9 @@ from ..core.animation_targets import Binding, TargetObject, TargetTree, bind_paths from ..core.model_space import ModelUnits, local_basis, local_values from ..core.transform import IDENTITY, UNITY_TO_BLENDER, Mat4, inverse_affine -from .fbx_motion import loop_strip from .log import warn_skipped from .model_import import FBX_NODE_PROP, MODEL_GUID_PROP, node_name +from .nla import MODE_ACTIVE, add_track CLIP_GUID_PROP = "unity_clip_guid" # GameObject の行列に、向きや形を足して置いたオブジェクト(Transform のカーブを当てない) @@ -94,7 +94,6 @@ def __init__(self, session, collection: bpy.types.Collection): self.scene = session.scene render = self.scene.render self.fps = render.fps / (render.fps_base or 1.0) - self.frame_start = self.scene.frame_start self.stats = ClipStats() self._units: dict[str, ModelUnits | None] = {} self._tree: TargetTree | None = None @@ -195,21 +194,10 @@ def slot_for(datablock: bpy.types.ID, id_type: str, label: str): bpy.data.actions.remove(action) return "bones" if bones else "none" for datablock, slot in users.items(): - self._add_track(datablock, action, slot, clip.name or entry.name) + add_track(datablock, clip.name or entry.name, action, slot, self.scene, + active=self.session.opts.animation == MODE_ACTIVE, loop=action.use_cyclic) return "loaded" - def _add_track(self, datablock, action, slot, name: str) -> None: - animation_data = datablock.animation_data or datablock.animation_data_create() - track = animation_data.nla_tracks.new() - active = self.session.opts.animation == "ACTIVE" and not any(not t.mute for t in animation_data.nla_tracks) - track.name = name - nla_strip = track.strips.new(name, self.frame_start, action) - if nla_strip.action_slot != slot: - nla_strip.action_slot = slot - if action.use_cyclic: - loop_strip(nla_strip, self.scene) - track.mute = not active - # 各種のカーブ ------------------------------------------------------ def _frame(self, time: float, clip: AnimationClip) -> float: diff --git a/unitypackage_loader/blender/fbx_motion.py b/unitypackage_loader/blender/fbx_motion.py index 074c9cd..120807d 100644 --- a/unitypackage_loader/blender/fbx_motion.py +++ b/unitypackage_loader/blender/fbx_motion.py @@ -9,22 +9,20 @@ - どのクリップにも使われないテイクの Action は消す。アクティブな Action は外す(読み込んだ直後の見た目を、アニメーションを 読まないときと同じにする)。 - 同じモデルを何度も読む(シーンの配置ごと)ときは、最初に読んだときの Action を使い回し、新しく作られた分は消す。 -- モーションだけのモデル(メッシュが無く、アーマチュアが 1 体)が同じ骨格で並ぶとき(Models 単位)は、アーマチュアを 1 体にまとめて - 全部のトラックを載せる(``merge_motion_rigs``)。 +- トラックの置き方(Active のときのミュート、ループ)は ``nla.py``。モーションだけのモデルのアーマチュアを 1 体にまとめるのは + ``rig_merge.py``。 """ from __future__ import annotations -import math -import re from dataclasses import dataclass, field import bpy -from mathutils import Euler, Matrix, Quaternion, Vector from ..core.animation import STATE_CLIP_MAX_LENGTH from ..core.meta import ModelClip, ModelImporterInfo, strip_numeric_suffix -from .model_import import FBX_NODE_PROP, MODEL_GUID_PROP, is_removed +from .model_import import FBX_NODE_PROP, is_removed +from .nla import MODE_ACTIVE, add_track # Blender の FBX インポーターの anim_offset の既定値(FBX のフレーム 0 を Blender のフレーム 1 に置く) ANIM_OFFSET = 1.0 @@ -32,12 +30,6 @@ TAKE_PROP = "unity_take" TAKE_MODEL_PROP = "unity_take_model" -MODE_MUTED = "MUTED" -MODE_ACTIVE = "ACTIVE" -MODE_NONE = "NONE" - -# keyframe_points の interpolation に foreach_set で渡す LINEAR の値 -_LINEAR = bpy.types.Keyframe.bl_rna.properties["interpolation"].enum_items["LINEAR"].value @dataclass @@ -155,7 +147,8 @@ def arrange(self, model_guid: str, pathname: str, info: ModelImporterInfo | None slot = clip.action.slots.get(identifier) if slot is None: continue - self._add_track(owner, clip, slot) + add_track(owner, clip.name, clip.action, slot, self.scene, active=self.mode == MODE_ACTIVE, + frame_range=(clip.start, clip.end), loop=clip.loop) used.add(take) if first_time: self.stats.clips.append(f"{pathname}: {clip.name}") @@ -188,264 +181,3 @@ def _clips(self, info: ModelImporterInfo | None, cached: dict[str, bpy.types.Act continue clips.append(_Clip(setting.name, action, setting.first_frame + ANIM_OFFSET, setting.last_frame + ANIM_OFFSET, setting.loop)) return clips - - def _add_track(self, owner: bpy.types.ID, clip: _Clip, slot) -> None: - animation_data = owner.animation_data or owner.animation_data_create() - active = self.mode == MODE_ACTIVE and not any(not t.mute for t in animation_data.nla_tracks) - track = animation_data.nla_tracks.new() - track.name = clip.name - strip = track.strips.new(clip.name, int(self.scene.frame_start), clip.action) - if strip.action_slot != slot: - strip.action_slot = slot - set_strip_range(strip, clip.start, clip.end) - if clip.loop: - loop_strip(strip, self.scene) - track.mute = not active - - -def loop_strip(strip, scene: bpy.types.Scene) -> None: - """ループするクリップ(Unity の Loop Time)のストリップを、シーンのフレーム範囲の終わりまで繰り返す。 - - NLA はストリップの範囲の外を評価しない(Action の Cycles モディファイアーは範囲の中でしか働かない)ので、繰り返しの回数で表す。 - """ - length = strip.action_frame_end - strip.action_frame_start - if length <= 0: - return - span = scene.frame_end - strip.frame_start + 1 - strip.repeat = float(max(1, math.ceil(span / length))) - - -def set_strip_range(strip, start: float, end: float) -> None: - """ストリップが使う Action の範囲を変え、ストリップの長さをそれに合わせる(置く位置は変えない)。""" - begin = strip.frame_start - if start >= strip.action_frame_end: - strip.action_frame_end = end - strip.action_frame_start = start - else: - strip.action_frame_start = start - strip.action_frame_end = end - strip.frame_start = begin - strip.frame_end = begin + (end - start) * strip.scale * strip.repeat - - -# --------------------------------------------------------------------------- -# モーションだけのモデルのアーマチュアをまとめる -# --------------------------------------------------------------------------- - -# 骨格・配置が同じとみなす行列の差 -_TOLERANCE = 1e-4 - - -def _skeleton(armature: bpy.types.Object) -> tuple: - """ボーンの名前と親の組(骨格が同じかの判定に使う)。""" - return tuple(sorted((b.name, b.parent.name if b.parent else "") for b in armature.data.bones)) - - -def _close(a, b, tolerance: float = _TOLERANCE) -> bool: - return all(abs(x - y) <= tolerance for ra, rb in zip(a, b) for x, y in zip(ra, rb)) - - -def _placement(armature: bpy.types.Object) -> Matrix: - """アーマチュアを置いた場所(親のワールドの行列)。アーマチュア自身の Transform は、FBX のルートのボーンがオブジェクトになった - もの(Everyday Motion Pack の Bip001)だとファイルの最初のフレームの値で、モーションごとに違うので比べない。""" - return armature.parent.matrix_world.copy() if armature.parent else Matrix.Identity(4) - - -def _relative_rest(bone) -> Matrix: - return bone.parent.matrix_local.inverted_safe() @ bone.matrix_local if bone.parent else bone.matrix_local.copy() - - -def motion_rigs(objects: list[bpy.types.Object]) -> dict[str, bpy.types.Object]: - """モデルの GUID → モーションだけのモデルのアーマチュア(メッシュが無く、アーマチュアが 1 体で、NLA のトラックを持つもの)。""" - by_model: dict[str, list[bpy.types.Object]] = {} - for obj in objects: - guid = obj.get(MODEL_GUID_PROP) - if guid: - by_model.setdefault(str(guid), []).append(obj) - rigs = {} - for guid, members in by_model.items(): - if any(o.type not in ("ARMATURE", "EMPTY") for o in members): - continue - armatures = [o for o in members if o.type == "ARMATURE"] - if len(armatures) == 1 and armatures[0].animation_data is not None and armatures[0].animation_data.nla_tracks: - rigs[guid] = armatures[0] - return rigs - - -def merge_motion_rigs(objects: list[bpy.types.Object], model_order: list[str]) -> list[bpy.types.Object]: - """同じ骨格のモーションだけのアーマチュアを 1 体にまとめ、消すべきオブジェクトを返す。 - - 骨格(ボーンの名前と親子)と、アーマチュアのワールドの行列が同じものをまとめる。骨格は、ボーンの多いほうに少ないほうが - 含まれていればよい(武器を持たせるボーンが無いモーションなど。無いボーンはレストのまま)。残すのはボーンがいちばん多く、 - その中で先に読んだモデルのアーマチュア。スキンの無い FBX は、ファイルの既定の姿勢を - レストにするので、レスト姿勢はファイルごとに違う。そのため、残すアーマチュアのレストで同じ姿勢になるようにキーを変換した - Action を作って、トラックを写す(``retarget_action``)。消すのは、まとめたモデルの全オブジェクト(アーマチュアと、その上の Empty)。 - """ - rigs = motion_rigs(objects) - order = {guid: i for i, guid in enumerate(model_order)} - groups: list[list[tuple[str, bpy.types.Object]]] = [] - ranked = sorted(rigs.items(), key=lambda item: (-len(item[1].data.bones), order.get(item[0], len(order)))) - for guid, armature in ranked: - for group in groups: - first = group[0][1] - if set(_skeleton(armature)) <= set(_skeleton(first)) and _close(_placement(first), _placement(armature)): - group.append((guid, armature)) - break - else: - groups.append([(guid, armature)]) - removed_models: set[str] = set() - converted: dict[tuple[int, int], bpy.types.Action] = {} - for members in groups: - if len(members) < 2: - continue - keeper = members[0][1] - for guid, armature in members[1:]: - for track in armature.animation_data.nla_tracks: - for strip in track.strips: - key = (strip.action.as_pointer(), keeper.as_pointer()) - if key not in converted: - converted[key] = retarget_action(strip.action, strip.action_slot, armature, keeper) - copy_track(keeper.animation_data, track, strip, converted[key]) - removed_models.add(guid) - return [o for o in objects if str(o.get(MODEL_GUID_PROP, "")) in removed_models] - - -def copy_track(animation_data, track, strip, action: bpy.types.Action) -> None: - """``strip`` と同じ範囲・名前のトラックを ``animation_data`` に足す(Action は ``action`` に差し替える)。""" - has_active = any(not t.mute for t in animation_data.nla_tracks) - new_track = animation_data.nla_tracks.new() - new_track.name = track.name - new_strip = new_track.strips.new(strip.name, int(strip.frame_start), action) - slot = action.slots.get(strip.action_slot.identifier) if strip.action_slot is not None else None - if slot is not None and new_strip.action_slot != slot: - new_strip.action_slot = slot - set_strip_range(new_strip, strip.action_frame_start, strip.action_frame_end) - new_strip.repeat = strip.repeat - new_track.mute = track.mute or has_active - - -_BONE_PATH = re.compile(r'^pose\.bones\["((?:[^"\\]|\\.)*)"\]\.(location|rotation_quaternion|rotation_euler|scale)$') - - -def retarget_action(action: bpy.types.Action, slot, source: bpy.types.Object, target: bpy.types.Object) -> bpy.types.Action: - """``source`` のレストで作られた ``action`` を、``target`` のレストで同じ姿勢になる Action にする。 - - ボーンのローカルの行列 B(レストからの差分)は、親からの相対のレスト R と合わせて R·B が姿勢を決める。レストが R' のボーンで - 同じ姿勢にするには B' = R'⁻¹·R·B。R が R' と同じボーンのカーブはそのまま写し、違うボーンはキーの時刻ごとに求め直す - (補間は LINEAR。FBX のモーションはフレームごとにキーがあるので、見た目は変わらない)。 - - オブジェクトの Transform のカーブは絶対値なのでそのまま使う。動かさないチャンネルは ``source`` の値を一定のキーで足す - (残すアーマチュアの値のままにしない)。 - """ - corrections: dict[str, Matrix] = {} - for bone in source.data.bones: - other = target.data.bones.get(bone.name) - if other is None: - continue - correction = _relative_rest(other).inverted_safe() @ _relative_rest(bone) - if not _close(correction, Matrix.Identity(4), 1e-5): - corrections[bone.name] = correction - same_basis = _close(source.matrix_basis, target.matrix_basis, _TOLERANCE) and source.rotation_mode == target.rotation_mode - if not corrections and same_basis: - return action - new = action.copy() - new.name = action.name - for key in (TAKE_PROP, TAKE_MODEL_PROP): - if key in action: - new[key] = action[key] - for layer in new.layers: - for strip in layer.strips: - for channelbag in strip.channelbags: - _retarget_channelbag(channelbag, corrections, target) - if not same_basis and channelbag.slot.target_id_type == "OBJECT": - _hold_object_transform(channelbag, source, target) - return new - - -def _hold_object_transform(channelbag, source: bpy.types.Object, target: bpy.types.Object) -> None: - """``channelbag`` が動かさないオブジェクトの Transform のチャンネルに、``source`` の値の一定のキーを足す。""" - location, rotation, scale = source.matrix_basis.decompose() - mode = target.rotation_mode - if mode == "QUATERNION": - rotation_path, rotation_values = "rotation_quaternion", tuple(rotation) - elif mode == "AXIS_ANGLE": - axis, angle = rotation.to_axis_angle() - rotation_path, rotation_values = "rotation_axis_angle", (angle, *axis) - else: - rotation_path, rotation_values = "rotation_euler", tuple(rotation.to_euler(mode)) - existing = {(fc.data_path, fc.array_index) for fc in channelbag.fcurves} - animated = {path for path, _ in existing} - for path, values in (("location", tuple(location)), (rotation_path, rotation_values), ("scale", tuple(scale))): - if path == rotation_path and animated & {"rotation_quaternion", "rotation_euler", "rotation_axis_angle"}: - continue - for index, value in enumerate(values): - if (path, index) in existing: - continue - fcurve = channelbag.fcurves.new(path, index=index) - fcurve.keyframe_points.insert(1.0, value) - - -def _retarget_channelbag(channelbag, corrections: dict[str, Matrix], target: bpy.types.Object) -> None: - by_bone: dict[str, dict[str, dict[int, bpy.types.FCurve]]] = {} - for fcurve in channelbag.fcurves: - match = _BONE_PATH.match(fcurve.data_path) - if match and match.group(1).replace('\\"', '"') in corrections: - by_bone.setdefault(match.group(1), {}).setdefault(match.group(2), {})[fcurve.array_index] = fcurve - for escaped, channels in by_bone.items(): - name = escaped.replace('\\"', '"') - correction = corrections[name] - pose_bone = target.pose.bones.get(name) - mode = pose_bone.rotation_mode if pose_bone is not None else "QUATERNION" - times = sorted({k.co.x for curves in channels.values() for fc in curves.values() for k in fc.keyframe_points}) - if not times: - continue - - def value(prop: str, index: int, frame: float, default: float) -> float: - fcurve = channels.get(prop, {}).get(index) - return fcurve.evaluate(frame) if fcurve is not None else default - - samples = [] - previous = None - for frame in times: - location = Vector([value("location", i, frame, 0.0) for i in range(3)]) - scale = Vector([value("scale", i, frame, 1.0) for i in range(3)]) - if "rotation_quaternion" in channels: - rotation = Quaternion([value("rotation_quaternion", i, frame, 1.0 if i == 0 else 0.0) for i in range(4)]) - else: - order = mode if mode not in ("QUATERNION", "AXIS_ANGLE") else "XYZ" - rotation = Euler([value("rotation_euler", i, frame, 0.0) for i in range(3)], order).to_quaternion() - basis = correction @ Matrix.LocRotScale(location, rotation, scale) - loc, rot, sca = basis.decompose() - if previous is not None and previous.dot(rot) < 0: - rot.negate() - previous = rot - samples.append((frame, loc, rot, sca)) - for curves in channels.values(): - for fcurve in curves.values(): - channelbag.fcurves.remove(fcurve) - path = f'pose.bones["{escaped}"]' - euler_order = mode if mode not in ("QUATERNION", "AXIS_ANGLE") else None - columns = [("location", 3, lambda s, i: s[1][i]), ("scale", 3, lambda s, i: s[3][i])] - if euler_order is None: - columns.append(("rotation_quaternion", 4, lambda s, i: s[2][i])) - else: - eulers = [] - last = None - for sample in samples: - euler = sample[2].to_euler(euler_order, last) if last is not None else sample[2].to_euler(euler_order) - eulers.append(euler) - last = euler - lookup = {id(s): e for s, e in zip(samples, eulers)} - columns.append(("rotation_euler", 3, lambda s, i: lookup[id(s)][i])) - for prop, size, get in columns: - for index in range(size): - fcurve = channelbag.fcurves.new(f"{path}.{prop}", index=index) - fcurve.group = channelbag.groups.get(name) or channelbag.groups.new(name) - points = fcurve.keyframe_points - points.add(len(samples)) - flat = [] - for sample in samples: - flat += [sample[0], get(sample, index)] - points.foreach_set("co", flat) - points.foreach_set("interpolation", [_LINEAR] * len(samples)) - fcurve.update() diff --git a/unitypackage_loader/blender/importer.py b/unitypackage_loader/blender/importer.py index 125cc9f..5a076bb 100644 --- a/unitypackage_loader/blender/importer.py +++ b/unitypackage_loader/blender/importer.py @@ -39,7 +39,7 @@ from . import outline as outline_builder from .animation import ClipImporter from .animation import report_lines as clip_report_lines -from .fbx_motion import MODE_NONE, MotionBuilder, merge_motion_rigs +from .fbx_motion import MotionBuilder from .log import record_failure, warn_skipped from .model_import import ( FBX_NODE_PROP, @@ -59,6 +59,7 @@ snapshot, vrm_addon_available, ) +from .nla import MODE_NONE from .options import ImportOptions from .prepare import ( BLEND_DISABLED_REASON, @@ -69,6 +70,7 @@ build_shader_table, prepare_package, ) +from .rig_merge import merge_motion_rigs from .scene_objects import ( arrange_collections, find_layer_collection, hide_objects, move_collection_contents, remove_parts, diff --git a/unitypackage_loader/blender/nla.py b/unitypackage_loader/blender/nla.py new file mode 100644 index 0000000..3ce0753 --- /dev/null +++ b/unitypackage_loader/blender/nla.py @@ -0,0 +1,82 @@ +"""読み込んだクリップを NLA のトラックに置く共通の処理(.anim は ``animation.py``、モデルのテイクは ``fbx_motion.py``)。 + +- クリップごとに、クリップの名前のトラックを 1 本足し、ストリップを 1 つ置く。 +- Animation のオプション(Muted / Active / None)が Active なら、対象ごとに最初の 1 本だけミュートを外す。残りはミュート。 +- ループするクリップ(Unity の Loop Time)は、ストリップの繰り返しでシーンのフレーム範囲の終わりまで伸ばす。 +""" + +from __future__ import annotations + +import math + +import bpy + +# Animation のオプションの値(``ImportOptions.animation``) +MODE_MUTED = "MUTED" +MODE_ACTIVE = "ACTIVE" +MODE_NONE = "NONE" + + +def add_track(owner: bpy.types.ID, name: str, action: bpy.types.Action, slot, scene: bpy.types.Scene, *, + active: bool, frame_range: tuple[float, float] | None = None, loop: bool = False) -> bpy.types.NlaStrip: + """``owner`` に ``name`` のトラックを足し、シーンの最初のフレームに ``action`` のストリップを置く。 + + ``active`` は Animation が Active かどうか。そのときでも、ミュートを外すのは ``owner`` の最初のトラックだけ。 + ``frame_range`` は使う Action の範囲(無ければ Action 全体)。``loop`` ならシーンの終わりまで繰り返す。 + """ + animation_data = owner.animation_data or owner.animation_data_create() + # 新しいトラックはミュートされていない状態で作られるので、足す前に数える + unmute = active and not any(not t.mute for t in animation_data.nla_tracks) + track = animation_data.nla_tracks.new() + track.name = name + strip = track.strips.new(name, int(scene.frame_start), action) + if slot is not None and strip.action_slot != slot: + strip.action_slot = slot + if frame_range is not None: + set_strip_range(strip, *frame_range) + if loop: + loop_strip(strip, scene) + track.mute = not unmute + return strip + + +def copy_track(animation_data, track, strip, action: bpy.types.Action) -> None: + """``strip`` と同じ範囲・名前・繰り返しのトラックを ``animation_data`` に足す(Action は ``action`` に差し替える)。 + + 元のトラックがミュートでなくても、``animation_data`` にミュートでないトラックがすでにあればミュートにする。 + """ + has_active = any(not t.mute for t in animation_data.nla_tracks) + new_track = animation_data.nla_tracks.new() + new_track.name = track.name + new_strip = new_track.strips.new(strip.name, int(strip.frame_start), action) + slot = action.slots.get(strip.action_slot.identifier) if strip.action_slot is not None else None + if slot is not None and new_strip.action_slot != slot: + new_strip.action_slot = slot + set_strip_range(new_strip, strip.action_frame_start, strip.action_frame_end) + new_strip.repeat = strip.repeat + new_track.mute = track.mute or has_active + + +def loop_strip(strip, scene: bpy.types.Scene) -> None: + """ループするクリップ(Unity の Loop Time)のストリップを、シーンのフレーム範囲の終わりまで繰り返す。 + + NLA はストリップの範囲の外を評価しない(Action の Cycles モディファイアーは範囲の中でしか働かない)ので、繰り返しの回数で表す。 + """ + length = strip.action_frame_end - strip.action_frame_start + if length <= 0: + return + span = scene.frame_end - strip.frame_start + 1 + strip.repeat = float(max(1, math.ceil(span / length))) + + +def set_strip_range(strip, start: float, end: float) -> None: + """ストリップが使う Action の範囲を変え、ストリップの長さをそれに合わせる(置く位置は変えない)。""" + begin = strip.frame_start + if start >= strip.action_frame_end: + strip.action_frame_end = end + strip.action_frame_start = start + else: + strip.action_frame_start = start + strip.action_frame_end = end + strip.frame_start = begin + strip.frame_end = begin + (end - start) * strip.scale * strip.repeat diff --git a/unitypackage_loader/blender/rig_merge.py b/unitypackage_loader/blender/rig_merge.py new file mode 100644 index 0000000..e7751bc --- /dev/null +++ b/unitypackage_loader/blender/rig_merge.py @@ -0,0 +1,225 @@ +"""モーションだけのモデルのアーマチュアを、同じ骨格のものどうしで 1 体にまとめる(#276。Models 単位)。 + +モーション集のパッケージは、モーションごとに FBX が分かれていて、読み込むとアーマチュアがモーションの数だけ並ぶ。 +メッシュが無く、アーマチュアが 1 体で、NLA のトラックを持つモデルを、骨格と置き場所が同じものどうしでまとめ、 +全部のトラックを 1 体に載せる。スキンの無い FBX はファイルの既定の姿勢をレストにするので、レストの違いはキーを変換して吸収する。 +""" + +from __future__ import annotations + +import re + +import bpy +from mathutils import Euler, Matrix, Quaternion, Vector + +from .fbx_motion import TAKE_MODEL_PROP, TAKE_PROP +from .model_import import MODEL_GUID_PROP +from .nla import copy_track + +# keyframe_points の interpolation に foreach_set で渡す LINEAR の値 +_LINEAR = bpy.types.Keyframe.bl_rna.properties["interpolation"].enum_items["LINEAR"].value + + +# 骨格・配置が同じとみなす行列の差 +_TOLERANCE = 1e-4 + + +def _skeleton(armature: bpy.types.Object) -> tuple: + """ボーンの名前と親の組(骨格が同じかの判定に使う)。""" + return tuple(sorted((b.name, b.parent.name if b.parent else "") for b in armature.data.bones)) + + +def _close(a, b, tolerance: float = _TOLERANCE) -> bool: + return all(abs(x - y) <= tolerance for ra, rb in zip(a, b) for x, y in zip(ra, rb)) + + +def _placement(armature: bpy.types.Object) -> Matrix: + """アーマチュアを置いた場所(親のワールドの行列)。アーマチュア自身の Transform は、FBX のルートのボーンがオブジェクトになった + もの(Everyday Motion Pack の Bip001)だとファイルの最初のフレームの値で、モーションごとに違うので比べない。""" + return armature.parent.matrix_world.copy() if armature.parent else Matrix.Identity(4) + + +def _relative_rest(bone) -> Matrix: + return bone.parent.matrix_local.inverted_safe() @ bone.matrix_local if bone.parent else bone.matrix_local.copy() + + +def motion_rigs(objects: list[bpy.types.Object]) -> dict[str, bpy.types.Object]: + """モデルの GUID → モーションだけのモデルのアーマチュア(メッシュが無く、アーマチュアが 1 体で、NLA のトラックを持つもの)。""" + by_model: dict[str, list[bpy.types.Object]] = {} + for obj in objects: + guid = obj.get(MODEL_GUID_PROP) + if guid: + by_model.setdefault(str(guid), []).append(obj) + rigs = {} + for guid, members in by_model.items(): + if any(o.type not in ("ARMATURE", "EMPTY") for o in members): + continue + armatures = [o for o in members if o.type == "ARMATURE"] + if len(armatures) == 1 and armatures[0].animation_data is not None and armatures[0].animation_data.nla_tracks: + rigs[guid] = armatures[0] + return rigs + + +def merge_motion_rigs(objects: list[bpy.types.Object], model_order: list[str]) -> list[bpy.types.Object]: + """同じ骨格のモーションだけのアーマチュアを 1 体にまとめ、消すべきオブジェクトを返す。 + + 骨格(ボーンの名前と親子)と、アーマチュアのワールドの行列が同じものをまとめる。骨格は、ボーンの多いほうに少ないほうが + 含まれていればよい(武器を持たせるボーンが無いモーションなど。無いボーンはレストのまま)。残すのはボーンがいちばん多く、 + その中で先に読んだモデルのアーマチュア。スキンの無い FBX は、ファイルの既定の姿勢を + レストにするので、レスト姿勢はファイルごとに違う。そのため、残すアーマチュアのレストで同じ姿勢になるようにキーを変換した + Action を作って、トラックを写す(``retarget_action``)。消すのは、まとめたモデルの全オブジェクト(アーマチュアと、その上の Empty)。 + """ + rigs = motion_rigs(objects) + order = {guid: i for i, guid in enumerate(model_order)} + groups: list[list[tuple[str, bpy.types.Object]]] = [] + ranked = sorted(rigs.items(), key=lambda item: (-len(item[1].data.bones), order.get(item[0], len(order)))) + for guid, armature in ranked: + for group in groups: + first = group[0][1] + if set(_skeleton(armature)) <= set(_skeleton(first)) and _close(_placement(first), _placement(armature)): + group.append((guid, armature)) + break + else: + groups.append([(guid, armature)]) + removed_models: set[str] = set() + converted: dict[tuple[int, int], bpy.types.Action] = {} + for members in groups: + if len(members) < 2: + continue + keeper = members[0][1] + for guid, armature in members[1:]: + for track in armature.animation_data.nla_tracks: + for strip in track.strips: + key = (strip.action.as_pointer(), keeper.as_pointer()) + if key not in converted: + converted[key] = retarget_action(strip.action, strip.action_slot, armature, keeper) + copy_track(keeper.animation_data, track, strip, converted[key]) + removed_models.add(guid) + return [o for o in objects if str(o.get(MODEL_GUID_PROP, "")) in removed_models] + + +_BONE_PATH = re.compile(r'^pose\.bones\["((?:[^"\\]|\\.)*)"\]\.(location|rotation_quaternion|rotation_euler|scale)$') + + +def retarget_action(action: bpy.types.Action, slot, source: bpy.types.Object, target: bpy.types.Object) -> bpy.types.Action: + """``source`` のレストで作られた ``action`` を、``target`` のレストで同じ姿勢になる Action にする。 + + ボーンのローカルの行列 B(レストからの差分)は、親からの相対のレスト R と合わせて R·B が姿勢を決める。レストが R' のボーンで + 同じ姿勢にするには B' = R'⁻¹·R·B。R が R' と同じボーンのカーブはそのまま写し、違うボーンはキーの時刻ごとに求め直す + (補間は LINEAR。FBX のモーションはフレームごとにキーがあるので、見た目は変わらない)。 + + オブジェクトの Transform のカーブは絶対値なのでそのまま使う。動かさないチャンネルは ``source`` の値を一定のキーで足す + (残すアーマチュアの値のままにしない)。 + """ + corrections: dict[str, Matrix] = {} + for bone in source.data.bones: + other = target.data.bones.get(bone.name) + if other is None: + continue + correction = _relative_rest(other).inverted_safe() @ _relative_rest(bone) + if not _close(correction, Matrix.Identity(4), 1e-5): + corrections[bone.name] = correction + same_basis = _close(source.matrix_basis, target.matrix_basis, _TOLERANCE) and source.rotation_mode == target.rotation_mode + if not corrections and same_basis: + return action + new = action.copy() + new.name = action.name + for key in (TAKE_PROP, TAKE_MODEL_PROP): + if key in action: + new[key] = action[key] + for layer in new.layers: + for strip in layer.strips: + for channelbag in strip.channelbags: + _retarget_channelbag(channelbag, corrections, target) + if not same_basis and channelbag.slot.target_id_type == "OBJECT": + _hold_object_transform(channelbag, source, target) + return new + + +def _hold_object_transform(channelbag, source: bpy.types.Object, target: bpy.types.Object) -> None: + """``channelbag`` が動かさないオブジェクトの Transform のチャンネルに、``source`` の値の一定のキーを足す。""" + location, rotation, scale = source.matrix_basis.decompose() + mode = target.rotation_mode + if mode == "QUATERNION": + rotation_path, rotation_values = "rotation_quaternion", tuple(rotation) + elif mode == "AXIS_ANGLE": + axis, angle = rotation.to_axis_angle() + rotation_path, rotation_values = "rotation_axis_angle", (angle, *axis) + else: + rotation_path, rotation_values = "rotation_euler", tuple(rotation.to_euler(mode)) + existing = {(fc.data_path, fc.array_index) for fc in channelbag.fcurves} + animated = {path for path, _ in existing} + for path, values in (("location", tuple(location)), (rotation_path, rotation_values), ("scale", tuple(scale))): + if path == rotation_path and animated & {"rotation_quaternion", "rotation_euler", "rotation_axis_angle"}: + continue + for index, value in enumerate(values): + if (path, index) in existing: + continue + fcurve = channelbag.fcurves.new(path, index=index) + fcurve.keyframe_points.insert(1.0, value) + + +def _retarget_channelbag(channelbag, corrections: dict[str, Matrix], target: bpy.types.Object) -> None: + by_bone: dict[str, dict[str, dict[int, bpy.types.FCurve]]] = {} + for fcurve in channelbag.fcurves: + match = _BONE_PATH.match(fcurve.data_path) + if match and match.group(1).replace('\\"', '"') in corrections: + by_bone.setdefault(match.group(1), {}).setdefault(match.group(2), {})[fcurve.array_index] = fcurve + for escaped, channels in by_bone.items(): + name = escaped.replace('\\"', '"') + correction = corrections[name] + pose_bone = target.pose.bones.get(name) + mode = pose_bone.rotation_mode if pose_bone is not None else "QUATERNION" + times = sorted({k.co.x for curves in channels.values() for fc in curves.values() for k in fc.keyframe_points}) + if not times: + continue + + def value(prop: str, index: int, frame: float, default: float) -> float: + fcurve = channels.get(prop, {}).get(index) + return fcurve.evaluate(frame) if fcurve is not None else default + + samples = [] + previous = None + for frame in times: + location = Vector([value("location", i, frame, 0.0) for i in range(3)]) + scale = Vector([value("scale", i, frame, 1.0) for i in range(3)]) + if "rotation_quaternion" in channels: + rotation = Quaternion([value("rotation_quaternion", i, frame, 1.0 if i == 0 else 0.0) for i in range(4)]) + else: + order = mode if mode not in ("QUATERNION", "AXIS_ANGLE") else "XYZ" + rotation = Euler([value("rotation_euler", i, frame, 0.0) for i in range(3)], order).to_quaternion() + basis = correction @ Matrix.LocRotScale(location, rotation, scale) + loc, rot, sca = basis.decompose() + if previous is not None and previous.dot(rot) < 0: + rot.negate() + previous = rot + samples.append((frame, loc, rot, sca)) + for curves in channels.values(): + for fcurve in curves.values(): + channelbag.fcurves.remove(fcurve) + path = f'pose.bones["{escaped}"]' + euler_order = mode if mode not in ("QUATERNION", "AXIS_ANGLE") else None + columns = [("location", 3, lambda s, i: s[1][i]), ("scale", 3, lambda s, i: s[3][i])] + if euler_order is None: + columns.append(("rotation_quaternion", 4, lambda s, i: s[2][i])) + else: + eulers = [] + last = None + for sample in samples: + euler = sample[2].to_euler(euler_order, last) if last is not None else sample[2].to_euler(euler_order) + eulers.append(euler) + last = euler + lookup = {id(s): e for s, e in zip(samples, eulers)} + columns.append(("rotation_euler", 3, lambda s, i: lookup[id(s)][i])) + for prop, size, get in columns: + for index in range(size): + fcurve = channelbag.fcurves.new(f"{path}.{prop}", index=index) + fcurve.group = channelbag.groups.get(name) or channelbag.groups.new(name) + points = fcurve.keyframe_points + points.add(len(samples)) + flat = [] + for sample in samples: + flat += [sample[0], get(sample, index)] + points.foreach_set("co", flat) + points.foreach_set("interpolation", [_LINEAR] * len(samples)) + fcurve.update() diff --git a/unitypackage_loader/blender_manifest.toml b/unitypackage_loader/blender_manifest.toml index c6d1550..b3cc4ab 100644 --- a/unitypackage_loader/blender_manifest.toml +++ b/unitypackage_loader/blender_manifest.toml @@ -1,7 +1,7 @@ schema_version = "1.0.0" id = "unitypackage_loader" -version = "1.18.0-dev.13" +version = "1.18.0-dev.14" name = "Unitypackage Importer" tagline = "Import meshes, materials and textures from .unitypackage files" maintainer = "utagestudio"