| 1 | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics) |
| 2 | // SPDX-FileCopyrightText: 2021 Jorrit Rouwe |
| 3 | // SPDX-License-Identifier: MIT |
| 4 | |
| 5 | #include <Jolt/Jolt.h> |
| 6 | |
| 7 | #include <Jolt/Skeleton/Skeleton.h> |
| 8 | #include <Jolt/ObjectStream/TypeDeclarations.h> |
| 9 | #include <Jolt/Core/StreamIn.h> |
| 10 | #include <Jolt/Core/StreamOut.h> |
| 11 | |
| 12 | JPH_NAMESPACE_BEGIN |
| 13 | |
| 14 | JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(Skeleton::Joint) |
| 15 | { |
| 16 | JPH_ADD_ATTRIBUTE(Joint, mName) |
| 17 | JPH_ADD_ATTRIBUTE(Joint, mParentName) |
| 18 | } |
| 19 | |
| 20 | JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(Skeleton) |
| 21 | { |
| 22 | JPH_ADD_ATTRIBUTE(Skeleton, mJoints) |
| 23 | } |
| 24 | |
| 25 | int Skeleton::GetJointIndex(const string_view &inName) const |
| 26 | { |
| 27 | for (int i = 0; i < (int)mJoints.size(); ++i) |
| 28 | if (mJoints[i].mName == inName) |
| 29 | return i; |
| 30 | |
| 31 | return -1; |
| 32 | } |
| 33 | |
| 34 | void Skeleton::CalculateParentJointIndices() |
| 35 | { |
| 36 | for (Joint &j : mJoints) |
| 37 | j.mParentJointIndex = GetJointIndex(j.mParentName); |
| 38 | } |
| 39 | |
| 40 | bool Skeleton::AreJointsCorrectlyOrdered() const |
| 41 | { |
| 42 | for (int i = 0; i < (int)mJoints.size(); ++i) |
| 43 | if (mJoints[i].mParentJointIndex >= i) |
| 44 | return false; |
| 45 | |
| 46 | return true; |
| 47 | } |
| 48 | |
| 49 | void Skeleton::SaveBinaryState(StreamOut &inStream) const |
| 50 | { |
| 51 | inStream.Write((uint32)mJoints.size()); |
| 52 | for (const Joint &j : mJoints) |
| 53 | { |
| 54 | inStream.Write(j.mName); |
| 55 | inStream.Write(j.mParentJointIndex); |
| 56 | inStream.Write(j.mParentName); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | Skeleton::SkeletonResult Skeleton::sRestoreFromBinaryState(StreamIn &inStream) |
| 61 | { |
| 62 | Ref<Skeleton> skeleton = new Skeleton; |
| 63 | |
| 64 | uint32 len = 0; |
| 65 | inStream.Read(len); |
| 66 | skeleton->mJoints.resize(len); |
| 67 | for (Joint &j : skeleton->mJoints) |
| 68 | { |
| 69 | inStream.Read(j.mName); |
| 70 | inStream.Read(j.mParentJointIndex); |
| 71 | inStream.Read(j.mParentName); |
| 72 | } |
| 73 | |
| 74 | SkeletonResult result; |
| 75 | if (inStream.IsEOF() || inStream.IsFailed()) |
| 76 | result.SetError("Failed to read skeleton from stream"); |
| 77 | else |
| 78 | result.Set(skeleton); |
| 79 | return result; |
| 80 | } |
| 81 | |
| 82 | JPH_NAMESPACE_END |