From c8068d8f3da95d641546b05ce19159e4dbe9c533 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:49:44 +0100 Subject: [PATCH] feat(model): animation clips of EU07M models, played on scenery instances Stage 8 of the EU07M model format. A model can carry animation clips; each track of a clip sets the translation, the rotation or the scale of a node at a time of the clip, and the parts of a node without a track keep its TRS. - Format, five optional sections: ACLP (clips: name, duration, flags 0x1 loop and 0x2 autoplay, range of tracks), ATRK (tracks: node, part, interpolation step / linear / cubic, ranges of keys), ATIM (key times), AVEC (vectors; with cubic the in-tangent, value and out-tangent of glTF) and AROT (rotations in 8 bytes, "smallest three": the three smaller components as snorm16 scaled by sqrt(2) and the index of the largest; eu07m::encode_rotation / decode_rotation). The validator refuses a node out of range, keys out of their arrays, times which aren't numbers from 0 up, a cubic rotation and tracks out of the range of the clip. -eu07m dump lists the clips and their tracks. The current release doesn't read these sections; a file without them loads as before. - Sampling (model/clip.cpp): step, lerp / slerp the shorter way, the Hermite spline of glTF with tangents per second; the first and the last key held outside of them; a looped clip goes around its duration, another stops at its end. - In the game: the clips play by the simulation time, from TAnimModel::play_clip(name, speed) or, flagged autoplay, from the first time the instance is drawn. RaPrepare() samples them for the instance drawn and sets the transforms of the nodes (TSubModel::SetClipTransform(), the new animation type at_Clip, gated by the instance like the others), so a clip moving the joints of a skin bends the skinned parts. The nodes a clip moves are flagged animated at load, which keeps the model out of the instancing. stop_clips() stops them. - The editor self-test gets "clip [speed]". Not yet: a scenery event starting a clip, and the CHNL channels bound to the time of a clip. Checked: a skinned tube with an autoplay clip (the tip to 60 degrees and back in 2 s, looped) beside a still one, six screenshots in Vulkan and in GL 4.6 go from straight to fully bent while the other stays (time let run in the editor for the test only). Unit tests 1200/1200, 6 new ones for the packing, the interpolations, the time and the file. Not built with GCC here. --- CMakeLists.txt | 1 + application/editormodeselftest.cpp | 1 + application/editormodeselftestscene.cpp | 14 +++ docs/eu07m-format.md | 23 ++++ model/AnimModel.cpp | 46 +++++++ model/AnimModel.h | 15 +++ model/Model3d.cpp | 14 +++ model/Model3d.h | 12 +- model/clip.cpp | 128 +++++++++++++++++++ model/clip.h | 80 ++++++++++++ model/eu07m/eu07m_build.cpp | 45 +++++++ model/eu07m/eu07m_build.h | 4 + model/eu07m/eu07m_dump.cpp | 21 ++++ model/eu07m/eu07m_format.h | 55 +++++++++ model/eu07m/eu07m_io.cpp | 70 +++++++++++ model/eu07m/eu07m_load.cpp | 60 +++++++++ model/eu07m/eu07m_model.h | 5 + tests/unit/test_clip.cpp | 158 ++++++++++++++++++++++++ tests/unit/test_skinning.cpp | 28 +++++ 19 files changed, 779 insertions(+), 1 deletion(-) create mode 100644 model/clip.cpp create mode 100644 model/clip.h create mode 100644 tests/unit/test_clip.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 80ccc1df5..5f1ebaf8d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -800,6 +800,7 @@ set(CORE_SOURCES "model/eu07m/eu07m_build.cpp" "model/eu07m/eu07m_dump.cpp" "model/skinning.cpp" +"model/clip.cpp" "${DEPS_DIR}/zstd/zstd.c" # the codecs of the vertex and index streams of EU07M "${DEPS_DIR}/meshoptimizer/src/vertexcodec.cpp" diff --git a/application/editormodeselftest.cpp b/application/editormodeselftest.cpp index 30c3f7ad9..c211d7ce3 100644 --- a/application/editormodeselftest.cpp +++ b/application/editormodeselftest.cpp @@ -99,6 +99,7 @@ editor_mode::selftest_result editor_mode::selftest_dispatch(std::string const &c // key [ctrl] a key or right button event, as the window gives it // lineside the tab of the objects along the track in the track window // event queues the event +// clip [speed] starts an animation clip of the model of the instance (EU07M), by the simulation time // animate turns a submodel of a model instance to the angles, as an animation event does (the // editor doesn't run the events); the animation goes by the simulation time // memcell logs the memory cell diff --git a/application/editormodeselftestscene.cpp b/application/editormodeselftestscene.cpp index 7c8f0d846..978fdae42 100644 --- a/application/editormodeselftestscene.cpp +++ b/application/editormodeselftestscene.cpp @@ -573,6 +573,20 @@ editor_mode::selftest_result editor_mode::selftest_scene(std::string const &comm WriteLog("SELFTEST event " + name + (event != nullptr ? " queued" : ": no such event")); return selftest_result::handled; } + if (command == "clip") + { + std::string node; + std::string name; + float speed{1.f}; + words >> node >> name; + words >> speed; + if (words.fail()) + speed = 1.f; + auto *model{simulation::Instances.find(node)}; + auto const started{(model != nullptr) && model->play_clip(name, speed)}; + WriteLog(format("SELFTEST clip %s %s: %s", node.c_str(), name.c_str(), started ? "playing" : "no such clip")); + return selftest_result::handled; + } if (command == "animate") { std::string node; diff --git a/docs/eu07m-format.md b/docs/eu07m-format.md index d16bf9914..4dbfc5436 100644 --- a/docs/eu07m-format.md +++ b/docs/eu07m-format.md @@ -88,6 +88,11 @@ strumień bez nagłówka: liczba elementów to rozmiar sekcji podzielony przez r | `CDAT` | nie | — | dane komponentów | | `BNDS` | nie | [T] 40 B | granice: `f32 × 3` min, `f32 × 3` max, sfera `f32 × 4`; jeden rekord na węzeł (geometria węzła w jego przestrzeni), ostatni dla całego modelu | | `EDIT` | nie | [T] 16 B | `u32` ścieżka pliku źródłowego (string), `u32` narzędzie (string), 8 B zera | +| `ACLP` | nie | [T] 32 B | klip animacji: `u32` nazwa, `u32` flagi (0x1 zapętlony, 0x2 gra sam od startu scenariusza), `u32` pierwsza ścieżka w `ATRK`, `u32` liczba, `f32` długość w sekundach, 12 B zera | +| `ATRK` | nie | [T] 24 B | ścieżka klipu: `u32` węzeł, `u8` część (0 przesunięcie, 1 obrót, 2 skala), `u8` interpolacja (0 skok, 1 liniowa, 2 sześcienna), `u16` 0, `u32` liczba kluczy, `u32` pierwszy czas w `ATIM`, `u32` pierwsza wartość w `AVEC` albo `AROT`, `u32` 0 | +| `ATIM` | nie | [S] 4 B | czasy kluczy `f32` w sekundach, od 0, niemalejące w ścieżce | +| `AVEC` | nie | [S] 12 B | wartości przesunięć i skal `f32 × 3`; przy interpolacji sześciennej trzy na klucz: styczna wejściowa, wartość, styczna wyjściowa (jak glTF) | +| `AROT` | nie | [S] 8 B | obroty „smallest three”: trzy mniejsze składowe kwaternionu `snorm16 × 3` (pomnożone przez √2), `u16` indeks największej (0 x … 3 w), która jest dodatnia i wyliczana z pozostałych | Wszystkie strumienie wierzchołków (`VPOS`, `VATT`, `VSKN`/`VSKW`, `VUSR`, `VBND`) mają tyle samo elementów: jeden na wierzchołek pliku. Strumień skóry obejmuje więc też wierzchołki siatek sztywnych (z zerami; zstd je zjada). Do GPU trafiają tylko @@ -242,6 +247,24 @@ Domyślne `modelformat legacy` zostawia pliki `.eu07m` w spokoju. strumieni przy pierwszym odczycie. - Gwiazdy (`STAR`) trzymają kolor w normalnej, więc idą jako `gfx::basic_vertex` również w Vulkanie. +### Klipy animacji + +Klip (`ACLP`) to zestaw ścieżek (`ATRK`), z których każda ustawia jedną część TRS węzła: przesunięcie, obrót albo skalę. +Części węzła bez ścieżki zostają takie, jak w jego TRS. + +- **Interpolacja.** Skok trzyma wartość klucza do następnego. Liniowa to lerp wektorów i slerp obrotów (krótszą drogą). + Sześcienna to spline Hermite'a z glTF, ze stycznymi w jednostkach na sekundę; tylko dla wektorów, obrót sześcienny + walidator odrzuca. Przed pierwszym i po ostatnim kluczu ścieżka trzyma jego wartość. +- **Czas.** Klip idzie po czasie symulacji od chwili startu, z tempem `speed`. Zapętlony zaczyna od nowa po swojej + długości, inny zatrzymuje się na końcu. Klip z flagą 0x2 startuje sam, gdy egzemplarz jest rysowany pierwszy raz. +- **W grze.** `TAnimModel::play_clip(nazwa, tempo)` startuje klip (komenda self-testu `clip [tempo]`), + a `stop_clips()` zatrzymuje wszystkie. Przy każdym rysowaniu egzemplarza `RaPrepare()` próbkuje grające klipy i + ustawia transformy węzłów (`TSubModel::SetClipTransform()`, animacja `at_Clip`), tak jak inne animacje egzemplarza. + Węzły, które klipy przesuwają, są przy wczytaniu oznaczane jako animowane, więc model z klipami nie jest + instancjonowany. Klip ruszający jointami skóry zgina skinowane części (sekcja „Skinning”). +- **Jeszcze nie:** event scenerii, który startuje klip, oraz powiązanie kanałów `CHNL` z czasem klipu. Obecne wydanie + nie czyta tych sekcji, a plik bez nich wczytuje się jak dotąd. + ### Skinning Prymityw ze skórą (`skin` ≥ 0, wagi w `VSKN` albo `VSKW`) jest rysowany przez jointy swojej skóry, w obu rendererach. diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 91cf164d1..d4abeb0b3 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -758,6 +758,7 @@ void TAnimModel::RaPrepare() for (auto entry : m_animlist) { entry->PrepareModel(); } + apply_clips(); } // the state of the lit and the dark part of a numbered light, as RaPrepare() shows them @@ -797,6 +798,51 @@ void TAnimModel::light_parts_shown( int const Light, bool &Lit, bool &Dark ) con } } +bool TAnimModel::play_clip( std::string_view const Name, float const Speed ) { + + if( pModel == nullptr ) { return false; } + auto const &clips { pModel->clips() }; + auto const found { std::ranges::find( clips, Name, &animation::clip::name ) }; + if( found == clips.end() ) { return false; } + auto const index { static_cast( std::distance( clips.begin(), found ) ) }; + std::erase_if( m_clips, [ index ]( clip_playing const &Playing ) { return Playing.clip == index; } ); + m_clips.push_back( { index, Timer::GetTime(), Speed } ); + m_autoplaystarted = true; + return true; +} + +void TAnimModel::stop_clips() { + + m_clips.clear(); + m_autoplaystarted = true; +} + +void TAnimModel::apply_clips() { + + if( ( pModel == nullptr ) || pModel->clips().empty() ) { return; } + auto const &clips { pModel->clips() }; + auto const now { Timer::GetTime() }; + if( false == m_autoplaystarted ) { + // the clips to play on their own start with the first time the instance is drawn, all at the same time + m_autoplaystarted = true; + for( std::size_t idx = 0; idx < clips.size(); ++idx ) { + if( clips[ idx ].autoplay ) { + m_clips.push_back( { idx, now, 1.f } ); + } + } + } + auto *root { pModel->GetSMRoot() }; + auto const count { pModel->submodel_count() }; + for( auto const &playing : m_clips ) { + auto const &clip { clips[ playing.clip ] }; + auto const time { animation::clip_time( clip, ( now - playing.start ) * playing.speed ) }; + for( auto const &node : clip.nodes ) { + if( ( node.node < 0 ) || ( node.node >= count ) ) { continue; } + root[ node.node ].SetClipTransform( animation::local_transform( clip, node, time ) ); + } + } +} + std::uint32_t TAnimModel::instance_light_bits() const { if( iNumLights == 0 ) { return 0; } diff --git a/model/AnimModel.h b/model/AnimModel.h index 2de51dbf8..986103591 100644 --- a/model/AnimModel.h +++ b/model/AnimModel.h @@ -189,6 +189,11 @@ public: // rotation and scale of the instance as a matrix: rotate y * rotate x * rotate z * scale glm::mat4 const &rotation_scale(); void RaAnimate( unsigned int const Framestamp ); // przeliczenie animacji egzemplarza + // starts the animation clip of the model (EU07M) with the name from its beginning, at Speed times its pace; a clip already playing + // starts over. false when the model has no clip of the name + bool play_clip( std::string_view Name, float Speed = 1.f ); + // stops the clips playing, the nodes they moved stay where they were last put till the next clip moves them + void stop_clips(); // radius() subclass details, calculates node's bounding radius float radius_() const override; @@ -235,6 +240,16 @@ public: bool m_transition { true }; // smooth transition between light states bool m_lightsanimated { false }; // the lights were brought to their state at least once unsigned int m_framestamp { 0 }; // id of last rendered gfx frame + // the animation clips of the model playing on the instance: the clip, the simulation time it started at and its pace + struct clip_playing { + std::size_t clip { 0 }; + double start { 0.0 }; + float speed { 1.f }; + }; + std::vector m_clips; + bool m_autoplaystarted { false }; // the clips of the model to play on their own were started + // the transforms of the nodes moved by the clips playing, set on the submodels for the instance drawn (RaPrepare()) + void apply_clips(); // true if this instance is eligible for the batched/instanced render path: // no lights, no submodel animations, no replacable skins, no seasonal variants. diff --git a/model/Model3d.cpp b/model/Model3d.cpp index bbd927c6d..9f4459973 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -1309,6 +1309,11 @@ void TSubModel::RaAnimation(glm::mat4 &m, TAnimType a) m = glm::rotate(m, glm::radians((float)Global.fLatitudeDeg), glm::vec3(0.0f, 1.0f, 0.0f)); // ustawienie osi OY na północ m = glm::rotate(m, glm::radians((float)-fmod(Global.fTimeAngleDeg, 360.0)), glm::vec3(0.0f, 1.0f, 0.0f)); break; + case TAnimType::at_Clip: + if (iAnimOwner != iInstance) + break; // cudza animacja + m *= m_clipanimation; + break; case TAnimType::at_DigiClk: // animacja zegara cyfrowego { // ustawienie animacji w submodelach potomnych TSubModel *sm = ChildGet(); @@ -1335,6 +1340,15 @@ void TSubModel::RaAnimation(glm::mat4 &m, TAnimType a) } }; +void TSubModel::SetClipTransform(glm::mat4 const &Local) +{ + // the walk applies the matrix of the submodel and then the animation: the clip replaces both + glm::mat4 const own{fMatrix ? glm::make_mat4(fMatrix->readArray()) : glm::mat4{1.f}}; + m_clipanimation = glm::inverse(own) * Local; + b_aAnim = TAnimType::at_Clip; + iAnimOwner = iInstance; +} + glm::mat4 TSubModel::posed_transform() { glm::mat4 result{1.f}; diff --git a/model/Model3d.h b/model/Model3d.h index b6df14651..41c9dc7eb 100644 --- a/model/Model3d.h +++ b/model/Model3d.h @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "model/material.h" #include "gl/query.h" #include "model/skinning.h" +#include "model/clip.h" #include @@ -45,7 +46,8 @@ enum class TAnimType // rodzaj animacji at_Sky, // animacja nieba at_Digital, // dziesięciocyfrowy licznik mechaniczny (z cylindrami) at_DigiClk, // zegar cyfrowy jako licznik na dziesięciościanach - at_Undefined // animacja chwilowo nieokreślona + at_Undefined, // animacja chwilowo nieokreślona + at_Clip // the transform from an animation clip of an EU07M model (SetClipTransform()) }; namespace scene { @@ -166,6 +168,7 @@ public: // chwilowo // a submodel of an EU07M model skinned by the joints of a skin: its bind pose, for the renderer to move the vertices by the pose of // the joints of each instance (rendering/common/skincache.h) std::shared_ptr m_skin; + glm::mat4 m_clipanimation{1.f}; // applied after the matrix of the submodel (at_Clip) float m_boundingradius { 0 }; std::uintptr_t iAnimOwner{ 0 }; // roboczy numer egzemplarza, który ustawił animację TAnimType b_aAnim{ TAnimType::at_None }; // kody animacji oddzielnie, bo zerowane @@ -191,6 +194,8 @@ public: // the transform of the submodel from the root of the model, with the animations of the instance drawn (iInstance), in the order the // walk of the renderer applies them: the matrix, then the animation, of each submodel flagged as transformed (0xC000) glm::mat4 posed_transform(); + // the transform of the submodel within its parent, from an animation clip, for the instance drawn (iInstance) + void SetClipTransform(glm::mat4 const &Local); // returns true if the submodel is a smoke emitter attachment point, false otherwise bool is_emitter() const; @@ -321,6 +326,7 @@ private: bool m_lodboundsfound { false }; std::uint32_t m_stateversion { 0 }; // see state_version() std::vector m_skins; // of an EU07M model, the skinned submodels refer to them + std::vector m_clips; // of an EU07M model, the nodes are the submodels of the same index void finish_binary( bool dynamic, bool hastangents ); @@ -346,6 +352,10 @@ public: ++m_stateversion; } std::vector const & skins() const { return m_skins; } + std::vector const & clips() const { + return m_clips; } + int submodel_count() const { + return iSubModelsCount; } TSubModel * AddToNamed(const char *Name, TSubModel *SubModel); nameoffset_sequence const & find_smoke_sources(); void AddTo(TSubModel *tmp, TSubModel *SubModel); diff --git a/model/clip.cpp b/model/clip.cpp new file mode 100644 index 000000000..0d6eea2f0 --- /dev/null +++ b/model/clip.cpp @@ -0,0 +1,128 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" + +#include "model/clip.h" + +#include +#include + +#include + +namespace animation +{ + +namespace +{ + +// the key at or before Time and the share of the way to the next one +struct key_span +{ + std::size_t key{0}; + float share{0.f}; + float length{0.f}; // seconds between the two keys + bool last{true}; // Time at or past the last key, or a single key +}; + +key_span find_span(std::span const Times, float const Time) +{ + key_span result; + if (Times.size() < 2 || Time <= Times.front()) + { + result.last = Times.size() < 2; + return result; + } + if (Time >= Times.back()) + { + result.key = Times.size() - 1; + return result; + } + auto const next{static_cast(std::distance(Times.begin(), std::ranges::upper_bound(Times, Time)))}; + result.key = next - 1; + result.length = Times[next] - Times[result.key]; + result.share = result.length > 0.f ? (Time - Times[result.key]) / result.length : 0.f; + result.last = false; + return result; +} + +glm::vec3 hermite(glm::vec3 const &From, glm::vec3 const &FromTangent, glm::vec3 const &To, glm::vec3 const &ToTangent, float const Share) +{ + auto const t2{Share * Share}; + auto const t3{t2 * Share}; + return (2.f * t3 - 3.f * t2 + 1.f) * From + (t3 - 2.f * t2 + Share) * FromTangent + (-2.f * t3 + 3.f * t2) * To + (t3 - t2) * ToTangent; +} + +glm::vec3 vector_value(track const &Track, std::size_t const Key) +{ + // with cubic the keys come as in-tangent, value, out-tangent + auto const index{Track.interpolation == curve::cubic ? Key * 3 + 1 : Key}; + return index < Track.vectors.size() ? Track.vectors[index] : glm::vec3{0.f}; +} + +} // namespace + +float clip_time(clip const &Clip, double const Elapsed) +{ + if (Clip.duration <= 0.f || Elapsed <= 0.0) + { + return 0.f; + } + auto const duration{static_cast(Clip.duration)}; + if (Clip.loop) + { + return static_cast(std::fmod(Elapsed, duration)); + } + return static_cast(std::min(Elapsed, duration)); +} + +glm::vec3 sample_vector(track const &Track, float const Time) +{ + auto const span{find_span(Track.times, Time)}; + if (span.last || Track.interpolation == curve::step || span.share <= 0.f) + { + return vector_value(Track, span.key); + } + auto const from{vector_value(Track, span.key)}; + auto const to{vector_value(Track, span.key + 1)}; + if (Track.interpolation == curve::linear) + { + return glm::mix(from, to, span.share); + } + auto const outtangent{Track.vectors.size() > span.key * 3 + 2 ? Track.vectors[span.key * 3 + 2] : glm::vec3{0.f}}; + auto const intangent{Track.vectors.size() > (span.key + 1) * 3 ? Track.vectors[(span.key + 1) * 3] : glm::vec3{0.f}}; + return hermite(from, outtangent * span.length, to, intangent * span.length, span.share); +} + +glm::quat sample_rotation(track const &Track, float const Time) +{ + if (Track.rotations.empty()) + { + return glm::quat{1.f, 0.f, 0.f, 0.f}; + } + auto const span{find_span(Track.times, Time)}; + auto const from{Track.rotations[std::min(span.key, Track.rotations.size() - 1)]}; + if (span.last || Track.interpolation == curve::step || span.share <= 0.f || span.key + 1 >= Track.rotations.size()) + { + return from; + } + // the shorter way round + return glm::normalize(glm::slerp(from, Track.rotations[span.key + 1], span.share)); +} + +glm::mat4 local_transform(clip const &Clip, node_tracks const &Node, float const Time) +{ + auto const tracked = [&Clip](int const Track) { return (Track >= 0) && (static_cast(Track) < Clip.tracks.size()); }; + auto const translation{tracked(Node.translation) ? sample_vector(Clip.tracks[Node.translation], Time) : Node.rest_translation}; + auto const rotation{tracked(Node.rotation) ? sample_rotation(Clip.tracks[Node.rotation], Time) : Node.rest_rotation}; + auto const scale{tracked(Node.scale) ? sample_vector(Clip.tracks[Node.scale], Time) : Node.rest_scale}; + return glm::translate(glm::mat4{1.f}, translation) * glm::mat4_cast(rotation) * glm::scale(glm::mat4{1.f}, scale); +} + +} // namespace animation diff --git a/model/clip.h b/model/clip.h new file mode 100644 index 000000000..2c498fa94 --- /dev/null +++ b/model/clip.h @@ -0,0 +1,80 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include + +#include +#include + +// the animation clips of an EU07M model (ACLP, ATRK and their keys), as the game samples them: each track sets the translation, the +// rotation or the scale of a node at a time of the clip, and the parts of a node without a track keep its own TRS +namespace animation +{ + +enum class part : std::uint8_t +{ + translation, + rotation, + scale +}; + +enum class curve : std::uint8_t +{ + step, + linear, // lerp of vectors, slerp of rotations + cubic // the Hermite spline of glTF: in-tangent, value and out-tangent for each key, vectors only +}; + +struct track +{ + part target{part::translation}; + curve interpolation{curve::linear}; + std::vector times; // seconds, not decreasing + std::vector vectors; // translation, scale; three for each key with cubic + std::vector rotations; +}; + +// the tracks of one node and the TRS the node has of its own +struct node_tracks +{ + int node{-1}; + int translation{-1}; // into the tracks of the clip, -1 without one + int rotation{-1}; + int scale{-1}; + glm::vec3 rest_translation{0.f}; + glm::quat rest_rotation{1.f, 0.f, 0.f, 0.f}; + glm::vec3 rest_scale{1.f}; +}; + +struct clip +{ + std::string name; + float duration{0.f}; + bool loop{false}; + bool autoplay{false}; + std::vector tracks; + std::vector nodes; // the nodes the clip moves, each once +}; + +// the time of the clip after Elapsed seconds of playing: around the duration for a looped clip, else held at its end +float clip_time(clip const &Clip, double Elapsed); + +// the value of the track at Time, held at the first and the last key outside of them +glm::vec3 sample_vector(track const &Track, float Time); +glm::quat sample_rotation(track const &Track, float Time); + +// the transform of the node within its parent at Time: T * R * S, each part from its track or the rest of the node +glm::mat4 local_transform(clip const &Clip, node_tracks const &Node, float Time); + +} // namespace animation diff --git a/model/eu07m/eu07m_build.cpp b/model/eu07m/eu07m_build.cpp index bae52d126..c1865d247 100644 --- a/model/eu07m/eu07m_build.cpp +++ b/model/eu07m/eu07m_build.cpp @@ -13,7 +13,10 @@ http://mozilla.org/MPL/2.0/. #include +#include +#include #include +#include #include namespace eu07m { @@ -138,6 +141,48 @@ std::array encode_qtangent(tangent_frame const &Frame) { return {pack_snorm16(rotation.x), pack_snorm16(rotation.y), pack_snorm16(rotation.z), pack_snorm16(rotation.w)}; } +packed_rotation encode_rotation(std::array const &Quaternion) { + auto quaternion{Quaternion}; + auto const length{std::sqrt(quaternion[0] * quaternion[0] + quaternion[1] * quaternion[1] + quaternion[2] * quaternion[2] + quaternion[3] * quaternion[3])}; + if (false == std::isfinite(length) || length <= 0.f) + return {}; + std::size_t largest{0}; + for (std::size_t idx = 0; idx < 4; ++idx) { + quaternion[idx] /= length; + if (std::abs(quaternion[idx]) > std::abs(quaternion[largest])) + largest = idx; + } + auto const sign{quaternion[largest] < 0.f ? -1.f : 1.f}; + packed_rotation packed; + packed.largest = static_cast(largest); + std::size_t slot{0}; + for (std::size_t idx = 0; idx < 4; ++idx) { + if (idx == largest) + continue; + // the other components lie within +-1/sqrt(2) + auto const scaled{std::clamp(sign * quaternion[idx] * std::numbers::sqrt2_v, -1.f, 1.f)}; + packed.components[slot] = static_cast(std::lround(scaled * 32767.f)); + ++slot; + } + return packed; +} + +std::array decode_rotation(packed_rotation const &Packed) { + std::array quaternion{0.f, 0.f, 0.f, 1.f}; + auto const largest{static_cast(std::min(Packed.largest, 3))}; + auto sum{0.f}; + std::size_t slot{0}; + for (std::size_t idx = 0; idx < 4; ++idx) { + if (idx == largest) + continue; + quaternion[idx] = static_cast(Packed.components[slot]) / 32767.f / std::numbers::sqrt2_v; + ++slot; + sum += quaternion[idx] * quaternion[idx]; + } + quaternion[largest] = std::sqrt(std::max(0.f, 1.f - sum)); + return quaternion; +} + tangent_frame decode_qtangent(std::array const &Packed) { // the first and the third column of the rotation matrix of the quaternion, which 2 / |q|^2 makes unit without a square root: // what glm::mat3_cast(glm::normalize(q)) gives, for the two columns needed, at a part of the cost (this runs for every vertex) diff --git a/model/eu07m/eu07m_build.h b/model/eu07m/eu07m_build.h index 38c485488..1a4e27435 100644 --- a/model/eu07m/eu07m_build.h +++ b/model/eu07m/eu07m_build.h @@ -27,6 +27,10 @@ struct tangent_frame { // the snorm16 quaternion of the frame. a degenerate normal or tangent gets an arbitrary perpendicular one std::array encode_qtangent(tangent_frame const &Frame); tangent_frame decode_qtangent(std::array const &Packed); +// a unit quaternion (x, y, z, w) packed as the three smallest components and the index of the largest, and back. the largest is made +// positive (q and -q are the same rotation); a quaternion of no length packs as the identity +packed_rotation encode_rotation(std::array const &Quaternion); +std::array decode_rotation(packed_rotation const &Packed); // the transform of the node within its parent: the matrix of XFRM, or T * R * S glm::mat4 local_transform(model const &Model, std::uint32_t Node); diff --git a/model/eu07m/eu07m_dump.cpp b/model/eu07m/eu07m_dump.cpp index 5e192e65a..874df85e2 100644 --- a/model/eu07m/eu07m_dump.cpp +++ b/model/eu07m/eu07m_dump.cpp @@ -11,7 +11,9 @@ http://mozilla.org/MPL/2.0/. #include "model/eu07m/eu07m_dump.h" +#include #include +#include namespace eu07m { @@ -98,6 +100,24 @@ void dump_model_components(model const &Model, std::string &Output) { } } +void dump_clips(model const &Model, std::string &Output) { + constexpr std::array paths{"translation", "rotation", "scale"}; + constexpr std::array interpolations{"step", "linear", "cubic"}; + for (std::uint32_t idx = 0; idx < Model.clips.size(); ++idx) { + auto const &clip{Model.clips[idx]}; + Output += std::format("clip {} {} {:.3f} s{}{}\n", idx, quoted(Model, clip.name), clip.duration, (clip.flags & clip_flags::loop) != 0 ? " loop" : "", + (clip.flags & clip_flags::autoplay) != 0 ? " autoplay" : ""); + for (auto track = clip.track_first; track < clip.track_first + clip.track_count && track < Model.clip_tracks.size(); ++track) { + auto const &record{Model.clip_tracks[track]}; + auto const path{static_cast(record.path)}; + auto const interpolation{static_cast(record.interpolation)}; + auto const node{record.node < Model.nodes.size() ? quoted(Model, Model.nodes[record.node].name) : std::string{"?"}}; + Output += std::format(" node {} {} {} {}, {} keys\n", record.node, node, path < paths.size() ? paths[path] : "?", interpolation < interpolations.size() ? interpolations[interpolation] : "?", + record.key_count); + } + } +} + } // namespace std::string dump(model const &Model) { @@ -105,6 +125,7 @@ std::string dump(model const &Model) { dump_counts(Model, output); dump_nodes(Model, output); dump_model_components(Model, output); + dump_clips(Model, output); if (false == Model.bounds.empty()) { auto const &whole{Model.bounds.back()}; output += std::format("bounds: ({:.3f} {:.3f} {:.3f}) - ({:.3f} {:.3f} {:.3f}), radius {:.3f}\n", whole.min[0], whole.min[1], whole.min[2], whole.max[0], whole.max[1], whole.max[2], diff --git a/model/eu07m/eu07m_format.h b/model/eu07m/eu07m_format.h index 51219f31b..8d46b97b7 100644 --- a/model/eu07m/eu07m_format.h +++ b/model/eu07m/eu07m_format.h @@ -59,6 +59,11 @@ constexpr std::uint32_t components{fourcc("CMPT")}; constexpr std::uint32_t component_data{fourcc("CDAT")}; constexpr std::uint32_t bounds{fourcc("BNDS")}; constexpr std::uint32_t edit{fourcc("EDIT")}; +constexpr std::uint32_t clips{fourcc("ACLP")}; +constexpr std::uint32_t clip_tracks{fourcc("ATRK")}; +constexpr std::uint32_t key_times{fourcc("ATIM")}; +constexpr std::uint32_t key_vectors{fourcc("AVEC")}; +constexpr std::uint32_t key_rotations{fourcc("AROT")}; } // namespace section // the components @@ -321,6 +326,56 @@ struct component_record { }; static_assert(sizeof(component_record) == 20); +// the animation clips (ACLP), their tracks (ATRK) and the keys of the tracks (ATIM, AVEC, AROT) +namespace clip_flags { +constexpr std::uint32_t loop{0x1}; // starts over at the end, else it stops at the last key +constexpr std::uint32_t autoplay{0x2}; // plays from the start of the scenario, without anything starting it +} // namespace clip_flags + +struct clip_record { + std::uint32_t name{no_index}; // string + std::uint32_t flags{0}; + std::uint32_t track_first{0}; // in ATRK + std::uint32_t track_count{0}; + float duration{0.f}; // seconds + std::array reserved{}; +}; +static_assert(sizeof(clip_record) == 32); + +enum class track_path : std::uint8_t { + translation = 0, // vectors + rotation = 1, // rotations + scale = 2, // vectors +}; + +enum class track_interpolation : std::uint8_t { + step = 0, + linear = 1, // lerp of vectors, slerp of rotations + cubic = 2, // the Hermite spline of glTF, vectors only: in-tangent, value and out-tangent for each key +}; + +// a track sets one part of the transform of a node (translation, rotation or scale) from its keys, replacing that part of the TRS of +// the node; the parts without a track keep the TRS of the node +struct track_record { + std::uint32_t node{0}; + track_path path{track_path::translation}; + track_interpolation interpolation{track_interpolation::linear}; + std::uint16_t reserved0{0}; + std::uint32_t key_count{0}; + std::uint32_t time_first{0}; // in ATIM, key_count times in seconds, not decreasing + std::uint32_t value_first{0}; // in AVEC (key_count vectors, three times as many for cubic) or AROT (key_count rotations) + std::uint32_t reserved1{0}; +}; +static_assert(sizeof(track_record) == 24); + +// a unit quaternion in 8 bytes, "smallest three": the three components other than the largest, scaled by sqrt(2) to the range of +// snorm16, and the index of the largest (0 x, 1 y, 2 z, 3 w), which is made positive and rebuilt from the other three +struct packed_rotation { + std::array components{}; + std::uint16_t largest{3}; +}; +static_assert(sizeof(packed_rotation) == 8); + struct bounds_record { std::array min{0.f, 0.f, 0.f}; std::array max{0.f, 0.f, 0.f}; diff --git a/model/eu07m/eu07m_io.cpp b/model/eu07m/eu07m_io.cpp index 915bf5e4e..2efcc6869 100644 --- a/model/eu07m/eu07m_io.cpp +++ b/model/eu07m/eu07m_io.cpp @@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/. #include "meshoptimizer.h" #include "zstd.h" +#include +#include #include #include #include @@ -570,6 +572,11 @@ bool file_reader::dispatch(section_entry const &Entry, section_bytes const &Sect case section::component_data: result = Section.stream(Model.component_data, error); break; case section::bounds: result = Section.table(Model.bounds, error); break; case section::edit: result = Section.table(Model.edit, error); break; + case section::clips: result = Section.table(Model.clips, error); break; + case section::clip_tracks: result = Section.table(Model.clip_tracks, error); break; + case section::key_times: result = Section.stream(Model.key_times, error); break; + case section::key_vectors: result = Section.stream(Model.key_vectors, error); break; + case section::key_rotations: result = Section.stream(Model.key_rotations, error); break; default: known = false; break; } if (false == result) @@ -813,6 +820,9 @@ class validator { void components(); void component_ranges(std::uint32_t First, std::uint32_t Count, target_kind Kind, std::uint32_t Target, std::string_view Owner); void tables(); + void clips(); + void track(std::uint32_t Index, track_record const &Track); + void track_times(std::uint32_t Index, track_record const &Track); model const &m_model; std::size_t m_limit; @@ -1069,6 +1079,60 @@ void validator::tables() { } } +// a clip names its tracks, a track its node, its keys and their values +void validator::clips() { + for (std::uint32_t idx = 0; idx < m_model.clips.size(); ++idx) { + auto const &clip{m_model.clips[idx]}; + if (false == valid_string(m_model, clip.name)) + fault(std::format("clip {} has a name out of range", idx)); + if (std::uint64_t{clip.track_first} + clip.track_count > m_model.clip_tracks.size()) + fault(std::format("clip {} has tracks out of range", idx)); + if (false == std::isfinite(clip.duration) || clip.duration < 0.f) + fault(std::format("clip {} has duration {}", idx, clip.duration)); + } + for (std::uint32_t idx = 0; idx < m_model.clip_tracks.size(); ++idx) + track(idx, m_model.clip_tracks[idx]); +} + +void validator::track(std::uint32_t const Index, track_record const &Track) { + if (Track.node >= m_model.nodes.size()) + fault(std::format("track {} has node {} out of range", Index, Track.node)); + if (Track.path > track_path::scale || Track.interpolation > track_interpolation::cubic) { + fault(std::format("track {} has an unknown path or interpolation", Index)); + return; + } + if (Track.key_count == 0) { + fault(std::format("track {} has no keys", Index)); + return; + } + auto const rotation{Track.path == track_path::rotation}; + if (rotation && Track.interpolation == track_interpolation::cubic) { + fault(std::format("track {} is a cubic rotation, which only vectors can be", Index)); + return; + } + auto const values{std::uint64_t{Track.key_count} * (Track.interpolation == track_interpolation::cubic ? 3u : 1u)}; + auto const available{rotation ? m_model.key_rotations.size() : m_model.key_vectors.size()}; + if (std::uint64_t{Track.value_first} + values > available) + fault(std::format("track {} has values out of range", Index)); + else if (rotation && std::ranges::any_of(std::span{m_model.key_rotations}.subspan(Track.value_first, Track.key_count), [](packed_rotation const &Value) { return Value.largest > 3; })) + fault(std::format("track {} has a rotation with no largest component", Index)); + else if (false == rotation && std::ranges::any_of(std::span{m_model.key_vectors}.subspan(Track.value_first, values), [](std::array const &Value) { + return std::ranges::any_of(Value, [](float const Component) { return false == std::isfinite(Component); }); + })) + fault(std::format("track {} has a value which isn't a number", Index)); + track_times(Index, Track); +} + +void validator::track_times(std::uint32_t const Index, track_record const &Track) { + if (std::uint64_t{Track.time_first} + Track.key_count > m_model.key_times.size()) { + fault(std::format("track {} has times out of range", Index)); + return; + } + auto const times{std::span{m_model.key_times}.subspan(Track.time_first, Track.key_count)}; + if (std::ranges::any_of(times, [](float const Time) { return false == std::isfinite(Time) || Time < 0.f; }) || false == std::ranges::is_sorted(times)) + fault(std::format("track {} has times which aren't numbers from 0 up", Index)); +} + std::vector validator::run() { nodes(); transforms(); @@ -1080,6 +1144,7 @@ std::vector validator::run() { vertex_groups(); components(); tables(); + clips(); return m_faults; } @@ -1104,6 +1169,11 @@ std::vector write(model const &Model, write_options const &Options) { builder.add(section::component_data, false, section_alignment, Model.component_data); builder.table(section::bounds, Model.bounds, false); builder.table(section::edit, Model.edit, false); + builder.table(section::clips, Model.clips, false); + builder.table(section::clip_tracks, Model.clip_tracks, false); + builder.stream(section::key_times, Model.key_times, false); + builder.stream(section::key_vectors, Model.key_vectors, false); + builder.stream(section::key_rotations, Model.key_rotations, false); builder.stream(section::positions, Model.positions, true, stream_codec::vertices); builder.stream(section::attributes, Model.vertex_attributes, true, stream_codec::vertices); builder.stream(section::skin_weights, Model.weights, false, stream_codec::vertices); diff --git a/model/eu07m/eu07m_load.cpp b/model/eu07m/eu07m_load.cpp index c517b6d81..3ff9ac189 100644 --- a/model/eu07m/eu07m_load.cpp +++ b/model/eu07m/eu07m_load.cpp @@ -351,6 +351,58 @@ void submodel_builder::fill_geometry() { } // the workers join here } +// the track of the file as the game samples it: the rotations unpacked, the vectors as glm +animation::track make_track(eu07m::model const &Model, eu07m::track_record const &Record) { + animation::track track; + track.target = static_cast(Record.path); + track.interpolation = static_cast(Record.interpolation); + auto const times{std::span{Model.key_times}.subspan(Record.time_first, Record.key_count)}; + track.times.assign(times.begin(), times.end()); + if (Record.path == eu07m::track_path::rotation) { + for (auto const &packed : std::span{Model.key_rotations}.subspan(Record.value_first, Record.key_count)) { + auto const value{eu07m::decode_rotation(packed)}; + track.rotations.emplace_back(value[3], value[0], value[1], value[2]); + } + return track; + } + auto const count{std::size_t{Record.key_count} * (Record.interpolation == eu07m::track_interpolation::cubic ? 3u : 1u)}; + for (auto const &value : std::span{Model.key_vectors}.subspan(Record.value_first, count)) + track.vectors.emplace_back(value[0], value[1], value[2]); + return track; +} + +// the tracks of the clip gathered by node, with the TRS of the node for the parts without one +animation::node_tracks &node_entry(animation::clip &Clip, eu07m::model const &Model, std::uint32_t const Node) { + if (auto const found{std::ranges::find(Clip.nodes, static_cast(Node), &animation::node_tracks::node)}; found != Clip.nodes.end()) + return *found; + auto const &record{Model.nodes[Node]}; + animation::node_tracks entry; + entry.node = static_cast(Node); + entry.rest_translation = {record.translation[0], record.translation[1], record.translation[2]}; + entry.rest_rotation = glm::quat{record.rotation[3], record.rotation[0], record.rotation[1], record.rotation[2]}; + entry.rest_scale = {record.scale[0], record.scale[1], record.scale[2]}; + return Clip.nodes.emplace_back(entry); +} + +animation::clip make_clip(eu07m::model const &Model, eu07m::clip_record const &Record) { + animation::clip clip; + clip.name = Model.string(Record.name); + clip.duration = Record.duration; + clip.loop = (Record.flags & eu07m::clip_flags::loop) != 0; + clip.autoplay = (Record.flags & eu07m::clip_flags::autoplay) != 0; + for (auto const &record : std::span{Model.clip_tracks}.subspan(Record.track_first, Record.track_count)) { + auto const index{static_cast(clip.tracks.size())}; + clip.tracks.push_back(make_track(Model, record)); + auto &node{node_entry(clip, Model, record.node)}; + switch (record.path) { + case eu07m::track_path::translation: node.translation = index; break; + case eu07m::track_path::rotation: node.rotation = index; break; + case eu07m::track_path::scale: node.scale = index; break; + } + } + return clip; +} + } // namespace bool TModel3d::LoadFromEU07M(std::string const &FileName, bool const dynamic) { @@ -396,6 +448,14 @@ bool TModel3d::LoadFromEU07M(std::string const &FileName, bool const dynamic) { } m_skins.push_back(std::move(skin)); } + // the clips; the nodes they move keep a transform of their own, as animated ones (0x4000) + m_clips.clear(); + for (auto const &record : model.clips) { + auto clip{make_clip(model, record)}; + for (auto const &node : clip.nodes) + Root[node.node].WillBeAnimated(); + m_clips.push_back(std::move(clip)); + } m_vertexcount += builder.vertex_count; m_indexcount += builder.index_count; // the tangents come with the vertices diff --git a/model/eu07m/eu07m_model.h b/model/eu07m/eu07m_model.h index 82567ab33..f72cac374 100644 --- a/model/eu07m/eu07m_model.h +++ b/model/eu07m/eu07m_model.h @@ -66,6 +66,11 @@ struct model { std::vector component_data; std::vector bounds; std::vector edit; + std::vector clips; + std::vector clip_tracks; + std::vector key_times; + std::vector> key_vectors; + std::vector key_rotations; std::vector unknown; // the id of the string, adding it when it isn't there yet diff --git a/tests/unit/test_clip.cpp b/tests/unit/test_clip.cpp new file mode 100644 index 000000000..d306d0de9 --- /dev/null +++ b/tests/unit/test_clip.cpp @@ -0,0 +1,158 @@ +#include "stdafx.h" + +#include "doctest.h" + +#include "model/clip.h" +#include "model/eu07m/eu07m_build.h" +#include "model/eu07m/eu07m_io.h" + +#include + +#include +#include + +namespace { + +bool same_rotation(glm::quat const &A, glm::quat const &B, float const Tolerance = 1e-3f) { + return std::abs(std::abs(glm::dot(A, B)) - 1.f) <= Tolerance; +} + +glm::quat about_x(float const Degrees) { + return glm::angleAxis(glm::radians(Degrees), glm::vec3{1.f, 0.f, 0.f}); +} + +animation::track vector_track(animation::curve const Curve, std::vector Times, std::vector Values) { + animation::track track; + track.interpolation = Curve; + track.times = std::move(Times); + track.vectors = std::move(Values); + return track; +} + +// a model of one node and a clip turning it, for the checks of the file +eu07m::model clip_model() { + eu07m::model model; + eu07m::node_record node; + node.name = model.intern("arm"); + node.subtree_end = 1; + model.nodes.push_back(node); + model.meshes.push_back({0, 0, -1, 0}); + model.positions.push_back({0.f, 0.f, 0.f}); + model.vertex_attributes.push_back({}); + model.materials.push_back({}); + eu07m::clip_record clip; + clip.name = model.intern("swing"); + clip.flags = eu07m::clip_flags::loop | eu07m::clip_flags::autoplay; + clip.track_count = 1; + clip.duration = 2.f; + model.clips.push_back(clip); + eu07m::track_record track; + track.path = eu07m::track_path::rotation; + track.key_count = 3; + model.clip_tracks.push_back(track); + model.key_times = {0.f, 1.f, 2.f}; + for (auto const degrees : {0.f, 60.f, 0.f}) { + auto const rotation{about_x(degrees)}; + model.key_rotations.push_back(eu07m::encode_rotation({rotation.x, rotation.y, rotation.z, rotation.w})); + } + return model; +} + +} // namespace + +TEST_CASE("clip: a rotation packed in 8 bytes comes back") { + std::vector const rotations{glm::quat{1.f, 0.f, 0.f, 0.f}, about_x(60.f), about_x(-170.f), glm::angleAxis(2.f, glm::normalize(glm::vec3{1.f, -2.f, 0.5f})), + glm::quat{-0.1f, 0.7f, -0.7f, 0.1f}}; + for (auto const &source : rotations) { + auto const rotation{glm::normalize(source)}; + auto const packed{eu07m::encode_rotation({rotation.x, rotation.y, rotation.z, rotation.w})}; + CHECK(packed.largest <= 3); + auto const value{eu07m::decode_rotation(packed)}; + CHECK(same_rotation(rotation, glm::quat{value[3], value[0], value[1], value[2]}, 1e-4f)); + } + // a quaternion of no length packs as the identity + auto const none{eu07m::decode_rotation(eu07m::encode_rotation({0.f, 0.f, 0.f, 0.f}))}; + CHECK(none[3] == doctest::Approx(1.f)); +} + +TEST_CASE("clip: vectors by step, linear and cubic keys") { + auto const linear{vector_track(animation::curve::linear, {1.f, 3.f}, {glm::vec3{0.f}, glm::vec3{2.f, 4.f, 0.f}})}; + CHECK(animation::sample_vector(linear, 2.f).x == doctest::Approx(1.f)); + CHECK(animation::sample_vector(linear, 2.f).y == doctest::Approx(2.f)); + // held at the first and the last key outside of them + CHECK(animation::sample_vector(linear, 0.f).x == doctest::Approx(0.f)); + CHECK(animation::sample_vector(linear, 9.f).y == doctest::Approx(4.f)); + auto step{linear}; + step.interpolation = animation::curve::step; + CHECK(animation::sample_vector(step, 2.9f).x == doctest::Approx(0.f)); + CHECK(animation::sample_vector(step, 3.f).x == doctest::Approx(2.f)); + // cubic with flat tangents eases in and out: half way at the middle, a quarter of the way gives 0.15625 + auto const cubic{vector_track(animation::curve::cubic, {0.f, 1.f}, {glm::vec3{0.f}, glm::vec3{0.f}, glm::vec3{0.f}, glm::vec3{0.f}, glm::vec3{1.f}, glm::vec3{0.f}})}; + CHECK(animation::sample_vector(cubic, 0.5f).x == doctest::Approx(0.5f)); + CHECK(animation::sample_vector(cubic, 0.25f).x == doctest::Approx(0.15625f)); + CHECK(animation::sample_vector(cubic, 1.f).x == doctest::Approx(1.f)); + // a tangent of 1 a second over a second from 0 to 1 is the straight line + auto const straight{vector_track(animation::curve::cubic, {0.f, 1.f}, {glm::vec3{1.f}, glm::vec3{0.f}, glm::vec3{1.f}, glm::vec3{1.f}, glm::vec3{1.f}, glm::vec3{1.f}})}; + CHECK(animation::sample_vector(straight, 0.3f).x == doctest::Approx(0.3f)); +} + +TEST_CASE("clip: rotations by slerp, the time looped or held") { + animation::track track; + track.target = animation::part::rotation; + track.times = {0.f, 1.f}; + track.rotations = {about_x(0.f), about_x(90.f)}; + CHECK(same_rotation(animation::sample_rotation(track, 0.5f), about_x(45.f))); + CHECK(same_rotation(animation::sample_rotation(track, 2.f), about_x(90.f))); + + animation::clip clip; + clip.duration = 2.f; + clip.loop = true; + CHECK(animation::clip_time(clip, 5.5) == doctest::Approx(1.5f)); + clip.loop = false; + CHECK(animation::clip_time(clip, 5.5) == doctest::Approx(2.f)); + CHECK(animation::clip_time(clip, -1.0) == doctest::Approx(0.f)); +} + +TEST_CASE("clip: the parts of a node without a track keep its own TRS") { + animation::clip clip; + clip.tracks.push_back(vector_track(animation::curve::linear, {0.f, 1.f}, {glm::vec3{0.f}, glm::vec3{0.f, 0.f, 4.f}})); + animation::node_tracks node; + node.node = 0; + node.translation = 0; + node.rest_translation = {9.f, 9.f, 9.f}; + node.rest_rotation = about_x(90.f); + auto const local{animation::local_transform(clip, node, 0.5f)}; + // the translation from the track, the rotation of the node + CHECK(local[3].z == doctest::Approx(2.f)); + CHECK(local[3].x == doctest::Approx(0.f)); + auto const up{glm::vec3{local * glm::vec4{0.f, 1.f, 0.f, 0.f}}}; + CHECK(up.z == doctest::Approx(1.f)); +} + +TEST_CASE("clip: the clips go through the file and its checks") { + auto const model{clip_model()}; + CHECK(eu07m::validate(model, 16).empty()); + eu07m::model read; + REQUIRE(eu07m::read(eu07m::write(model, {true, 9}), read, {true, true}).ok); + REQUIRE(read.clips.size() == 1); + CHECK(read.clips[0].flags == (eu07m::clip_flags::loop | eu07m::clip_flags::autoplay)); + CHECK(read.clip_tracks.size() == 1); + CHECK(read.key_times.size() == 3); + CHECK(read.key_rotations.size() == 3); + + auto broken{model}; + broken.clip_tracks[0].interpolation = eu07m::track_interpolation::cubic; + CHECK_FALSE(eu07m::validate(broken, 16).empty()); + broken = model; + broken.key_times = {0.f, 2.f, 1.f}; + CHECK_FALSE(eu07m::validate(broken, 16).empty()); + broken = model; + broken.clip_tracks[0].node = 5; + CHECK_FALSE(eu07m::validate(broken, 16).empty()); + broken = model; + broken.clip_tracks[0].key_count = 4; + CHECK_FALSE(eu07m::validate(broken, 16).empty()); + broken = model; + broken.clips[0].track_count = 2; + CHECK_FALSE(eu07m::validate(broken, 16).empty()); +} diff --git a/tests/unit/test_skinning.cpp b/tests/unit/test_skinning.cpp index 39f4970ec..e30abd3ba 100644 --- a/tests/unit/test_skinning.cpp +++ b/tests/unit/test_skinning.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -196,3 +197,30 @@ TEST_CASE("skinning: the skinned tube is a valid EU07M file") { output.write(reinterpret_cast(file.data()), static_cast(file.size())); CHECK(output.good()); } + +TEST_CASE("skinning: the tube bent by a clip of its own") { + // the tip swings to 60 degrees about x and back in 2 s, looped, from the start of the scenario + auto model{skinned_tube()}; + eu07m::clip_record clip; + clip.name = model.intern("bend"); + clip.flags = eu07m::clip_flags::loop | eu07m::clip_flags::autoplay; + clip.track_count = 1; + clip.duration = 2.f; + model.clips.push_back(clip); + eu07m::track_record track; + track.node = 3; // tube_tip + track.path = eu07m::track_path::rotation; + track.key_count = 3; + model.clip_tracks.push_back(track); + model.key_times = {0.f, 1.f, 2.f}; + for (auto const degrees : {0.f, 60.f, 0.f}) { + auto const rotation{glm::angleAxis(glm::radians(degrees), glm::vec3{1.f, 0.f, 0.f})}; + model.key_rotations.push_back(eu07m::encode_rotation({rotation.x, rotation.y, rotation.z, rotation.w})); + } + CHECK(eu07m::validate(model, 16).empty()); + auto const file{eu07m::write(model, {true, 9})}; + auto const path{std::filesystem::path{EU07_UNIT_TESTS_SCRATCH} / "clip_tube.eu07m"}; + std::ofstream output{path, std::ios::binary}; + output.write(reinterpret_cast(file.data()), static_cast(file.size())); + CHECK(output.good()); +}