LCOV - code coverage report
Current view: top level - source/collada - CommonConvert.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 103 181 56.9 %
Date: 2026-12-03 01:19:39 Functions: 11 17 64.7 %

          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 "CommonConvert.h"
      21             : 
      22             : #include "DLL.h"
      23             : #include "StdSkeletons.h"
      24             : #include "XMLFix.h"
      25             : 
      26             : #include <FCDocument/FCDAsset.h>
      27             : #include <FCDocument/FCDControllerInstance.h>
      28             : #include <FCDocument/FCDEntity.h>
      29             : #include <FCDocument/FCDEntityInstance.h>
      30             : #include <FCDocument/FCDSceneNode.h>
      31             : #include <FCDocument/FCDSkinController.h>
      32             : #include <FCollada.h>
      33             : #include <FMath/FMVector3.h>
      34             : #include <FUtils/FUString.h>
      35             : #include <algorithm>
      36             : #include <cassert>
      37             : #include <cstdarg>
      38             : #include <cstdio>
      39             : #include <libxml/xmlerror.h>
      40             : #include <libxml/xmlmemory.h>
      41             : #include <utility>
      42             : 
      43          40 : void require_(int line, bool value, const char* type, const char* message)
      44             : {
      45          40 :     if (value) return;
      46           0 :     char linestr[16];
      47           0 :     snprintf(linestr, sizeof(linestr), "%d", line);
      48           0 :     throw ColladaException(std::string(type) + " (line " + linestr + "): " + message);
      49             : }
      50             : 
      51             : /** Error handler for libxml2 */
      52          18 : void errorHandler(void* ctx, const char* msg, ...)
      53             : {
      54          18 :     char buffer[1024];
      55          18 :     va_list ap;
      56          18 :     va_start(ap, msg);
      57          18 :     vsnprintf(buffer, sizeof(buffer), msg, ap);
      58          18 :     buffer[sizeof(buffer)-1] = '\0';
      59          18 :     va_end(ap);
      60             : 
      61          18 :     *((std::string*)ctx) += buffer;
      62          18 : }
      63             : 
      64           6 : FColladaErrorHandler::FColladaErrorHandler(std::string& xmlErrors_)
      65           6 : : xmlErrors(xmlErrors_)
      66             : {
      67             :     // Grab all the error output from libxml2, for useful error reporting
      68           6 :     xmlSetGenericErrorFunc(&xmlErrors, &errorHandler);
      69             : 
      70           6 :     FUError::AddErrorCallback(FUError::DEBUG_LEVEL, this, &FColladaErrorHandler::OnError);
      71           6 :     FUError::AddErrorCallback(FUError::WARNING_LEVEL, this, &FColladaErrorHandler::OnError);
      72           6 :     FUError::AddErrorCallback(FUError::ERROR_LEVEL, this, &FColladaErrorHandler::OnError);
      73           6 : }
      74             : 
      75           6 : FColladaErrorHandler::~FColladaErrorHandler()
      76             : {
      77           6 :     xmlSetGenericErrorFunc(NULL, NULL);
      78             : 
      79           6 :     FUError::RemoveErrorCallback(FUError::DEBUG_LEVEL, this, &FColladaErrorHandler::OnError);
      80           6 :     FUError::RemoveErrorCallback(FUError::WARNING_LEVEL, this, &FColladaErrorHandler::OnError);
      81           6 :     FUError::RemoveErrorCallback(FUError::ERROR_LEVEL, this, &FColladaErrorHandler::OnError);
      82           6 : }
      83             : 
      84           8 : void FColladaErrorHandler::OnError(FUError::Level errorLevel, uint32 errorCode, uint32 /*lineNumber*/)
      85             : {
      86             :     // Ignore warnings about missing materials, since we ignore materials entirely anyway
      87           8 :     if (errorCode == FUError::WARNING_INVALID_POLYGON_MAT_SYMBOL)
      88             :         return;
      89             : 
      90           7 :     const char* errorString = FUError::GetErrorString((FUError::Code) errorCode);
      91           7 :     if (! errorString)
      92           0 :         errorString = "Unknown error code";
      93             : 
      94           7 :     if (errorLevel == FUError::DEBUG_LEVEL)
      95           5 :         Log(LOG_INFO, "FCollada %d: %s", errorCode, errorString);
      96           2 :     else if (errorLevel == FUError::WARNING_LEVEL)
      97           0 :         Log(LOG_WARNING, "FCollada %d: %s", errorCode, errorString);
      98             :     else
      99           4 :         throw ColladaException(errorString);
     100             : }
     101             : 
     102             : 
     103             : //////////////////////////////////////////////////////////////////////////
     104             : 
     105           6 : void FColladaDocument::LoadFromText(const char *text)
     106             : {
     107           6 :     document.reset(FCollada::NewTopDocument());
     108             : 
     109           6 :     const char* newText = NULL;
     110           6 :     size_t newTextSize = 0;
     111           6 :     FixBrokenXML(text, &newText, &newTextSize);
     112             : 
     113             :     // Log(LOG_INFO, "%s", newText);
     114           6 :     bool status = FCollada::LoadDocumentFromMemory("unknown.dae", document.get(), (void*)newText, newTextSize);
     115             : 
     116           5 :     if (newText != text)
     117           1 :         xmlFree((void*)newText);
     118             : 
     119           5 :     REQUIRE_SUCCESS(status);
     120           5 : }
     121             : 
     122           0 : void FColladaDocument::ReadExtras(xmlNode* /*colladaNode*/)
     123             : {
     124             :     // TODO: This was needed to recognise and load XSI models.
     125             :     // XSI support should be reintroduced some time, but this function
     126             :     // may not be necessary since FCollada might now provide access to the
     127             :     // 'extra' data via a proper API.
     128             : 
     129             :     /*
     130             :     if (! IsEquivalent(colladaNode->name, DAE_COLLADA_ELEMENT))
     131             :         return;
     132             : 
     133             :     extra.reset(new FCDExtra(document.get()));
     134             : 
     135             :     xmlNodeList extraNodes;
     136             :     FUXmlParser::FindChildrenByType(colladaNode, DAE_EXTRA_ELEMENT, extraNodes);
     137             :     for (xmlNodeList::iterator it = extraNodes.begin(); it != extraNodes.end(); ++it)
     138             :     {
     139             :         xmlNode* extraNode = (*it);
     140             :         extra->LoadFromXML(extraNode);
     141             :     }
     142             :     */
     143           0 : }
     144             : 
     145             : //////////////////////////////////////////////////////////////////////////
     146             : 
     147           6 : CommonConvert::CommonConvert(const char* text, std::string& xmlErrors)
     148           6 : : m_Err(xmlErrors)
     149             : {
     150           6 :     m_Doc.LoadFromText(text);
     151           5 :     FCDSceneNode* root = m_Doc.GetDocument()->GetVisualSceneRoot();
     152           5 :     REQUIRE(root != NULL, "has root object");
     153             : 
     154             :     // Find the instance to convert
     155           5 :     if (! FindSingleInstance(root, m_Instance, m_EntityTransform))
     156           0 :         throw ColladaException("Couldn't find object to convert");
     157             : 
     158           5 :     assert(m_Instance);
     159          10 :     Log(LOG_INFO, "Converting '%s'", m_Instance->GetEntity()->GetName().c_str());
     160             : 
     161           5 :     m_IsXSI = false;
     162           5 :     FCDAsset* asset = m_Doc.GetDocument()->GetAsset();
     163           5 :     if (asset && asset->GetContributorCount() >= 1)
     164             :     {
     165           8 :         std::string tool (asset->GetContributor(0)->GetAuthoringTool());
     166           4 :         if (tool.find("XSI") != tool.npos)
     167           0 :             m_IsXSI = true;
     168           4 :     }
     169             : 
     170           5 :     FMVector3 upAxis = m_Doc.GetDocument()->GetAsset()->GetUpAxis();
     171           5 :     m_YUp = (upAxis.y != 0); // assume either Y_UP or Z_UP (TODO: does anyone ever do X_UP?)
     172           7 : }
     173             : 
     174           5 : CommonConvert::~CommonConvert()
     175             : {
     176           5 : }
     177             : 
     178             : //////////////////////////////////////////////////////////////////////////
     179             : 
     180             : // HACK: The originals don't get exported properly from FCollada (3.02, DLL), so define
     181             : // them here instead of fixing it correctly.
     182             : const FMVector3 FMVector3_XAxis(1.0f, 0.0f, 0.0f);
     183             : static float identity[] = { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 };
     184             : FMMatrix44 FMMatrix44_Identity(identity);
     185             : 
     186           5 : struct FoundInstance
     187             : {
     188             :     FCDEntityInstance* instance;
     189             :     FMMatrix44 transform;
     190             : };
     191             : 
     192           5 : static bool IsVisible_XSI(FCDSceneNode* node, bool& visible)
     193             : {
     194             :     // Look for <extra><technique profile="XSI"><SI_Visibility><xsi_param sid="visibility">
     195             : 
     196           5 :     FCDExtra* extra = node->GetExtra();
     197           5 :     if (! extra) return false;
     198             : 
     199           5 :     FCDEType* type = extra->GetDefaultType();
     200           5 :     if (! type) return false;
     201             : 
     202           5 :     FCDETechnique* technique = type->FindTechnique("XSI");
     203           5 :     if (! technique) return false;
     204             : 
     205           0 :     FCDENode* visibility1 = technique->FindChildNode("SI_Visibility");
     206           0 :     if (! visibility1) return false;
     207             : 
     208           0 :     FCDENode* visibility2 = visibility1->FindChildNode("xsi_param");
     209           0 :     if (! visibility2) return false;
     210             : 
     211           0 :     if (IsEquivalent(visibility2->GetContent(), "TRUE"))
     212           0 :         visible = true;
     213           0 :     else if (IsEquivalent(visibility2->GetContent(), "FALSE"))
     214           0 :         visible = false;
     215             :     return true;
     216             : }
     217             : 
     218           5 : static bool IsVisible(FCDSceneNode* node)
     219             : {
     220           5 :     bool visible = false;
     221             : 
     222             :     // Try the XSI visibility property
     223           5 :     if (IsVisible_XSI(node, visible))
     224           0 :         return visible;
     225             : 
     226             :     // Else fall back to the FCollada-specific setting
     227           5 :     visible = (node->GetVisibility() != 0.0);
     228           5 :     return visible;
     229             : }
     230             : 
     231             : /**
     232             :  * Recursively finds all entities under the current node. If onlyMarked is
     233             :  * set, only matches entities where the user-defined property was set to
     234             :  * "export" in the modelling program.
     235             :  *
     236             :  * @param node root of subtree to search
     237             :  * @param instances output - appends matching entities
     238             :  * @param transform transform matrix of current subtree
     239             :  * @param onlyMarked only match entities with "export" property
     240             :  */
     241          22 : static void FindInstances(FCDSceneNode* node, std::vector<FoundInstance>& instances, const FMMatrix44& transform, bool onlyMarked)
     242             : {
     243          34 :     for (size_t i = 0; i < node->GetChildrenCount(); ++i)
     244             :     {
     245          12 :         FCDSceneNode* child = node->GetChild(i);
     246          12 :         FindInstances(child, instances, transform * node->ToMatrix(), onlyMarked);
     247             :     }
     248             : 
     249          32 :     for (size_t i = 0; i < node->GetInstanceCount(); ++i)
     250             :     {
     251          10 :         if (onlyMarked)
     252             :         {
     253           5 :             if (node->GetNote() != "export")
     254           5 :                 continue;
     255             :         }
     256             : 
     257             :         // Only accept instances of appropriate types, and not e.g. lights
     258          10 :         FCDEntity::Type type = node->GetInstance(i)->GetEntityType();
     259           5 :         if (! (type == FCDEntity::GEOMETRY || type == FCDEntity::CONTROLLER))
     260           0 :             continue;
     261             : 
     262             :         // Ignore invisible objects, because presumably nobody wanted to export them
     263          10 :         if (! IsVisible(node))
     264           0 :             continue;
     265             : 
     266           5 :         FoundInstance f;
     267           5 :         f.transform = transform * node->ToMatrix();
     268           5 :         f.instance = node->GetInstance(i);
     269           5 :         instances.push_back(f);
     270          10 :         Log(LOG_INFO, "Found convertible object '%s'", node->GetName().c_str());
     271             :     }
     272          22 : }
     273             : 
     274           5 : bool FindSingleInstance(FCDSceneNode* node, FCDEntityInstance*& instance, FMMatrix44& transform)
     275             : {
     276           5 :     std::vector<FoundInstance> instances;
     277             : 
     278           5 :     FindInstances(node, instances, FMMatrix44_Identity, true);
     279           5 :     if (instances.size() > 1)
     280             :     {
     281           0 :         Log(LOG_ERROR, "Found too many export-marked objects");
     282             :         return false;
     283             :     }
     284           5 :     if (instances.empty())
     285             :     {
     286           5 :         FindInstances(node, instances, FMMatrix44_Identity, false);
     287           5 :         if (instances.size() > 1)
     288             :         {
     289           0 :             Log(LOG_ERROR, "Found too many possible objects to convert - try adding the 'export' property to disambiguate one");
     290             :             return false;
     291             :         }
     292           5 :         if (instances.empty())
     293             :         {
     294           0 :             Log(LOG_ERROR, "Didn't find any objects in the scene");
     295             :             return false;
     296             :         }
     297             :     }
     298             : 
     299           5 :     assert(instances.size() == 1); // if we got this far
     300           5 :     instance = instances[0].instance;
     301           5 :     transform = instances[0].transform;
     302             :     return true;
     303           5 : }
     304             : 
     305             : //////////////////////////////////////////////////////////////////////////
     306             : 
     307           0 : static bool ReverseSortWeight(const FCDJointWeightPair& a, const FCDJointWeightPair& b)
     308             : {
     309           0 :     return (a.weight > b.weight);
     310             : }
     311             : 
     312           0 : void SkinReduceInfluences(FCDSkinController* skin, size_t maxInfluenceCount, float minimumWeight)
     313             : {
     314             :     // Approximately equivalent to:
     315             :     //    skin->ReduceInfluences(maxInfluenceCount, minimumWeight);
     316             :     // except this version merges multiple weights for the same joint
     317             : 
     318           0 :     for (size_t i = 0; i < skin->GetInfluenceCount(); ++i)
     319             :     {
     320           0 :         FCDSkinControllerVertex& influence = *skin->GetVertexInfluence(i);
     321             : 
     322           0 :         std::vector<FCDJointWeightPair> newWeights;
     323           0 :         for (size_t j = 0; j < influence.GetPairCount(); ++j)
     324             :         {
     325           0 :             FCDJointWeightPair* weight = influence.GetPair(j);
     326             : 
     327           0 :             for (size_t k = 0; k < newWeights.size(); ++k)
     328             :             {
     329           0 :                 FCDJointWeightPair& newWeight = newWeights[k];
     330           0 :                 if (weight->jointIndex == newWeight.jointIndex)
     331             :                 {
     332           0 :                     newWeight.weight += weight->weight;
     333           0 :                     goto MERGED_WEIGHTS;
     334             :                 }
     335             :             }
     336             : 
     337           0 :             newWeights.push_back(*weight);
     338           0 : MERGED_WEIGHTS: ;
     339             :         }
     340             : 
     341             :         // Put highest-weighted influences at the front of the list
     342           0 :         std::sort(newWeights.begin(), newWeights.end(), ReverseSortWeight);
     343             : 
     344             :         // Limit the maximum number of influences
     345           0 :         if (newWeights.size() > maxInfluenceCount)
     346           0 :             newWeights.resize(maxInfluenceCount);
     347             : 
     348             :         // Enforce the minimum weight per influence
     349             :         // (This is done here rather than in the earlier loop, because several
     350             :         // small weights for the same bone might add up to a value above the
     351             :         // threshold)
     352           0 :         while (!newWeights.empty() && newWeights.back().weight < minimumWeight)
     353           0 :             newWeights.pop_back();
     354             : 
     355             :         // Renormalise, so sum(weights)=1
     356           0 :         float totalWeight = 0;
     357           0 :         for (std::vector<FCDJointWeightPair>::iterator itNW = newWeights.begin(); itNW != newWeights.end(); ++itNW)
     358           0 :             totalWeight += itNW->weight;
     359           0 :         for (std::vector<FCDJointWeightPair>::iterator itNW = newWeights.begin(); itNW != newWeights.end(); ++itNW)
     360           0 :             itNW->weight /= totalWeight;
     361             : 
     362             :         // Copy new weights into the skin
     363           0 :         influence.SetPairCount(0);
     364           0 :         for (std::vector<FCDJointWeightPair>::iterator itNW = newWeights.begin(); itNW != newWeights.end(); ++itNW)
     365           0 :             influence.AddPair(itNW->jointIndex, itNW->weight);
     366           0 :     }
     367             : 
     368           0 :     skin->SetDirtyFlag();
     369           0 : }
     370             : 
     371             : 
     372           0 : void FixSkeletonRoots(FCDControllerInstance&)
     373             : {
     374             :     // TODO: Need to reintroduce XSI support at some point
     375             : #if 0
     376             :     // HACK: The XSI exporter doesn't do a <skeleton> and FCollada doesn't
     377             :     // seem to know where else to look, so just guess that it's somewhere
     378             :     // under Scene_Root
     379             :     if (controllerInstance.GetSkeletonRoots().empty())
     380             :     {
     381             :         // HACK (evil): SetSkeletonRoot is declared but not defined, and there's
     382             :         // no other proper way to modify the skeleton-roots list, so cheat horribly
     383             :         FUUriList& uriList = const_cast<FUUriList&>(controllerInstance.GetSkeletonRoots());
     384             :         uriList.push_back(FUUri("Scene_Root"));
     385             :         controllerInstance.LinkImport();
     386             :     }
     387             : #endif
     388           0 : }
     389             : 
     390           0 : const Skeleton& FindSkeleton(const FCDControllerInstance& controllerInstance)
     391             : {
     392             :     // I can't see any proper way to determine the real root of the skeleton,
     393             :     // so just choose an arbitrary bone and search upwards until we find a
     394             :     // recognised ancestor (or until we fall off the top of the tree)
     395             : 
     396           0 :     const Skeleton* skeleton = NULL;
     397           0 :     const FCDSceneNode* joint = controllerInstance.GetJoint(0);
     398           0 :     while (joint && (skeleton = Skeleton::FindSkeleton(joint->GetName().c_str())) == NULL)
     399             :     {
     400           0 :         joint = joint->GetParent();
     401             :     }
     402           0 :     REQUIRE(skeleton != NULL, "recognised skeleton structure");
     403           0 :     return *skeleton;
     404             : }
     405             : 
     406           0 : void TransformBones(std::vector<BoneTransform>& bones, const FMMatrix44& scaleTransform, bool yUp)
     407             : {
     408           0 :     for (size_t i = 0; i < bones.size(); ++i)
     409             :     {
     410             :         // Apply the desired transformation to the bone coordinates
     411           0 :         FMVector3 trans(bones[i].translation, 0);
     412           0 :         trans = scaleTransform.TransformCoordinate(trans);
     413           0 :         bones[i].translation[0] = trans.x;
     414           0 :         bones[i].translation[1] = trans.y;
     415           0 :         bones[i].translation[2] = trans.z;
     416             : 
     417             :         // DON'T apply the transformation to orientation, because I can't get
     418             :         // that kind of thing to work in practice (interacting nicely between
     419             :         // the models and animations), so this function assumes the transform
     420             :         // just does scaling, so there's no need to rotate anything. (But I think
     421             :         // this code would work for rotation, though not very efficiently.)
     422             :         /*
     423             :         FMMatrix44 m = FMQuaternion(bones[i].orientation[0], bones[i].orientation[1], bones[i].orientation[2], bones[i].orientation[3]).ToMatrix();
     424             :         m *= scaleTransform;
     425             :         HMatrix matrix;
     426             :         memcpy(matrix, m.Transposed().m, sizeof(matrix));
     427             :         AffineParts parts;
     428             :         decomp_affine(matrix, &parts);
     429             : 
     430             :         bones[i].orientation[0] = parts.q.x;
     431             :         bones[i].orientation[1] = parts.q.y;
     432             :         bones[i].orientation[2] = parts.q.z;
     433             :         bones[i].orientation[3] = parts.q.w;
     434             :         */
     435             : 
     436           0 :         if (yUp)
     437             :         {
     438             :             // TODO: this is all just guesses which seem to work for data
     439             :             // exported from XSI, rather than having been properly thought
     440             :             // through
     441           0 :             bones[i].translation[2] = -bones[i].translation[2];
     442           0 :             bones[i].orientation[2] = -bones[i].orientation[2];
     443           0 :             bones[i].orientation[3] = -bones[i].orientation[3];
     444             :         }
     445             :         else
     446             :         {
     447             :             // Convert bone translations from xyz into xzy axes:
     448           0 :             std::swap(bones[i].translation[1], bones[i].translation[2]);
     449             : 
     450             :             // To convert the quaternions: imagine you're using the axis/angle
     451             :             // representation, then swap the y,z basis vectors and change the
     452             :             // direction of rotation by negating the angle ( => negating sin(angle)
     453             :             // => negating x,y,z => changing (x,y,z,w) to (-x,-z,-y,w)
     454             :             // but then (-x,-z,-y,w) == (x,z,y,-w) so do that instead)
     455           0 :             std::swap(bones[i].orientation[1], bones[i].orientation[2]);
     456           0 :             bones[i].orientation[3] = -bones[i].orientation[3];
     457             :         }
     458             :     }
     459           0 : }

Generated by: LCOV version 1.16