LCOV - code coverage report
Current view: top level - source/collada - PMDConvert.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 120 286 42.0 %
Date: 2026-12-03 01:19:39 Functions: 8 9 88.9 %

          Line data    Source code
       1             : /* Copyright (C) 2025 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "PMDConvert.h"
      21             : 
      22             : #include "CommonConvert.h"
      23             : #include "DLL.h"
      24             : #include "StdSkeletons.h"
      25             : #include "Decompose.h"
      26             : #include "Maths.h"
      27             : #include "GeomReindex.h"
      28             : 
      29             : #include <FCDocument/FCDController.h>
      30             : #include <FCDocument/FCDControllerInstance.h>
      31             : #include <FCDocument/FCDEntity.h>
      32             : #include <FCDocument/FCDEntityInstance.h>
      33             : #include <FCDocument/FCDGeometry.h>
      34             : #include <FCDocument/FCDGeometryMesh.h>
      35             : #include <FCDocument/FCDGeometryPolygons.h>
      36             : #include <FCDocument/FCDGeometryPolygonsInput.h>
      37             : #include <FCDocument/FCDGeometryPolygonsTools.h>
      38             : #include <FCDocument/FCDGeometrySource.h>
      39             : #include <FCDocument/FCDSceneNode.h>
      40             : #include <FCDocument/FCDSkinController.h>
      41             : #include <FMath/FMMatrix44.h>
      42             : #include <FMath/FMVector3.h>
      43             : #include <FUtils/FUDaeEnum.h>
      44             : #include <FUtils/FUString.h>
      45             : #include <FUtils/Platforms.h>
      46             : #include <algorithm>
      47             : #include <cassert>
      48             : #include <cstring>
      49             : #include <utility>
      50             : #include <vector>
      51             : 
      52             : const size_t maxInfluences = 4;
      53             : struct VertexBlend
      54             : {
      55             :     uint8 bones[maxInfluences];
      56             :     float weights[maxInfluences];
      57             : };
      58             : VertexBlend defaultInfluences = { { 0xFF, 0xFF, 0xFF, 0xFF }, { 0, 0, 0, 0 } };
      59             : 
      60          10 : struct PropPoint
      61             : {
      62             :     std::string name;
      63             :     float translation[3];
      64             :     float orientation[4];
      65             :     uint8 bone;
      66             : };
      67             : 
      68             : // Based on FMVector3::Normalize, but that function uses a static member
      69             : // FMVector3::XAxis which causes irritating linker errors. Rather than trying
      70             : // to make that XAxis work in a cross-platform way, just reimplement Normalize:
      71         361 : static FMVector3 FMVector3_Normalize(const FMVector3& vec)
      72             : {
      73         361 :     float l = vec.Length();
      74         361 :     if (l > 0.0f)
      75         361 :         return FMVector3(vec.x/l, vec.y/l, vec.z/l);
      76             :     else
      77           0 :         return FMVector3(1.0f, 0.0f, 0.0f);
      78             : }
      79             : 
      80           5 : static void AddStaticPropPoints(std::vector<PropPoint> &propPoints, const FMMatrix44& upAxisTransform, FCDSceneNode* node)
      81             : {
      82           5 :     if (node->GetName().find("prop-") == 0 || node->GetName().find("prop_") == 0)
      83             :     {
      84             :         // Strip off the "prop-" from the name
      85           0 :         std::string propPointName (node->GetName().substr(5));
      86             : 
      87           0 :         Log(LOG_INFO, "Adding prop point %s", propPointName.c_str());
      88             : 
      89             :         // CalculateWorldTransform applies transformations recursively for all parents of this node
      90             :         // upAxisTransform transforms this node to right-handed Z_UP coordinates
      91             : 
      92           0 :         FMMatrix44 transform = upAxisTransform * node->CalculateWorldTransform();
      93             : 
      94           0 :         HMatrix matrix;
      95           0 :         memcpy(matrix, transform.Transposed().m, sizeof(matrix));
      96             : 
      97           0 :         AffineParts parts;
      98           0 :         decomp_affine(matrix, &parts);
      99             : 
     100             :         // Add prop point in game coordinates
     101             : 
     102           0 :         PropPoint p = {
     103             :             propPointName,
     104             : 
     105             :             // Flip translation across the x-axis by swapping y and z
     106           0 :             { parts.t.x, parts.t.z, parts.t.y },
     107             : 
     108             :             // To convert the quaternions: imagine you're using the axis/angle
     109             :             // representation, then swap the y,z basis vectors and change the
     110             :             // direction of rotation by negating the angle ( => negating sin(angle)
     111             :             // => negating x,y,z => changing (x,y,z,w) to (-x,-z,-y,w)
     112             :             // but then (-x,-z,-y,w) == (x,z,y,-w) so do that instead)
     113           0 :             { parts.q.x, parts.q.z, parts.q.y, -parts.q.w },
     114             : 
     115             :             0xff
     116           0 :         };
     117           0 :         propPoints.push_back(p);
     118           0 :     }
     119             : 
     120             :     // Search children for prop points
     121           5 :     for (size_t i = 0; i < node->GetChildrenCount(); ++i)
     122           0 :         AddStaticPropPoints(propPoints, upAxisTransform, node->GetChild(i));
     123           5 : }
     124             : 
     125             : class PMDConvert
     126             : {
     127             : public:
     128             :     /**
     129             :      * Converts a COLLADA XML document into the PMD mesh format.
     130             :      *
     131             :      * @param input XML document to parse
     132             :      * @param output callback for writing the PMD data; called lots of times
     133             :      *               with small strings
     134             :      * @param xmlErrors output - errors reported by the XML parser
     135             :      * @throws ColladaException on failure
     136             :      */
     137           6 :     static void ColladaToPMD(const char* input, OutputCB& output, std::string& xmlErrors)
     138             :     {
     139           6 :         CommonConvert converter(input, xmlErrors);
     140             : 
     141           5 :         if (converter.GetInstance().GetEntity()->GetType() == FCDEntity::GEOMETRY)
     142             :         {
     143           5 :             Log(LOG_INFO, "Found static geometry");
     144             : 
     145           5 :             FCDGeometryPolygons* polys = GetPolysFromGeometry((FCDGeometry*)converter.GetInstance().GetEntity());
     146             : 
     147             :             // Convert the geometry into a suitable form for the game
     148           5 :             ReindexGeometry(polys);
     149             : 
     150           5 :             std::vector<VertexBlend> boneWeights; // unused
     151           5 :             std::vector<BoneTransform> boneTransforms;    // unused
     152           5 :             std::vector<PropPoint> propPoints;
     153             : 
     154             :             // Get the raw vertex data
     155             : 
     156           5 :             FCDGeometryPolygonsInput* inputPosition = polys->FindInput(FUDaeGeometryInput::POSITION);
     157           5 :             FCDGeometryPolygonsInput* inputNormal   = polys->FindInput(FUDaeGeometryInput::NORMAL);
     158             : 
     159           5 :             const uint32* indicesCombined = inputPosition->GetIndices();
     160           5 :             size_t indicesCombinedCount = inputPosition->GetIndexCount();
     161             :             // (ReindexGeometry guarantees position/normal/texcoord have the same indexes)
     162             : 
     163           5 :             FCDGeometrySource* sourcePosition = inputPosition->GetSource();
     164           5 :             FCDGeometrySource* sourceNormal   = inputNormal  ->GetSource();
     165             : 
     166           5 :             FCDGeometrySourceList texcoordSources;
     167           5 :             polys->GetParent()->FindSourcesByType(FUDaeGeometryInput::TEXCOORD, texcoordSources);
     168             : 
     169           5 :             float* dataPosition = sourcePosition->GetData();
     170           5 :             float* dataNormal   = sourceNormal  ->GetData();
     171           5 :             size_t vertexCount = sourcePosition->GetDataCount() / 3;
     172           5 :             assert(sourcePosition->GetDataCount() == vertexCount*3);
     173           5 :             assert(sourceNormal  ->GetDataCount() == vertexCount*3);
     174             : 
     175           5 :             std::vector<float*> dataTexcoords;
     176          10 :             for (size_t i = 0; i < texcoordSources.size(); ++i)
     177             :             {
     178          10 :                 dataTexcoords.push_back(texcoordSources[i]->GetData());
     179             :             }
     180             : 
     181             :             // Transform mesh coordinate system to game coordinates
     182             :             // (doesn't modify prop points)
     183             : 
     184           5 :             TransformStaticModel(dataPosition, dataNormal, vertexCount, converter.GetEntityTransform(), converter.IsYUp());
     185             : 
     186             :             // Add static prop points
     187             :             //  which are empty child nodes of the main parent
     188             : 
     189             :             // Default prop points are already given in game coordinates
     190           5 :             AddDefaultPropPoints(propPoints);
     191             : 
     192             :             // Calculate transform to convert from COLLADA-defined up_axis to Z-up because
     193             :             //  it's relatively straightforward to convert that to game coordinates
     194           5 :             FMMatrix44 upAxisTransform = FMMatrix44_Identity;
     195           5 :             if (converter.IsYUp())
     196             :             {
     197             :                 // Prop points are rotated -90 degrees about the X-axis, reverse that rotation
     198             :                 // (do this once now because it's easier than messing with quaternions later)
     199           0 :                 upAxisTransform = FMMatrix44::XAxisRotationMatrix(1.57f);
     200             :             }
     201             : 
     202           5 :             AddStaticPropPoints(propPoints, upAxisTransform, converter.GetInstance().GetParent());
     203             : 
     204           5 :             WritePMD(output, indicesCombined, indicesCombinedCount, dataPosition, dataNormal, dataTexcoords, vertexCount, boneWeights, boneTransforms, propPoints);
     205          10 :         }
     206           0 :         else if (converter.GetInstance().GetType() == FCDEntityInstance::CONTROLLER)
     207             :         {
     208           0 :             Log(LOG_INFO, "Found skinned geometry");
     209             : 
     210           0 :             FCDControllerInstance& controllerInstance = static_cast<FCDControllerInstance&>(converter.GetInstance());
     211             : 
     212             :             // (NB: GetType is deprecated and should be replaced with HasType,
     213             :             // except that has irritating linker errors when using a DLL, so don't
     214             :             // bother)
     215             : 
     216           0 :             assert(converter.GetInstance().GetEntity()->GetType() == FCDEntity::CONTROLLER); // assume this is always true?
     217           0 :             FCDController* controller = static_cast<FCDController*>(converter.GetInstance().GetEntity());
     218             : 
     219           0 :             FCDSkinController* skin = controller->GetSkinController();
     220           0 :             REQUIRE(skin != NULL, "is skin controller");
     221             : 
     222           0 :             FixSkeletonRoots(controllerInstance);
     223             : 
     224             :             // Data for joints is stored in two places - avoid overflows by limiting
     225             :             // to the minimum of the two sizes, and warn if they're different (which
     226             :             // happens in practice for slightly-broken meshes)
     227           0 :             size_t jointCount = std::min(skin->GetJointCount(), controllerInstance.GetJointCount());
     228           0 :             if (skin->GetJointCount() != controllerInstance.GetJointCount())
     229             :             {
     230           0 :                 Log(LOG_WARNING, "Mismatched bone counts (skin has %d, skeleton has %d)",
     231             :                     skin->GetJointCount(), controllerInstance.GetJointCount());
     232           0 :                 for (size_t i = 0; i < skin->GetJointCount(); ++i)
     233           0 :                     Log(LOG_INFO, "Skin joint %d: %s", i, skin->GetJoint(i)->GetId().c_str());
     234           0 :                 for (size_t i = 0; i < controllerInstance.GetJointCount(); ++i)
     235           0 :                     Log(LOG_INFO, "Skeleton joint %d: %s", i, controllerInstance.GetJoint(i)->GetName().c_str());
     236             :             }
     237             : 
     238             :             // Get the skinned mesh for this entity
     239           0 :             FCDGeometry* baseGeometry = controller->GetBaseGeometry();
     240           0 :             REQUIRE(baseGeometry != NULL, "controller has base geometry");
     241           0 :             FCDGeometryPolygons* polys = GetPolysFromGeometry(baseGeometry);
     242             : 
     243             :             // Make sure it doesn't use more bones per vertex than the game can handle
     244           0 :             SkinReduceInfluences(skin, maxInfluences, 0.001f);
     245             : 
     246             :             // Convert the geometry into a suitable form for the game
     247           0 :             ReindexGeometry(polys, skin);
     248             : 
     249           0 :             const Skeleton& skeleton = FindSkeleton(controllerInstance);
     250             : 
     251             :             // Convert the bone influences into VertexBlend structures for the PMD:
     252             : 
     253           0 :             bool hasComplainedAboutNonexistentJoints = false; // because we want to emit a warning only once
     254             : 
     255           0 :             std::vector<VertexBlend> boneWeights; // one per vertex
     256             : 
     257           0 :             const FCDSkinControllerVertex* vertexInfluences = skin->GetVertexInfluences();
     258           0 :             for (size_t i = 0; i < skin->GetInfluenceCount(); ++i)
     259             :             {
     260           0 :                 VertexBlend influences = defaultInfluences;
     261             : 
     262           0 :                 assert(vertexInfluences[i].GetPairCount() <= maxInfluences);
     263             :                     // guaranteed by ReduceInfluences; necessary for avoiding
     264             :                     // out-of-bounds writes to the VertexBlend
     265             : 
     266           0 :                 if (vertexInfluences[i].GetPairCount() == 0)
     267             :                 {
     268             :                     // Blender exports some models with vertices that have no influences,
     269             :                     //  which I've not found details about in the COLLADA spec, however,
     270             :                     //  it seems to work OK to treat these vertices the same as if they
     271             :                     //  were only influenced by the bind-shape matrix (see comment below),
     272             :                     //  so we use the same special case here.
     273           0 :                     influences.bones[0] = (uint8)jointCount;
     274           0 :                     influences.weights[0] = 1.0f;
     275             :                 }
     276             : 
     277           0 :                 for (size_t j = 0; j < vertexInfluences[i].GetPairCount(); ++j)
     278             :                 {
     279           0 :                     if (vertexInfluences[i].GetPair(j)->jointIndex == -1)
     280             :                     {
     281             :                         // This is a special case we must handle, according to the COLLADA spec:
     282             :                         //  "An index of -1 into the array of joints refers to the bind shape"
     283             :                         //
     284             :                         //  which basically means when skinning the vertex it's relative to the
     285             :                         //  bind-shape transform instead of an animated bone. Since our skinning
     286             :                         //  is in world space, we will have already applied the bind-shape transform,
     287             :                         //  so we don't have to worry about that, though we DO have to apply the
     288             :                         //  world space transform of the model for the indicated vertex.
     289             :                         //
     290             :                         //  To indicate this special case, we use a bone ID set to the total number
     291             :                         //  of bones in the model, which will have a special "bone matrix" reserved
     292             :                         //  that contains the world space transform of the model during skinning.
     293             :                         //  (see https://gitea.wildfiregames.com/0ad/0ad/issues/1012)
     294           0 :                         influences.bones[j] = (uint8)jointCount;
     295           0 :                         influences.weights[j] = vertexInfluences[i].GetPair(j)->weight;
     296             :                     }
     297             :                     else
     298             :                     {
     299             :                         // Check for less than 254 joints because we store them in a
     300             :                         //  std::uint8_t, 0xFF is a reserved value (no influence), and we
     301             :                         //  reserve one slot for the above special case.
     302           0 :                         uint32 jointIdx = vertexInfluences[i].GetPair(j)->jointIndex;
     303           0 :                         REQUIRE(jointIdx < 0xFE, "sensible number of joints (<254)");
     304             : 
     305             :                         // Find the joint on the skeleton, after checking it really exists
     306           0 :                         FCDSceneNode* joint = NULL;
     307           0 :                         if (jointIdx < controllerInstance.GetJointCount())
     308           0 :                             joint = controllerInstance.GetJoint(jointIdx);
     309             : 
     310             :                         // Complain on error
     311           0 :                         if (! joint)
     312             :                         {
     313           0 :                             if (! hasComplainedAboutNonexistentJoints)
     314             :                             {
     315           0 :                                 Log(LOG_WARNING, "Vertexes influenced by nonexistent joint");
     316             :                                 hasComplainedAboutNonexistentJoints = true;
     317             :                             }
     318           0 :                             continue;
     319             :                         }
     320             : 
     321             :                         // Store into the VertexBlend
     322           0 :                         int boneId = skeleton.GetBoneID(joint->GetName().c_str());
     323           0 :                         if (boneId < 0)
     324             :                         {
     325             :                             // The relevant joint does exist, but it's not a recognised
     326             :                             // bone in our chosen skeleton structure
     327           0 :                             Log(LOG_ERROR, "Vertex influenced by unrecognized bone '%s'", joint->GetName().c_str());
     328           0 :                             continue;
     329             :                         }
     330             : 
     331           0 :                         influences.bones[j] = (uint8)boneId;
     332           0 :                         influences.weights[j] = vertexInfluences[i].GetPair(j)->weight;
     333             :                     }
     334             :                 }
     335             : 
     336           0 :                 boneWeights.push_back(influences);
     337             :             }
     338             : 
     339             :             // Convert the bind pose into BoneTransform structures for the PMD:
     340             : 
     341           0 :             BoneTransform boneDefault  = { { 0, 0, 0 }, { 0, 0, 0, 1 } }; // identity transform
     342           0 :             std::vector<BoneTransform> boneTransforms (skeleton.GetBoneCount(), boneDefault);
     343             : 
     344           0 :             for (size_t i = 0; i < jointCount; ++i)
     345             :             {
     346           0 :                 FCDSceneNode* joint = controllerInstance.GetJoint(i);
     347             : 
     348           0 :                 int boneId = skeleton.GetRealBoneID(joint->GetName().c_str());
     349           0 :                 if (boneId < 0)
     350             :                 {
     351             :                     // unrecognised joint - it's probably just a prop point
     352             :                     // or something, so ignore it
     353           0 :                     continue;
     354             :                 }
     355             : 
     356           0 :                 FMMatrix44 bindPose = skin->GetJoint(i)->GetBindPoseInverse().Inverted();
     357             : 
     358           0 :                 HMatrix matrix;
     359           0 :                 memcpy(matrix, bindPose.Transposed().m, sizeof(matrix));
     360             :                     // set matrix = bindPose^T, to match what decomp_affine wants
     361             : 
     362           0 :                 AffineParts parts;
     363           0 :                 decomp_affine(matrix, &parts);
     364             : 
     365           0 :                 BoneTransform b = {
     366           0 :                     { parts.t.x, parts.t.y, parts.t.z },
     367           0 :                     { parts.q.x, parts.q.y, parts.q.z, parts.q.w }
     368           0 :                 };
     369             : 
     370           0 :                 boneTransforms[boneId] = b;
     371             :             }
     372             : 
     373             :             // Construct the list of prop points.
     374             :             // Currently takes all objects that are directly attached to a
     375             :             // standard bone, and whose name begins with "prop-" or "prop_".
     376             : 
     377           0 :             std::vector<PropPoint> propPoints;
     378           0 :             AddDefaultPropPoints(propPoints);
     379             : 
     380           0 :             for (size_t i = 0; i < jointCount; ++i)
     381             :             {
     382           0 :                 FCDSceneNode* joint = controllerInstance.GetJoint(i);
     383             : 
     384           0 :                 int boneId = skeleton.GetBoneID(joint->GetName().c_str());
     385           0 :                 if (boneId < 0)
     386             :                 {
     387             :                     // unrecognised joint name - ignore, same as before
     388           0 :                     continue;
     389             :                 }
     390             : 
     391             :                 // Check all the objects attached to this bone
     392           0 :                 for (size_t j = 0; j < joint->GetChildrenCount(); ++j)
     393             :                 {
     394           0 :                     FCDSceneNode* child = joint->GetChild(j);
     395           0 :                     if (child->GetName().find("prop-") != 0 && child->GetName().find("prop_") != 0)
     396             :                     {
     397             :                         // doesn't begin with "prop-", so skip it
     398           0 :                         continue;
     399             :                     }
     400             :                     // Strip off the "prop-" from the name
     401           0 :                     std::string propPointName (child->GetName().substr(5));
     402             : 
     403           0 :                     Log(LOG_INFO, "Adding prop point %s", propPointName.c_str());
     404             : 
     405             :                     // Get translation and orientation of local transform
     406             : 
     407           0 :                     FMMatrix44 localTransform = child->ToMatrix();
     408             : 
     409           0 :                     HMatrix matrix;
     410           0 :                     memcpy(matrix, localTransform.Transposed().m, sizeof(matrix));
     411             : 
     412           0 :                     AffineParts parts;
     413           0 :                     decomp_affine(matrix, &parts);
     414             : 
     415             :                     // Add prop point to list
     416             : 
     417           0 :                     PropPoint p = {
     418             :                         propPointName,
     419           0 :                         { parts.t.x, parts.t.y, parts.t.z },
     420           0 :                         { parts.q.x, parts.q.y, parts.q.z, parts.q.w },
     421             :                         (uint8)boneId
     422           0 :                     };
     423           0 :                     propPoints.push_back(p);
     424           0 :                 }
     425             :             }
     426             : 
     427             :             // Get the raw vertex data
     428             : 
     429           0 :             FCDGeometryPolygonsInput* inputPosition = polys->FindInput(FUDaeGeometryInput::POSITION);
     430           0 :             FCDGeometryPolygonsInput* inputNormal   = polys->FindInput(FUDaeGeometryInput::NORMAL);
     431             : 
     432           0 :             const uint32* indicesCombined = inputPosition->GetIndices();
     433           0 :             size_t indicesCombinedCount = inputPosition->GetIndexCount();
     434             :             // (ReindexGeometry guarantees position/normal/texcoord have the same indexes)
     435             : 
     436           0 :             FCDGeometrySource* sourcePosition = inputPosition->GetSource();
     437           0 :             FCDGeometrySource* sourceNormal   = inputNormal  ->GetSource();
     438             : 
     439           0 :             FCDGeometrySourceList texcoordSources;
     440           0 :             polys->GetParent()->FindSourcesByType(FUDaeGeometryInput::TEXCOORD, texcoordSources);
     441             : 
     442           0 :             float* dataPosition = sourcePosition->GetData();
     443           0 :             float* dataNormal   = sourceNormal  ->GetData();
     444           0 :             size_t vertexCount = sourcePosition->GetDataCount() / 3;
     445           0 :             assert(sourcePosition->GetDataCount() == vertexCount*3);
     446           0 :             assert(sourceNormal  ->GetDataCount() == vertexCount*3);
     447             : 
     448           0 :             std::vector<float*> dataTexcoords;
     449           0 :             for (size_t i = 0; i < texcoordSources.size(); ++i)
     450             :             {
     451           0 :                 dataTexcoords.push_back(texcoordSources[i]->GetData());
     452             :             }
     453             : 
     454             :             // Transform model coordinate system to game coordinates
     455             : 
     456           0 :             TransformSkinnedModel(dataPosition, dataNormal, vertexCount, boneTransforms, propPoints,
     457             :                 converter.GetEntityTransform(), skin->GetBindShapeTransform(),
     458           0 :                 converter.IsYUp(), converter.IsXSI());
     459             : 
     460           0 :             WritePMD(output, indicesCombined, indicesCombinedCount, dataPosition, dataNormal, dataTexcoords, vertexCount, boneWeights, boneTransforms, propPoints);
     461           0 :         }
     462             :         else
     463             :         {
     464           0 :             throw ColladaException("Unrecognized object type");
     465             :         }
     466             : 
     467           5 :     }
     468             : 
     469             :     /**
     470             :      * Adds the default "root" prop-point.
     471             :      */
     472           5 :     static void AddDefaultPropPoints(std::vector<PropPoint>& propPoints)
     473             :     {
     474           5 :         PropPoint root;
     475           5 :         root.name = "root";
     476           5 :         root.translation[0] = root.translation[1] = root.translation[2] = 0.0f;
     477           5 :         root.orientation[0] = root.orientation[1] = root.orientation[2] = 0.0f;
     478           5 :         root.orientation[3] = 1.0f;
     479           5 :         root.bone = 0xFF;
     480           5 :         propPoints.push_back(root);
     481           5 :     }
     482             : 
     483             :     /**
     484             :      * Writes the model data in the PMD format.
     485             :      */
     486           5 :     static void WritePMD(OutputCB& output,
     487             :         const uint32* indices, size_t indexCount,
     488             :         const float* position, const float* normal,
     489             :         const std::vector<float*>& texcoords,
     490             :         size_t vertexCount,
     491             :         const std::vector<VertexBlend>& boneWeights, const std::vector<BoneTransform>& boneTransforms,
     492             :         const std::vector<PropPoint>& propPoints)
     493             :     {
     494           5 :         static const VertexBlend noBlend = { { 0xFF, 0xFF, 0xFF, 0xFF }, { 0, 0, 0, 0 } };
     495             : 
     496           5 :         size_t faceCount = indexCount/3;
     497           5 :         size_t boneCount = boneTransforms.size();
     498           5 :         if (boneCount)
     499             :             assert(boneWeights.size() == vertexCount);
     500             : 
     501           5 :         size_t propPointsSize = 0; // can't calculate this statically, so loop over all the prop points
     502          10 :         for (size_t i = 0; i < propPoints.size(); ++i)
     503             :         {
     504           5 :             propPointsSize += 4 + propPoints[i].name.length();
     505           5 :             propPointsSize += 3*4 + 4*4 + 1;
     506             :         }
     507             : 
     508           5 :         output("PSMD", 4);  // magic number
     509           5 :         write(output, (uint32)4); // version number
     510          10 :         write(output, (uint32)(
     511             :             // for UVs, we add one uint32 (i.e. 4 bytes) per model that gives the number of
     512             :             // texcoord sets in the model, plus 2 floats per new UV
     513             :             // pair per vertex (i.e. 8 bytes * number of pairs * vertex count)
     514           5 :             4 + 11*4*vertexCount + 4 + 8*texcoords.size()*vertexCount + // vertices
     515             :             4 + 6*faceCount + // faces
     516           5 :             4 + 7*4*boneCount + // bones
     517           5 :             4 + propPointsSize // props
     518             :             )); // data size
     519             : 
     520             :         // Vertex data
     521           5 :         write<uint32>(output, (uint32)vertexCount);
     522           5 :         write<uint32>(output, (uint32)texcoords.size()); // UV pairs per vertex
     523         366 :         for (size_t i = 0; i < vertexCount; ++i)
     524             :         {
     525         361 :             output((char*)&position[i*3], 12);
     526         361 :             output((char*)&normal  [i*3], 12);
     527             : 
     528         722 :             for (size_t s = 0; s < texcoords.size(); ++s)
     529             :             {
     530         361 :                 output((char*)&texcoords[s][i*2], 8);
     531             :             }
     532             : 
     533         361 :             if (boneCount)
     534           0 :                 write(output, boneWeights[i]);
     535             :             else
     536         722 :                 write(output, noBlend);
     537             :         }
     538             : 
     539             :         // Face data
     540           5 :         write(output, (uint32)faceCount);
     541        1013 :         for (size_t i = 0; i < indexCount; ++i)
     542             :         {
     543        1008 :             write(output, (uint16)indices[i]);
     544             :         }
     545             : 
     546             :         // Bones data
     547           5 :         write(output, (uint32)boneCount);
     548           5 :         for (size_t i = 0; i < boneCount; ++i)
     549             :         {
     550           0 :             output((char*)&boneTransforms[i], 7*4);
     551             :         }
     552             : 
     553             :         // Prop points data
     554           5 :         write(output, (uint32)propPoints.size());
     555          10 :         for (size_t i = 0; i < propPoints.size(); ++i)
     556             :         {
     557           5 :             uint32 nameLen = (uint32)propPoints[i].name.length();
     558           5 :             write(output, nameLen);
     559           5 :             output(propPoints[i].name.c_str(), nameLen);
     560           5 :             write(output, propPoints[i].translation);
     561           5 :             write(output, propPoints[i].orientation);
     562           5 :             write(output, propPoints[i].bone);
     563             :         }
     564           5 :     }
     565             : 
     566           5 :     static FCDGeometryPolygons* GetPolysFromGeometry(FCDGeometry* geom)
     567             :     {
     568           5 :         REQUIRE(geom->IsMesh(), "geometry is mesh");
     569           5 :         FCDGeometryMesh* mesh = geom->GetMesh();
     570             : 
     571           5 :         if (! mesh->IsTriangles())
     572           1 :             FCDGeometryPolygonsTools::Triangulate(mesh);
     573             : 
     574           5 :         REQUIRE(mesh->IsTriangles(), "mesh is made of triangles");
     575           5 :         REQUIRE(mesh->GetPolygonsCount() == 1, "mesh has single set of polygons");
     576           5 :         FCDGeometryPolygons* polys = mesh->GetPolygons(0);
     577           5 :         REQUIRE(polys->FindInput(FUDaeGeometryInput::POSITION) != NULL, "mesh has vertex positions");
     578           5 :         REQUIRE(polys->FindInput(FUDaeGeometryInput::NORMAL) != NULL, "mesh has vertex normals");
     579           5 :         REQUIRE(polys->FindInput(FUDaeGeometryInput::TEXCOORD) != NULL, "mesh has vertex tex coords");
     580           5 :         return polys;
     581             :     }
     582             : 
     583             :     /**
     584             :      * Applies world-space transform to vertex data and transforms Collada's right-handed
     585             :      *  Y-up / Z-up coordinates to the game's left-handed Y-up coordinate system
     586             :      *
     587             :      * TODO: Maybe we should use FCDocumentTools::StandardizeUpAxisAndLength in addition
     588             :      *      to this, so we'd only have one up-axis case to worry about, but it doesn't seem to
     589             :      *      correctly adjust the prop points in Y_UP models.
     590             :      */
     591           5 :     static void TransformStaticModel(float* position, float* normal, size_t vertexCount,
     592             :         const FMMatrix44& transform, bool yUp)
     593             :     {
     594         366 :         for (size_t i = 0; i < vertexCount; ++i)
     595             :         {
     596         361 :             FMVector3 pos (&position[i*3], 0);
     597         361 :             FMVector3 norm (&normal[i*3], 0);
     598             : 
     599             :             // Apply the scene-node transforms
     600         361 :             pos = transform.TransformCoordinate(pos);
     601         361 :             norm = FMVector3_Normalize(transform.TransformVector(norm));
     602             : 
     603             :             // Convert from right-handed Y_UP or Z_UP to the game's coordinate system (left-handed Y-up)
     604             : 
     605         361 :             if (yUp)
     606             :             {
     607           0 :                 pos.z = -pos.z;
     608           0 :                 norm.z = -norm.z;
     609             :             }
     610             :             else
     611             :             {
     612         361 :                 std::swap(pos.y, pos.z);
     613         361 :                 std::swap(norm.y, norm.z);
     614             :             }
     615             : 
     616             :             // Copy back to array
     617             : 
     618         361 :             position[i*3] = pos.x;
     619         361 :             position[i*3+1] = pos.y;
     620         361 :             position[i*3+2] = pos.z;
     621             : 
     622         361 :             normal[i*3] = norm.x;
     623         361 :             normal[i*3+1] = norm.y;
     624         361 :             normal[i*3+2] = norm.z;
     625             :         }
     626           5 :     }
     627             : 
     628             :     /**
     629             :      * Applies world-space transform to vertex data and transforms Collada's right-handed
     630             :      *  Y-up / Z-up coordinates to the game's left-handed Y-up coordinate system
     631             :      *
     632             :      * TODO: Maybe we should use FCDocumentTools::StandardizeUpAxisAndLength in addition
     633             :      *      to this, so we'd only have one up-axis case to worry about, but it doesn't seem to
     634             :      *      correctly adjust the prop points in Y_UP models.
     635             :      */
     636           0 :     static void TransformSkinnedModel(float* position, float* normal, size_t vertexCount,
     637             :         std::vector<BoneTransform>& bones, std::vector<PropPoint>& propPoints,
     638             :         const FMMatrix44& transform, const FMMatrix44& bindTransform, bool yUp, bool isXSI)
     639             :     {
     640           0 :         FMMatrix44 scaledTransform; // for vertexes
     641           0 :         FMMatrix44 scaleMatrix; // for bones
     642             : 
     643             :         // HACK: see comment in PSAConvert::TransformVertices
     644           0 :         if (isXSI)
     645             :         {
     646           0 :             scaleMatrix = DecomposeToScaleMatrix(transform);
     647           0 :             scaledTransform = DecomposeToScaleMatrix(bindTransform) * transform;
     648             :         }
     649             :         else
     650             :         {
     651           0 :             scaleMatrix = FMMatrix44_Identity;
     652           0 :             scaledTransform = bindTransform;
     653             :         }
     654             : 
     655             :         // Update the vertex positions and normals
     656           0 :         for (size_t i = 0; i < vertexCount; ++i)
     657             :         {
     658           0 :             FMVector3 pos (&position[i*3], 0);
     659           0 :             FMVector3 norm (&normal[i*3], 0);
     660             : 
     661             :             // Apply the scene-node transforms
     662           0 :             pos = scaledTransform.TransformCoordinate(pos);
     663           0 :             norm = FMVector3_Normalize(scaledTransform.TransformVector(norm));
     664             : 
     665             :             // Convert from right-handed Y_UP or Z_UP to the game's coordinate system (left-handed Y-up)
     666             : 
     667           0 :             if (yUp)
     668             :             {
     669           0 :                 pos.z = -pos.z;
     670           0 :                 norm.z = -norm.z;
     671             :             }
     672             :             else
     673             :             {
     674           0 :                 std::swap(pos.y, pos.z);
     675           0 :                 std::swap(norm.y, norm.z);
     676             :             }
     677             : 
     678             :             // and copy back into the original array
     679             : 
     680           0 :             position[i*3] = pos.x;
     681           0 :             position[i*3+1] = pos.y;
     682           0 :             position[i*3+2] = pos.z;
     683             : 
     684           0 :             normal[i*3] = norm.x;
     685           0 :             normal[i*3+1] = norm.y;
     686           0 :             normal[i*3+2] = norm.z;
     687             :         }
     688             : 
     689           0 :         TransformBones(bones, scaleMatrix, yUp);
     690             : 
     691             :         // And do the same for prop points
     692           0 :         for (size_t i = 0; i < propPoints.size(); ++i)
     693             :         {
     694           0 :             if (yUp)
     695             :             {
     696           0 :                 propPoints[i].translation[0] = -propPoints[i].translation[0];
     697           0 :                 propPoints[i].orientation[0] = -propPoints[i].orientation[0];
     698           0 :                 propPoints[i].orientation[3] = -propPoints[i].orientation[3];
     699             :             }
     700             :             else
     701             :             {
     702             :                 // Flip translation across the x-axis by swapping y and z
     703           0 :                 std::swap(propPoints[i].translation[1], propPoints[i].translation[2]);
     704             : 
     705             :                 // To convert the quaternions: imagine you're using the axis/angle
     706             :                 // representation, then swap the y,z basis vectors and change the
     707             :                 // direction of rotation by negating the angle ( => negating sin(angle)
     708             :                 // => negating x,y,z => changing (x,y,z,w) to (-x,-z,-y,w)
     709             :                 // but then (-x,-z,-y,w) == (x,z,y,-w) so do that instead)
     710           0 :                 std::swap(propPoints[i].orientation[1], propPoints[i].orientation[2]);
     711           0 :                 propPoints[i].orientation[3] = -propPoints[i].orientation[3];
     712             :             }
     713             :         }
     714             : 
     715           0 :     }
     716             : };
     717             : 
     718             : 
     719             : // The above stuff is just in a class since I don't like having to bother
     720             : // with forward declarations of functions - but provide the plain function
     721             : // interface here:
     722             : 
     723           6 : void ColladaToPMD(const char* input, OutputCB& output, std::string& xmlErrors)
     724             : {
     725           6 :     PMDConvert::ColladaToPMD(input, output, xmlErrors);
     726           5 : }

Generated by: LCOV version 1.16