From 4e50b07e5974e172f4f16e318cc4136bae849028 Mon Sep 17 00:00:00 2001 From: utagestudio Date: Sat, 28 Nov 2026 16:08:23 +0900 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20Generic=20=E3=81=AA=20.anim=20?= =?UTF-8?q?=E3=81=AE=E3=83=9C=E3=83=BC=E3=83=B3=E3=81=AE=20Transform=20?= =?UTF-8?q?=E3=81=AE=E3=82=AB=E3=83=BC=E3=83=96=E3=82=92=E3=83=9D=E3=83=BC?= =?UTF-8?q?=E3=82=BA=E3=83=9C=E3=83=BC=E3=83=B3=E3=81=AB=E8=AA=AD=E3=81=BF?= =?UTF-8?q?=E8=BE=BC=E3=82=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #209 では読み飛ばしていた、ボーンを対象にした m_PositionCurves / m_RotationCurves / m_EulerCurves / m_ScaleCurves を、 ポーズボーンの位置・回転・スケールのキーにする(#270)。 - 新旧どちらの FBX インポーターも、このアドオンの呼び方ではボーンの軸を付け替えない(3ds Max・Maya・MotionBuilder・ Unity FBX Exporter・Blender の FBX 10 本で、新旧のボーンの行列が一致)。そのため、親(親のボーンかアーマチュア)から 見たボーンの行列はオブジェクトの子と同じ A⁻¹·L·A になる。Issue に書いた軸の補正は要らなかった。 - フレームごとに祖先から順にポーズの行列を求め、Bone.convert_local_to_pose でポーズボーンの値にする。新しいインポーターが Maya の FBX で inherit_scale を NONE にするボーンも、これで正しく扱える。 - Unity 6 で .anim をサンプリングした値と突き合わせた。Ghoul Crew の Scavenger(Maya)はフレームの時刻で位置・回転とも一致し、 Thalassophobia のサメ(Blender)は補間の差(1.3 mm・0.04°)だけだった。 - 同点の結び付き先が別々のモデルにまたがるときは、クリップとフォルダが近いモデルだけに付ける(prefer_nearest_models)。 ボーン名が共通の Ghoul Crew では、各クリップが 10 体すべてのアーマチュアに付いていた。 - 速さのために、カーブを時刻の列でまとめて評価し(evaluate_many / transform_specs)、クリップの中で使い回す。値が変わらない チャンネルはキー 1 つにし、キーがフレームより密なときはキーの時刻を足さない。Ghoul Crew(.anim 45 本)で読み込みは main より約 6 秒増える。 - Blender 4.5 の channelbag.fcurves.new は group_name を取らないので、グループは後から付ける。 - 合成パッケージの Wave.anim を、Hips の位置・回転と Spine のオイラー回転・スケールに作り替え、期待値は Unity 6 で再生した ボーンの向きと位置にした。統合テストにボーンの頭の位置のチェック(bone_head)を足した。 Closes #270 Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 4 +- DESIGN.md | 21 +- README.md | 10 +- README_ja.md | 9 +- tests/expectations_synthetic_anim.json | 8 +- tests/expectations_synthetic_anim_scene.json | 16 ++ tests/integration_import.py | 6 + tests/make_synthetic_anim_package.py | 17 +- tests/test_animation.py | 49 +++- unitypackage_loader/blender/animation.py | 211 ++++++++++++++++-- unitypackage_loader/blender_manifest.toml | 2 +- unitypackage_loader/core/animation.py | 55 ++++- unitypackage_loader/core/animation_targets.py | 36 ++- 13 files changed, 399 insertions(+), 45 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 2df394a..c582fa2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,8 +8,8 @@ - メッシュ(アーマチュア・シェイプキー込み)に、Unity 側のマテリアル設定とテクスチャを反映した状態で読み込む。 - Unity と Blender のマテリアルは 1:1 に対応しないので「参考にできる値だけ」を反映し、残りはカスタムプロパティに保存する。 -- シェーダー本体、C#、Humanoid のアニメーション・ボーンのカーブ・Animator Controller、Expression メニュー等は読み込まない。 - Generic な `.anim`(シェイプキー・表示の切り替え・オブジェクトの Transform)は、ミュートした NLA トラックの Action にする(`core/animation.py`。#209)。 +- シェーダー本体、C#、Humanoid のアニメーション・Animator Controller、Expression メニュー等は読み込まない。 + Generic な `.anim`(シェイプキー・表示の切り替え・オブジェクトとボーンの Transform)は、ミュートした NLA トラックの Action にする(`core/animation.py`。#209 / #270)。 値が変わらないか 0.1 秒以下で終わる、状態を切り替えるだけのクリップ(Animator のステート用)は読み込まない。 FBX の中のテイクは、.meta の clipAnimations どおりのクリップにして同じく NLA に並べ、同じ骨格のモーションだけのモデルは レストの違いを変換して 1 体のアーマチュアにまとめる(`blender/fbx_motion.py` と `rig_merge.py`。NLA への置き方は両方で `nla.py`。#276)。オプションは Animation(Muted / Active / None)。 diff --git a/DESIGN.md b/DESIGN.md index 203e7ab..c7a4722 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -323,7 +323,7 @@ Material: - モデルの中のモーション: FBX のテイクを、.meta の `clipAnimations` どおりのクリップにして NLA に並べる。同じ骨格のモーションだけのモデルは 1 体のアーマチュアにまとめる(§4.7.2。#276)。 ### 読み込まない -- シェーダー本体(`.shader` `.cginc`)、C#(`.cs` `.dll`)、Animator Controller(`.controller`)と Humanoid の `.anim`・ボーンのカーブ(§4.7.1)、Expression/Parameter アセット、PhysBone 等の MonoBehaviour、prefab 階層(シーンを読み込む場合はモデルの配置と、その上の GameObject、ライト・カメラだけ再現する)、アイコン画像、`preview.png`。 +- シェーダー本体(`.shader` `.cginc`)、C#(`.cs` `.dll`)、Animator Controller(`.controller`)と Humanoid の `.anim`(§4.7.1)、Expression/Parameter アセット、PhysBone 等の MonoBehaviour、prefab 階層(シーンを読み込む場合はモデルの配置と、その上の GameObject、ライト・カメラだけ再現する)、アイコン画像、`preview.png`。 ### マテリアルの対応方針 Unity と 1:1 は不可能なので、**「Unity マテリアル → シェーダー非依存の中間表現(NormalizedMaterial)→ Blender ノード」** の 2 段変換にし、シェーダーごとの差は「プロファイル」に閉じ込める(§4.5)。 @@ -1091,7 +1091,9 @@ def run(ctx, filepath, opts) -> Report: - **対象の決め方**(`core/animation_targets.py`): クリップは Animator を付けた GameObject からの相対パスしか持たないので、読み込んだ階層 (パッケージのコレクションの全オブジェクト)で、パスがいちばん多く解決できるオブジェクトをルートとみなす。Models 単位のように ルートのオブジェクトが無いときは、コレクションごとの最上位のオブジェクトの集まりをルートの候補にする。解決できたパスが半分に満たなければ付けない。 - 同じだけ解決できるルートはすべて対象にする(シーンに同じモデルを複数置いたとき)。ただし別のルートの子孫は外す(prefab の GameObject と、その下に置いた + 同じだけ解決できるルートはすべて対象にする(シーンに同じモデルを複数置いたとき)。ただし、それが別々のモデルにまたがるときは、クリップと先頭から共通する + フォルダがいちばん多いモデルのものだけを残す(`prefer_nearest_models`。#270。Ghoul Crew は 5 体の骨格のボーン名が共通で、クリップがすべての体に付いていた。 + `Ghoul-Scavenger/Animations/run.anim` は `Ghoul-Scavenger/Source/` の通常版と allinone 版の 2 体に付く)。また別のルートの子孫は外す(prefab の GameObject と、その下に置いた FBX の同じ名前のノードを、両方動かさない。Super Cub の prefab で見つけた)。名前は完全一致 → 連番を外した形が 1 つだけの順で引き、 Blender の FBX インポーターがアーマチュアの子にしたスキンメッシュは、Unity と同じくアーマチュアの親の子としても引く。アーマチュアの下はボーン名でたどる。 読み込み側が足した Empty(FBX のルートなど)で一致しなければ、Empty の子を 1 段だけ探す。空のパス(ルート自身)だけのクリップは、 @@ -1110,8 +1112,19 @@ def run(ctx, filepath, opts) -> Report: シーン・prefab の GameObject の Empty と Unity の Mesh・組み込みメッシュのオブジェクトが C·L·C⁻¹。A はモデルの `ModelUnits.basis_a` で、 オブジェクトに残した元のモデルの GUID(`unity_model_guid`)から引く。スキンメッシュ・ボーンの子・ライト・カメラ・Terrain・デカールは Unity と親子や形が違うので当てずに数える。アニメーションしない成分は元の値(オイラー角は元の回転を同じ順のオイラー角にした値)を使う。 - - ボーンのカーブは読み込まない(#270。FBX インポーターがボーンの軸を付け替えるので、レスト姿勢の差の補正が要る)。 -- **レポート**: 読み込んだクリップの数を要約に、読まなかったものの内訳(状態のクリップ、Humanoid、ボーンだけ、ルートだけ、当てはまらない、対象が無いカーブ)を + - ボーンの Transform(#270): 新旧どちらの FBX インポーターも、このアドオンの呼び方(ボーンの軸の付け替えのオプションは既定のまま)では + ボーンの軸を付け替えず、ポーズボーンの行列(アーマチュアの空間)は FBX のノードの行列そのもの。3ds Max・Maya・MotionBuilder・Unity FBX Exporter・ + Blender で作った 10 本の FBX で、新旧のボーンの行列(レストとポーズ)が一致した。インポーターが足したアーマチュア(Maya の FBX の `Armature`)の + 行列は C·A で、Unity の値が単位行列のノードと同じ。どちらの場合も、親(親のボーンかアーマチュアのオブジェクト)から見たボーンの行列は + Q = A⁻¹·L·A になる。フレームごとに、動かすボーンとその祖先のポーズの行列を親から順に求め、目標の行列 M_parent·Q を + `Bone.convert_local_to_pose`(invert)でポーズボーンの値にする。継承の設定もここで扱う(新しいインポーターは Maya の Segment Scale Compensate の + ボーンを `inherit_scale = NONE` にする)。アニメーションしない成分は、読み込んだときのポーズから L₀ = A·Q₀·A⁻¹ を求めて使う。 + 回転はクォータニオンの符号を前のフレームにそろえ、値が変わらないチャンネルはキー 1 つにする。カーブの値はクリップの中で使い回す + (同じ骨格の複数のモデル・配置)。Unity 6 で .anim をサンプリングした各ボーンのワールドの値と突き合わせ、Ghoul Crew の Scavenger(Maya。 + run / attack)はフレームの時刻で位置・回転とも一致、Thalassophobia のサメ(Blender)はシーンのフレームレートとの補間の差だけ(1.3 mm・0.04°)だった。 + GameObject の `m_IsActive` などボーンへの Transform 以外のカーブは読まずに数える。 + - 焼く時刻は、キーの時刻の数がフレームの数より多い(毎フレームに焼いたモーション)ときはフレームだけにする(`sample_times`)。 +- **レポート**: 読み込んだクリップの数を要約に、読まなかったものの内訳(状態のクリップ、Humanoid、ルートだけ、当てはまらない、対象が無いカーブ、ボーンへの Transform 以外のカーブ)を `clip_notes` に出す(警告にはしない)。 - Python から `NlaTrack.mute` を切り替えても依存関係は組み直されず、一度評価したトラックは切り替わらない(NLA エディターでの切り替えでは組み直される)。 統合テストはコレクションを付け外しして組み直させてから値を確かめる。 diff --git a/README.md b/README.md index 19b288b..6621027 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ A Blender Extension that imports `.unitypackage` files directly from File > Impo - Supported Blender: 4.5 or later (developed on 5.2 LTS, tested on 4.5 LTS and 5.2 LTS) - What is imported: FBX / OBJ / glTF / VRM / Collada (Blender 4.5 only; removed in Blender 5.0) / bundled .blend files (opt-in), `.mat` files (lilToon / MToon / Poiyomi / Standard / URP / HDRP / VRChat Mobile (Quest) shaders; others on a best-effort basis using generic rules), referenced textures, and animation as actions on muted NLA tracks: the animation takes inside models (split into Unity's clips; motion-only FBX files with the same skeleton are merged into one armature) and Generic animation clips (`.anim`: blend shapes, object visibility and transforms) -- What is not imported: shader source code, C# scripts, Humanoid animation clips, animation curves on bones, Animator Controllers, Expression menus, etc. Prefab hierarchies, lights and cameras are reproduced only when a scene is imported. +- What is not imported: shader source code, C# scripts, Humanoid animation clips, Animator Controllers, Expression menus, etc. Prefab hierarchies, lights and cameras are reproduced only when a scene is imported. - VRM: when the [VRM format](https://extensions.blender.org/add-ons/vrm/) add-on is installed, `.vrm` models are handed to it (MToon materials, humanoid rig, spring bones and expressions are reproduced by the add-on). Without it, the glTF importer is used and materials are rebuilt from the bundled `.mat` files. ## Installation @@ -198,10 +198,12 @@ Generic animation clips (`.anim`) in the package become one action per clip. The - Blend shape weights (`blendShape.`, 0–100 in Unity) → shape key values (0–1) - GameObject active state (`m_IsActive`) and Renderer `m_Enabled` → `hide_viewport` / `hide_render` (deactivating a GameObject also hides its children) - Transform position, rotation (quaternion or Euler) and scale → the object's location, rotation and scale, sampled every frame +- Bone transforms → the pose bone's location, rotation and scale, sampled every frame (components the clip does not animate keep the imported pose) A clip does not say which model it belongs to, so the importer looks for the imported object under which the most curve -paths resolve, and treats it as the object the clip is played on (all placements of the same model get the clip). -Each clip gets an NLA track on every object or shape key it animates. Keys start at the scene's start frame and use the scene's frame rate. +paths resolve, and treats it as the object the clip is played on (all placements of the same model get the clip; when different +models match equally well, as in character packs whose skeletons share bone names, the models in folders nearest to the clip get it). +Each clip gets an NLA track on every object or shape key it animates (bone keys go on the armature's track). Keys start at the scene's start frame and use the scene's frame rate. Looping clips (Loop Time in Unity) repeat their strip until the end of the scene's frame range. Clips that only switch a state are skipped: clips whose values never change, or that end within 0.1 seconds. Unity's @@ -209,7 +211,7 @@ Animator uses such clips as states and makes the motion with transitions (outfit the steering angle of a vehicle, and so on), so they have nothing to play back in Blender. Not imported (the report lists how many were skipped): state clips (above), Humanoid clips (the body motion is stored as muscle curves, so the whole clip is skipped, including its other curves; the original motion is usually in an FBX in the package, which is imported as above), -curves on bones, clips that only animate the object they are played on (no path, so the object is unknown), and curves on +clips that only animate the object they are played on (no path, so the object is unknown), and curves on materials or object references. Clips whose paths match no imported object are skipped too. Animator Controllers are not read. ### Security notes diff --git a/README_ja.md b/README_ja.md index 577358b..9c2a03e 100644 --- a/README_ja.md +++ b/README_ja.md @@ -9,7 +9,7 @@ Unity 側のマテリアル設定とテクスチャを反映した状態で配 - 対応 Blender: 4.5 以降(開発は 5.2 LTS、検証は 4.5 LTS と 5.2 LTS) - 読み込むもの: FBX / OBJ / glTF / VRM / Collada(Blender 4.5 のみ。5.0 で削除された)/ 同梱 .blend(オプトイン)、`.mat`(lilToon / MToon / Poiyomi / Standard / URP / HDRP / VRChat Mobile(Quest 向け)シェーダー、その他は一般規則で最善努力)、参照テクスチャ、アニメーション(ミュートした NLA トラックの Action にする。モデルの中のテイクを Unity のクリップどおりに分けたもの(同じ骨格のモーションだけの FBX は 1 体のアーマチュアにまとめる)と、Generic な `.anim` のシェイプキー・表示の切り替え・Transform) -- 読み込まないもの: シェーダー本体、C#、Humanoid のアニメーションクリップ、ボーンのアニメーションのカーブ、Animator Controller、Expression メニュー等。prefab の階層、ライト、カメラは、シーンを読み込むときだけ再現します +- 読み込まないもの: シェーダー本体、C#、Humanoid のアニメーションクリップ、Animator Controller、Expression メニュー等。prefab の階層、ライト、カメラは、シーンを読み込むときだけ再現します - VRM: [VRM format](https://extensions.blender.org/add-ons/vrm/) add-on が入っていれば `.vrm` はそちらに委譲します(MToon マテリアル、Humanoid リグ、スプリングボーン、表情は add-on が再現)。無ければ glTF インポーターで読み、同梱の `.mat` からマテリアルを組み直します。 ## インストール @@ -179,16 +179,17 @@ NLA トラックとして並べます(Models 単位)。スキンの無い FB - シェイプキーの重み(`blendShape.<名前>`。Unity では 0〜100)→ シェイプキーの値(0〜1) - GameObject のアクティブ(`m_IsActive`)と Renderer の `m_Enabled` → `hide_viewport` / `hide_render`(GameObject を非アクティブにすると子も隠れる) - Transform の位置・回転(クォータニオンかオイラー角)・スケール → オブジェクトの位置・回転・スケール(フレームごとに求める) +- ボーンの Transform → ポーズボーンの位置・回転・スケール(フレームごとに求める。動かさない成分は読み込んだときのポーズのまま) クリップは対象のモデルを持たないので、カーブの階層パスがいちばん多く当てはまる読み込んだオブジェクトを、クリップを再生する -オブジェクトとみなします(同じモデルを複数置いていれば、すべてに付けます)。動かすオブジェクトとシェイプキーごとに -NLA トラックを足します。キーはシーンの開始フレームから、シーンのフレームレートで並べます。ループするクリップ(Unity の Loop Time)は、シーンのフレーム範囲の終わりまでストリップを繰り返します。 +オブジェクトとみなします(同じモデルを複数置いていれば、すべてに付けます。ボーンの名前が共通のキャラクターのパックのように、別々のモデルが同じだけ当てはまるときは、クリップとフォルダが近いモデルに付けます)。動かすオブジェクトとシェイプキーごとに +NLA トラックを足します(ボーンのキーはアーマチュアのトラックに入ります)。キーはシーンの開始フレームから、シーンのフレームレートで並べます。ループするクリップ(Unity の Loop Time)は、シーンのフレーム範囲の終わりまでストリップを繰り返します。 状態を切り替えるだけのクリップ(値が変わらないもの、0.1 秒以下で終わるもの)は読み込みません。Unity の Animator はこうしたクリップを ステートとして使い、動きは遷移で作ります(VRChat のアバターの衣装の切り替えや表情、車両のハンドルの角度など)。 Blender では再生しても何も動かないためです。 -読み込まないもの(件数はレポートに出ます): 状態を切り替えるだけのクリップ(上記)、Humanoid のクリップ(体の動きがマッスル値で入っているため、ほかのカーブも含めてクリップごと外します。元のモーションはたいていパッケージの FBX にあり、上記のとおり読み込みます)、ボーンのカーブ、 +読み込まないもの(件数はレポートに出ます): 状態を切り替えるだけのクリップ(上記)、Humanoid のクリップ(体の動きがマッスル値で入っているため、ほかのカーブも含めてクリップごと外します。元のモーションはたいていパッケージの FBX にあり、上記のとおり読み込みます)、 再生するオブジェクト自身だけを動かすクリップ(パスが無く、どのオブジェクトか決められない)、マテリアルやオブジェクト参照のカーブ。 読み込んだオブジェクトにパスが当てはまらないクリップも外します。Animator Controller は読みません。 diff --git a/tests/expectations_synthetic_anim.json b/tests/expectations_synthetic_anim.json index 26ff6d6..a997d61 100644 --- a/tests/expectations_synthetic_anim.json +++ b/tests/expectations_synthetic_anim.json @@ -13,7 +13,6 @@ "skipped 2 animation clip(s) that only switch a state", "skipped 2 Humanoid animation clip", "skipped 1 animation clip(s) that only animate the object", - "skipped 4 animation curve(s) targeting bones", "1 animation clip(s) did not match" ], "tracks": { @@ -22,7 +21,7 @@ "Door": ["DoorOpen"], "Knob": ["DoorOpen"], "Body": ["Wave"], - "Armature": [] + "Armature": ["Wave"] }, "values": [ { "track": "Smile", "object": "Face", "seconds": 0, "shape_key": "smile", "value": 0.0 }, @@ -31,6 +30,11 @@ { "track": "HatOff", "object": "Hat", "seconds": 0, "hidden": false }, { "track": "HatOff", "object": "Hat", "seconds": 0.75, "hidden": true }, { "track": "Wave", "object": "Body", "seconds": 0, "hidden": true }, + { "track": "Wave", "object": "Armature", "seconds": 0, "bone_direction": { "bone": "Spine", "vector": [0, 0, 1] } }, + { "track": "Wave", "object": "Armature", "seconds": 0, "bone_head": { "bone": "Head", "location": [0, 0, 1.3] } }, + { "track": "Wave", "object": "Armature", "seconds": 0.5, "bone_head": { "bone": "Hips", "location": [-0.1, 0, 0.85] } }, + { "track": "Wave", "object": "Armature", "seconds": 0.5, "bone_direction": { "bone": "Spine", "vector": [-0.5, -0.5, 0.7071] } }, + { "track": "Wave", "object": "Armature", "seconds": 0.5, "bone_head": { "bone": "Head", "location": [-0.325, -0.225, 1.3682] } }, { "track": "DoorOpen", "object": "Door", "rotation_delta": { "from": 0, "to": 0.5, "axis": [0, 0, 1], "degrees": -45 } }, { "track": "DoorOpen", "object": "Door", "rotation_delta": { "from": 0, "to": 1.5, "axis": [0, 0, 1], "degrees": -45 } }, { "track": "DoorOpen", "object": "Knob", "seconds": 0, "distance_to": "Door", "distance": 111.8034 } diff --git a/tests/expectations_synthetic_anim_scene.json b/tests/expectations_synthetic_anim_scene.json index ae7a307..2c9f78f 100644 --- a/tests/expectations_synthetic_anim_scene.json +++ b/tests/expectations_synthetic_anim_scene.json @@ -34,6 +34,9 @@ ], "Body": [ "Wave" + ], + "Armature": [ + "Wave" ] }, "values": [ @@ -70,6 +73,19 @@ "seconds": 0, "distance_to": "Door", "distance": 111.8034 + }, + { + "track": "Wave", + "object": "Armature", + "seconds": 0.5, + "bone_direction": { + "bone": "Spine", + "vector": [ + -0.5, + -0.5, + 0.7071 + ] + } } ] } diff --git a/tests/integration_import.py b/tests/integration_import.py index a770ac3..d6318c2 100644 --- a/tests/integration_import.py +++ b/tests/integration_import.py @@ -700,6 +700,12 @@ def check_clips(ctx: Context) -> None: error = max(abs(a - b) for a, b in zip(direction, spec_bone["vector"])) c.true(f"{label} {spec_bone['bone']} direction at {value['seconds']}s", error < 1e-3, f"expected {spec_bone['vector']}, got {[round(v, 4) for v in direction]}") + if "bone_head" in value: # ボーンの頭のワールドの位置(#270) + spec_bone = value["bone_head"] + _at_clip_time([obj], value["track"], value["seconds"]) + evaluated = obj.evaluated_get(bpy.context.evaluated_depsgraph_get()) + head = evaluated.matrix_world @ evaluated.pose.bones[spec_bone["bone"]].head + c.near(f"{label} {spec_bone['bone']} head at {value['seconds']}s", head, spec_bone["location"]) if "rotation_delta" in value: delta = value["rotation_delta"] _at_clip_time([obj], value["track"], delta["from"]) diff --git a/tests/make_synthetic_anim_package.py b/tests/make_synthetic_anim_package.py index 7bb0ed7..9c2e9e0 100644 --- a/tests/make_synthetic_anim_package.py +++ b/tests/make_synthetic_anim_package.py @@ -4,13 +4,14 @@ 実在アセットのデータは使わない。 -- Models/Rig.fbx: 最上位のノード Face(シェイプキー smile を持つ板)・Hat・Door(子に Knob)・Armature(ボーン Hips → Spine。 +- Models/Rig.fbx: 最上位のノード Face(シェイプキー smile を持つ板)・Hat・Door(子に Knob)・Armature(ボーン Hips → Spine → Head。 スキンメッシュ Body はアーマチュアの子として書き出す。Unity では Armature と兄弟)。 - Animations/ - Smile.anim: Face の blendShape.smile を 0 → 100(1 秒、接線 0)。 - HatOff.anim: Hat の m_IsActive を 0.5 秒で 1 → 0(階段。1 秒)。 - DoorOpen.anim: Door のオイラー回転を (0, 0, 0) → (0, 90, 0)(1 秒)、Door/Knob の位置を (0.5, 1, 0)。ループする。 - - Wave.anim: ボーン Armature/Hips/Spine の回転(読み込まない。#270)と、Body の m_Enabled を 0。 + - Wave.anim: ボーンの Transform(#270)と、Body の m_Enabled を 0。Hips は位置(WAVE_HIPS_POSITION)と回転(レストの X まわり 90° から、ボーンの軸の Y まわりに 90° ひねる)、 + Spine はオイラー回転(X まわりに 0 → 90°)とスケール(Y を 1 → 2)。期待値のボーンの向きと位置は、Unity 6 で再生した値。 - Gesture.anim: Humanoid のマッスル値だけ(読み込まない)。 - Fist.anim: Humanoid のマッスル値と、Face のシェイプキー(値が変わる)。Humanoid なのでクリップごと読み込まない。 - Spin.anim: ルート自身(空のパス)の回転だけ(どのオブジェクトのものか決められない)。 @@ -40,6 +41,8 @@ INF = float("inf") ZERO3 = (0, 0, 0) ZERO4 = (0, 0, 0, 0) +# Wave.anim の Hips の位置(0 秒と 1 秒)。Unity での Hips のローカルの位置に合わせる +WAVE_HIPS_POSITION = ((0, 0, 0.008), (0.002, 0, 0.009)) def export_rig_fbx(path: Path) -> None: @@ -75,6 +78,8 @@ def export_rig_fbx(path: Path) -> None: hips.head, hips.tail = (0, 0, 0.8), (0, 0, 1.0) spine = bones.new("Spine") spine.head, spine.tail, spine.parent = (0, 0, 1.0), (0, 0, 1.3), hips + head = bones.new("Head") + head.head, head.tail, head.parent = (0, 0, 1.3), (0, 0, 1.5), spine bpy.ops.object.mode_set(mode="OBJECT") bpy.ops.mesh.primitive_cube_add(size=0.4, location=(0, 0, 1.0)) body = bpy.context.object @@ -119,7 +124,13 @@ def clip(name: str, text: str) -> None: clip("Wave", clip_yaml( "Wave", float_curves=[("Body", "m_Enabled", 137, [(0, 0, INF, INF)])], - vector_curves={"m_RotationCurves": [("Armature/Hips/Spine", [(0, (0, 0, 0, 1), ZERO4, ZERO4), (1, (0, 0.38268343, 0, 0.9238795), ZERO4, ZERO4)])]}, + vector_curves={ + "m_RotationCurves": [("Armature/Hips", [(0, (0.70710678, 0, 0, 0.70710678), ZERO4, ZERO4), (1, (0.5, 0.5, 0.5, 0.5), ZERO4, ZERO4)])], + "m_EulerCurves": [("Armature/Hips/Spine", [(0, ZERO3, ZERO3, ZERO3), (1, (90, 0, 0), ZERO3, ZERO3)])], + "m_ScaleCurves": [("Armature/Hips/Spine", [(0, (1, 1, 1), ZERO3, ZERO3), (1, (1, 2, 1), ZERO3, ZERO3)])], + "m_PositionCurves": [("Armature/Hips", [(0, WAVE_HIPS_POSITION[0], ZERO3, ZERO3), (1, WAVE_HIPS_POSITION[1], ZERO3, ZERO3)])] + if WAVE_HIPS_POSITION else [], + }, stop_time=1, )) clip("Gesture", clip_yaml("Gesture", float_curves=[("", "LeftHand.Index.1 Stretched", 95, [(0, -1, 0, 0)]), ("", "RootT.y", 95, [(0, 1, 0, 0)])])) diff --git a/tests/test_animation.py b/tests/test_animation.py index 1e9b6f0..002804d 100644 --- a/tests/test_animation.py +++ b/tests/test_animation.py @@ -17,13 +17,22 @@ bezier_handles, euler_to_quaternion, evaluate, + evaluate_many, is_state_clip, parse_clip, quaternion_to_euler, sample_times, transform_spec, + transform_specs, +) +from unitypackage_loader.core.animation_targets import ( + Binding, + TargetObject, + TargetTree, + bind_paths, + folder_affinity, + prefer_nearest_models, ) -from unitypackage_loader.core.animation_targets import TargetObject, TargetTree, bind_paths from unitypackage_loader.core.model_space import local_basis, local_values, node_basis from unitypackage_loader.core.transform import UNITY_TO_BLENDER, chain, inverse_affine, trs from tests.test_transform import assert_mat @@ -207,6 +216,23 @@ def test_handles_constant_and_scale(self): self.assertTrue(handles[0].constant) self.assertAlmostEqual(handles[1].value, 0.5) + def test_evaluate_many_matches_evaluate(self): + # エルミート・weighted・階段(同じ時刻に並んだキー)・範囲の外を混ぜる + keys = [Key(0, 0, 0, 2), Key(0.5, 1, 1, INF), Key(0.5, 3, INF, -1, 0.2, 0.6, 2), Key(1.2, 0, 0.5, 0, 0.7, 0.1, 1), Key(2, 2, 0, 0)] + times = [-0.5, 0, 0.1, 0.25, 0.5, 0.5, 0.75, 1.2, 1.5, 2, 3] + self.assertEqual(evaluate_many(keys, times), [evaluate(keys, t) for t in times]) + self.assertEqual(evaluate_many([], [0, 1]), [0.0, 0.0]) + + def test_transform_specs_match_transform_spec(self): + curves = [ + Curve("A", "m_LocalPosition.y", 4, KIND_POSITION, [Key(0, 1, 0, 0), Key(1, 2, 0, 0)], component=1), + Curve("A", "localEulerAnglesRaw.x", 4, KIND_EULER, [Key(0, 0, 0, 0), Key(1, 90, 0, 0)], component=0), + Curve("A", "m_LocalScale.z", 4, KIND_SCALE, [Key(0, 1, 0, 0), Key(1, 3, 0, 0)], component=2), + ] + rest = euler_to_quaternion((10, 20, 30)) + times = [0, 0.3, 0.6, 1] + self.assertEqual(transform_specs(curves, times, rest), [transform_spec(curves, t, rest) for t in times]) + def test_sample_times(self): curve = Curve("a", "m_LocalPosition.x", 4, KIND_POSITION, [Key(0, 0), Key(0.05, 1), Key(1, 0)]) times = sample_times([curve], 0.0, 0.1, 30) @@ -331,3 +357,24 @@ def test_unity_descendants(self): if __name__ == "__main__": unittest.main() + + +class NearestModelTest(unittest.TestCase): + def test_folder_affinity(self): + self.assertEqual(folder_affinity("Assets/Pack/Ghoul/Animations/run.anim", "Assets/Pack/Ghoul/Source/ghoul.fbx"), 3) + self.assertEqual(folder_affinity("Assets/Pack/Boss/Animations/run.anim", "Assets/Pack/Ghoul/Source/ghoul.fbx"), 2) + self.assertEqual(folder_affinity("run.anim", "Assets/ghoul.fbx"), 0) + + def test_prefers_models_near_the_clip(self): + # ボーンの名前が共通のキャラクターのパック: クリップと同じフォルダのモデル(通常版と allinone 版)だけを残す + models = {"ghoul": "Assets/Pack/Ghoul/Source/ghoul.fbx", "ghoul_all": "Assets/Pack/Ghoul/Source/ghoul_allinone.fbx", + "boss": "Assets/Pack/Boss/Source/boss.fbx", "unknown": None} + bindings = [Binding(key) for key in models] + kept = prefer_nearest_models(bindings, "Assets/Pack/Ghoul/Animations/run.anim", lambda b: models[b.root]) + self.assertEqual([b.root for b in kept], ["ghoul", "ghoul_all", "unknown"]) + + def test_one_model_keeps_every_placement(self): + # 同じモデルを複数置いたシーンは、モデルが 1 種類なのですべて残す + bindings = [Binding("a"), Binding("b")] + kept = prefer_nearest_models(bindings, "Assets/Elsewhere/clip.anim", lambda b: "Assets/Models/rig.fbx") + self.assertEqual(kept, bindings) diff --git a/unitypackage_loader/blender/animation.py b/unitypackage_loader/blender/animation.py index 9b745c8..8529848 100644 --- a/unitypackage_loader/blender/animation.py +++ b/unitypackage_loader/blender/animation.py @@ -6,7 +6,11 @@ - シェイプキーの値(Unity の 0〜100 → 0〜1)と表示の切り替え(``hide_viewport`` / ``hide_render``)は、キーと接線を そのままベジェ(階段は CONSTANT)にする。GameObject の非アクティブは、Unity の階層での子孫にも当てる。 - Transform は Unity のローカルの値をフレームごとに求め、オブジェクトの行列にしてから位置・回転・スケールのキーにする - (行列の対応は ``core/model_space.local_basis``)。ボーンを対象にしたカーブは読み込まない(#270)。 + (行列の対応は ``core/model_space.local_basis``)。 +- ボーンの Transform も同じく行列にしてから、ポーズボーンの位置・回転・スケールのキーにする(#270)。新旧どちらの FBX インポーターも + (このアドオンの呼び方では)ボーンの軸を付け替えないので、ポーズの行列は FBX のノードの行列そのままで、親(親のボーンか + アーマチュアのオブジェクト)から見た行列は A⁻¹·L·A になる。ポーズボーンの値への変換は、継承の設定(Maya の FBX では + ``inherit_scale`` が NONE になる)を含めて ``Bone.convert_local_to_pose`` に任せる。 - 対象ごとに、クリップの名前の NLA トラックを足す(``nla.add_track``)。既定はミュートで、読み込んだ直後の見た目は変わらない。 """ @@ -16,7 +20,7 @@ from dataclasses import dataclass, field import bpy -from mathutils import Matrix +from mathutils import Matrix, Quaternion, Vector from ..core.animation import ( KIND_ACTIVE, @@ -26,12 +30,14 @@ AnimationClip, Curve, bezier_handles, + evaluate_many, is_state_clip, parse_clip, sample_times, transform_spec, + transform_specs, ) -from ..core.animation_targets import Binding, TargetObject, TargetTree, bind_paths +from ..core.animation_targets import Binding, TargetObject, TargetTree, bind_paths, prefer_nearest_models from ..core.model_space import ModelUnits, local_basis, local_values from ..core.transform import IDENTITY, UNITY_TO_BLENDER, Mat4, inverse_affine from .log import warn_skipped @@ -42,6 +48,10 @@ # GameObject の行列に、向きや形を足して置いたオブジェクト(Transform のカーブを当てない) _ADDED_SHAPE_PROPS = ("unity_terrain", "unity_decal", "unity_light", "unity_camera") CLIP_PATH_PROP = "unity_clip_path" +# ボーンのチャンネルを、値が変わらないものとしてキー 1 つにまとめる幅 +_CONSTANT_EPSILON = 1e-6 +# Keyframe.interpolation の LINEAR の値(foreach_set では列挙の番号で渡す) +_LINEAR = 1 @dataclass @@ -54,8 +64,7 @@ class ClipStats: root_only: list[str] = field(default_factory=list) # ルート自身だけを動かすクリップ(どのオブジェクトのものか決められない) unbound: list[str] = field(default_factory=list) # 対象のオブジェクトが見つからなかったクリップ empty: list[str] = field(default_factory=list) # 読み込める種類のカーブが無いクリップ - bone_only: list[str] = field(default_factory=list) # ボーンだけを動かすクリップ(#270 まで読み込まない) - bone_curves: int = 0 # ボーンを対象にしたカーブ(#270 まで読み込まない) + bone_other: int = 0 # ボーンを対象にした Transform 以外のカーブ(GameObject の m_IsActive など。読み込まない) missing: int = 0 # 対象が見つからなかったカーブ(シェイプキーが無い、など) transform_skipped: int = 0 # 行列の対応が分からないオブジェクトの Transform のカーブ @@ -97,6 +106,7 @@ def __init__(self, session, collection: bpy.types.Collection): self.stats = ClipStats() self._units: dict[str, ModelUnits | None] = {} self._tree: TargetTree | None = None + self._column_cache: dict[tuple, list[float]] = {} # カーブの値。クリップ 1 つの中だけで使う(build で空にする) # ------------------------------------------------------------------ @@ -129,22 +139,33 @@ def run(self) -> ClipStats: if not bindings: self.stats.unbound.append(entry.pathname) continue + bindings = prefer_nearest_models(bindings, entry.pathname, self._binding_model) try: result = self.build(entry, clip, bindings) if result == "loaded": self.stats.loaded.append(entry.pathname) - elif result == "bones": - self.stats.bone_only.append(entry.pathname) else: self.stats.unbound.append(entry.pathname) except Exception as exc: # noqa: BLE001 - そのクリップだけを外して続ける warn_skipped(self.report.warn, f"could not import animation clip {entry.pathname}", exc) return self.stats + def _binding_model(self, binding: Binding) -> str | None: + """結び付けの候補のモデルのアセットのパス(ルートか、行き先のオブジェクトのモデル。分からなければ None)。""" + objects = [binding.root] if binding.root is not None else [] + objects += [target.key for target in binding.targets.values()] + for obj in objects: + guid = obj.get(MODEL_GUID_PROP) if obj is not None else None + if guid: + entry = self.pkg.entries.get(str(guid)) + return entry.pathname if entry is not None else None + return None + # ------------------------------------------------------------------ def build(self, entry, clip: AnimationClip, bindings: list[Binding]) -> str: - """クリップの Action を作って NLA に並べる。"loaded"、ボーンだけなら "bones"、何も当てられなければ "none"。""" + """クリップの Action を作って NLA に並べる。"loaded"、何も当てられなければ "none"。""" + self._column_cache.clear() action = bpy.data.actions.new(clip.name or entry.name) action[CLIP_GUID_PROP] = entry.guid action[CLIP_PATH_PROP] = entry.pathname @@ -166,15 +187,18 @@ def slot_for(datablock: bpy.types.ID, id_type: str, label: str): for curve in clip.curves: by_path.setdefault(curve.path, []).append(curve) tree = self._tree - bones = 0 for binding in bindings: + bone_curves: dict[bpy.types.Object, dict[str, list[Curve]]] = {} for path, curves in by_path.items(): target = binding.targets.get(path) if target is None: self.stats.missing += len(curves) continue if target.bone is not None: - bones += len(curves) + transforms = [c for c in curves if c.kind in TRANSFORM_KINDS] + self.stats.bone_other += len(curves) - len(transforms) + if transforms: + bone_curves.setdefault(target.key, {}).setdefault(target.bone, []).extend(transforms) continue obj = target.key for curve in curves: @@ -189,10 +213,11 @@ def slot_for(datablock: bpy.types.ID, id_type: str, label: str): transforms = [c for c in curves if c.kind in TRANSFORM_KINDS] if transforms: self._transform(strip, slot_for, obj, transforms, clip) - self.stats.bone_curves += bones + for armature, by_bone in bone_curves.items(): + self._bones(strip, slot_for, armature, by_bone, clip) if not users: bpy.data.actions.remove(action) - return "bones" if bones else "none" + return "none" for datablock, slot in users.items(): add_track(datablock, clip.name or entry.name, action, slot, self.scene, active=self.session.opts.animation == MODE_ACTIVE, loop=action.use_cyclic) @@ -298,6 +323,160 @@ def _transform(self, strip, slot_for, obj, curves: list[Curve], clip: AnimationC fcurve.modifiers.new("CYCLES") fcurve.update() + def _bones(self, strip, slot_for, armature, by_bone: dict[str, list[Curve]], clip: AnimationClip) -> None: + """アーマチュアのボーンの Transform のカーブを、ポーズボーンの位置・回転・スケールのキーにする。 + + 親から見たボーンの行列は Q = A⁻¹·L·A(A は ``ModelUnits.basis_a``)。アニメーションしていない成分の値は、読み込んだときの + ポーズ(FBX のノードの既定の値)から求める。フレームごとに、動かすボーンとその祖先のポーズの行列を親から順に求め、 + 目標の行列 M_parent·Q を ``Bone.convert_local_to_pose`` でポーズボーンの値(matrix_basis)に直す。 + """ + a = self._bone_basis_a(armature) + a_inverse = inverse_affine(a) if a is not None else None + if a is None or a_inverse is None: + self.stats.transform_skipped += sum(len(curves) for curves in by_bone.values()) + return + bones = armature.data.bones + animated: dict[str, list[Curve]] = {} + for name, curves in by_bone.items(): + if name in bones: + animated[name] = curves + else: + self.stats.missing += len(curves) + if not animated: + return + needed: set[str] = set() + for name in animated: + bone = bones[name] + while bone is not None and bone.name not in needed: + needed.add(bone.name) + bone = bone.parent + order = sorted((b for b in bones if b.name in needed), key=lambda b: len(b.parent_recursive)) + pose = armature.pose.bones + + def pose_matrix(bone, basis: Matrix, parent_matrix: Matrix | None, invert: bool = False) -> Matrix: + if bone.parent is None or parent_matrix is None: + return bone.convert_local_to_pose(basis, bone.matrix_local, invert=invert) + return bone.convert_local_to_pose(basis, bone.matrix_local, parent_matrix=parent_matrix, + parent_matrix_local=bone.parent.matrix_local, invert=invert) + + # 読み込んだときのポーズから、Unity のローカルの値 L₀ = A·Q₀·A⁻¹ を求める(アニメーションしていない成分に使う) + a_matrix, a_inverse_matrix = Matrix(a), Matrix(a_inverse) + rest_pose: dict[str, Matrix] = {} + for bone in order: + parent = rest_pose.get(bone.parent.name) if bone.parent is not None else None + rest_pose[bone.name] = pose_matrix(bone, pose[bone.name].matrix_basis, parent) + rest_values: dict[str, tuple] = {} + rest_rotation: dict[str, list[float]] = {} + for name in animated: + bone = bones[name] + parent = rest_pose.get(bone.parent.name) if bone.parent is not None else None + local = parent.inverted_safe() @ rest_pose[name] if parent is not None else rest_pose[name] + location, rotation, scale = (a_matrix @ local @ a_inverse_matrix).decompose() + rest_values[name] = (location, rotation, scale) + rest_rotation[name] = [rotation.x, rotation.y, rotation.z, rotation.w] + + slot = slot_for(armature, "OBJECT", node_name(armature)) + bag = strip.channelbag(slot, ensure=True) + all_curves = [c for curves in animated.values() for c in curves] + times = sample_times(all_curves, clip.start, clip.stop, self.fps) + has = {name: {c.kind for c in curves} for name, curves in animated.items()} + specs = {name: self._specs(curves, times, rest_rotation[name]) for name, curves in animated.items()} + channels: dict[tuple[str, str, int], list[tuple[float, float]]] = {} + previous: dict[str, object] = {} + for step, time in enumerate(times): + frame = self._frame(time, clip) + current: dict[str, Matrix] = {} + for bone in order: + name = bone.name + parent = current.get(bone.parent.name) if bone.parent is not None else None + if name not in animated: + current[name] = pose_matrix(bone, pose[name].matrix_basis, parent) + continue + spec = specs[name][step] + location, rotation, scale = rest_values[name] + position = spec["position"] + if any(v is not None for v in position): + location = Vector([location[i] if v is None else v for i, v in enumerate(position)]) + if spec["rotation"][0] is not None: + x, y, z, w = spec["rotation"] + rotation = Quaternion((w, x, y, z)) + factors = spec["scale"] + if any(v is not None for v in factors): + scale = Vector([scale[i] if v is None else v for i, v in enumerate(factors)]) + local = a_inverse_matrix @ Matrix.LocRotScale(location, rotation, scale) @ a_matrix + target = parent @ local if parent is not None else local + current[name] = target + basis = pose_matrix(bone, target, parent, invert=True) + self._bone_channels(channels, pose[name], basis, frame, has[name], previous) + groups: dict[str, object] = {g.name: g for g in bag.groups} + for (bone_name, data_path, index), points in channels.items(): + if bag.fcurves.find(data_path, index=index) is not None: + continue + values = [value for _, value in points] + if max(values) - min(values) <= _CONSTANT_EPSILON: + points = points[:1] # 値が変わらないチャンネル(Unity のクリップはスケールなどを定数のカーブで持つ) + fcurve = bag.fcurves.new(data_path, index=index) # 4.5 の fcurves.new は group_name を取らない + group = groups.get(bone_name) + if group is None: + group = groups[bone_name] = bag.groups.new(bone_name) + fcurve.group = group + fcurve.keyframe_points.add(len(points)) + fcurve.keyframe_points.foreach_set("co", [v for point in points for v in point]) + fcurve.keyframe_points.foreach_set("interpolation", [_LINEAR] * len(points)) + if clip.loop and len(points) > 1: + fcurve.modifiers.new("CYCLES") + fcurve.update() + + def _specs(self, curves: list[Curve], times: list[float], rest_rotation: list[float]) -> list[dict]: + """``transform_specs`` の結果。カーブの値は、同じクリップの中では評価し直さない(同じ骨格のモデルや配置が複数あるとき)。""" + key_times = tuple(times) + columns = [] + for curve in curves: + key = (id(curve), key_times) + column = self._column_cache.get(key) + if column is None: + column = self._column_cache[key] = evaluate_many(curve.keys, times) + columns.append(column) + return transform_specs(curves, times, rest_rotation, columns) + + @staticmethod + def _bone_channels(channels, pose_bone, basis: Matrix, frame: float, has: set[str], previous: dict) -> None: + """ポーズボーンの値 ``basis`` を、F カーブの点として ``channels`` に足す(回転は前のフレームと連続にする)。""" + prefix = f'pose.bones["{_escape(pose_bone.name)}"].' + location, rotation, scale = basis.decompose() + if "position" in has: + for i in range(3): + channels.setdefault((pose_bone.name, prefix + "location", i), []).append((frame, location[i])) + if has & {"rotation", "euler"}: + mode = pose_bone.rotation_mode + last = previous.get(pose_bone.name) + if mode == "QUATERNION": + if last is not None and rotation.dot(last) < 0.0: + rotation.negate() + previous[pose_bone.name] = rotation + for i in range(4): + channels.setdefault((pose_bone.name, prefix + "rotation_quaternion", i), []).append((frame, rotation[i])) + elif mode == "AXIS_ANGLE": + axis, angle = rotation.to_axis_angle() + for i, value in enumerate((angle, *axis)): + channels.setdefault((pose_bone.name, prefix + "rotation_axis_angle", i), []).append((frame, value)) + else: + euler = rotation.to_euler(mode, last) if last is not None else rotation.to_euler(mode, pose_bone.rotation_euler) + previous[pose_bone.name] = euler + for i in range(3): + channels.setdefault((pose_bone.name, prefix + "rotation_euler", i), []).append((frame, euler[i])) + if "scale" in has: + for i in range(3): + channels.setdefault((pose_bone.name, prefix + "scale", i), []).append((frame, scale[i])) + + def _bone_basis_a(self, armature) -> Mat4 | None: + """ボーンの行列の対応に使う A(アーマチュアのモデルの ``ModelUnits.basis_a``)。分からなければ None。""" + guid = armature.get(MODEL_GUID_PROP) + if not guid: + return None + units = self._model_units(str(guid)) + return units.basis_a() if units is not None else None + def _basis_sides(self, obj) -> tuple[Mat4, Mat4] | None: """オブジェクトの行列 basis = left·L·right の (left, right)。分からなければ None。 @@ -347,13 +526,11 @@ def report_lines(stats: ClipStats) -> Iterable[str]: yield f"skipped {len(stats.humanoid)} Humanoid animation clip(s) (muscle curves are not supported)" if stats.root_only: yield f"skipped {len(stats.root_only)} animation clip(s) that only animate the object they are played on (target unknown)" - if stats.bone_only: - yield f"skipped {len(stats.bone_only)} animation clip(s) that only animate bones (not supported yet)" - if stats.bone_curves: - yield f"skipped {stats.bone_curves} animation curve(s) targeting bones (not supported yet)" + if stats.bone_other: + yield f"skipped {stats.bone_other} animation curve(s) on bones other than Transform (such as GameObject active)" if stats.missing: yield f"{stats.missing} animation curve(s) had no matching shape key or object" if stats.unbound: yield f"{len(stats.unbound)} animation clip(s) did not match any imported object" if stats.transform_skipped: - yield f"skipped {stats.transform_skipped} Transform curve(s) on objects whose Unity transform could not be determined" + yield f"skipped {stats.transform_skipped} Transform curve(s) on objects or bones whose Unity transform could not be determined" diff --git a/unitypackage_loader/blender_manifest.toml b/unitypackage_loader/blender_manifest.toml index 0c1dc3e..1ee0709 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" +version = "1.19.0-dev.1" name = "Unitypackage Importer" tagline = "Import meshes, materials and textures from .unitypackage files" maintainer = "utagestudio" diff --git a/unitypackage_loader/core/animation.py b/unitypackage_loader/core/animation.py index 7e024aa..2f6a37e 100644 --- a/unitypackage_loader/core/animation.py +++ b/unitypackage_loader/core/animation.py @@ -48,11 +48,13 @@ "parse_clip", "is_state_clip", "evaluate", + "evaluate_many", "bezier_handles", "euler_to_quaternion", "quaternion_to_euler", "sample_times", "transform_spec", + "transform_specs", ] CLASS_ANIMATION_CLIP = 74 @@ -462,7 +464,11 @@ def evaluate(keys: Sequence[Key], time: float) -> float: lo = mid else: hi = mid - k0, k1 = keys[lo], keys[hi] + return _segment_value(keys[lo], keys[hi], time) + + +def _segment_value(k0: Key, k1: Key, time: float) -> float: + """k0 → k1 の区間の、``time`` での値(k0.time ≤ time ≤ k1.time)。""" dt = k1.time - k0.time if dt <= 0.0: return k1.value @@ -482,6 +488,27 @@ def evaluate(keys: Sequence[Key], time: float) -> float: return h00 * k0.value + h10 * dt * k0.out_slope + h01 * k1.value + h11 * dt * k1.in_slope +def evaluate_many(keys: Sequence[Key], times: Sequence[float]) -> list[float]: + """昇順の時刻の列での値(``evaluate`` を時刻ごとに呼ぶのと同じ値。キーを前から順にたどる)。""" + if not keys: + return [0.0] * len(times) + first, last = keys[0], keys[-1] + result: list[float] = [] + index = 0 # keys[index].time <= time < keys[index + 1].time を保つ + count = len(keys) + for time in times: + if time <= first.time: + result.append(first.value) + continue + if time >= last.time: + result.append(last.value) + continue + while index + 1 < count and keys[index + 1].time <= time: + index += 1 + result.append(_segment_value(keys[index], keys[index + 1], time)) + return result + + @dataclass(frozen=True) class BezierKey: """Blender のキーフレームにする値(時刻は秒)。``constant`` はこのキーから次のキーまで値を保つ。""" @@ -535,6 +562,8 @@ def sample_times(curves: Iterable[Curve], start: float, stop: float, rate: float """Transform をフレームごとに焼くときの時刻(``rate`` 毎秒。キーの時刻も含める)。 数が ``MAX_SAMPLES`` を超えるときは、間隔を広げて ``MAX_SAMPLES`` に収める(キーの時刻は数に入れない)。 + キーの時刻の数がフレームの数より多い(毎フレームに焼いたモーションなど)ときは、キーの時刻を足さない + (フレームごとの値で動きは表せ、時刻の数が倍近くになるのを避ける。#270)。 """ rate = rate if rate > 0 else 60.0 times = {start, stop} @@ -553,7 +582,8 @@ def sample_times(curves: Iterable[Curve], start: float, stop: float, rate: float keys.add(key.time) if len(keys) > MAX_SAMPLES: break - times |= keys + if len(keys) <= count + 1: + times |= keys return sorted(t for t in times if start <= t <= stop) @@ -618,13 +648,30 @@ def transform_spec(curves: Iterable[Curve], time: float, rest_rotation: Sequence オイラー回転のカーブはクォータニオンにする(アニメーションしていない成分は、元の回転をオイラー角にした値)。 クォータニオンの一部の成分だけのカーブは、残りを元の回転で埋めてから正規化する。 """ + curves = list(curves) + return _spec(curves, [evaluate(curve.keys, time) for curve in curves], rest_rotation) + + +def transform_specs(curves: Iterable[Curve], times: Sequence[float], rest_rotation: Sequence[float], + columns: Sequence[Sequence[float]] | None = None) -> list[dict[str, list[float | None]]]: + """昇順の時刻の列での ``transform_spec``(カーブごとに ``evaluate_many`` でまとめて評価する)。 + + ``columns`` はカーブごとの ``evaluate_many(curve.keys, times)``(評価済みのものを使い回すとき)。 + """ + curves = list(curves) + if columns is None: + columns = [evaluate_many(curve.keys, times) for curve in curves] + return [_spec(curves, [column[i] for column in columns], rest_rotation) for i in range(len(times))] + + +def _spec(curves: Sequence[Curve], values: Sequence[float], rest_rotation: Sequence[float]) -> dict[str, list[float | None]]: + """カーブとその値から ``transform_spec`` の形を作る。""" position: list[float | None] = [None, None, None] scale: list[float | None] = [None, None, None] rotation: list[float | None] = [None, None, None, None] euler: list[float | None] = [None, None, None] order = DEFAULT_ROTATION_ORDER - for curve in curves: - value = evaluate(curve.keys, time) + for curve, value in zip(curves, values): if curve.kind == KIND_POSITION and curve.component < 3: position[curve.component] = value elif curve.kind == KIND_SCALE and curve.component < 3: diff --git a/unitypackage_loader/core/animation_targets.py b/unitypackage_loader/core/animation_targets.py index 358f889..bc6544a 100644 --- a/unitypackage_loader/core/animation_targets.py +++ b/unitypackage_loader/core/animation_targets.py @@ -9,18 +9,21 @@ - 名前は完全一致を先に、なければ連番(``.001``)を外した形が 1 つだけのものを使う。 - Blender の FBX インポーターはスキンメッシュをアーマチュアの子にするが、Unity ではアーマチュアの GameObject と兄弟。 アーマチュアのオブジェクトの子(ボーンの子でないもの)は、アーマチュアの親の子としても引けるようにする。 -- アーマチュアの下はボーンの名前でたどる(ボーンを対象にしたカーブは #270 まで読み込まない)。 +- アーマチュアの下はボーンの名前でたどる(ボーンの Transform のカーブは #270 でポーズボーンに当てる)。 - 読み込み側が足した Empty(FBX のルートなど)で一致しなければ、Empty の子を 1 段だけ探す。 + +同じだけ解決できるルートが別々のモデルにまたがるとき(ボーンの名前が共通のキャラクターのパックなど)は、クリップと +フォルダが近いモデルのものだけを残す(``prefer_nearest_models``。#270)。同じモデルの複数の配置はすべて残る。 """ from __future__ import annotations -from collections.abc import Hashable, Iterable, Sequence +from collections.abc import Callable, Hashable, Iterable, Sequence from dataclasses import dataclass, field from .meta import strip_numeric_suffix -__all__ = ["TargetObject", "TargetTree", "Resolved", "Binding", "bind_paths"] +__all__ = ["TargetObject", "TargetTree", "Resolved", "Binding", "bind_paths", "folder_affinity", "prefer_nearest_models"] # 対象が決まったとみなす、解決できたパスの割合(ルート自身を指す空のパスは数えない) MIN_MATCH_RATIO = 0.5 @@ -295,3 +298,30 @@ def _higher(tree: TargetTree, a: Binding, b: Binding) -> bool: if a.root is None: return True return tree.depth(a.root) < tree.depth(b.root) + + +def folder_affinity(a: str, b: str) -> int: + """2 つのアセットのパスの、先頭から共通するフォルダの数(ファイル名は数えない)。""" + folders_a = a.split("/")[:-1] + folders_b = b.split("/")[:-1] + count = 0 + for x, y in zip(folders_a, folders_b): + if x != y: + break + count += 1 + return count + + +def prefer_nearest_models(bindings: Sequence[Binding], clip_path: str, + model_path: Callable[[Binding], str | None]) -> list[Binding]: + """結び付けの候補が別々のモデルにまたがるとき、クリップとフォルダがいちばん近いモデルのものだけを残す。 + + ``model_path`` は候補のモデルのアセットのパス(分からなければ None。その候補は常に残す)。モデルが 1 種類なら + (同じモデルを複数置いたシーンなど)そのまま返す。 + """ + paths = [model_path(b) for b in bindings] + known = {p for p in paths if p} + if len(known) <= 1: + return list(bindings) + best = max(folder_affinity(clip_path, p) for p in known) + return [b for b, p in zip(bindings, paths) if not p or folder_affinity(clip_path, p) == best] From 443d255333b16f31ed2d68b84fb9d81484ed002b Mon Sep 17 00:00:00 2001 From: utagestudio Date: Sat, 28 Nov 2026 17:46:09 +0900 Subject: [PATCH 2/2] =?UTF-8?q?chore:=20=E3=83=90=E3=83=BC=E3=82=B8?= =?UTF-8?q?=E3=83=A7=E3=83=B3=E3=82=92=201.19.0=20=E3=81=AB=E3=81=99?= =?UTF-8?q?=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- unitypackage_loader/blender_manifest.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/unitypackage_loader/blender_manifest.toml b/unitypackage_loader/blender_manifest.toml index 1ee0709..9725463 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.19.0-dev.1" +version = "1.19.0" name = "Unitypackage Importer" tagline = "Import meshes, materials and textures from .unitypackage files" maintainer = "utagestudio"