assetImporter.cpp 144 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402
  1. #include "assetImporter.h"
  2. #include "assetImporter_ScriptBinding.h"
  3. #include "core/strings/findMatch.h"
  4. #include "ImageAsset.h"
  5. #include "ShapeAsset.h"
  6. #include "SoundAsset.h"
  7. #include "MaterialAsset.h"
  8. #include "ShapeAnimationAsset.h"
  9. #include "ts/collada/colladaUtils.h"
  10. #include "ts/collada/colladaAppNode.h"
  11. #include "ts/collada/colladaShapeLoader.h"
  12. #include "ts/assimp/assimpShapeLoader.h"
  13. #include "ts/tsShapeConstruct.h"
  14. #include "core/resourceManager.h"
  15. #include "materials/materialManager.h"
  16. #include "console/persistenceManager.h"
  17. #include "core/util/timeClass.h"
  18. ConsoleDocClass(AssetImportConfig,
  19. "@brief Defines properties for an AssetImprotConfig object.\n"
  20. "@AssetImportConfig is a SimObject derived object intended to act as a container for all the necessary configuration data when running the Asset Importer.\n"
  21. "@It dictates if and how any given asset type will be processed when running an import action. This is because the Asset Importer utilizes a lot of informed logic\n"
  22. "@to try and automate as much of the import process as possible. In theory, you would run the import on a given file, and based on your config the importer will do\n"
  23. "@everything from importing the designated file, as well as finding and importing any associated files such as images or materials, and prepping the objects at time\n"
  24. "@of import to avoid as much manual post-processing as possible.\n\n"
  25. "@ingroup Assets\n"
  26. );
  27. IMPLEMENT_CONOBJECT(AssetImportConfig);
  28. AssetImportConfig::AssetImportConfig() :
  29. DuplicateAutoResolution("AutoRename"),
  30. WarningsAsErrors(false),
  31. PreventImportWithErrors(true),
  32. AutomaticallyPromptMissingFiles(false),
  33. AddDirectoryPrefixToAssetName(false),
  34. ImportMesh(true),
  35. AlwaysAddShapeSuffix(false),
  36. AddedShapeSuffix("_shape"),
  37. UseManualShapeConfigRules(false),
  38. DoUpAxisOverride(false),
  39. UpAxisOverride("Z_AXIS"),
  40. DoScaleOverride(false),
  41. ScaleOverride(false),
  42. IgnoreNodeScale(false),
  43. AdjustCenter(false),
  44. AdjustFloor(false),
  45. CollapseSubmeshes(false),
  46. LODType("TrailingNumber"),
  47. AlwaysImportedNodes(""),
  48. AlwaysIgnoreNodes(""),
  49. AlwaysImportMeshes(""),
  50. AlwaysIgnoreMeshes(""),
  51. convertLeftHanded(false),
  52. calcTangentSpace(false),
  53. removeRedundantMats(false),
  54. genUVCoords(false),
  55. TransformUVs(false),
  56. flipUVCoords(false),
  57. findInstances(false),
  58. limitBoneWeights(false),
  59. JoinIdenticalVerts(false),
  60. reverseWindingOrder(false),
  61. invertNormals(false),
  62. ImportMaterials(true),
  63. AlwaysAddMaterialSuffix(true),
  64. AddedMaterialSuffix("_mat"),
  65. CreateORMConfig(true),
  66. UseDiffuseSuffixOnOriginImage(false),
  67. UseExistingMaterials(false),
  68. IgnoreMaterials(""),
  69. PopulateMaterialMaps(true),
  70. ImportAnimations(true),
  71. SeparateAnimations(false),
  72. SeparateAnimationPrefix(""),
  73. animTiming("FrameCount"),
  74. animFPS(30),
  75. AlwaysAddShapeAnimationSuffix(true),
  76. AddedShapeAnimationSuffix("_anim"),
  77. GenerateCollisions(false),
  78. GenCollisionType(""),
  79. CollisionMeshPrefix(""),
  80. GenerateLOSCollisions(false),
  81. GenLOSCollisionType(""),
  82. LOSCollisionMeshPrefix(""),
  83. importImages(true),
  84. AlwaysAddImageSuffix(true),
  85. AddedImageSuffix("_image"),
  86. ImageType("GUI"),
  87. DiffuseTypeSuffixes("_ALBEDO,_DIFFUSE,_ALB,_DIF,_COLOR,_COL,_A,_C,-ALBEDO,-DIFFUSE,-ALB,-DIF,-COLOR,-COL,-A,-C"),
  88. NormalTypeSuffixes("_NORMAL,_NORM,_N,-NORMAL,-NORM,-N"),
  89. MetalnessTypeSuffixes("_METAL,_MET,_METALNESS,_METALLIC,_M,-METAL,-MET,-METALNESS,-METALLIC,-M"),
  90. RoughnessTypeSuffixes("_ROUGH,_ROUGHNESS,_R,-ROUGH,-ROUGHNESS,-R"),
  91. SmoothnessTypeSuffixes("_SMOOTH,_SMOOTHNESS,_S,-SMOOTH,-SMOOTHNESS,-S"),
  92. AOTypeSuffixes("_AO,_AMBIENT,_AMBIENTOCCLUSION,-AO,-AMBIENT,-AMBIENTOCCLUSION"),
  93. PBRTypeSuffixes("_COMP,_COMPOSITE,_PBR,-COMP,-COMPOSITE,-PBR,_ORM,-ORM"),
  94. TextureFilteringMode("Bilinear"),
  95. UseMips(true),
  96. IsHDR(false),
  97. Scaling(false),
  98. ImagesCompressed(false),
  99. GenerateMaterialOnImport(true),
  100. importSounds(true),
  101. VolumeAdjust(false),
  102. PitchAdjust(false),
  103. SoundsCompressed(false),
  104. AlwaysAddSoundSuffix(false),
  105. AddedSoundSuffix("_sound")
  106. {
  107. }
  108. AssetImportConfig::~AssetImportConfig()
  109. {
  110. }
  111. bool AssetImportConfig::onAdd()
  112. {
  113. if (!Parent::onAdd())
  114. return false;
  115. return true;
  116. }
  117. void AssetImportConfig::onRemove()
  118. {
  119. Parent::onRemove();
  120. }
  121. /// Engine.
  122. void AssetImportConfig::initPersistFields()
  123. {
  124. docsURL;
  125. Parent::initPersistFields();
  126. addGroup("General");
  127. addField("DuplicateAutoResolution", TypeRealString, Offset(DuplicateAutoResolution, AssetImportConfig), "Duplicate Asset Auto-Resolution Action. Options are None, AutoPrune, AutoRename, FolderPrefix");
  128. addField("WarningsAsErrors", TypeBool, Offset(WarningsAsErrors, AssetImportConfig), "Indicates if warnings should be treated as errors");
  129. addField("PreventImportWithErrors", TypeBool, Offset(PreventImportWithErrors, AssetImportConfig), "Indicates if importing should be prevented from completing if any errors are detected at all");
  130. addField("AutomaticallyPromptMissingFiles", TypeBool, Offset(AutomaticallyPromptMissingFiles, AssetImportConfig), "Should the importer automatically prompt to find missing files if they are not detected automatically by the importer");
  131. addField("AddDirectoryPrefixToAssetName", TypeBool, Offset(AddDirectoryPrefixToAssetName, AssetImportConfig), "Should the importer add the folder name as a prefix to the assetName. Helps prevent name collisions.");
  132. endGroup("General");
  133. addGroup("Meshes");
  134. addField("ImportMesh", TypeBool, Offset(ImportMesh, AssetImportConfig), "Indicates if this config supports importing meshes");
  135. addField("AlwaysAddShapeSuffix", TypeBool, Offset(AlwaysAddShapeSuffix, AssetImportConfig), "When importing a shape, this indicates if it should automatically add a standard suffix onto the name");
  136. addField("AddedShapeSuffix", TypeString, Offset(AddedShapeSuffix, AssetImportConfig), " If AlwaysAddShapeSuffix is on, this is the suffix to be added");
  137. addField("UseManualShapeConfigRules", TypeBool, Offset(UseManualShapeConfigRules, AssetImportConfig), "Indicates if this config should override the per-format sis files with the config's specific settings");
  138. addField("DoUpAxisOverride", TypeBool, Offset(DoUpAxisOverride, AssetImportConfig), "Indicates if the up axis in the model file should be overridden");
  139. addField("UpAxisOverride", TypeRealString, Offset(UpAxisOverride, AssetImportConfig), "If overriding, what axis should be used as up. Options are X_AXIS, Y_AXIS, Z_AXIS");
  140. addField("DoScaleOverride", TypeBool, Offset(DoScaleOverride, AssetImportConfig), "Indicates if the scale in the model file should be overridden");
  141. addFieldV("ScaleOverride", TypeRangedF32, Offset(ScaleOverride, AssetImportConfig), &CommonValidators::PositiveFloat, "If overriding, what scale should be used");
  142. addField("IgnoreNodeScale", TypeBool, Offset(IgnoreNodeScale, AssetImportConfig), "Indicates if scale of nodes should be ignored");
  143. addField("AdjustCenter", TypeBool, Offset(AdjustCenter, AssetImportConfig), "Indicates if the center of the model file should be automatically recentered");
  144. addField("AdjustFloor", TypeBool, Offset(AdjustFloor, AssetImportConfig), "Indicates if the floor height of the model file should be automatically zero'd");
  145. addField("CollapseSubmeshes", TypeBool, Offset(CollapseSubmeshes, AssetImportConfig), "Indicates if submeshes should be collapsed down into a single main mesh");
  146. addField("LODType", TypeRealString, Offset(LODType, AssetImportConfig), "Indicates what LOD mode the model file should utilize to process out LODs. Options are TrailingNumber, DetectDTS, SingleSize");
  147. addField("singleDetailSize", TypeS32, Offset(singleDetailSize, AssetImportConfig), "what lod value to use if all submeshes are set to the same detail level");
  148. addField("AlwaysImportedNodes", TypeRealString, Offset(AlwaysImportedNodes, AssetImportConfig), " A list of what nodes should be guaranteed to be imported if found in the model file. Separated by either , or ;");
  149. addField("AlwaysIgnoreNodes", TypeRealString, Offset(AlwaysIgnoreNodes, AssetImportConfig), "A list of what nodes should be guaranteed to not be imported if found in the model file. Separated by either , or ;");
  150. addField("AlwaysImportMeshes", TypeRealString, Offset(AlwaysImportMeshes, AssetImportConfig), "A list of what mesh objects should be guaranteed to be imported if found in the model file. Separated by either , or ;");
  151. addField("AlwaysIgnoreMeshes", TypeRealString, Offset(AlwaysIgnoreMeshes, AssetImportConfig), "A list of what mesh objects should be guaranteed to not be imported if found in the model file. Separated by either , or ;");
  152. addField("convertLeftHanded", TypeBool, Offset(convertLeftHanded, AssetImportConfig), "Flag to indicate the shape loader should convert to a left-handed coordinate system");
  153. addField("calcTangentSpace", TypeBool, Offset(calcTangentSpace, AssetImportConfig), "Should the shape loader calculate tangent space values");
  154. addField("removeRedundantMats", TypeBool, Offset(removeRedundantMats, AssetImportConfig), "Should the shape loader automatically prune redundant/duplicate materials");
  155. addField("genUVCoords", TypeBool, Offset(genUVCoords, AssetImportConfig), "Should the shape loader auto-generate UV Coordinates for the mesh.");
  156. addField("TransformUVs", TypeBool, Offset(TransformUVs, AssetImportConfig), "Should the UV coordinates be transformed");
  157. addField("flipUVCoords", TypeBool, Offset(flipUVCoords, AssetImportConfig), "Should the UV coordinates be flipped");
  158. addField("findInstances", TypeBool, Offset(findInstances, AssetImportConfig), "Should the shape loader automatically look for instanced submeshes in the model file");
  159. addField("limitBoneWeights", TypeBool, Offset(limitBoneWeights, AssetImportConfig), "Should the shape loader limit the bone weights");
  160. addField("JoinIdenticalVerts", TypeBool, Offset(JoinIdenticalVerts, AssetImportConfig), "Should the shape loader automatically merge identical/duplicate verts");
  161. addField("reverseWindingOrder", TypeBool, Offset(reverseWindingOrder, AssetImportConfig), "Should the shape loader reverse the winding order of the mesh's face indicies");
  162. addField("invertNormals", TypeBool, Offset(invertNormals, AssetImportConfig), "Should the normals on the model be inverted");
  163. endGroup("Meshes");
  164. addGroup("Materials");
  165. addField("ImportMaterials", TypeBool, Offset(ImportMaterials, AssetImportConfig), "Does this config allow for importing of materials");
  166. addField("AlwaysAddMaterialSuffix", TypeBool, Offset(AlwaysAddMaterialSuffix, AssetImportConfig), "When importing a material, this indicates if it should automatically add a standard suffix onto the name");
  167. addField("AddedMaterialSuffix", TypeString, Offset(AddedMaterialSuffix, AssetImportConfig), " If AlwaysAddMaterialSuffix is on, this is the suffix to be added");
  168. addField("CreateORMConfig", TypeBool, Offset(PreventImportWithErrors, AssetImportConfig), "When importing a material, should it automatically attempt to merge Roughness, AO and Metalness maps into a single, composited PBR Configuration map");
  169. addField("UseDiffuseSuffixOnOriginImage", TypeBool, Offset(UseDiffuseSuffixOnOriginImage, AssetImportConfig), "When generating a material off of an importing image, should the importer force appending a diffusemap suffix onto the end to avoid potential naming confusion.\n e.g. MyCoolStuff.png is imported, generating MyCoolStuff material asset and MyCoolStuff_Diffuse image asset");
  170. addField("UseExistingMaterials", TypeBool, Offset(UseExistingMaterials, AssetImportConfig), "Should the importer try and use existing material assets in the game directory if at all possible. (Not currently utilized)");
  171. addField("IgnoreMaterials", TypeRealString, Offset(IgnoreMaterials, AssetImportConfig), "A list of material names that should not be imported. Separated by either , or ;");
  172. addField("PopulateMaterialMaps", TypeBool, Offset(PopulateMaterialMaps, AssetImportConfig), "When processing a material asset, should the importer attempt to populate the various material maps on it by looking up common naming conventions for potentially relevent image files.\n e.g. If MyCoolStuff_Diffuse.png is imported, generating MyCoolStuff material, it would also find MyCoolStuff_Normal and MyCoolStuff_PBR images and map them to the normal and ORMConfig maps respectively automatically");
  173. endGroup("Materials");
  174. addGroup("Animation");
  175. addField("ImportAnimations", TypeBool, Offset(ImportAnimations, AssetImportConfig), "Does this config allow for importing Shape Animations");
  176. addField("SeparateAnimations", TypeBool, Offset(SeparateAnimations, AssetImportConfig), "When importing a shape file, should the animations within be separated out into unique files");
  177. addField("SeparateAnimationPrefix", TypeRealString, Offset(SeparateAnimationPrefix, AssetImportConfig), "If separating animations out from a source file, what prefix should be added to the names for grouping association");
  178. addField("animTiming", TypeRealString, Offset(animTiming, AssetImportConfig), "Defines the animation timing for the given animation sequence. Options are FrameTime, Seconds, Milliseconds");
  179. addField("animFPS", TypeF32, Offset(animFPS, AssetImportConfig), "The FPS of the animation sequence");
  180. addField("AlwaysAddShapeAnimationSuffix", TypeBool, Offset(AlwaysAddShapeAnimationSuffix, AssetImportConfig), "When importing a shape animation, this indicates if it should automatically add a standard suffix onto the name");
  181. addField("AddedShapeAnimationSuffix", TypeString, Offset(AddedShapeAnimationSuffix, AssetImportConfig), " If AlwaysAddShapeAnimationSuffix is on, this is the suffix to be added");
  182. endGroup("Animation");
  183. addGroup("Collision");
  184. addField("GenerateCollisions", TypeBool, Offset(GenerateCollisions, AssetImportConfig), "Does this configuration generate collision geometry when importing. (Not currently enabled)");
  185. addField("GenCollisionType", TypeRealString, Offset(GenCollisionType, AssetImportConfig), "What sort of collision geometry is generated. (Not currently enabled)");
  186. addField("CollisionMeshPrefix", TypeRealString, Offset(CollisionMeshPrefix, AssetImportConfig), "What prefix is added to the collision geometry generated. (Not currently enabled)");
  187. addField("GenerateLOSCollisions", TypeBool, Offset(GenerateLOSCollisions, AssetImportConfig), "Does this configuration generate Line of Sight collision geometry. (Not currently enabled)");
  188. addField("GenLOSCollisionType", TypeRealString, Offset(GenLOSCollisionType, AssetImportConfig), "What sort of Line of Sight collision geometry is generated. (Not currently enabled)");
  189. addField("LOSCollisionMeshPrefix", TypeRealString, Offset(LOSCollisionMeshPrefix, AssetImportConfig), "What prefix is added to the Line of Sight collision geometry generated. (Not currently enabled)");
  190. endGroup("Collision");
  191. addGroup("Images");
  192. addField("importImages", TypeBool, Offset(importImages, AssetImportConfig), "Does this configuration support importing images.");
  193. addField("AlwaysAddImageSuffix", TypeBool, Offset(AlwaysAddImageSuffix, AssetImportConfig), "When importing an image, this indicates if it should automatically add a standard suffix onto the name");
  194. addField("AddedImageSuffix", TypeString, Offset(AddedImageSuffix, AssetImportConfig), " If AlwaysAddImageSuffix is on, this is the suffix to be added");
  195. addField("ImageType", TypeRealString, Offset(ImageType, AssetImportConfig), "What is the default ImageType images are imported as. Options are: N/A, Diffuse, Normal, Metalness, Roughness, AO, ORMConfig, GUI, Cubemap");
  196. addField("DiffuseTypeSuffixes", TypeRealString, Offset(DiffuseTypeSuffixes, AssetImportConfig), "What type of suffixes are scanned to detect if an importing image is a diffuse map. \n e.g. _Albedo or _Color");
  197. addField("NormalTypeSuffixes", TypeRealString, Offset(NormalTypeSuffixes, AssetImportConfig), "What type of suffixes are scanned to detect if an importing image is a normal map. \n e.g. _Normal or _Norm");
  198. addField("MetalnessTypeSuffixes", TypeRealString, Offset(MetalnessTypeSuffixes, AssetImportConfig), "What type of suffixes are scanned to detect if an importing image is a metalness map. \n e.g. _Metalness or _Metal");
  199. addField("RoughnessTypeSuffixes", TypeRealString, Offset(RoughnessTypeSuffixes, AssetImportConfig), "What type of suffixes are scanned to detect if an importing image is a roughness map.\n e.g. _roughness or _rough");
  200. addField("SmoothnessTypeSuffixes", TypeRealString, Offset(SmoothnessTypeSuffixes, AssetImportConfig), "What type of suffixes are scanned to detect if an importing image is a smoothness map. \n e.g. _smoothness or _smooth");
  201. addField("AOTypeSuffixes", TypeRealString, Offset(AOTypeSuffixes, AssetImportConfig), "What type of suffixes are scanned to detect if an importing image is a ambient occlusion map. \n e.g. _ambient or _ao");
  202. addField("PBRTypeSuffixes", TypeRealString, Offset(PBRTypeSuffixes, AssetImportConfig), "What type of suffixes are scanned to detect if an importing image is a ORMConfig map.\n e.g. _Composite or _PBR");
  203. addField("TextureFilteringMode", TypeRealString, Offset(TextureFilteringMode, AssetImportConfig), "Indicates what filter mode images imported with this configuration utilizes. Options are Linear, Bilinear, Trilinear");
  204. addField("UseMips", TypeBool, Offset(UseMips, AssetImportConfig), "Indicates if images imported with this configuration utilize mipmaps");
  205. addField("IsHDR", TypeBool, Offset(IsHDR, AssetImportConfig), "Indicates if images imported with this configuration are in an HDR format");
  206. addFieldV("Scaling", TypeRangedF32, Offset(Scaling, AssetImportConfig), &CommonValidators::PositiveFloat, "Indicates what amount of scaling images imported with this configuration use");
  207. addField("ImagesCompressed", TypeBool, Offset(ImagesCompressed, AssetImportConfig), "Indicates if images imported with this configuration are compressed");
  208. addField("GenerateMaterialOnImport", TypeBool, Offset(GenerateMaterialOnImport, AssetImportConfig), "Indicates if images imported with this configuration generate a parent material for it as well");
  209. endGroup("Images");
  210. addGroup("Sounds");
  211. addField("importSounds", TypeBool, Offset(importSounds, AssetImportConfig), "Indicates if sounds are imported with this configuration");
  212. addFieldV("VolumeAdjust", TypeRangedF32, Offset(VolumeAdjust, AssetImportConfig), &CommonValidators::PositiveFloat, "Indicates what amount the volume is adjusted on sounds imported with this configuration");
  213. addFieldV("PitchAdjust", TypeRangedF32, Offset(PitchAdjust, AssetImportConfig), &CommonValidators::PositiveFloat, "Indicates what amount the pitch is adjusted on sounds imported with this configuration");
  214. addField("SoundsCompressed", TypeBool, Offset(SoundsCompressed, AssetImportConfig), "Indicates if sounds imported with this configuration are compressed");
  215. endGroup("Sounds");
  216. }
  217. void AssetImportConfig::loadImportConfig(Settings* configSettings, String configName)
  218. {
  219. //General
  220. DuplicateAutoResolution = configSettings->value(String(configName + "/General/DuplicateAutoResolution").c_str());
  221. WarningsAsErrors = dAtob(configSettings->value(String(configName + "/General/WarningsAsErrors").c_str()));
  222. PreventImportWithErrors = dAtob(configSettings->value(String(configName + "/General/PreventImportWithErrors").c_str()));
  223. AutomaticallyPromptMissingFiles = dAtob(configSettings->value(String(configName + "/General/AutomaticallyPromptMissingFiles").c_str()));
  224. AddDirectoryPrefixToAssetName = dAtob(configSettings->value(String(configName + "/General/AddDirectoryPrefixToAssetName").c_str()));
  225. //Meshes
  226. ImportMesh = dAtob(configSettings->value(String(configName + "/Meshes/ImportMesh").c_str()));
  227. AlwaysAddShapeSuffix = dAtob(configSettings->value(String(configName + "/Meshes/AlwaysAddShapeSuffix").c_str()));
  228. AddedShapeSuffix = configSettings->value(String(configName + "/Meshes/AddedShapeSuffix").c_str());
  229. UseManualShapeConfigRules = dAtob(configSettings->value(String(configName + "/Meshes/UseManualShapeConfigRules").c_str()));
  230. DoUpAxisOverride = dAtob(configSettings->value(String(configName + "/Meshes/DoUpAxisOverride").c_str()));
  231. UpAxisOverride = configSettings->value(String(configName + "/Meshes/UpAxisOverride").c_str());
  232. DoScaleOverride = dAtob(configSettings->value(String(configName + "/Meshes/DoScaleOverride").c_str()));
  233. ScaleOverride = dAtof(configSettings->value(String(configName + "/Meshes/ScaleOverride").c_str()));
  234. IgnoreNodeScale = dAtob(configSettings->value(String(configName + "/Meshes/IgnoreNodeScale").c_str()));
  235. AdjustCenter = dAtob(configSettings->value(String(configName + "/Meshes/AdjustCenter").c_str()));
  236. AdjustFloor = dAtob(configSettings->value(String(configName + "/Meshes/AdjustFloor").c_str()));
  237. CollapseSubmeshes = dAtob(configSettings->value(String(configName + "/Meshes/CollapseSubmeshes").c_str()));
  238. LODType = configSettings->value(String(configName + "/Meshes/LODType").c_str());
  239. singleDetailSize = dAtoi(configSettings->value(String(configName + "/Meshes/singleDetailSize").c_str()));
  240. AlwaysImportedNodes = configSettings->value(String(configName + "/Meshes/AlwaysImportedNodes").c_str());
  241. AlwaysIgnoreNodes = configSettings->value(String(configName + "/Meshes/AlwaysIgnoreNodes").c_str());
  242. AlwaysImportMeshes = configSettings->value(String(configName + "/Meshes/AlwaysImportMeshes").c_str());
  243. AlwaysIgnoreMeshes = configSettings->value(String(configName + "/Meshes/AlwaysIgnoreMeshes").c_str());
  244. //Assimp/Collada
  245. convertLeftHanded = dAtob(configSettings->value(String(configName + "/Meshes/convertLeftHanded").c_str()));
  246. calcTangentSpace = dAtob(configSettings->value(String(configName + "/Meshes/calcTangentSpace").c_str()));
  247. removeRedundantMats = dAtob(configSettings->value(String(configName + "/Meshes/removeRedundantMats").c_str()));
  248. genUVCoords = dAtob(configSettings->value(String(configName + "/Meshes/genUVCoords").c_str()));
  249. TransformUVs = dAtob(configSettings->value(String(configName + "/Meshes/TransformUVs").c_str()));
  250. flipUVCoords = dAtob(configSettings->value(String(configName + "/Meshes/flipUVCoords").c_str()));
  251. findInstances = dAtob(configSettings->value(String(configName + "/Meshes/findInstances").c_str()));
  252. limitBoneWeights = dAtob(configSettings->value(String(configName + "/Meshes/limitBoneWeights").c_str()));
  253. JoinIdenticalVerts = dAtob(configSettings->value(String(configName + "/Meshes/JoinIdenticalVerts").c_str()));
  254. reverseWindingOrder = dAtob(configSettings->value(String(configName + "/Meshes/reverseWindingOrder").c_str()));
  255. invertNormals = dAtob(configSettings->value(String(configName + "/Meshes/invertNormals").c_str()));
  256. //Materials
  257. ImportMaterials = dAtob(configSettings->value(String(configName + "/Materials/ImportMaterials").c_str()));
  258. AlwaysAddMaterialSuffix = dAtob(configSettings->value(String(configName + "/Materials/AlwaysAddMaterialSuffix").c_str()));
  259. AddedMaterialSuffix = configSettings->value(String(configName + "/Materials/AddedMaterialSuffix").c_str());
  260. CreateORMConfig = dAtob(configSettings->value(String(configName + "/Materials/CreateORMConfig").c_str()));
  261. UseDiffuseSuffixOnOriginImage = dAtob(configSettings->value(String(configName + "/Materials/UseDiffuseSuffixOnOriginImage").c_str()));
  262. UseExistingMaterials = dAtob(configSettings->value(String(configName + "/Materials/UseExistingMaterials").c_str()));
  263. IgnoreMaterials = configSettings->value(String(configName + "/Materials/IgnoreMaterials").c_str());
  264. PopulateMaterialMaps = dAtob(configSettings->value(String(configName + "/Materials/PopulateMaterialMaps").c_str()));
  265. //Animations
  266. ImportAnimations = dAtob(configSettings->value(String(configName + "/Animations/ImportAnimations").c_str()));
  267. SeparateAnimations = dAtob(configSettings->value(String(configName + "/Animations/SeparateAnimations").c_str()));
  268. SeparateAnimationPrefix = configSettings->value(String(configName + "/Animations/SeparateAnimationPrefix").c_str());
  269. animTiming = configSettings->value(String(configName + "/Animations/animTiming").c_str());
  270. animFPS = dAtof(configSettings->value(String(configName + "/Animations/animFPS").c_str()));
  271. AlwaysAddShapeAnimationSuffix = dAtob(configSettings->value(String(configName + "/Animations/AlwaysAddShapeAnimationSuffix").c_str()));
  272. AddedShapeAnimationSuffix = configSettings->value(String(configName + "/Animations/AddedShapeAnimationSuffix").c_str());
  273. //Collisions
  274. GenerateCollisions = dAtob(configSettings->value(String(configName + "/Collision/GenerateCollisions").c_str()));
  275. GenCollisionType = configSettings->value(String(configName + "/Collision/GenCollisionType").c_str());
  276. CollisionMeshPrefix = configSettings->value(String(configName + "/Collision/CollisionMeshPrefix").c_str());
  277. GenerateLOSCollisions = dAtob(configSettings->value(String(configName + "/Collision/GenerateLOSCollisions").c_str()));
  278. GenLOSCollisionType = configSettings->value(String(configName + "/Collision/GenLOSCollisionType").c_str());
  279. LOSCollisionMeshPrefix = configSettings->value(String(configName + "/Collision/LOSCollisionMeshPrefix").c_str());
  280. //Images
  281. importImages = dAtob(configSettings->value(String(configName + "/Images/importImages").c_str()));
  282. AlwaysAddImageSuffix = dAtob(configSettings->value(String(configName + "/Images/AlwaysAddImageSuffix").c_str()));
  283. AddedImageSuffix = configSettings->value(String(configName + "/Images/AddedImageSuffix").c_str());
  284. ImageType = configSettings->value(String(configName + "/Images/ImageType").c_str());
  285. DiffuseTypeSuffixes = configSettings->value(String(configName + "/Images/DiffuseTypeSuffixes").c_str());
  286. NormalTypeSuffixes = configSettings->value(String(configName + "/Images/NormalTypeSuffixes").c_str());
  287. MetalnessTypeSuffixes = configSettings->value(String(configName + "/Images/MetalnessTypeSuffixes").c_str());
  288. RoughnessTypeSuffixes = configSettings->value(String(configName + "/Images/RoughnessTypeSuffixes").c_str());
  289. SmoothnessTypeSuffixes = configSettings->value(String(configName + "/Images/SmoothnessTypeSuffixes").c_str());
  290. AOTypeSuffixes = configSettings->value(String(configName + "/Images/AOTypeSuffixes").c_str());
  291. PBRTypeSuffixes = configSettings->value(String(configName + "/Images/PBRTypeSuffixes").c_str());
  292. TextureFilteringMode = configSettings->value(String(configName + "/Images/TextureFilteringMode").c_str());
  293. UseMips = dAtob(configSettings->value(String(configName + "/Images/UseMips").c_str()));
  294. IsHDR = dAtob(configSettings->value(String(configName + "/Images/IsHDR").c_str()));
  295. Scaling = dAtof(configSettings->value(String(configName + "/Images/Scaling").c_str()));
  296. ImagesCompressed = dAtob(configSettings->value(String(configName + "/Images/Compressed").c_str()));
  297. GenerateMaterialOnImport = dAtob(configSettings->value(String(configName + "/Images/GenerateMaterialOnImport").c_str()));
  298. //Sounds
  299. VolumeAdjust = dAtof(configSettings->value(String(configName + "/Sounds/VolumeAdjust").c_str()));
  300. PitchAdjust = dAtof(configSettings->value(String(configName + "/Sounds/PitchAdjust").c_str()));
  301. SoundsCompressed = dAtob(configSettings->value(String(configName + "/Sounds/Compressed").c_str()));
  302. AlwaysAddSoundSuffix = dAtob(configSettings->value(String(configName + "/Sounds/AlwaysAddSoundSuffix").c_str()));
  303. AddedSoundSuffix = configSettings->value(String(configName + "/Sounds/AddedSoundSuffix").c_str());
  304. }
  305. void AssetImportConfig::CopyTo(AssetImportConfig* target) const
  306. {
  307. target->DuplicateAutoResolution = DuplicateAutoResolution;
  308. target->WarningsAsErrors = WarningsAsErrors;
  309. target->PreventImportWithErrors = PreventImportWithErrors;
  310. target->AutomaticallyPromptMissingFiles = AutomaticallyPromptMissingFiles;
  311. target->AddDirectoryPrefixToAssetName = AddDirectoryPrefixToAssetName;
  312. //Meshes
  313. target->ImportMesh = ImportMesh;
  314. target->AlwaysAddShapeSuffix = AlwaysAddShapeSuffix;
  315. target->AddedShapeSuffix = AddedShapeSuffix;
  316. target->UseManualShapeConfigRules = UseManualShapeConfigRules;
  317. target->DoUpAxisOverride = DoUpAxisOverride;
  318. target->UpAxisOverride = UpAxisOverride;
  319. target->DoScaleOverride = DoScaleOverride;
  320. target->ScaleOverride = ScaleOverride;
  321. target->IgnoreNodeScale = IgnoreNodeScale;
  322. target->AdjustCenter = AdjustCenter;
  323. target->AdjustFloor = AdjustFloor;
  324. target->CollapseSubmeshes = CollapseSubmeshes;
  325. target->LODType = LODType;
  326. target->singleDetailSize = singleDetailSize;
  327. target->AlwaysImportedNodes = AlwaysImportedNodes;
  328. target->AlwaysIgnoreNodes = AlwaysIgnoreNodes;
  329. target->AlwaysImportMeshes = AlwaysImportMeshes;
  330. target->AlwaysIgnoreMeshes = AlwaysIgnoreMeshes;
  331. //Assimp/Collada
  332. target->convertLeftHanded = convertLeftHanded;
  333. target->calcTangentSpace = calcTangentSpace;
  334. target->removeRedundantMats = removeRedundantMats;
  335. target->genUVCoords = genUVCoords;
  336. target->TransformUVs = TransformUVs;
  337. target->flipUVCoords = flipUVCoords;
  338. target->findInstances = findInstances;
  339. target->limitBoneWeights = limitBoneWeights;
  340. target->JoinIdenticalVerts = JoinIdenticalVerts;
  341. target->reverseWindingOrder = reverseWindingOrder;
  342. target->invertNormals = invertNormals;
  343. //Materials
  344. target->ImportMaterials = ImportMaterials;
  345. target->AlwaysAddMaterialSuffix = AlwaysAddMaterialSuffix;
  346. target->AddedMaterialSuffix = AddedMaterialSuffix;
  347. target->CreateORMConfig = CreateORMConfig;
  348. target->UseDiffuseSuffixOnOriginImage = UseDiffuseSuffixOnOriginImage;
  349. target->UseExistingMaterials = UseExistingMaterials;
  350. target->IgnoreMaterials = IgnoreMaterials;
  351. target->PopulateMaterialMaps = PopulateMaterialMaps;
  352. //Animations
  353. target->ImportAnimations = ImportAnimations;
  354. target->SeparateAnimations = SeparateAnimations;
  355. target->SeparateAnimationPrefix = SeparateAnimationPrefix;
  356. target->animTiming = animTiming;
  357. target->animFPS = animFPS;
  358. target->AlwaysAddShapeAnimationSuffix = AlwaysAddShapeAnimationSuffix;
  359. target->AddedShapeAnimationSuffix = AddedShapeAnimationSuffix;
  360. //Collisions
  361. target->GenerateCollisions = GenerateCollisions;
  362. target->GenCollisionType = GenCollisionType;
  363. target->CollisionMeshPrefix = CollisionMeshPrefix;
  364. target->GenerateLOSCollisions = GenerateLOSCollisions;
  365. target->GenLOSCollisionType = GenLOSCollisionType;
  366. target->LOSCollisionMeshPrefix = LOSCollisionMeshPrefix;
  367. //Images
  368. target->importImages = importImages;
  369. target->AlwaysAddImageSuffix = AlwaysAddImageSuffix;
  370. target->AddedImageSuffix = AddedImageSuffix;
  371. target->ImageType = ImageType;
  372. target->DiffuseTypeSuffixes = DiffuseTypeSuffixes;
  373. target->NormalTypeSuffixes = NormalTypeSuffixes;
  374. target->MetalnessTypeSuffixes = MetalnessTypeSuffixes;
  375. target->RoughnessTypeSuffixes = RoughnessTypeSuffixes;
  376. target->SmoothnessTypeSuffixes = SmoothnessTypeSuffixes;
  377. target->AOTypeSuffixes = AOTypeSuffixes;
  378. target->PBRTypeSuffixes = PBRTypeSuffixes;
  379. target->TextureFilteringMode = TextureFilteringMode;
  380. target->UseMips = UseMips;
  381. target->IsHDR = IsHDR;
  382. target->Scaling = Scaling;
  383. target->ImagesCompressed = ImagesCompressed;
  384. target->GenerateMaterialOnImport = GenerateMaterialOnImport;
  385. //Sounds
  386. target->VolumeAdjust = VolumeAdjust;
  387. target->PitchAdjust = PitchAdjust;
  388. target->SoundsCompressed = SoundsCompressed;
  389. target->AlwaysAddSoundSuffix = AlwaysAddSoundSuffix;
  390. target->AddedSoundSuffix = AddedSoundSuffix;
  391. }
  392. ConsoleDocClass(AssetImportObject,
  393. "@brief Defines properties for an AssetImportObject object.\n"
  394. "@AssetImportObject is a SimObject derived object intended to act as a stand-in for the to-be imported objects.\n"
  395. "@It contains important info such as dependencies, if it's been processed, any error/status issues and the originating file\n"
  396. "@or if it's been programmatically generated as part of the import process.\n\n"
  397. "@ingroup Assets\n"
  398. );
  399. IMPLEMENT_CONOBJECT(AssetImportObject);
  400. AssetImportObject::AssetImportObject() :
  401. dirty(false),
  402. importStatus(AssetImportObject::NotProcessed),
  403. generatedAsset(false),
  404. parentAssetItem(nullptr),
  405. tamlFilePath(""),
  406. imageSuffixType(""),
  407. shapeInfo(nullptr),
  408. filePathString(StringTable->EmptyString())
  409. {
  410. }
  411. AssetImportObject::~AssetImportObject()
  412. {
  413. }
  414. bool AssetImportObject::onAdd()
  415. {
  416. if (!Parent::onAdd())
  417. return false;
  418. return true;
  419. }
  420. void AssetImportObject::onRemove()
  421. {
  422. Parent::onRemove();
  423. }
  424. void AssetImportObject::initPersistFields()
  425. {
  426. docsURL;
  427. Parent::initPersistFields();
  428. addField("assetType", TypeRealString, Offset(assetType, AssetImportObject), "What type is the importing asset");
  429. addProtectedField("filePath", TypeFilename, Offset(filePathString, AssetImportObject), &_setFilePath, &defaultProtectedGetFn, "What is the source file path of the importing asset");
  430. addField("assetName", TypeRealString, Offset(assetName, AssetImportObject), "What is the asset's name");
  431. addField("cleanAssetName", TypeRealString, Offset(cleanAssetName, AssetImportObject), "What is the original, unmodified by processing, asset name");
  432. addField("status", TypeRealString, Offset(status, AssetImportObject), "What is the current status of this asset item in it's import process");
  433. addField("statusType", TypeRealString, Offset(statusType, AssetImportObject), "If there is a warning or error status, what type is the condition for this asset item");
  434. addField("statusInfo", TypeRealString, Offset(statusInfo, AssetImportObject), "What is the articulated information of the status of the asset. Contains the error or warning log data");
  435. addField("dirty", TypeBool, Offset(dirty, AssetImportObject), "Is the asset item currently flagged as dirty");
  436. addField("generatedAsset", TypeBool, Offset(generatedAsset, AssetImportObject), "Is this specific asset item generated as part of the import process of another item");
  437. addField("tamlFilePath", TypeRealString, Offset(tamlFilePath, AssetImportObject), "What is the ultimate asset taml file path for this import item");
  438. addField("imageType", TypeRealString, Offset(imageSuffixType, AssetImportObject), "Specific to ImageAsset type. What is the image asset's suffix type. Options are: Albedo, Normal, Roughness, AO, Metalness, ORMConfig");
  439. addField("shapeInfo", TYPEID< GuiTreeViewCtrl >(), Offset(shapeInfo, AssetImportObject), "Specific to ShapeAsset type. Processed information about the shape file. Contains numbers and lists of meshes, materials and animations");
  440. }
  441. bool AssetImportObject::_setFilePath(void* obj, const char* index, const char* data)
  442. {
  443. AssetImportObject* importObj = static_cast<AssetImportObject*>(obj);
  444. importObj->setFilePath(StringTable->insert(data));
  445. return false;
  446. }
  447. void AssetImportObject::setFilePath(StringTableEntry pFilePath)
  448. {
  449. filePathString = pFilePath;
  450. filePath = Torque::Path(pFilePath);
  451. }
  452. ConsoleDocClass(AssetImporter,
  453. "@brief Defines properties for an AssetImportObject object.\n"
  454. "@AssetImportObject is a SimObject derived object intended to act as a stand-in for the to-be imported objects.\n"
  455. "@It contains important info such as dependencies, if it's been processed, any error/status issues and the originating file\n"
  456. "@or if it's been programmatically generated as part of the import process.\n\n"
  457. "@ingroup Assets\n"
  458. );
  459. IMPLEMENT_CONOBJECT(AssetImporter);
  460. AssetImporter::AssetImporter() :
  461. importIssues(false),
  462. isReimport(false),
  463. assetHeirarchyChanged(false),
  464. importLogBuffer(""),
  465. activeImportConfig(nullptr),
  466. mDumpLogs(true)
  467. {
  468. }
  469. AssetImporter::~AssetImporter()
  470. {
  471. }
  472. bool AssetImporter::onAdd()
  473. {
  474. if (!Parent::onAdd())
  475. return false;
  476. return true;
  477. }
  478. void AssetImporter::onRemove()
  479. {
  480. Parent::onRemove();
  481. }
  482. void AssetImporter::initPersistFields()
  483. {
  484. docsURL;
  485. Parent::initPersistFields();
  486. addField("targetModuleId", TypeRealString, Offset(targetModuleId, AssetImporter), "The Id of the module the assets are to be imported into");
  487. addField("finalImportedAssetPath", TypeRealString, Offset(finalImportedAssetPath, AssetImporter), "The Id of the module the assets are to be imported into");
  488. addField("targetPath", TypeRealString, Offset(targetPath, AssetImporter), "The path any imported assets are placed in as their destination");
  489. addField("dumpLogs", TypeBool, Offset(mDumpLogs, AssetImporter), "Indicates if the importer always dumps its logs or not");
  490. }
  491. //
  492. // Utility Functions
  493. //
  494. AssetImportObject* AssetImporter::addImportingFile(Torque::Path filePath)
  495. {
  496. String assetType = getAssetTypeByFile(filePath);
  497. if (assetType.isEmpty())
  498. {
  499. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Unable to import file %s because it is of an unrecognized/unsupported type.", filePath.getFullPath().c_str());
  500. activityLog.push_back(importLogBuffer);
  501. return nullptr;
  502. }
  503. AssetImportObject* newAssetItem = addImportingAsset(assetType, filePath, nullptr, "");
  504. originalImportingFiles.push_back(filePath);
  505. return newAssetItem;
  506. }
  507. void AssetImporter::addImportingAssetItem(AssetImportObject* assetItem, AssetImportObject* parentItem)
  508. {
  509. if (assetItem == nullptr)
  510. {
  511. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Cannot add a null AssetImportObject to import session!");
  512. activityLog.push_back(importLogBuffer);
  513. return;
  514. }
  515. if (parentItem != nullptr)
  516. {
  517. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Added Child Importing Asset to %s", parentItem->assetName.c_str());
  518. activityLog.push_back(importLogBuffer);
  519. parentItem->childAssetItems.push_back(assetItem);
  520. assetItem->parentAssetItem = parentItem;
  521. }
  522. else
  523. {
  524. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Added Importing Asset");
  525. activityLog.push_back(importLogBuffer);
  526. importingAssets.push_back(assetItem);
  527. }
  528. dSprintf(importLogBuffer, sizeof(importLogBuffer), " Asset Info: Name: %s | Type: %s", assetItem->assetName.c_str(), assetItem->assetType.c_str());
  529. activityLog.push_back(importLogBuffer);
  530. if (!assetItem->filePath.isEmpty())
  531. {
  532. dSprintf(importLogBuffer, sizeof(importLogBuffer), " File: %s", assetItem->filePath.getFullPath().c_str());
  533. activityLog.push_back(importLogBuffer);
  534. }
  535. }
  536. AssetImportObject* AssetImporter::addImportingAsset(String assetType, Torque::Path filePath, AssetImportObject* parentItem, String assetNameOverride)
  537. {
  538. String assetName;
  539. String origionalName;
  540. //In some cases(usually generated assets on import, like materials) we'll want to specifically define the asset name instead of peeled from the filePath
  541. if (assetNameOverride.isNotEmpty())
  542. assetName = assetNameOverride;
  543. else
  544. assetName = filePath.getFileName();
  545. AssetImportObject* assetImportObj = new AssetImportObject();
  546. assetImportObj->registerObject();
  547. //sanitize
  548. String processedString = assetName;
  549. U32 start;
  550. U32 end;
  551. String firstNumber = String::GetFirstNumber(processedString, start, end);
  552. if (!firstNumber.isEmpty() && processedString.startsWith(firstNumber.c_str()))
  553. processedString = processedString.replace(firstNumber, "");
  554. processedString = processedString.replace(" ", "_");
  555. U32 len = processedString.length() + 1;
  556. char* sanitizedStr = Con::getReturnBuffer(len);
  557. dStrcpy(sanitizedStr, processedString.c_str(), len);
  558. U32 pos = dStrcspn(sanitizedStr, "-+*/%$&�=()[].?\\\"#,;!~<>|�^{}");
  559. while (pos < dStrlen(sanitizedStr))
  560. {
  561. dStrcpy(sanitizedStr + pos, sanitizedStr + pos + 1, (dsize_t)(len - pos));
  562. pos = dStrcspn(sanitizedStr, "-+*/%$&�=()[].?\\\"#,;!~<>|�^{}");
  563. }
  564. origionalName = assetName;
  565. //If we did, indeed, modify the name, update it now
  566. if (String(sanitizedStr) != assetName)
  567. {
  568. assetName = sanitizedStr;
  569. }
  570. assetImportObj->assetType = assetType;
  571. assetImportObj->filePath = filePath;
  572. assetImportObj->filePathString = StringTable->insert(filePath.getFullPath().c_str());
  573. assetImportObj->assetName = assetName;
  574. assetImportObj->cleanAssetName = origionalName;
  575. assetImportObj->moduleName = targetModuleId;
  576. assetImportObj->status = "";
  577. assetImportObj->statusType = "";
  578. assetImportObj->statusInfo = "";
  579. assetImportObj->dirty = false;
  580. assetImportObj->importStatus = AssetImportObject::NotProcessed;
  581. assetImportObj->generatedAsset = false;
  582. //If the config is marked to always set the directory prefix, do that now
  583. if (activeImportConfig->AddDirectoryPrefixToAssetName)
  584. {
  585. assetName = getFolderPrefixedName(assetImportObj);
  586. assetImportObj->assetName = assetName;
  587. assetImportObj->cleanAssetName = assetName;
  588. }
  589. if (parentItem != nullptr)
  590. {
  591. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Added Child Importing Asset to %s", parentItem->assetName.c_str());
  592. activityLog.push_back(importLogBuffer);
  593. parentItem->childAssetItems.push_back(assetImportObj);
  594. assetImportObj->parentAssetItem = parentItem;
  595. }
  596. else
  597. {
  598. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Added Importing Asset");
  599. activityLog.push_back(importLogBuffer);
  600. importingAssets.push_back(assetImportObj);
  601. }
  602. dSprintf(importLogBuffer, sizeof(importLogBuffer), " Asset Info: Name: %s | Type: %s", assetImportObj->assetName.c_str(), assetImportObj->assetType.c_str());
  603. activityLog.push_back(importLogBuffer);
  604. if (!filePath.isEmpty())
  605. {
  606. dSprintf(importLogBuffer, sizeof(importLogBuffer), " File: %s", filePath.getFullPath().c_str());
  607. activityLog.push_back(importLogBuffer);
  608. }
  609. return assetImportObj;
  610. }
  611. void AssetImporter::deleteImportingAsset(AssetImportObject* assetItem)
  612. {
  613. assetItem->importStatus = AssetImportObject::Skipped;
  614. //log it
  615. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Deleting Importing Asset %s and all it's child items", assetItem->assetName.c_str());
  616. activityLog.push_back(importLogBuffer);
  617. }
  618. AssetImportObject* AssetImporter::findImportingAssetByName(String assetName, AssetImportObject* assetItem)
  619. {
  620. Vector<AssetImportObject*> itemList = importingAssets;
  621. if (assetItem != nullptr)
  622. itemList = assetItem->childAssetItems;
  623. for (U32 i = 0; i < itemList.size(); i++)
  624. {
  625. if (itemList[i]->cleanAssetName == assetName)
  626. {
  627. return itemList[i];
  628. }
  629. //If it wasn't a match, try recusing on the children(if any)
  630. AssetImportObject* retItem = findImportingAssetByName(assetName, itemList[i]);
  631. if (retItem != nullptr)
  632. return retItem;
  633. }
  634. return nullptr;
  635. }
  636. ModuleDefinition* AssetImporter::getModuleFromPath(Torque::Path filePath)
  637. {
  638. // Use a relative path so modules on mounted file systems will be found.
  639. ModuleDefinition* moduleDef = ModuleDatabase.findModuleByFilePath(Platform::makeRelativePathName(filePath.getFullPath().c_str(), NULL));
  640. return moduleDef;
  641. }
  642. String AssetImporter::parseImageSuffixes(String assetName, String* suffixType)
  643. {
  644. //Here, we loop over our different suffix lists progressively.
  645. //This lets us walk through a list of suffixes in the Import Config, such as DiffuseTypeSuffixes
  646. //And then iterate over the delinated list of items within it to look for a match.
  647. //If we don't find a match, we then increment our list switch index and scan through the next list.
  648. U32 suffixTypeIdx = 0;
  649. while (suffixTypeIdx < 6)
  650. {
  651. String suffixList;
  652. switch (suffixTypeIdx)
  653. {
  654. case 0:
  655. suffixList = activeImportConfig->DiffuseTypeSuffixes;
  656. suffixType->insert(0, "Albedo", 6);
  657. break;
  658. case 1:
  659. suffixList = activeImportConfig->NormalTypeSuffixes;
  660. suffixType->insert(0, "Normal", 6);
  661. break;
  662. case 2:
  663. suffixList = activeImportConfig->RoughnessTypeSuffixes;
  664. suffixType->insert(0, "Roughness", 9);
  665. break;
  666. case 3:
  667. suffixList = activeImportConfig->AOTypeSuffixes;
  668. suffixType->insert(0, "AO", 2);
  669. break;
  670. case 4:
  671. suffixList = activeImportConfig->MetalnessTypeSuffixes;
  672. suffixType->insert(0, "Metalness", 9);
  673. break;
  674. case 5:
  675. suffixList = activeImportConfig->PBRTypeSuffixes;
  676. suffixType->insert(0, "ORMConfig", 9);
  677. break;
  678. default:
  679. suffixList = "";
  680. }
  681. suffixTypeIdx++;
  682. U32 suffixCount = StringUnit::getUnitCount(suffixList, ",;\t");
  683. for (U32 i = 0; i < suffixCount; i++)
  684. {
  685. String suffix = StringUnit::getUnit(suffixList, i, ",;\t");
  686. String searchSuffix = String("*") + suffix;
  687. if (FindMatch::isMatch(searchSuffix.c_str(), assetName.c_str(), false))
  688. {
  689. //We have a match, so indicate as such
  690. S32 pos = assetName.length();
  691. pos -= searchSuffix.length();
  692. suffix = assetName.substr(pos+1);
  693. return suffix;
  694. }
  695. }
  696. }
  697. suffixType->clear();
  698. return "";
  699. }
  700. String AssetImporter::getAssetTypeByFile(Torque::Path filePath)
  701. {
  702. String fileExt = String::ToLower(filePath.getExtension());
  703. String fileName = String::ToLower(filePath.getFileName());
  704. if (fileExt == String("dts") && fileName.endsWith("cached"))
  705. return "";
  706. if (fileExt == String("png") || fileExt == String("jpg") || fileExt == String("jpeg") || fileExt == String("dds"))
  707. return "ImageAsset";
  708. else if (fileExt == String("dae") || fileExt == String("fbx") || fileExt == String("blend") || fileExt == String("obj") || fileExt == String("dts") || fileExt == String("gltf") || fileExt == String("glb"))
  709. return "ShapeAsset";
  710. else if (fileExt == String("dsq"))
  711. return "ShapeAnimationAsset";
  712. else if (fileExt == String("ogg") || fileExt == String("wav") || fileExt == String("mp3"))
  713. return "SoundAsset";
  714. else if (fileExt == String("zip"))
  715. return "Zip";
  716. else if (fileExt.isEmpty())
  717. return "Folder";
  718. return "";
  719. }
  720. String AssetImporter::getTrueFilename(const String& fileName)
  721. {
  722. Torque::Path pth(fileName);
  723. String pattern = pth.getFullPath() + "*";
  724. static const String sSlash("/");
  725. Vector<String> findFilesResults;
  726. String sPattern(Torque::Path::CleanSeparators(pattern));
  727. if (sPattern.isEmpty())
  728. {
  729. Con::errorf("findFirstFile() requires a search pattern");
  730. return "";
  731. }
  732. char scriptFilenameBuffer[1024];
  733. if (!Con::expandScriptFilename(scriptFilenameBuffer, sizeof(scriptFilenameBuffer), sPattern.c_str()))
  734. {
  735. Con::errorf("findFirstFile() given initial directory cannot be expanded: '%s'", pattern.c_str());
  736. return "";
  737. }
  738. sPattern = String::ToString(scriptFilenameBuffer);
  739. String::SizeType slashPos = sPattern.find('/', 0, String::Right);
  740. // if(slashPos == String::NPos)
  741. // {
  742. // Con::errorf("findFirstFile() missing search directory or expression: '%s'", sPattern.c_str());
  743. // return -1;
  744. // }
  745. // Build the initial search path
  746. Torque::Path givenPath(Torque::Path::CompressPath(sPattern));
  747. givenPath.setFileName("*");
  748. givenPath.setExtension("*");
  749. if (givenPath.getPath().length() > 0 && givenPath.getPath().find('*', 0, String::Right) == givenPath.getPath().length() - 1)
  750. {
  751. // Deal with legacy searches of the form '*/*.*'
  752. String suspectPath = givenPath.getPath();
  753. String::SizeType newLen = suspectPath.length() - 1;
  754. if (newLen > 0 && suspectPath.find('/', 0, String::Right) == suspectPath.length() - 2)
  755. {
  756. --newLen;
  757. }
  758. givenPath.setPath(suspectPath.substr(0, newLen));
  759. }
  760. Torque::FS::FileSystemRef fs = Torque::FS::GetFileSystem(givenPath);
  761. //Torque::Path path = fs->mapTo(givenPath);
  762. Torque::Path path = givenPath;
  763. // Make sure that we have a root so the correct file system can be determined when using zips
  764. if (givenPath.isRelative())
  765. path = Torque::Path::Join(Torque::FS::GetCwd(), '/', givenPath);
  766. path.setFileName(String::EmptyString);
  767. path.setExtension(String::EmptyString);
  768. if (!Torque::FS::IsDirectory(path))
  769. {
  770. Con::errorf("findFirstFile() invalid initial search directory: '%s'", path.getFullPath().c_str());
  771. return "";
  772. }
  773. // Build the search expression
  774. const String expression(slashPos != String::NPos ? sPattern.substr(slashPos + 1) : sPattern);
  775. if (expression.isEmpty())
  776. {
  777. Con::errorf("findFirstFile() requires a search expression: '%s'", sPattern.c_str());
  778. return "";
  779. }
  780. S32 results = Torque::FS::FindByPattern(path, expression, false, findFilesResults, false);
  781. if (givenPath.isRelative() && results > 0)
  782. {
  783. // Strip the CWD out of the returned paths
  784. // MakeRelativePath() returns incorrect results (it adds a leading ..) so doing this the dirty way
  785. const String cwd = Torque::FS::GetCwd().getFullPath();
  786. for (S32 i = 0; i < findFilesResults.size(); ++i)
  787. {
  788. String str = findFilesResults[i];
  789. if (str.compare(cwd, cwd.length(), String::NoCase) == 0)
  790. str = str.substr(cwd.length());
  791. findFilesResults[i] = str;
  792. }
  793. }
  794. for (U32 i = 0; i < findFilesResults.size(); i++)
  795. {
  796. if (!findFilesResults[i].compare(fileName, 0, String::NoCase|String::Left))
  797. return findFilesResults[i];
  798. }
  799. return "";
  800. }
  801. void AssetImporter::resetImportSession(bool hardClearSession)
  802. {
  803. importingAssets.clear();
  804. activityLog.clear();
  805. if (hardClearSession)
  806. {
  807. originalImportingFiles.clear();
  808. }
  809. else
  810. {
  811. Vector<Torque::Path> tempImportingFiles = originalImportingFiles;
  812. originalImportingFiles.clear();
  813. for (U32 i = 0; i < tempImportingFiles.size(); i++)
  814. {
  815. addImportingFile(tempImportingFiles[i]);
  816. }
  817. }
  818. }
  819. S32 AssetImporter::getActivityLogLineCount()
  820. {
  821. return activityLog.size();
  822. }
  823. String AssetImporter::getActivityLogLine(U32 line)
  824. {
  825. if (line >= activityLog.size())
  826. return "";
  827. return activityLog[line];
  828. }
  829. void AssetImporter::dumpActivityLog()
  830. {
  831. if (!mDumpLogs)
  832. return;
  833. FileObject logFile;
  834. //If there's nothing logged, don't bother
  835. if (activityLog.size() == 0)
  836. return;
  837. Torque::Time::DateTime curTime;
  838. Torque::Time::getCurrentDateTime(curTime);
  839. String logName = String("tools/logs/AssetImportLog_") + String::ToString(curTime.year + 1900) + "-" +
  840. String::ToString(curTime.month + 1) + "-" + String::ToString(curTime.day) + "_" +
  841. String::ToString(curTime.hour) + "-" + String::ToString(curTime.minute) + "-" + String::ToString(curTime.second)
  842. + "-" + String::ToString(curTime.microsecond) + ".log";
  843. if (logFile.openForWrite(logName.c_str()))
  844. {
  845. for (U32 i = 0; i < activityLog.size(); i++)
  846. {
  847. logFile.writeLine((const U8*)activityLog[i].c_str());
  848. }
  849. logFile.close();
  850. Con::warnf("Asset Import log file dumped to: %s", logName.c_str());
  851. }
  852. else
  853. {
  854. Con::errorf("Error: Failed to open log file for writing! Dumping log results to console!");
  855. for (U32 i = 0; i < activityLog.size(); i++)
  856. {
  857. Con::printf(activityLog[i].c_str());
  858. }
  859. }
  860. }
  861. S32 AssetImporter::getAssetItemCount()
  862. {
  863. return importingAssets.size();
  864. }
  865. AssetImportObject* AssetImporter::getAssetItem(U32 index)
  866. {
  867. if (index >= importingAssets.size())
  868. return nullptr;
  869. return importingAssets[index];
  870. }
  871. S32 AssetImporter::getAssetItemChildCount(AssetImportObject* assetItem)
  872. {
  873. return assetItem->childAssetItems.size();
  874. }
  875. AssetImportObject* AssetImporter::getAssetItemChild(AssetImportObject* assetItem, U32 index)
  876. {
  877. if (index >= assetItem->childAssetItems.size())
  878. return nullptr;
  879. return assetItem->childAssetItems[index];
  880. }
  881. //
  882. // Processing
  883. //
  884. // Helper struct for counting nodes, meshes and polygons down through the scene
  885. // hierarchy
  886. struct SceneStats
  887. {
  888. S32 numNodes;
  889. S32 numMeshes;
  890. S32 numPolygons;
  891. S32 numMaterials;
  892. S32 numLights;
  893. S32 numClips;
  894. SceneStats() : numNodes(0), numMeshes(0), numPolygons(0), numMaterials(0), numLights(0), numClips(0) { }
  895. };
  896. // Recurse through the <visual_scene> adding nodes and geometry to the GuiTreeView control
  897. static void processNode(GuiTreeViewCtrl* tree, domNode* node, S32 parentID, SceneStats& stats)
  898. {
  899. stats.numNodes++;
  900. S32 nodeID = tree->insertItem(parentID, _GetNameOrId(node), "node", "", 0, 0);
  901. // Update mesh and poly counts
  902. for (S32 i = 0; i < node->getContents().getCount(); i++)
  903. {
  904. domGeometry* geom = 0;
  905. const char* elemName = "";
  906. daeElement* child = node->getContents()[i];
  907. switch (child->getElementType())
  908. {
  909. case COLLADA_TYPE::INSTANCE_GEOMETRY:
  910. {
  911. domInstance_geometry* instgeom = daeSafeCast<domInstance_geometry>(child);
  912. if (instgeom)
  913. {
  914. geom = daeSafeCast<domGeometry>(instgeom->getUrl().getElement());
  915. elemName = _GetNameOrId(geom);
  916. }
  917. break;
  918. }
  919. case COLLADA_TYPE::INSTANCE_CONTROLLER:
  920. {
  921. domInstance_controller* instctrl = daeSafeCast<domInstance_controller>(child);
  922. if (instctrl)
  923. {
  924. domController* ctrl = daeSafeCast<domController>(instctrl->getUrl().getElement());
  925. elemName = _GetNameOrId(ctrl);
  926. if (ctrl && ctrl->getSkin())
  927. geom = daeSafeCast<domGeometry>(ctrl->getSkin()->getSource().getElement());
  928. else if (ctrl && ctrl->getMorph())
  929. geom = daeSafeCast<domGeometry>(ctrl->getMorph()->getSource().getElement());
  930. }
  931. break;
  932. }
  933. case COLLADA_TYPE::INSTANCE_LIGHT:
  934. stats.numLights++;
  935. tree->insertItem(nodeID, _GetNameOrId(node), "light", "", 0, 0);
  936. break;
  937. }
  938. if (geom && geom->getMesh())
  939. {
  940. const char* name = _GetNameOrId(node);
  941. if (dStrEqual(name, "null") || dStrEndsWith(name, "PIVOT"))
  942. name = _GetNameOrId(daeSafeCast<domNode>(node->getParent()));
  943. stats.numMeshes++;
  944. tree->insertItem(nodeID, name, "mesh", "", 0, 0);
  945. for (S32 j = 0; j < geom->getMesh()->getTriangles_array().getCount(); j++)
  946. stats.numPolygons += geom->getMesh()->getTriangles_array()[j]->getCount();
  947. for (S32 j = 0; j < geom->getMesh()->getTristrips_array().getCount(); j++)
  948. stats.numPolygons += geom->getMesh()->getTristrips_array()[j]->getCount();
  949. for (S32 j = 0; j < geom->getMesh()->getTrifans_array().getCount(); j++)
  950. stats.numPolygons += geom->getMesh()->getTrifans_array()[j]->getCount();
  951. for (S32 j = 0; j < geom->getMesh()->getPolygons_array().getCount(); j++)
  952. stats.numPolygons += geom->getMesh()->getPolygons_array()[j]->getCount();
  953. for (S32 j = 0; j < geom->getMesh()->getPolylist_array().getCount(); j++)
  954. stats.numPolygons += geom->getMesh()->getPolylist_array()[j]->getCount();
  955. }
  956. }
  957. // Recurse into child nodes
  958. for (S32 i = 0; i < node->getNode_array().getCount(); i++)
  959. processNode(tree, node->getNode_array()[i], nodeID, stats);
  960. for (S32 i = 0; i < node->getInstance_node_array().getCount(); i++)
  961. {
  962. domInstance_node* instnode = node->getInstance_node_array()[i];
  963. domNode* dNode = daeSafeCast<domNode>(instnode->getUrl().getElement());
  964. if (dNode)
  965. processNode(tree, dNode, nodeID, stats);
  966. }
  967. }
  968. static bool enumColladaForImport(const char* shapePath, GuiTreeViewCtrl* tree, bool loadCachedDts)
  969. {
  970. // Check if a cached DTS is available => no need to import the collada file
  971. // if we can load the DTS instead
  972. Torque::Path path(shapePath);
  973. if (loadCachedDts && ColladaShapeLoader::canLoadCachedDTS(path))
  974. return false;
  975. // Check if this is a Sketchup file (.kmz) and if so, mount the zip filesystem
  976. // and get the path to the DAE file.
  977. String mountPoint;
  978. Torque::Path daePath;
  979. bool isSketchup = ColladaShapeLoader::checkAndMountSketchup(path, mountPoint, daePath);
  980. // Load the Collada file into memory
  981. domCOLLADA* root = ColladaShapeLoader::getDomCOLLADA(daePath);
  982. if (!root)
  983. {
  984. TSShapeLoader::updateProgress(TSShapeLoader::Load_Complete, "Load complete");
  985. return false;
  986. }
  987. if (isSketchup)
  988. {
  989. // Unmount the zip if we mounted it
  990. Torque::FS::Unmount(mountPoint);
  991. }
  992. // Initialize tree
  993. tree->removeItem(0);
  994. S32 nodesID = tree->insertItem(0, "Shape", "", "", 0, 0);
  995. S32 matsID = tree->insertItem(0, "Materials", "", "", 0, 0);
  996. S32 animsID = tree->insertItem(0, "Animations", "", "", 0, 0);
  997. SceneStats stats;
  998. // Query DOM for shape summary details
  999. for (S32 i = 0; i < root->getLibrary_visual_scenes_array().getCount(); i++)
  1000. {
  1001. const domLibrary_visual_scenes* libScenes = root->getLibrary_visual_scenes_array()[i];
  1002. for (S32 j = 0; j < libScenes->getVisual_scene_array().getCount(); j++)
  1003. {
  1004. const domVisual_scene* visualScene = libScenes->getVisual_scene_array()[j];
  1005. for (S32 k = 0; k < visualScene->getNode_array().getCount(); k++)
  1006. processNode(tree, visualScene->getNode_array()[k], nodesID, stats);
  1007. }
  1008. }
  1009. // Get material count
  1010. for (S32 i = 0; i < root->getLibrary_materials_array().getCount(); i++)
  1011. {
  1012. const domLibrary_materials* libraryMats = root->getLibrary_materials_array()[i];
  1013. stats.numMaterials += (S32)libraryMats->getMaterial_array().getCount();
  1014. for (S32 j = 0; j < libraryMats->getMaterial_array().getCount(); j++)
  1015. {
  1016. domMaterial* mat = libraryMats->getMaterial_array()[j];
  1017. tree->insertItem(matsID, _GetNameOrId(mat), "", "", 0, 0);
  1018. }
  1019. }
  1020. // Get images count
  1021. for (S32 i = 0; i < root->getLibrary_images_array().getCount(); i++)
  1022. {
  1023. const domLibrary_images* libraryImages = root->getLibrary_images_array()[i];
  1024. for (S32 j = 0; j < libraryImages->getImage_array().getCount(); j++)
  1025. {
  1026. domImage* img = libraryImages->getImage_array()[j];
  1027. String imageName = _GetNameOrId(img);
  1028. S32 materialID = tree->findItemByName(imageName.c_str());
  1029. if (materialID == 0)
  1030. {
  1031. bool materialFound = false;
  1032. String matName = "";
  1033. //If we don't have an immediate name match, we'll have to actually go look it up
  1034. for (S32 e = 0; e < root->getLibrary_effects_array().getCount(); e++)
  1035. {
  1036. const domLibrary_effects* libraryEffects = root->getLibrary_effects_array()[e];
  1037. for (S32 f = 0; f < libraryEffects->getEffect_array().getCount(); f++)
  1038. {
  1039. domEffect* efct = libraryEffects->getEffect_array()[f];
  1040. String effectName = efct->getID();
  1041. for (S32 p = 0; p < efct->getFx_profile_abstract_array().getCount(); p++)
  1042. {
  1043. domProfile_COMMON* profile = daeSafeCast<domProfile_COMMON>(efct->getFx_profile_abstract_array()[p]);
  1044. for (S32 n = 0; n < profile->getNewparam_array().getCount(); n++)
  1045. {
  1046. domCommon_newparam_typeRef param = profile->getNewparam_array()[n];
  1047. String paramName = param->getSid();
  1048. if (paramName.endsWith("-surface"))
  1049. {
  1050. //ok it's surface data, parse out the name
  1051. String surfaceName = paramName.substr(0, paramName.length() - 8);
  1052. if (surfaceName == imageName)
  1053. {
  1054. //got a match!
  1055. matName = effectName;
  1056. if (matName.endsWith("-effect"))
  1057. {
  1058. matName = matName.substr(0, matName.length() - 7);
  1059. materialFound = true;
  1060. break;
  1061. }
  1062. }
  1063. }
  1064. }
  1065. if (materialFound)
  1066. break;
  1067. }
  1068. if (materialFound)
  1069. {
  1070. materialID = tree->findItemByName(matName.c_str());
  1071. }
  1072. if (materialID != 0)
  1073. break;
  1074. }
  1075. }
  1076. //if we STILL haven't found a match, then yes, we've failed
  1077. if (materialID == 0)
  1078. continue;
  1079. }
  1080. String imagePath = img->getInit_from()->getValue().str().c_str();
  1081. if (imagePath.startsWith("/"))
  1082. imagePath = imagePath.substr(1, imagePath.length() - 1);
  1083. tree->setItemValue(materialID, StringTable->insert(imagePath.c_str()));
  1084. }
  1085. }
  1086. // Get animation count
  1087. for (S32 i = 0; i < root->getLibrary_animation_clips_array().getCount(); i++)
  1088. {
  1089. const domLibrary_animation_clips* libraryClips = root->getLibrary_animation_clips_array()[i];
  1090. stats.numClips += (S32)libraryClips->getAnimation_clip_array().getCount();
  1091. for (S32 j = 0; j < libraryClips->getAnimation_clip_array().getCount(); j++)
  1092. {
  1093. domAnimation_clip* clip = libraryClips->getAnimation_clip_array()[j];
  1094. tree->insertItem(animsID, _GetNameOrId(clip), "animation", "", 0, 0);
  1095. }
  1096. }
  1097. if (stats.numClips == 0)
  1098. {
  1099. // No clips => check if there are any animations (these will be added to a default clip)
  1100. for (S32 i = 0; i < root->getLibrary_animations_array().getCount(); i++)
  1101. {
  1102. const domLibrary_animations* libraryAnims = root->getLibrary_animations_array()[i];
  1103. if (libraryAnims->getAnimation_array().getCount())
  1104. {
  1105. stats.numClips = 1;
  1106. tree->insertItem(animsID, "ambient", "animation", "", 0, 0);
  1107. break;
  1108. }
  1109. }
  1110. }
  1111. // Extract the global scale and up_axis from the top level <asset> element,
  1112. F32 unit = 1.0f;
  1113. domUpAxisType upAxis = UPAXISTYPE_Z_UP;
  1114. if (root->getAsset()) {
  1115. if (root->getAsset()->getUnit())
  1116. unit = root->getAsset()->getUnit()->getMeter();
  1117. if (root->getAsset()->getUp_axis())
  1118. upAxis = root->getAsset()->getUp_axis()->getValue();
  1119. }
  1120. TSShapeLoader::updateProgress(TSShapeLoader::Load_Complete, "Load complete");
  1121. // Store shape information in the tree control
  1122. tree->setDataField(StringTable->insert("_nodeCount"), 0, avar("%d", stats.numNodes));
  1123. tree->setDataField(StringTable->insert("_meshCount"), 0, avar("%d", stats.numMeshes));
  1124. tree->setDataField(StringTable->insert("_polygonCount"), 0, avar("%d", stats.numPolygons));
  1125. tree->setDataField(StringTable->insert("_materialCount"), 0, avar("%d", stats.numMaterials));
  1126. tree->setDataField(StringTable->insert("_lightCount"), 0, avar("%d", stats.numLights));
  1127. tree->setDataField(StringTable->insert("_animCount"), 0, avar("%d", stats.numClips));
  1128. tree->setDataField(StringTable->insert("_unit"), 0, avar("%g", unit));
  1129. if (upAxis == UPAXISTYPE_X_UP)
  1130. tree->setDataField(StringTable->insert("_upAxis"), 0, "X_AXIS");
  1131. else if (upAxis == UPAXISTYPE_Y_UP)
  1132. tree->setDataField(StringTable->insert("_upAxis"), 0, "Y_AXIS");
  1133. else
  1134. tree->setDataField(StringTable->insert("_upAxis"), 0, "Z_AXIS");
  1135. char shapesStr[16];
  1136. dSprintf(shapesStr, 16, "%i", stats.numMeshes);
  1137. char materialsStr[16];
  1138. dSprintf(materialsStr, 16, "%i", stats.numMaterials);
  1139. char animationsStr[16];
  1140. dSprintf(animationsStr, 16, "%i", stats.numClips);
  1141. tree->setItemValue(nodesID, StringTable->insert(shapesStr));
  1142. tree->setItemValue(matsID, StringTable->insert(materialsStr));
  1143. tree->setItemValue(animsID, StringTable->insert(animationsStr));
  1144. return true;
  1145. }
  1146. static bool enumDTSForImport(const char* shapePath, GuiTreeViewCtrl* tree)
  1147. {
  1148. // Check if a cached DTS is available => no need to import the collada file
  1149. // if we can load the DTS instead
  1150. Torque::Path path(shapePath);
  1151. Resource<TSShape> dtsShape = ResourceManager::get().load(shapePath);
  1152. if (!dtsShape)
  1153. return false;
  1154. // Initialize tree
  1155. tree->removeItem(0);
  1156. S32 nodesID = tree->insertItem(0, "Shape", "", "", 0, 0);
  1157. S32 matsID = tree->insertItem(0, "Materials", "", "", 0, 0);
  1158. S32 animsID = tree->insertItem(0, "Animations", "", "", 0, 0);
  1159. SceneStats stats;
  1160. // Query DOM for shape summary details
  1161. for (S32 i = 0; i < dtsShape->objects.size(); i++)
  1162. {
  1163. tree->insertItem(nodesID, dtsShape->names[dtsShape->objects[i].nameIndex], "", "", 0, 0);
  1164. stats.numMeshes++;
  1165. }
  1166. // Get material count
  1167. for (S32 i = 0; i < dtsShape->materialList->size(); i++)
  1168. {
  1169. S32 matId = tree->insertItem(matsID, dtsShape->materialList->getMaterialName(i).c_str(), "", "", 0, 0);
  1170. stats.numMaterials++;
  1171. GFXTextureObject* difTex = dtsShape->materialList->getDiffuseTexture(i);
  1172. if (difTex)
  1173. {
  1174. tree->insertItem(matId, difTex->getPath().c_str(), "", "", 0, 0);
  1175. }
  1176. }
  1177. // Get animation count
  1178. for (S32 i = 0; i < dtsShape->sequences.size(); i++)
  1179. {
  1180. tree->insertItem(animsID, dtsShape->names[dtsShape->sequences[i].nameIndex], "animation", "", 0, 0);
  1181. stats.numClips++;
  1182. }
  1183. /*if (stats.numClips == 0)
  1184. {
  1185. // No clips => check if there are any animations (these will be added to a default clip)
  1186. for (S32 i = 0; i < root->getLibrary_animations_array().getCount(); i++)
  1187. {
  1188. const domLibrary_animations* libraryAnims = root->getLibrary_animations_array()[i];
  1189. if (libraryAnims->getAnimation_array().getCount())
  1190. {
  1191. stats.numClips = 1;
  1192. tree->insertItem(animsID, "ambient", "animation", "", 0, 0);
  1193. break;
  1194. }
  1195. }
  1196. }*/
  1197. F32 unit = 1.0f;
  1198. // Store shape information in the tree control
  1199. tree->setDataField(StringTable->insert("_nodeCount"), 0, avar("%d", stats.numNodes));
  1200. tree->setDataField(StringTable->insert("_meshCount"), 0, avar("%d", stats.numMeshes));
  1201. tree->setDataField(StringTable->insert("_polygonCount"), 0, avar("%d", stats.numPolygons));
  1202. tree->setDataField(StringTable->insert("_materialCount"), 0, avar("%d", stats.numMaterials));
  1203. tree->setDataField(StringTable->insert("_lightCount"), 0, avar("%d", stats.numLights));
  1204. tree->setDataField(StringTable->insert("_animCount"), 0, avar("%d", stats.numClips));
  1205. tree->setDataField(StringTable->insert("_unit"), 0, avar("%g", unit));
  1206. tree->setDataField(StringTable->insert("_upAxis"), 0, "Z_AXIS");
  1207. char shapesStr[16];
  1208. dSprintf(shapesStr, 16, "%i", stats.numMeshes);
  1209. char materialsStr[16];
  1210. dSprintf(materialsStr, 16, "%i", stats.numMaterials);
  1211. char animationsStr[16];
  1212. dSprintf(animationsStr, 16, "%i", stats.numClips);
  1213. tree->setItemValue(nodesID, StringTable->insert(shapesStr));
  1214. tree->setItemValue(matsID, StringTable->insert(materialsStr));
  1215. tree->setItemValue(animsID, StringTable->insert(animationsStr));
  1216. return true;
  1217. }
  1218. void AssetImportConfig::loadSISFile(Torque::Path filePath)
  1219. {
  1220. String settingsFilePath = "Tools";
  1221. Settings* editorSettings;
  1222. //See if we can get our editor settings
  1223. if (Sim::findObject("EditorSettings", editorSettings))
  1224. {
  1225. settingsFilePath = editorSettings->value("defaultSettingsPath", "Tools");
  1226. }
  1227. String fileExtension = filePath.getExtension();
  1228. String settingsFile = settingsFilePath + "/" + fileExtension + ".sis";
  1229. FileObject* fileObj = new FileObject();
  1230. if (Torque::FS::IsFile(settingsFile))
  1231. {
  1232. if (!fileObj->readMemory(settingsFile.c_str()))
  1233. {
  1234. Con::errorf("AssetImporter::loadSISFile() - Error opening file to load settings: %s", settingsFile.c_str());
  1235. fileObj->deleteObject();
  1236. return;
  1237. }
  1238. }
  1239. else
  1240. {
  1241. return;
  1242. }
  1243. String headerLine = (const char*)fileObj->readLine();
  1244. if (headerLine.substr(0, 4).compare("SISV", 0U, String::NoCase) != 0)
  1245. return; //not a sis file?
  1246. while (!fileObj->isEOF())
  1247. {
  1248. const char* line = (const char*)fileObj->readLine();
  1249. String key = StringUnit::getUnit(line, 0, "\t");
  1250. String value = StringUnit::getUnit(line, 1, "\t");
  1251. if (key.compare("DoUpAxisOverride", 0U, String::NoCase) == 0)
  1252. DoUpAxisOverride = dAtob(value.c_str());
  1253. else if (key.compare("UpAxisOverride", 0U, String::NoCase) == 0)
  1254. UpAxisOverride = value.c_str();
  1255. else if (key.compare("DoScaleOverride", 0U, String::NoCase) == 0)
  1256. DoScaleOverride = dAtob(value.c_str());
  1257. else if (key.compare("ScaleOverride", 0U, String::NoCase) == 0)
  1258. ScaleOverride = dAtof(value.c_str());
  1259. else if (key.compare("IgnoreNodeScale", 0U, String::NoCase) == 0)
  1260. IgnoreNodeScale = dAtob(value.c_str());
  1261. else if (key.compare("AdjustCenter", 0U, String::NoCase) == 0)
  1262. AdjustCenter = dAtob(value.c_str());
  1263. else if (key.compare("AdjustFloor", 0U, String::NoCase) == 0)
  1264. AdjustFloor = dAtob(value.c_str());
  1265. else if (key.compare("CollapseSubmeshes", 0U, String::NoCase) == 0)
  1266. CollapseSubmeshes = dAtob(value.c_str());
  1267. else if (key.compare("LODType", 0U, String::NoCase) == 0)
  1268. LODType = value.c_str();
  1269. else if (key.compare("singleDetailSize", 0U, String::NoCase) == 0)
  1270. singleDetailSize = dAtoi(value.c_str());
  1271. else if (key.compare("AlwaysImportedNodes", 0U, String::NoCase) == 0)
  1272. AlwaysImportedNodes = value.c_str();
  1273. else if (key.compare("AlwaysIgnoreNodes", 0U, String::NoCase) == 0)
  1274. AlwaysIgnoreNodes = value.c_str();
  1275. else if (key.compare("AlwaysImportMeshes", 0U, String::NoCase) == 0)
  1276. AlwaysImportMeshes = value.c_str();
  1277. else if (key.compare("AlwaysIgnoreMeshes", 0U, String::NoCase) == 0)
  1278. AlwaysIgnoreMeshes = value.c_str();
  1279. else if (key.compare("convertLeftHanded", 0U, String::NoCase) == 0)
  1280. convertLeftHanded = dAtob(value.c_str());
  1281. else if (key.compare("calcTangentSpace", 0U, String::NoCase) == 0)
  1282. calcTangentSpace = dAtob(value.c_str());
  1283. else if (key.compare("removeRedundantMats", 0U, String::NoCase) == 0)
  1284. removeRedundantMats = dAtob(value.c_str());
  1285. else if (key.compare("genUVCoords", 0U, String::NoCase) == 0)
  1286. genUVCoords = dAtob(value.c_str());
  1287. else if (key.compare("TransformUVs", 0U, String::NoCase) == 0)
  1288. TransformUVs = dAtob(value.c_str());
  1289. else if (key.compare("flipUVCoords", 0U, String::NoCase) == 0)
  1290. flipUVCoords = dAtob(value.c_str());
  1291. else if (key.compare("findInstances", 0U, String::NoCase) == 0)
  1292. findInstances = dAtob(value.c_str());
  1293. else if (key.compare("limitBoneWeights", 0U, String::NoCase) == 0)
  1294. limitBoneWeights = dAtob(value.c_str());
  1295. else if (key.compare("JoinIdenticalVerts", 0U, String::NoCase) == 0)
  1296. JoinIdenticalVerts = dAtob(value.c_str());
  1297. else if (key.compare("reverseWindingOrder", 0U, String::NoCase) == 0)
  1298. reverseWindingOrder = dAtob(value.c_str());
  1299. else if (key.compare("invertNormals", 0U, String::NoCase) == 0)
  1300. invertNormals = dAtob(value.c_str());
  1301. }
  1302. fileObj->close();
  1303. fileObj->deleteObject();
  1304. }
  1305. void AssetImporter::processImportAssets(AssetImportObject* assetItem)
  1306. {
  1307. Vector<AssetImportObject*> itemList = importingAssets;
  1308. if (assetItem != nullptr)
  1309. itemList = assetItem->childAssetItems;
  1310. assetHeirarchyChanged = false;
  1311. for (U32 i = 0; i < itemList.size(); i++)
  1312. {
  1313. AssetImportObject* item = itemList[i];
  1314. if (item->importStatus != AssetImportObject::NotProcessed)
  1315. continue;
  1316. //Sanitize before modifying our asset name(suffix additions, etc)
  1317. if (item->assetName != item->cleanAssetName)
  1318. item->assetName = item->cleanAssetName;
  1319. //process the asset items
  1320. if (item->assetType == String("ImageAsset"))
  1321. {
  1322. processImageAsset(item);
  1323. }
  1324. else if (item->assetType == String("ShapeAsset"))
  1325. {
  1326. processShapeAsset(item);
  1327. }
  1328. else if (item->assetType == String("SoundAsset"))
  1329. {
  1330. processSoundAsset(item);
  1331. }
  1332. else if (item->assetType == String("MaterialAsset"))
  1333. {
  1334. processMaterialAsset(item);
  1335. }
  1336. else if (item->assetType == String("ShapeAnimationAsset"))
  1337. {
  1338. processShapeAnimationAsset(item);
  1339. }
  1340. else
  1341. {
  1342. String processCommand = "process";
  1343. processCommand += item->assetType;
  1344. if (isMethod(processCommand.c_str()))
  1345. Con::executef(this, processCommand.c_str(), item);
  1346. }
  1347. //If we've already set our status in the processing phase, don't override that new status
  1348. if(item->importStatus == AssetImportObject::NotProcessed)
  1349. item->importStatus = AssetImportObject::Processed;
  1350. //try recusing on the children(if any)
  1351. processImportAssets(item);
  1352. }
  1353. //If our hierarchy changed, it's because we did so during processing
  1354. //so we'll loop back through again until everything has been processed
  1355. if (assetHeirarchyChanged)
  1356. processImportAssets();
  1357. }
  1358. void AssetImporter::processImageAsset(AssetImportObject* assetItem)
  1359. {
  1360. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Preparing Image for Import: %s", assetItem->assetName.c_str());
  1361. activityLog.push_back(importLogBuffer);
  1362. if ((activeImportConfig->GenerateMaterialOnImport && assetItem->parentAssetItem == nullptr)/* || assetItem->parentAssetItem != nullptr*/)
  1363. {
  1364. //find our suffix match, if any
  1365. String noSuffixName = assetItem->assetName;
  1366. String suffixType;
  1367. String suffix = parseImageSuffixes(assetItem->assetName, &suffixType);
  1368. if (suffix.isNotEmpty())
  1369. {
  1370. assetItem->imageSuffixType = suffixType;
  1371. S32 suffixPos =assetItem->assetName.find(suffix, 0, String::NoCase|String::Left);
  1372. noSuffixName = assetItem->assetName.substr(0, suffixPos);
  1373. }
  1374. //We try to automatically populate materials under the naming convention: materialName: Rock, image maps: Rock_Albedo, Rock_Normal, etc
  1375. AssetImportObject* materialAsset = findImportingAssetByName(noSuffixName);
  1376. if (materialAsset != nullptr && materialAsset->assetType != String("MaterialAsset"))
  1377. {
  1378. //We may have a situation where an asset matches the no-suffix name, but it's not a material asset. Ignore this
  1379. //asset item for now
  1380. materialAsset = nullptr;
  1381. }
  1382. //If we didn't find a matching material asset in our current items, we'll make one now
  1383. if (materialAsset == nullptr)
  1384. {
  1385. if (!assetItem->filePath.isEmpty())
  1386. {
  1387. materialAsset = addImportingAsset("MaterialAsset", assetItem->filePath, nullptr, noSuffixName);
  1388. }
  1389. }
  1390. //Not that, one way or another, we have the generated material asset, lets move on to associating our image with it
  1391. if (materialAsset != nullptr && materialAsset != assetItem->parentAssetItem)
  1392. {
  1393. if (assetItem->parentAssetItem != nullptr)
  1394. {
  1395. //If the image had an existing parent, it gets removed from that parent's child item list
  1396. assetItem->parentAssetItem->childAssetItems.remove(assetItem);
  1397. }
  1398. else
  1399. {
  1400. //If it didn't have one, we're going to pull it from the importingAssets list
  1401. importingAssets.remove(assetItem);
  1402. }
  1403. //Now we can add it to the correct material asset
  1404. materialAsset->childAssetItems.push_back(assetItem);
  1405. assetItem->parentAssetItem = materialAsset;
  1406. assetHeirarchyChanged = true;
  1407. }
  1408. //Now to do some cleverness. If we're generating a material, we can parse like assets being imported(similar filenames) but different suffixes
  1409. //If we find these, we'll just populate into the original's material
  1410. //if we need to append the diffuse suffix and indeed didn't find a suffix on the name, do that here
  1411. if (suffixType.isEmpty())
  1412. {
  1413. if (activeImportConfig->UseDiffuseSuffixOnOriginImage)
  1414. {
  1415. String diffuseToken = StringUnit::getUnit(activeImportConfig->DiffuseTypeSuffixes, 0, ",;\t");
  1416. assetItem->assetName = assetItem->assetName + diffuseToken;
  1417. //assetItem->cleanAssetName = assetItem->assetName;
  1418. }
  1419. else
  1420. {
  1421. //We need to ensure that our image asset doesn't match the same name as the material asset, so if we're not trying to force the diffuse suffix
  1422. //we'll give it a generic one
  1423. if ((materialAsset && materialAsset->assetName.compare(assetItem->assetName) == 0) || activeImportConfig->AlwaysAddImageSuffix)
  1424. {
  1425. assetItem->assetName = assetItem->assetName + activeImportConfig->AddedImageSuffix;
  1426. //assetItem->cleanAssetName = assetItem->assetName;
  1427. }
  1428. }
  1429. //Assume for abledo if it has no suffix matches
  1430. assetItem->imageSuffixType = "Albedo";
  1431. }
  1432. else
  1433. {
  1434. }
  1435. }
  1436. else
  1437. {
  1438. //If we're processing an unaffiliated image without generating materials for it, we can check some other bits
  1439. if (assetItem->parentAssetItem == nullptr)
  1440. {
  1441. if (assetItem->typeHint != String::EmptyString)
  1442. {
  1443. ImageAssetType type = ImageAsset::getImageTypeFromName(StringTable->insert(assetItem->typeHint.c_str()));
  1444. if (type == ImageAssetType::GUI)
  1445. {
  1446. }
  1447. }
  1448. }
  1449. }
  1450. if(assetItem->assetName == assetItem->cleanAssetName && activeImportConfig->AlwaysAddImageSuffix)
  1451. {
  1452. if (!assetItem->assetName.endsWith(activeImportConfig->AddedImageSuffix.c_str()))
  1453. assetItem->assetName = assetItem->assetName + activeImportConfig->AddedImageSuffix;
  1454. }
  1455. assetItem->importStatus = AssetImportObject::Processed;
  1456. }
  1457. void AssetImporter::processMaterialAsset(AssetImportObject* assetItem)
  1458. {
  1459. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Preparing Material for Import: %s", assetItem->assetName.c_str());
  1460. activityLog.push_back(importLogBuffer);
  1461. String filePath = assetItem->filePath.getFullPath();
  1462. String fileName = assetItem->filePath.getFileName();
  1463. String fileExt = assetItem->filePath.getExtension();
  1464. const char* assetName = assetItem->assetName.c_str();
  1465. assetItem->generatedAsset = true;
  1466. if (activeImportConfig->IgnoreMaterials.isNotEmpty())
  1467. {
  1468. U32 ignoredMatNameCount = StringUnit::getUnitCount(activeImportConfig->IgnoreMaterials, ",;\t");
  1469. for (U32 i = 0; i < ignoredMatNameCount; i++)
  1470. {
  1471. String ignoredName = StringUnit::getUnit(activeImportConfig->IgnoreMaterials, i, ",;\t");
  1472. if (FindMatch::isMatch(ignoredName.c_str(), assetName, false))
  1473. {
  1474. assetItem->importStatus = AssetImportObject::Skipped;
  1475. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Material %s has been ignored due to it's name being listed in the IgnoreMaterials list in the Import Config.", assetItem->assetName.c_str());
  1476. activityLog.push_back(importLogBuffer);
  1477. return;
  1478. }
  1479. }
  1480. }
  1481. bool foundExistingMaterial = false;
  1482. if (activeImportConfig->UseExistingMaterials)
  1483. {
  1484. //So if the material already exists, we should just use that. So first, let's find out if it already exists
  1485. if (activeImportConfig->AlwaysAddMaterialSuffix)
  1486. {
  1487. StringTableEntry suffix = activeImportConfig->AddedMaterialSuffix.c_str();
  1488. char buf[1024];
  1489. dSprintf(buf, sizeof(buf), "%s%s", assetName, suffix);
  1490. assetName = buf;
  1491. }
  1492. //check to see if the definition for this already exists
  1493. StringTableEntry existingMatAsset = MaterialAsset::getAssetIdByMaterialName(StringTable->insert(assetName));
  1494. if (existingMatAsset != StringTable->EmptyString() && existingMatAsset != StringTable->insert("Core_Rendering:NoMaterial"))
  1495. {
  1496. assetItem->importStatus = AssetImportObject::UseForDependencies;
  1497. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Material %s has been skipped because we already found an asset Id that uses that material definition. The found assetId is: %s", assetItem->assetName.c_str(), existingMatAsset);
  1498. activityLog.push_back(importLogBuffer);
  1499. return;
  1500. }
  1501. //If there was no existing assetId, then lets see if it already exists in a legacy file, like a materials.cs or materials.tscript
  1502. //If it does, we'll just make our asset point to that instead of a new file
  1503. Material* mat;
  1504. Sim::findObject(assetName, mat);
  1505. if (!mat)
  1506. mat = MATMGR->getMaterialDefinitionByMapTo(assetName);
  1507. if (!mat && assetItem->assetName != assetItem->cleanAssetName)
  1508. {
  1509. mat = MATMGR->getMaterialDefinitionByName(assetItem->cleanAssetName);
  1510. if (!mat)
  1511. mat = MATMGR->getMaterialDefinitionByMapTo(assetItem->cleanAssetName);
  1512. }
  1513. if(mat)
  1514. {
  1515. //We found a match, so just modify our asset item's info to point against it. This will create the asset definition, but otherwise leave the material definition as-is.
  1516. assetItem->filePath = (Torque::Path)(mat->getFilename());
  1517. foundExistingMaterial = true;
  1518. }
  1519. }
  1520. if(!foundExistingMaterial)
  1521. {
  1522. if (activeImportConfig->AlwaysAddMaterialSuffix) //we only opt to force on the suffix if we're not obligating using the original material defs
  1523. {
  1524. if(!assetItem->assetName.endsWith(activeImportConfig->AddedMaterialSuffix.c_str()))
  1525. assetItem->assetName += activeImportConfig->AddedMaterialSuffix;
  1526. }
  1527. if (activeImportConfig->PopulateMaterialMaps)
  1528. {
  1529. //If we're trying to populate the rest of our material maps, we need to go looking
  1530. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Attempting to Auto-Populate Material Maps");
  1531. activityLog.push_back(importLogBuffer);
  1532. AssetImportObject* matchedImageTypes[ImageAsset::ImageTypeCount] = { nullptr };
  1533. String materialImageNoSuffix;
  1534. for (U32 i = 0; i < assetItem->childAssetItems.size(); i++)
  1535. {
  1536. AssetImportObject* childAssetItem = assetItem->childAssetItems[i];
  1537. if (childAssetItem->importStatus == AssetImportObject::Skipped || childAssetItem->assetType != String("ImageAsset"))
  1538. continue;
  1539. for (S32 t = 0; t < ImageAsset::ImageTypeCount; t++)
  1540. {
  1541. //If the imageType name and child asset image type match, check it off our list
  1542. if (!dStricmp(ImageAsset::getImageTypeNameFromType((ImageAsset::ImageTypes)t), childAssetItem->imageSuffixType.c_str()))
  1543. {
  1544. matchedImageTypes[t] = childAssetItem;
  1545. if (t == ImageAsset::ImageTypes::Albedo)
  1546. {
  1547. String sufType;
  1548. String suffix = parseImageSuffixes(childAssetItem->assetName, &sufType);
  1549. String imageAssetName = childAssetItem->assetName;
  1550. if (suffix.isEmpty())
  1551. materialImageNoSuffix = imageAssetName;
  1552. else
  1553. materialImageNoSuffix = imageAssetName.erase(imageAssetName.length() - suffix.length(), suffix.length());//cache this for later as we may need it for file association lookups
  1554. }
  1555. }
  1556. }
  1557. }
  1558. //Now that we've checked off any existingly matched image types, process through the unmatched to look for files that associate
  1559. for (S32 t = 0; t < ImageAsset::ImageTypeCount; t++)
  1560. {
  1561. //This type wasn't found, so try and find a match based on suffix
  1562. String suffixList;
  1563. switch (t)
  1564. {
  1565. case ImageAsset::Albedo:
  1566. suffixList = activeImportConfig->DiffuseTypeSuffixes;
  1567. break;
  1568. case ImageAsset::Normal:
  1569. suffixList = activeImportConfig->NormalTypeSuffixes;
  1570. break;
  1571. case ImageAsset::ORMConfig:
  1572. suffixList = activeImportConfig->PBRTypeSuffixes;
  1573. break;
  1574. case ImageAsset::Metalness:
  1575. suffixList = activeImportConfig->MetalnessTypeSuffixes;
  1576. break;
  1577. case ImageAsset::AO:
  1578. suffixList = activeImportConfig->AOTypeSuffixes;
  1579. break;
  1580. case ImageAsset::Roughness:
  1581. suffixList = activeImportConfig->RoughnessTypeSuffixes;
  1582. break;
  1583. //TODO: Glow map lookup too
  1584. }
  1585. if (!matchedImageTypes[t])
  1586. {
  1587. U32 suffixCount = StringUnit::getUnitCount(suffixList.c_str(), ",;\t");
  1588. for (U32 i = 0; i < suffixCount; i++)
  1589. {
  1590. //First, try checking based on the material's assetName for our patternbase
  1591. String testPath = assetItem->filePath.getRootAndPath();
  1592. testPath += "/" + assetItem->cleanAssetName + StringUnit::getUnit(suffixList.c_str(), i, ",;\t");
  1593. String imagePath = AssetImporter::findImagePath(testPath);
  1594. if (imagePath.isNotEmpty())
  1595. {
  1596. //got a match!
  1597. AssetImportObject* newImageAssetObj = addImportingAsset("ImageAsset", imagePath, assetItem, "");
  1598. newImageAssetObj->imageSuffixType = ImageAsset::getImageTypeNameFromType((ImageAsset::ImageTypes)t);
  1599. matchedImageTypes[t] = newImageAssetObj;
  1600. break;
  1601. }
  1602. else
  1603. {
  1604. //Check to see if our target module has a matching assetId for this slot already
  1605. String testAssetId = targetModuleId + ":" + assetItem->cleanAssetName + StringUnit::getUnit(suffixList.c_str(), i, ",;\t");
  1606. bool localAssetFound = false;
  1607. if (AssetDatabase.isDeclaredAsset(testAssetId.c_str()))
  1608. localAssetFound = true;
  1609. if (localAssetFound == false)
  1610. //Didn't work, try checking the common default type suffix
  1611. testAssetId = targetModuleId + ":" + assetItem->cleanAssetName + StringUnit::getUnit(suffixList.c_str(), i, ",;\t") + activeImportConfig->AddedImageSuffix;
  1612. if (localAssetFound)
  1613. {
  1614. //got a match!
  1615. ImageAsset* foundImageAsset = AssetDatabase.acquireAsset<ImageAsset>(testAssetId.c_str());
  1616. imagePath = foundImageAsset->getImageFile();
  1617. AssetImportObject* newImageAssetObj = addImportingAsset("ImageAsset", imagePath, assetItem, "");
  1618. newImageAssetObj->imageSuffixType = ImageAsset::getImageTypeNameFromType((ImageAsset::ImageTypes)t);
  1619. newImageAssetObj->importStatus = AssetImportObject::UseForDependencies; //we aren't going to actually IMPORT an already imported asset,
  1620. //so mark it as dependency use only
  1621. matchedImageTypes[t] = newImageAssetObj;
  1622. break;
  1623. }
  1624. if (materialImageNoSuffix.isNotEmpty())
  1625. {
  1626. testPath = assetItem->filePath.getRootAndPath();
  1627. testPath += "/" + materialImageNoSuffix + StringUnit::getUnit(suffixList.c_str(), i, ",;\t");
  1628. imagePath = AssetImporter::findImagePath(testPath);
  1629. if (imagePath.isNotEmpty())
  1630. {
  1631. //got a match!
  1632. AssetImportObject* newImageAssetObj = addImportingAsset("ImageAsset", imagePath, assetItem, "");
  1633. newImageAssetObj->imageSuffixType = ImageAsset::getImageTypeNameFromType((ImageAsset::ImageTypes)t);
  1634. matchedImageTypes[t] = newImageAssetObj;
  1635. break;
  1636. }
  1637. //Check to see if our target module has a matching assetId for this slot already based on our trimmed mat name
  1638. testAssetId = targetModuleId + ":" + materialImageNoSuffix + StringUnit::getUnit(suffixList.c_str(), i, ",;\t");
  1639. localAssetFound = false;
  1640. if (AssetDatabase.isDeclaredAsset(testAssetId.c_str()))
  1641. localAssetFound = true;
  1642. if (localAssetFound == false)
  1643. //Didn't work, try checking the common default type suffix
  1644. testAssetId = targetModuleId + ":" + materialImageNoSuffix + StringUnit::getUnit(suffixList.c_str(), i, ",;\t") + activeImportConfig->AddedImageSuffix;
  1645. if (localAssetFound)
  1646. {
  1647. //got a match!
  1648. ImageAsset* foundImageAsset = AssetDatabase.acquireAsset<ImageAsset>(testAssetId.c_str());
  1649. imagePath = foundImageAsset->getImageFile();
  1650. AssetImportObject* newImageAssetObj = addImportingAsset("ImageAsset", imagePath, assetItem, "");
  1651. newImageAssetObj->imageSuffixType = ImageAsset::getImageTypeNameFromType((ImageAsset::ImageTypes)t);
  1652. newImageAssetObj->importStatus = AssetImportObject::UseForDependencies; //we aren't going to actually IMPORT an already imported asset,
  1653. //so mark it as dependency use only
  1654. matchedImageTypes[t] = newImageAssetObj;
  1655. break;
  1656. }
  1657. }
  1658. }
  1659. }
  1660. //If we're the abledo slot and after all that we didn't find anything, it probably is a suffixless image
  1661. if (t == ImageAsset::Albedo && matchedImageTypes[t] == nullptr)
  1662. {
  1663. String testPath = assetItem->filePath.getRootAndPath() + "/" + assetItem->cleanAssetName;
  1664. String imagePath = AssetImporter::findImagePath(testPath);
  1665. if (imagePath.isNotEmpty())
  1666. {
  1667. //got a match!
  1668. AssetImportObject* newImageAssetObj = addImportingAsset("ImageAsset", imagePath, assetItem, "");
  1669. //In the event that the names match, we want to avoid duplications, so we'll go ahead and append a suffix onto our new image asset
  1670. if (newImageAssetObj->assetName == assetItem->assetName)
  1671. {
  1672. newImageAssetObj->assetName += StringUnit::getUnit(suffixList.c_str(), 0, ",;\t");
  1673. //newImageAssetObj->cleanAssetName = newImageAssetObj->assetName;
  1674. }
  1675. newImageAssetObj->imageSuffixType = ImageAsset::getImageTypeNameFromType(ImageAsset::ImageTypes::Albedo);
  1676. matchedImageTypes[t] = newImageAssetObj;
  1677. }
  1678. }
  1679. }
  1680. else
  1681. {
  1682. //just a bit of cleanup and logical testing for matches
  1683. //in the event we KNOW what the type is, but we don't have a suffix, such as a found image on a material lookup
  1684. //that doesn't have a suffix, we assume it to be the albedo, so we'll just append the suffix to avoid collisions if
  1685. //the name already matches our material name, similar to above logic
  1686. if (matchedImageTypes[t]->assetName == assetItem->assetName)
  1687. {
  1688. matchedImageTypes[t]->assetName += StringUnit::getUnit(suffixList.c_str(), 0, ",;\t");
  1689. //matchedImageTypes[t]->cleanAssetName = matchedImageTypes[t]->assetName;
  1690. }
  1691. }
  1692. }
  1693. }
  1694. }
  1695. assetItem->importStatus = AssetImportObject::Processed;
  1696. }
  1697. void AssetImporter::processShapeAsset(AssetImportObject* assetItem)
  1698. {
  1699. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Preparing Shape for Import: %s", assetItem->assetName.c_str());
  1700. activityLog.push_back(importLogBuffer);
  1701. String filePath = assetItem->filePath.getFullPath();
  1702. String fileName = assetItem->filePath.getFileName();
  1703. String fileExt = assetItem->filePath.getExtension();
  1704. if (assetItem->shapeInfo == nullptr)
  1705. {
  1706. GuiTreeViewCtrl* shapeInfo = new GuiTreeViewCtrl();
  1707. shapeInfo->registerObject();
  1708. if (fileExt.compare("dae") == 0)
  1709. {
  1710. enumColladaForImport(filePath, shapeInfo, false);
  1711. }
  1712. else if (fileExt.compare("dts") == 0)
  1713. {
  1714. enumDTSForImport(filePath, shapeInfo);
  1715. }
  1716. else
  1717. {
  1718. // Check if a cached DTS is available => no need to import the source file
  1719. // if we can load the DTS instead
  1720. AssimpShapeLoader loader;
  1721. loader.fillGuiTreeView(filePath.c_str(), shapeInfo);
  1722. }
  1723. assetItem->shapeInfo = shapeInfo;
  1724. }
  1725. if (activeImportConfig->AlwaysAddShapeSuffix)
  1726. {
  1727. if(!assetItem->assetName.endsWith(activeImportConfig->AddedShapeSuffix.c_str()))
  1728. assetItem->assetName += activeImportConfig->AddedShapeSuffix;
  1729. }
  1730. S32 meshCount = dAtoi(assetItem->shapeInfo->getDataField(StringTable->insert("_meshCount"), nullptr));
  1731. S32 animCount = dAtoi(assetItem->shapeInfo->getDataField(StringTable->insert("_animCount"), nullptr));
  1732. S32 materialCount = dAtoi(assetItem->shapeInfo->getDataField(StringTable->insert("_materialCount"), nullptr));
  1733. S32 matItem = assetItem->shapeInfo->findItemByName("Materials");
  1734. dSprintf(importLogBuffer, sizeof(importLogBuffer), " Shape Info: Mesh Count: %i | Material Count: %i | Anim Count: %i", meshCount, animCount, materialCount);
  1735. activityLog.push_back(importLogBuffer);
  1736. AssetImportConfig* cachedConfig = new AssetImportConfig();;
  1737. cachedConfig->registerObject();
  1738. activeImportConfig->CopyTo(cachedConfig);
  1739. if (!activeImportConfig->UseManualShapeConfigRules)
  1740. {
  1741. //Try and load a sis file if it exists for this format
  1742. activeImportConfig->loadSISFile(assetItem->filePath);
  1743. }
  1744. if (activeImportConfig->ImportMesh && meshCount > 0)
  1745. {
  1746. }
  1747. if (activeImportConfig->ImportAnimations && animCount > 0)
  1748. {
  1749. //If we have animations but no meshes, then this is a pure animation file so we can swap the asset type here
  1750. if (meshCount == 0)
  1751. {
  1752. assetItem->assetType = "ShapeAnimationAsset";
  1753. }
  1754. }
  1755. if (activeImportConfig->ImportMaterials && materialCount > 0)
  1756. {
  1757. S32 materialId = assetItem->shapeInfo->getChildItem(matItem);
  1758. processShapeMaterialInfo(assetItem, materialId);
  1759. materialId = assetItem->shapeInfo->getNextSiblingItem(materialId);
  1760. while (materialId != 0)
  1761. {
  1762. processShapeMaterialInfo(assetItem, materialId);
  1763. materialId = assetItem->shapeInfo->getNextSiblingItem(materialId);
  1764. }
  1765. }
  1766. //restore the cached version just in case we loaded a sis file
  1767. cachedConfig->CopyTo(activeImportConfig);
  1768. cachedConfig->deleteObject();
  1769. assetItem->importStatus = AssetImportObject::Processed;
  1770. }
  1771. void AssetImporter::processShapeAnimationAsset(AssetImportObject* assetItem)
  1772. {
  1773. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Preparing Shape Animation for Import: %s", assetItem->assetName.c_str());
  1774. activityLog.push_back(importLogBuffer);
  1775. String filePath = assetItem->filePath.getFullPath();
  1776. String fileName = assetItem->filePath.getFileName();
  1777. String fileExt = assetItem->filePath.getExtension();
  1778. if (assetItem->shapeInfo == nullptr)
  1779. {
  1780. GuiTreeViewCtrl* shapeInfo = new GuiTreeViewCtrl();
  1781. shapeInfo->registerObject();
  1782. if (fileExt.compare("dae") == 0)
  1783. {
  1784. enumColladaForImport(filePath, shapeInfo, false);
  1785. }
  1786. else if (fileExt.compare("dts") == 0)
  1787. {
  1788. enumDTSForImport(filePath, shapeInfo);
  1789. }
  1790. else
  1791. {
  1792. // Check if a cached DTS is available => no need to import the source file
  1793. // if we can load the DTS instead
  1794. AssimpShapeLoader loader;
  1795. loader.fillGuiTreeView(filePath.c_str(), shapeInfo);
  1796. }
  1797. assetItem->shapeInfo = shapeInfo;
  1798. }
  1799. if (activeImportConfig->AlwaysAddShapeAnimationSuffix)
  1800. {
  1801. if (!assetItem->assetName.endsWith(activeImportConfig->AddedShapeAnimationSuffix.c_str()))
  1802. assetItem->assetName += activeImportConfig->AddedShapeAnimationSuffix;
  1803. }
  1804. S32 animCount = dAtoi(assetItem->shapeInfo->getDataField(StringTable->insert("_animCount"), nullptr));
  1805. dSprintf(importLogBuffer, sizeof(importLogBuffer), " Shape Animation Info: Anim Count: %i", animCount);
  1806. activityLog.push_back(importLogBuffer);
  1807. AssetImportConfig* cachedConfig = new AssetImportConfig();;
  1808. cachedConfig->registerObject();
  1809. activeImportConfig->CopyTo(cachedConfig);
  1810. if (!activeImportConfig->UseManualShapeConfigRules)
  1811. {
  1812. //Try and load a sis file if it exists for this format
  1813. activeImportConfig->loadSISFile(assetItem->filePath);
  1814. }
  1815. if (activeImportConfig->ImportAnimations && animCount > 0)
  1816. {
  1817. }
  1818. //restore the cached version just in case we loaded a sis file
  1819. cachedConfig->CopyTo(activeImportConfig);
  1820. cachedConfig->deleteObject();
  1821. assetItem->importStatus = AssetImportObject::Processed;
  1822. }
  1823. void AssetImporter::processShapeMaterialInfo(AssetImportObject* assetItem, S32 materialItemId)
  1824. {
  1825. String matName = assetItem->shapeInfo->getItemText(materialItemId);
  1826. String matAssetName = matName;
  1827. if (matName == assetItem->assetName)
  1828. {
  1829. //So apparently we managed to name the material the same as the shape. So we'll tweak the name
  1830. matAssetName += activeImportConfig->AddedMaterialSuffix;
  1831. }
  1832. //Do a check so we don't import materials that are on our ignore list
  1833. if (activeImportConfig->IgnoreMaterials.isNotEmpty())
  1834. {
  1835. U32 ignoredMatNamesCount = StringUnit::getUnitCount(activeImportConfig->IgnoreMaterials, ",;\t");
  1836. for (U32 i = 0; i < ignoredMatNamesCount; i++)
  1837. {
  1838. const char* ignoreMatName = StringUnit::getUnit(activeImportConfig->IgnoreMaterials, i, ",;\t");
  1839. if (FindMatch::isMatch(ignoreMatName, matName.c_str(), false))
  1840. {
  1841. //If we have a match to one of our ignore names, just bail out here and skip the material wholesale
  1842. return;
  1843. }
  1844. }
  1845. }
  1846. String materialItemValue = assetItem->shapeInfo->getItemValue(materialItemId);
  1847. AssetImportObject* matAssetItem = nullptr;
  1848. //If it happens to just be a color value instead of an image, we'll go ahead and skip doing any lookups
  1849. //TODO: properly map the 'texture' color to the material that gets created
  1850. if (materialItemValue.startsWith("Color:"))
  1851. {
  1852. matAssetItem = addImportingAsset("MaterialAsset", "", assetItem, matName);
  1853. }
  1854. else
  1855. {
  1856. Torque::Path filePath = materialItemValue;
  1857. String fullFilePath = filePath.getFullPath().c_str();
  1858. String shapePathBase = assetItem->filePath.getRootAndPath();
  1859. if (fullFilePath.isNotEmpty())
  1860. {
  1861. if (!Torque::FS::IsFile(fullFilePath.c_str()))
  1862. {
  1863. //could be a stale path reference, such as if it was downloaded elsewhere. Trim to just the filename and see
  1864. //if we can find it there
  1865. //trim (not found) if needbe
  1866. fullFilePath = fullFilePath.replace(" (Not Found)", "");
  1867. fullFilePath = fullFilePath.replace(" (not found)", "");
  1868. if(filePath.getPath().isEmpty())
  1869. fullFilePath = shapePathBase + "/" + fullFilePath;
  1870. if (Torque::FS::IsFile(fullFilePath.c_str()))
  1871. {
  1872. filePath = Torque::Path(fullFilePath);
  1873. }
  1874. else
  1875. {
  1876. //Hmm, didn't find it. It could be that the in-model filename could be different by virtue of
  1877. //image extension. Some files have source content files like psd's, but the mesh was exported to use
  1878. //a dds or png, etc
  1879. Torque::Path testFilePath = fullFilePath;
  1880. String imgFileName = AssetImporter::findImagePath(testFilePath.getPath() + "/" + testFilePath.getFileName());
  1881. if (imgFileName.isNotEmpty())
  1882. filePath = imgFileName;
  1883. else
  1884. filePath = Torque::Path(""); //no luck, so we just won't try importing in the image
  1885. }
  1886. }
  1887. matAssetItem = addImportingAsset("MaterialAsset", shapePathBase + "/" + matName, assetItem, matName);
  1888. if (!filePath.isEmpty())
  1889. {
  1890. AssetImportObject* imageAssetItem = addImportingAsset("ImageAsset", filePath, matAssetItem, "");
  1891. String suffixType;
  1892. String suffix = parseImageSuffixes(imageAssetItem->assetName, &suffixType);
  1893. if (suffix.isNotEmpty())
  1894. {
  1895. imageAssetItem->imageSuffixType = suffixType;
  1896. }
  1897. else
  1898. {
  1899. //we'll assume it's albedo
  1900. imageAssetItem->imageSuffixType = "Albedo";
  1901. }
  1902. }
  1903. }
  1904. else
  1905. {
  1906. matAssetItem = addImportingAsset("MaterialAsset", shapePathBase + "/" + matName, assetItem, matName);
  1907. }
  1908. }
  1909. //In the event we modified the asset name(such as appending _Mat to avoid naming conflicts) update the name here
  1910. //This preseves the 'clean asset name' which we can later use for lookups and the like as needed
  1911. if (matAssetItem && matAssetName != matName)
  1912. matAssetItem->assetName = matAssetName;
  1913. }
  1914. void AssetImporter::processSoundAsset(AssetImportObject* assetItem)
  1915. {
  1916. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Preparing Sound for Import: %s", assetItem->assetName.c_str());
  1917. activityLog.push_back(importLogBuffer);
  1918. if (activeImportConfig->AlwaysAddSoundSuffix)
  1919. {
  1920. if (!assetItem->assetName.endsWith(activeImportConfig->AddedSoundSuffix.c_str()))
  1921. assetItem->assetName += activeImportConfig->AddedSoundSuffix;
  1922. }
  1923. assetItem->importStatus = AssetImportObject::Processed;
  1924. }
  1925. //
  1926. // Validation
  1927. //
  1928. bool AssetImporter::validateAssets()
  1929. {
  1930. importIssues = false;
  1931. resetAssetValidationStatus();
  1932. for (U32 i = 0; i < importingAssets.size(); i++)
  1933. {
  1934. validateAsset(importingAssets[i]);
  1935. resolveAssetItemIssues(importingAssets[i]);
  1936. }
  1937. return importIssues;
  1938. }
  1939. void AssetImporter::validateAsset(AssetImportObject* assetItem)
  1940. {
  1941. if (assetItem->importStatus == AssetImportObject::Skipped || assetItem->importStatus == AssetImportObject::NotProcessed
  1942. || assetItem->importStatus == AssetImportObject::UseForDependencies)
  1943. return;
  1944. //If this item's already been marked as being in error, don't bother with it. It knows what it did.
  1945. //This avoids running collision checks on an item already known to have a collision, which could erroneously
  1946. //mark the original, not-colliding item as colliding with this item, invaliding both
  1947. if (assetItem->status == String("Error") || assetItem->statusType.isNotEmpty())
  1948. {
  1949. importIssues = true;
  1950. return;
  1951. }
  1952. //Runm this item against our other importing assets and check for any collisions
  1953. if (checkAssetForCollision(assetItem))
  1954. {
  1955. importIssues = true;
  1956. return;
  1957. }
  1958. if (!isReimport)
  1959. {
  1960. AssetQuery aQuery;
  1961. U32 numAssetsFound = AssetDatabase.findAllAssets(&aQuery);
  1962. for (U32 i = 0; i < numAssetsFound; i++)
  1963. {
  1964. StringTableEntry assetId = aQuery.mAssetList[i];
  1965. ModuleDefinition* moduleDef = AssetDatabase.getAssetModuleDefinition(assetId);
  1966. if ((moduleDef == NULL) || moduleDef->getModuleId() != StringTable->insert(targetModuleId.c_str()))
  1967. continue;
  1968. StringTableEntry assetName = AssetDatabase.getAssetName(assetId);
  1969. if (assetName == StringTable->insert(assetItem->assetName.c_str()))
  1970. {
  1971. assetItem->status = "Error";
  1972. assetItem->statusType = "DuplicateAsset";
  1973. assetItem->statusInfo = "Duplicate asset names found within the target module!\nAsset \"" + assetItem->assetName + "\" of type \"" + assetItem->assetType + "\" has a matching name.\nPlease rename it and try again!";
  1974. //log it
  1975. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Error! Asset %s has an identically named asset in the target module.", assetItem->assetName.c_str());
  1976. activityLog.push_back(importLogBuffer);
  1977. break;
  1978. }
  1979. }
  1980. }
  1981. if (!assetItem->filePath.isEmpty() && !assetItem->generatedAsset && !Torque::FS::IsFile(assetItem->filePath.getFullPath().c_str()))
  1982. {
  1983. assetItem->status = "Error";
  1984. assetItem->statusType = "MissingFile";
  1985. assetItem->statusInfo = "Unable to find file to be imported with provided path: " + assetItem->filePath + "\n Please select a valid file.";
  1986. //log it
  1987. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Error! Asset %s's file at %s was not found.", assetItem->assetName.c_str(), assetItem->filePath.getFullPath().c_str());
  1988. activityLog.push_back(importLogBuffer);
  1989. }
  1990. if (assetItem->status == String("Warning"))
  1991. {
  1992. if (activeImportConfig->WarningsAsErrors)
  1993. {
  1994. assetItem->status = "Error";
  1995. //log it
  1996. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Error! Import configuration has treated an import warning as an error.", assetItem->assetName.c_str());
  1997. activityLog.push_back(importLogBuffer);
  1998. }
  1999. }
  2000. if (assetItem->status == String("Error"))
  2001. importIssues = true;
  2002. for (U32 i = 0; i < assetItem->childAssetItems.size(); i++)
  2003. {
  2004. validateAsset(assetItem->childAssetItems[i]);
  2005. resolveAssetItemIssues(assetItem->childAssetItems[i]);
  2006. }
  2007. return;
  2008. }
  2009. void AssetImporter::resetAssetValidationStatus(AssetImportObject* assetItem)
  2010. {
  2011. Vector<AssetImportObject*> itemList = importingAssets;
  2012. if (assetItem != nullptr)
  2013. itemList = assetItem->childAssetItems;
  2014. for (U32 i = 0; i < itemList.size(); i++)
  2015. {
  2016. if (itemList[i]->importStatus == AssetImportObject::Skipped)
  2017. continue;
  2018. itemList[i]->status = "";
  2019. itemList[i]->statusType = "";
  2020. itemList[i]->statusInfo = "";
  2021. //If it wasn't a match, try recusing on the children(if any)
  2022. resetAssetValidationStatus(itemList[i]);
  2023. }
  2024. }
  2025. bool AssetImporter::checkAssetForCollision(AssetImportObject* assetItemToCheck, AssetImportObject* assetItem)
  2026. {
  2027. bool results = false;
  2028. Vector<AssetImportObject*> itemList = importingAssets;
  2029. if (assetItem != nullptr)
  2030. itemList = assetItem->childAssetItems;
  2031. for (U32 i = 0; i < itemList.size(); i++)
  2032. {
  2033. AssetImportObject* importingAsset = itemList[i];
  2034. if (importingAsset->importStatus == AssetImportObject::Skipped || importingAsset->importStatus == AssetImportObject::UseForDependencies)
  2035. continue;
  2036. if ((assetItemToCheck->assetName.compare(importingAsset->assetName) == 0) && (assetItemToCheck->getId() != importingAsset->getId()))
  2037. {
  2038. //we do have a collision, note the collsion and bail out
  2039. assetItemToCheck->status = "Warning";
  2040. assetItemToCheck->statusType = "DuplicateImportAsset";
  2041. assetItemToCheck->statusInfo = "Duplicate asset names found with importing assets!\nAsset \"" + importingAsset->assetName + "\" of the type \"" + importingAsset->assetType + "\" and \"" +
  2042. assetItemToCheck->assetName + "\" of the type \"" + assetItemToCheck->assetType + "\" have matching names.\nPlease rename one of them.";
  2043. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Warning! Asset %s, type %s has a naming collision with another importing asset: %s, type %s",
  2044. assetItemToCheck->assetName.c_str(), assetItemToCheck->assetType.c_str(),
  2045. importingAsset->assetName.c_str(), importingAsset->assetType.c_str());
  2046. activityLog.push_back(importLogBuffer);
  2047. return true;
  2048. }
  2049. //If it wasn't a match, try recusing on the children(if any)
  2050. results = checkAssetForCollision(assetItemToCheck, importingAsset);
  2051. if (results)
  2052. return results;
  2053. }
  2054. return results;
  2055. }
  2056. void AssetImporter::resolveAssetItemIssues(AssetImportObject* assetItem)
  2057. {
  2058. if(assetItem->importStatus == AssetImportObject::UseForDependencies)
  2059. {
  2060. //if we've already marked as only existing for dependency reasons, we'll just skip resolving any issues with it
  2061. importIssues = false;
  2062. return;
  2063. }
  2064. if (assetItem->statusType == String("DuplicateImportAsset") || assetItem->statusType == String("DuplicateAsset"))
  2065. {
  2066. String humanReadableReason = assetItem->statusType == String("DuplicateImportAsset") ? "Importing asset was duplicate of another importing asset" : "Importing asset was duplicate of an existing asset";
  2067. //get the config value for duplicateAutoResolution
  2068. if (activeImportConfig->DuplicateAutoResolution == String("AutoPrune"))
  2069. {
  2070. //delete the item
  2071. if (assetItem->parentAssetItem == nullptr)
  2072. {
  2073. //if there's no parent, just delete
  2074. deleteImportingAsset(assetItem);
  2075. }
  2076. else
  2077. {
  2078. //otherwise, we'll likely want to retain our dependency for our parent
  2079. assetItem->importStatus = AssetImportObject::UseForDependencies;
  2080. }
  2081. //log it's deletion
  2082. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Asset %s was autopruned due to %s as part of the Import Configuration", assetItem->assetName.c_str(), humanReadableReason.c_str());
  2083. activityLog.push_back(importLogBuffer);
  2084. importIssues = false;
  2085. }
  2086. else if (activeImportConfig->DuplicateAutoResolution == String("AutoRename"))
  2087. {
  2088. //Set trailing number
  2089. String renamedAssetName = assetItem->assetName;
  2090. String renamedAssetId = assetItem->moduleName + ":" + renamedAssetName;
  2091. String addedSuffix;
  2092. if (assetItem->assetType == String("ShapeAsset"))
  2093. addedSuffix = activeImportConfig->AddedShapeSuffix;
  2094. else if (assetItem->assetType == String("MaterialAsset"))
  2095. addedSuffix = activeImportConfig->AddedMaterialSuffix;
  2096. else if (assetItem->assetType == String("ImageAsset"))
  2097. addedSuffix = activeImportConfig->AddedImageSuffix;
  2098. else if (assetItem->assetType == String("SoundAsset"))
  2099. addedSuffix = activeImportConfig->AddedSoundSuffix;
  2100. //do the suffix if it isn't already on it
  2101. if (!renamedAssetName.endsWith(addedSuffix.c_str()))
  2102. {
  2103. renamedAssetName += addedSuffix;
  2104. renamedAssetId = assetItem->moduleName + ":" + renamedAssetName;
  2105. assetItem->assetName = renamedAssetName;
  2106. }
  2107. //if still conflicted
  2108. //add the directory prefix
  2109. if (AssetDatabase.isDeclaredAsset(renamedAssetId.c_str()))
  2110. {
  2111. renamedAssetName = getFolderPrefixedName(assetItem);
  2112. renamedAssetId = assetItem->moduleName + ":" + renamedAssetName;
  2113. assetItem->assetName = renamedAssetName;
  2114. }
  2115. bool appendedNumber = false;
  2116. U32 uniqueNumber = 0;
  2117. while (AssetDatabase.isDeclaredAsset(renamedAssetId.c_str()))
  2118. {
  2119. uniqueNumber++;
  2120. renamedAssetId = assetItem->moduleName + ":" + renamedAssetName + String::ToString(uniqueNumber);
  2121. appendedNumber = true;
  2122. }
  2123. if (appendedNumber)
  2124. {
  2125. renamedAssetName += String::ToString(uniqueNumber);
  2126. }
  2127. //Log it's renaming
  2128. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Asset %s was renamed due to %s as part of the Import Configuration", assetItem->assetName.c_str(), humanReadableReason.c_str());
  2129. activityLog.push_back(importLogBuffer);
  2130. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Asset %s was renamed to %s", assetItem->assetName.c_str(), renamedAssetName.c_str());
  2131. activityLog.push_back(importLogBuffer);
  2132. assetItem->assetName = renamedAssetName;
  2133. //Whatever status we had prior is no longer relevent, so reset the status
  2134. resetAssetValidationStatus(assetItem);
  2135. importIssues = false;
  2136. }
  2137. else if (activeImportConfig->DuplicateAutoResolution == String("UseExisting"))
  2138. {
  2139. }
  2140. else if (activeImportConfig->DuplicateAutoResolution == String("FolderPrefix"))
  2141. {
  2142. String renamedAssetName = getFolderPrefixedName(assetItem);
  2143. //Log it's renaming
  2144. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Asset %s was renamed due to %s as part of the Import Configuration", assetItem->assetName.c_str(), humanReadableReason.c_str());
  2145. activityLog.push_back(importLogBuffer);
  2146. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Asset %s was renamed to %s", assetItem->assetName.c_str(), renamedAssetName.c_str());
  2147. activityLog.push_back(importLogBuffer);
  2148. assetItem->assetName = renamedAssetName;
  2149. //Whatever status we had prior is no longer relevent, so reset the status
  2150. resetAssetValidationStatus(assetItem);
  2151. importIssues = false;
  2152. }
  2153. }
  2154. else if (assetItem->statusType == String("MissingFile"))
  2155. {
  2156. //Trigger callback to look?
  2157. }
  2158. }
  2159. void AssetImporter::resetImportConfig()
  2160. {
  2161. //use a default import config
  2162. if (activeImportConfig == nullptr)
  2163. {
  2164. activeImportConfig = new AssetImportConfig();
  2165. activeImportConfig->registerObject();
  2166. }
  2167. Settings* editorSettings;
  2168. //See if we can get our editor settings
  2169. if (Sim::findObject("EditorSettings", editorSettings))
  2170. {
  2171. String defaultImportConfig = editorSettings->value("Assets/AssetImporDefaultConfig");
  2172. //If we found it, grab the import configs
  2173. Settings* importConfigs;
  2174. if (Sim::findObject("AssetImportSettings", importConfigs))
  2175. {
  2176. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Loading import config: %s!", defaultImportConfig.c_str());
  2177. activityLog.push_back(importLogBuffer);
  2178. //Now load the editor setting-deigned config!
  2179. activeImportConfig->loadImportConfig(importConfigs, defaultImportConfig.c_str());
  2180. }
  2181. }
  2182. }
  2183. //
  2184. // Importing
  2185. //
  2186. StringTableEntry AssetImporter::autoImportFile(Torque::Path filePath, String typeHint)
  2187. {
  2188. //Just in case we're reusing the same importer object from another import session, nuke any existing files
  2189. resetImportSession(true);
  2190. String assetType = getAssetTypeByFile(filePath);
  2191. if (assetType == String("Folder") || assetType == String("Zip"))
  2192. {
  2193. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Unable to import file %s because it is a folder or zip.", filePath.getFullPath().c_str());
  2194. activityLog.push_back(importLogBuffer);
  2195. dumpActivityLog();
  2196. return StringTable->EmptyString();
  2197. }
  2198. if (assetType.isEmpty())
  2199. {
  2200. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Unable to import file %s because it is of an unrecognized/unsupported type.", filePath.getFullPath().c_str());
  2201. activityLog.push_back(importLogBuffer);
  2202. dumpActivityLog();
  2203. return StringTable->EmptyString();
  2204. }
  2205. //Find out if the filepath has an associated module to it. If we're importing in-place, it needs to be within a module's directory
  2206. ModuleDefinition* targetModuleDef = AssetImporter::getModuleFromPath(filePath);
  2207. if (targetModuleDef == nullptr)
  2208. {
  2209. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Unable to import file %s because it is not in a valid module folder.", filePath.getFullPath().c_str());
  2210. activityLog.push_back(importLogBuffer);
  2211. dumpActivityLog();
  2212. return StringTable->EmptyString();
  2213. }
  2214. else
  2215. {
  2216. targetModuleId = targetModuleDef->getModuleId();
  2217. }
  2218. //set our path
  2219. targetPath = filePath.getPath();
  2220. resetImportConfig();
  2221. AssetImportObject* assetItem = addImportingAsset(assetType, filePath, nullptr, "");
  2222. processImportAssets();
  2223. bool hasIssues = validateAssets();
  2224. if (hasIssues)
  2225. {
  2226. //log it
  2227. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Error! Import process has failed due to issues discovered during validation!");
  2228. activityLog.push_back(importLogBuffer);
  2229. }
  2230. else
  2231. {
  2232. importAssets();
  2233. acquireAssets();
  2234. }
  2235. dumpActivityLog();
  2236. if (hasIssues ||
  2237. assetItem->importStatus == AssetImportObject::Skipped ||
  2238. assetItem->importStatus == AssetImportObject::UseForDependencies ||
  2239. assetItem->importStatus == AssetImportObject::Error)
  2240. {
  2241. return StringTable->EmptyString();
  2242. }
  2243. else
  2244. {
  2245. String assetId = targetModuleId + ":" + assetItem->assetName;
  2246. return StringTable->insert(assetId.c_str());
  2247. }
  2248. }
  2249. void AssetImporter::importAssets(AssetImportObject* assetItem)
  2250. {
  2251. ModuleDefinition* moduleDef = ModuleDatabase.findModule(targetModuleId.c_str(), 1);
  2252. if (moduleDef == nullptr)
  2253. {
  2254. dSprintf(importLogBuffer, sizeof(importLogBuffer), "AssetImporter::importAssets - Unable to find moduleId %s", targetModuleId.c_str());
  2255. activityLog.push_back(importLogBuffer);
  2256. dumpActivityLog();
  2257. return;
  2258. }
  2259. Vector<AssetImportObject*> itemList = importingAssets;
  2260. if (assetItem != nullptr)
  2261. itemList = assetItem->childAssetItems;
  2262. for (U32 i = 0; i < itemList.size(); i++)
  2263. {
  2264. AssetImportObject* item = itemList[i];
  2265. if (!item->canImport())
  2266. continue;
  2267. Torque::Path assetPath;
  2268. if (item->assetType == String("ImageAsset"))
  2269. {
  2270. assetPath = importImageAsset(item);
  2271. }
  2272. else if (item->assetType == String("ShapeAsset"))
  2273. {
  2274. assetPath = importShapeAsset(item);
  2275. }
  2276. else if (item->assetType == String("SoundAsset"))
  2277. {
  2278. assetPath = importSoundAsset(item);
  2279. }
  2280. else if (item->assetType == String("MaterialAsset"))
  2281. {
  2282. assetPath = importMaterialAsset(item);
  2283. }
  2284. else if (item->assetType == String("ShapeAnimationAsset"))
  2285. {
  2286. assetPath = importShapeAnimationAsset(item);
  2287. }
  2288. else
  2289. {
  2290. finalImportedAssetPath = String::EmptyString;
  2291. String processCommand = "import";
  2292. processCommand += item->assetType;
  2293. if (isMethod(processCommand.c_str()))
  2294. {
  2295. Con::executef(this, processCommand.c_str(), item);
  2296. assetPath = finalImportedAssetPath;
  2297. }
  2298. }
  2299. /*else if (importingAssets[i]->assetType == String("ShapeAnimationAsset"))
  2300. assetPath = ShapeAnimationAsset::importAsset(importingAssets[i]);*/
  2301. if (assetPath.isEmpty() && item->assetType != String("MaterialAsset"))
  2302. {
  2303. dSprintf(importLogBuffer, sizeof(importLogBuffer), "AssetImporter::importAssets - Import attempt of %s failed, so skipping asset.", item->assetName.c_str());
  2304. activityLog.push_back(importLogBuffer);
  2305. continue;
  2306. }
  2307. else
  2308. {
  2309. //If we got a valid filepath back from the import action, then we know we're good to go and we can go ahead and register the asset!
  2310. if (!isReimport)
  2311. {
  2312. bool registerSuccess = AssetDatabase.addDeclaredAsset(moduleDef, assetPath.getFullPath().c_str());
  2313. String assetIdStr = item->moduleName + ":" + item->assetName;
  2314. StringTableEntry assetId = StringTable->insert(assetIdStr.c_str());
  2315. if (!registerSuccess)
  2316. {
  2317. dSprintf(importLogBuffer, sizeof(importLogBuffer), "AssetImporter::importAssets - Failed to successfully register new asset at path %s to moduleId %s", assetPath.getFullPath().c_str(), targetModuleId.c_str());
  2318. activityLog.push_back(importLogBuffer);
  2319. }
  2320. else
  2321. {
  2322. //Any special-case post-reg stuff here
  2323. if (item->assetType == String("ShapeAsset") || item->assetType == String("ShapeAnimationAsset"))
  2324. {
  2325. //forcefully update it's shape constructor
  2326. TSShapeConstructor* tss = TSShapeConstructor::findShapeConstructorByAssetId(assetId);
  2327. if(tss)
  2328. tss->setShapeAssetId(assetId);
  2329. }
  2330. }
  2331. }
  2332. else
  2333. {
  2334. String assetId = item->moduleName + ":" + item->assetName;
  2335. bool refreshSuccess = AssetDatabase.refreshAsset(assetId.c_str());
  2336. if (!refreshSuccess)
  2337. {
  2338. dSprintf(importLogBuffer, sizeof(importLogBuffer), "AssetImporter::importAssets - Failed to refresh reimporting asset %s.", item->assetName.c_str());
  2339. activityLog.push_back(importLogBuffer);
  2340. }
  2341. }
  2342. }
  2343. //Mark us as successfully imported
  2344. item->importStatus = AssetImportObject::Imported;
  2345. //recurse if needed
  2346. importAssets(item);
  2347. }
  2348. dumpActivityLog();
  2349. }
  2350. void AssetImporter::acquireAssets(AssetImportObject* assetItem)
  2351. {
  2352. Vector<AssetImportObject*> itemList = importingAssets;
  2353. if (assetItem != nullptr)
  2354. itemList = assetItem->childAssetItems;
  2355. for (U32 i = 0; i < itemList.size(); i++)
  2356. {
  2357. AssetImportObject* item = itemList[i];
  2358. if (item->importStatus == AssetImportObject::Skipped ||
  2359. item->importStatus == AssetImportObject::NotProcessed ||
  2360. item->importStatus == AssetImportObject::Error)
  2361. continue;
  2362. //recurse if needed, we want to process child items first for dependency reasons
  2363. acquireAssets(item);
  2364. //Go ahead and force the asset to load now just to kick it for immediate use
  2365. String assetId = item->moduleName + ":" + item->assetName;
  2366. if (AssetDatabase.isDeclaredAsset(assetId))
  2367. {
  2368. AssetDatabase.acquireAsset<AssetBase>(assetId);
  2369. AssetDatabase.refreshAsset(assetId);
  2370. AssetDatabase.releaseAsset(assetId);
  2371. }
  2372. }
  2373. }
  2374. //
  2375. // Type-specific import logic
  2376. //
  2377. Torque::Path AssetImporter::importImageAsset(AssetImportObject* assetItem)
  2378. {
  2379. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Beginning importing of Image Asset: %s", assetItem->assetName.c_str());
  2380. activityLog.push_back(importLogBuffer);
  2381. ImageAsset* newAsset = new ImageAsset();
  2382. newAsset->registerObject();
  2383. StringTableEntry assetName = StringTable->insert(assetItem->assetName.c_str());
  2384. String imageFileName = assetItem->filePath.getFullFileName();
  2385. String assetPath = "@" + imageFileName;
  2386. String tamlPath = targetPath + "/" + assetName + ".asset.taml";
  2387. String originalPath = assetItem->filePath.getFullPath().c_str();
  2388. newAsset->setAssetName(assetName);
  2389. newAsset->setImageFile(assetPath.c_str());
  2390. //If it's not a re-import, check that the file isn't being in-place imported. If it isn't, store off the original
  2391. //file path for reimporting support later
  2392. if (!isReimport)
  2393. {
  2394. newAsset->setDataField(StringTable->insert("originalFilePath"), nullptr, originalPath.c_str());
  2395. }
  2396. if (assetItem->typeHint != String::EmptyString)
  2397. {
  2398. newAsset->setImageType(ImageAsset::getImageTypeFromName(StringTable->insert(assetItem->typeHint.c_str())));
  2399. }
  2400. else
  2401. {
  2402. ImageAsset::ImageTypes imageType = ImageAsset::getImageTypeFromName(assetItem->imageSuffixType.c_str());
  2403. newAsset->setImageType(imageType);
  2404. }
  2405. Taml tamlWriter;
  2406. bool importSuccessful = tamlWriter.write(newAsset, tamlPath.c_str());
  2407. if (!importSuccessful)
  2408. {
  2409. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Error! Unable to write asset taml file %s", tamlPath.c_str());
  2410. activityLog.push_back(importLogBuffer);
  2411. return "";
  2412. }
  2413. return tamlPath;
  2414. }
  2415. Torque::Path AssetImporter::importMaterialAsset(AssetImportObject* assetItem)
  2416. {
  2417. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Beginning importing of Material Asset: %s", assetItem->assetName.c_str());
  2418. activityLog.push_back(importLogBuffer);
  2419. MaterialAsset* newAsset = new MaterialAsset();
  2420. newAsset->registerObject();
  2421. StringTableEntry assetName = StringTable->insert(assetItem->assetName.c_str());
  2422. String tamlPath = targetPath + "/" + assetName + ".asset.taml";
  2423. String originalPath = assetItem->filePath.getFullPath().c_str();
  2424. char qualifiedFromFile[2048];
  2425. #ifndef TORQUE_SECURE_VFS
  2426. Platform::makeFullPathName(originalPath.c_str(), qualifiedFromFile, sizeof(qualifiedFromFile));
  2427. #else
  2428. dStrcpy(qualifiedFromFile, originalPath.c_str(), sizeof(qualifiedFromFile));
  2429. #endif
  2430. newAsset->setAssetName(assetName);
  2431. if (!isReimport && Torque::FS::IsFile(qualifiedFromFile))
  2432. {
  2433. newAsset->setDataField(StringTable->insert("originalFilePath"), nullptr, qualifiedFromFile);
  2434. }
  2435. newAsset->setDataField(StringTable->insert("materialDefinitionName"), nullptr, assetName);
  2436. //iterate through and write out the material maps dependencies
  2437. S32 dependencySlotId = 0;
  2438. for (U32 i = 0; i < assetItem->childAssetItems.size(); i++)
  2439. {
  2440. AssetImportObject* childItem = assetItem->childAssetItems[i];
  2441. if ((!childItem->canImport() && childItem->importStatus != AssetImportObject::UseForDependencies) || childItem->assetType.compare("ImageAsset") != 0)
  2442. continue;
  2443. char dependencyFieldName[64];
  2444. dSprintf(dependencyFieldName, 64, "imageMap%i", dependencySlotId);
  2445. char dependencyFieldDef[512];
  2446. dSprintf(dependencyFieldDef, 512, "%s=%s:%s", ASSET_ID_SIGNATURE, targetModuleId.c_str(), childItem->assetName.c_str());
  2447. newAsset->setDataField(StringTable->insert(dependencyFieldName), nullptr, dependencyFieldDef);
  2448. dependencySlotId++;
  2449. }
  2450. //build the ORMConfig file if we're flagged to and have valid image maps
  2451. if (activeImportConfig->CreateORMConfig)
  2452. {
  2453. AssetImportObject* ormMap = nullptr;
  2454. AssetImportObject* roughnessMap = nullptr;
  2455. AssetImportObject* metalnessMap = nullptr;
  2456. AssetImportObject* aoMap = nullptr;
  2457. //We need to find any/all respective image maps for the given channels
  2458. for (U32 i = 0; i < assetItem->childAssetItems.size(); i++)
  2459. {
  2460. AssetImportObject* childItem = assetItem->childAssetItems[i];
  2461. if (childItem->canImport() || childItem->assetType.compare("ImageAsset") != 0)
  2462. continue;
  2463. if (childItem->imageSuffixType.compare("ORMConfig") == 0)
  2464. ormMap = childItem;
  2465. else if(childItem->imageSuffixType.compare("Roughness") == 0)
  2466. roughnessMap = childItem;
  2467. else if (childItem->imageSuffixType.compare("Metalness") == 0)
  2468. metalnessMap = childItem;
  2469. else if (childItem->imageSuffixType.compare("AO") == 0)
  2470. aoMap = childItem;
  2471. }
  2472. if (ormMap != nullptr && ormMap->generatedAsset)
  2473. {
  2474. if (roughnessMap != nullptr || metalnessMap != nullptr || aoMap != nullptr)
  2475. {
  2476. U32 channelKey[4] = { 0,1,2,3 };
  2477. GFX->getTextureManager()->saveCompositeTexture(aoMap->filePath.getFullPath(), roughnessMap->filePath.getFullPath(), metalnessMap->filePath.getFullPath(), "",
  2478. channelKey, ormMap->filePath.getFullPath(), &GFXTexturePersistentProfile);
  2479. }
  2480. }
  2481. }
  2482. //If we're not using existing materials, or the material in question doesn't actually already exist, spool it up
  2483. if (!activeImportConfig->UseExistingMaterials || !Sim::findObject(assetName))
  2484. {
  2485. Material* newMat = new Material();
  2486. newMat->registerObject(assetName);
  2487. newMat->mMapTo = assetItem->cleanAssetName;
  2488. bool hasRoughness = false;
  2489. for (U32 i = 0; i < assetItem->childAssetItems.size(); i++)
  2490. {
  2491. AssetImportObject* childItem = assetItem->childAssetItems[i];
  2492. if ((!childItem->canImport() && childItem->importStatus != AssetImportObject::UseForDependencies) || childItem->assetType.compare("ImageAsset") != 0)
  2493. continue;
  2494. ImageAsset::ImageTypes imageType = ImageAsset::getImageTypeFromName(childItem->imageSuffixType);
  2495. String assetMapFillIn = targetModuleId + ":" + childItem->assetName;
  2496. StringTableEntry assetMapFillInStr = StringTable->insert(assetMapFillIn.c_str());
  2497. if (imageType == ImageAsset::ImageTypes::Albedo || childItem->imageSuffixType.isEmpty())
  2498. {
  2499. newMat->_setDiffuseMap(assetMapFillInStr,0);
  2500. }
  2501. else if (imageType == ImageAsset::ImageTypes::Normal)
  2502. {
  2503. newMat->_setNormalMap(assetMapFillInStr, 0);
  2504. }
  2505. else if (imageType == ImageAsset::ImageTypes::ORMConfig)
  2506. {
  2507. newMat->_setORMConfigMap(assetMapFillInStr, 0);
  2508. }
  2509. else if (imageType == ImageAsset::ImageTypes::Metalness)
  2510. {
  2511. newMat->_setMetalMap(assetMapFillInStr, 0);
  2512. }
  2513. else if (imageType == ImageAsset::ImageTypes::AO)
  2514. {
  2515. newMat->_setAOMap(assetMapFillInStr, 0);
  2516. }
  2517. else if (imageType == ImageAsset::ImageTypes::Roughness)
  2518. {
  2519. newMat->_setRoughMap(assetMapFillInStr, 0);
  2520. hasRoughness = true;
  2521. }
  2522. }
  2523. if (hasRoughness)
  2524. {
  2525. newMat->mInvertRoughness[0] = true;
  2526. }
  2527. newAsset->addObject(newMat);
  2528. }
  2529. else
  2530. {
  2531. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Set to use an existing material, so avoiding writing a material definition to new asset definition for material: %s", assetName);
  2532. activityLog.push_back(importLogBuffer);
  2533. return "";
  2534. }
  2535. Taml tamlWriter;
  2536. bool importSuccessful = tamlWriter.write(newAsset, tamlPath.c_str());
  2537. if (!importSuccessful)
  2538. {
  2539. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Error! Unable to write asset taml file %s", tamlPath.c_str());
  2540. activityLog.push_back(importLogBuffer);
  2541. return "";
  2542. }
  2543. return tamlPath;
  2544. }
  2545. Torque::Path AssetImporter::importShapeAsset(AssetImportObject* assetItem)
  2546. {
  2547. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Beginning importing of Shape Asset: %s", assetItem->assetName.c_str());
  2548. activityLog.push_back(importLogBuffer);
  2549. ShapeAsset* newAsset = new ShapeAsset();
  2550. newAsset->registerObject();
  2551. StringTableEntry assetName = StringTable->insert(assetItem->assetName.c_str());
  2552. String shapeFileName = "@" + assetItem->filePath.getFileName() + "." + assetItem->filePath.getExtension();
  2553. String constructorFileName = assetItem->filePath.getFileName() + "." TORQUE_SCRIPT_EXTENSION;
  2554. String assetPath = targetPath + "/" + shapeFileName;
  2555. String constructorPath = targetPath + "/" + constructorFileName;
  2556. constructorFileName = "@" + constructorFileName;
  2557. String tamlPath = targetPath + "/" + assetName + ".asset.taml";
  2558. String originalPath = assetItem->filePath.getFullPath().c_str();
  2559. String originalConstructorPath = assetItem->filePath.getPath() + "/" + constructorFileName;
  2560. newAsset->setAssetName(assetName);
  2561. newAsset->setShapeFile(shapeFileName.c_str());
  2562. newAsset->setShapeConstructorFile(constructorFileName.c_str());
  2563. AssetImportConfig* cachedConfig = new AssetImportConfig();
  2564. cachedConfig->registerObject();
  2565. activeImportConfig->CopyTo(cachedConfig);
  2566. if (!activeImportConfig->UseManualShapeConfigRules)
  2567. {
  2568. //Try and load a sis file if it exists for this format
  2569. activeImportConfig->loadSISFile(assetItem->filePath);
  2570. }
  2571. //If it's not a re-import, check that the file isn't being in-place imported. If it isn't, store off the original
  2572. //file path for reimporting support later
  2573. if (!isReimport && Torque::FS::IsFile(originalPath))
  2574. {
  2575. newAsset->setDataField(StringTable->insert("originalFilePath"), nullptr, originalPath.c_str());
  2576. }
  2577. //iterate through and write out the material maps dependencies
  2578. S32 dependencySlotId = 0;
  2579. for (U32 i = 0; i < assetItem->childAssetItems.size(); i++)
  2580. {
  2581. AssetImportObject* childItem = assetItem->childAssetItems[i];
  2582. if (!childItem->canImport() && childItem->importStatus != AssetImportObject::UseForDependencies)
  2583. continue;
  2584. if (childItem->assetType.compare("MaterialAsset") == 0)
  2585. {
  2586. char dependencyFieldName[64];
  2587. dSprintf(dependencyFieldName, 64, "materialSlot%i", dependencySlotId);
  2588. char dependencyFieldDef[512];
  2589. dSprintf(dependencyFieldDef, 512, "%s=%s:%s", ASSET_ID_SIGNATURE, targetModuleId.c_str(), childItem->assetName.c_str());
  2590. newAsset->setDataField(StringTable->insert(dependencyFieldName), nullptr, dependencyFieldDef);
  2591. dependencySlotId++;
  2592. }
  2593. else if (childItem->assetType.compare("ShapeAnimationAsset") == 0)
  2594. {
  2595. char dependencyFieldName[64];
  2596. dSprintf(dependencyFieldName, 64, "animationSequence%i", dependencySlotId);
  2597. char dependencyFieldDef[512];
  2598. dSprintf(dependencyFieldDef, 512, "%s=%s:%s", ASSET_ID_SIGNATURE, targetModuleId.c_str(), childItem->assetName.c_str());
  2599. newAsset->setDataField(StringTable->insert(dependencyFieldName), nullptr, dependencyFieldDef);
  2600. dependencySlotId++;
  2601. }
  2602. }
  2603. if (Con::getBoolVariable("$TSLastDetail::dumpImposters", false))
  2604. {
  2605. String imposterPath = "@" + assetItem->assetName + "_imposter.png";
  2606. String normalsPath = "@" + assetItem->assetName + "_imposter_normals.png";
  2607. newAsset->setDiffuseImposterFile(imposterPath.c_str());
  2608. newAsset->setNormalImposterFile(normalsPath.c_str());
  2609. }
  2610. Taml tamlWriter;
  2611. bool importSuccessful = tamlWriter.write(newAsset, tamlPath.c_str());
  2612. if (!importSuccessful)
  2613. {
  2614. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Error! Unable to write asset taml file %s", tamlPath.c_str());
  2615. activityLog.push_back(importLogBuffer);
  2616. return "";
  2617. }
  2618. bool makeNewConstructor = true;
  2619. if (!isReimport)
  2620. {
  2621. //We're doing an in-place import, so double check we've already got a constructor file in the expected spot
  2622. if (Torque::FS::IsFile(constructorPath))
  2623. {
  2624. //Yup, found it, we're good to go
  2625. makeNewConstructor = false;
  2626. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Existing TSShape Constructor file %s found", constructorPath.c_str());
  2627. activityLog.push_back(importLogBuffer);
  2628. }
  2629. else
  2630. {
  2631. //Didn't work, but it's possible it's using the old .cs extension when our extension variable is set to something else, so check that one as well just to be sure
  2632. Torque::Path constrFilePath = constructorPath;
  2633. constrFilePath.setExtension("cs");
  2634. if (Torque::FS::IsFile(constrFilePath.getFullPath().c_str()))
  2635. {
  2636. //Yup, found it, we're good to go
  2637. makeNewConstructor = false;
  2638. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Existing TSShape Constructor file %s found", constrFilePath.getFullPath().c_str());
  2639. activityLog.push_back(importLogBuffer);
  2640. }
  2641. }
  2642. }
  2643. if (makeNewConstructor)
  2644. {
  2645. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Beginning creation of new TSShapeConstructor file: %s", constructorPath.c_str());
  2646. activityLog.push_back(importLogBuffer);
  2647. //find/create shape constructor
  2648. TSShapeConstructor* constructor = TSShapeConstructor::findShapeConstructorByFilename(Torque::Path(constructorPath).getFullPath());
  2649. if (constructor == nullptr)
  2650. {
  2651. String fullAssetName = assetItem->moduleName + ":" + assetItem->assetName;
  2652. constructor = new TSShapeConstructor(StringTable->insert(fullAssetName.c_str()));
  2653. String constructorName = assetItem->filePath.getFileName() + assetItem->filePath.getExtension().substr(0, 3);
  2654. constructorName.replace(" ", "_");
  2655. constructorName.replace("-", "_");
  2656. constructorName.replace(".", "_");
  2657. constructorName = Sim::getUniqueName(constructorName.c_str());
  2658. constructor->registerObject(constructorName.c_str());
  2659. }
  2660. //now we write the import config logic into the constructor itself to ensure we load like we wanted it to
  2661. String neverImportMats;
  2662. if (activeImportConfig->IgnoreMaterials.isNotEmpty())
  2663. {
  2664. U32 ignoredMatNamesCount = StringUnit::getUnitCount(activeImportConfig->IgnoreMaterials, ",;\t");
  2665. for (U32 i = 0; i < ignoredMatNamesCount; i++)
  2666. {
  2667. if (i == 0)
  2668. neverImportMats = StringUnit::getUnit(activeImportConfig->IgnoreMaterials, i, ",;\t");
  2669. else
  2670. neverImportMats += String("\t") + StringUnit::getUnit(activeImportConfig->IgnoreMaterials, i, ",;\t");
  2671. }
  2672. }
  2673. if (activeImportConfig->DoUpAxisOverride)
  2674. {
  2675. S32 upAxis = domUpAxisType::UPAXISTYPE_Z_UP;
  2676. if (activeImportConfig->UpAxisOverride.compare("X_AXIS") == 0)
  2677. {
  2678. upAxis = domUpAxisType::UPAXISTYPE_X_UP;
  2679. }
  2680. else if (activeImportConfig->UpAxisOverride.compare("Y_AXIS") == 0)
  2681. {
  2682. upAxis = domUpAxisType::UPAXISTYPE_Y_UP;
  2683. }
  2684. else if (activeImportConfig->UpAxisOverride.compare("Z_AXIS") == 0)
  2685. {
  2686. upAxis = domUpAxisType::UPAXISTYPE_Z_UP;
  2687. }
  2688. constructor->mOptions.upAxis = (domUpAxisType)upAxis;
  2689. }
  2690. if (activeImportConfig->DoScaleOverride)
  2691. constructor->mOptions.unit = activeImportConfig->ScaleOverride;
  2692. else
  2693. constructor->mOptions.unit = -1;
  2694. enum eAnimTimingType
  2695. {
  2696. FrameCount = 0,
  2697. Seconds = 1,
  2698. Milliseconds = 1000
  2699. };
  2700. S32 lodType = ColladaUtils::ImportOptions::eLodType::TrailingNumber;
  2701. if (activeImportConfig->LODType.compare("TrailingNumber") == 0)
  2702. lodType = ColladaUtils::ImportOptions::eLodType::TrailingNumber;
  2703. else if (activeImportConfig->LODType.compare("SingleSize") == 0)
  2704. lodType = ColladaUtils::ImportOptions::eLodType::SingleSize;
  2705. else if (activeImportConfig->LODType.compare("DetectDTS") == 0)
  2706. lodType = ColladaUtils::ImportOptions::eLodType::DetectDTS;
  2707. constructor->mOptions.lodType = (ColladaUtils::ImportOptions::eLodType)lodType;
  2708. constructor->mOptions.singleDetailSize = activeImportConfig->singleDetailSize;
  2709. constructor->mOptions.alwaysImport = activeImportConfig->AlwaysImportedNodes;
  2710. constructor->mOptions.neverImport = activeImportConfig->AlwaysIgnoreNodes;
  2711. constructor->mOptions.alwaysImportMesh = activeImportConfig->AlwaysImportMeshes;
  2712. constructor->mOptions.neverImportMesh = activeImportConfig->AlwaysIgnoreMeshes;
  2713. constructor->mOptions.ignoreNodeScale = activeImportConfig->IgnoreNodeScale;
  2714. constructor->mOptions.adjustCenter = activeImportConfig->AdjustCenter;
  2715. constructor->mOptions.adjustFloor = activeImportConfig->AdjustFloor;
  2716. constructor->mOptions.convertLeftHanded = activeImportConfig->convertLeftHanded;
  2717. constructor->mOptions.calcTangentSpace = activeImportConfig->calcTangentSpace;
  2718. constructor->mOptions.genUVCoords = activeImportConfig->genUVCoords;
  2719. constructor->mOptions.flipUVCoords = activeImportConfig->flipUVCoords;
  2720. constructor->mOptions.findInstances = activeImportConfig->findInstances;
  2721. constructor->mOptions.limitBoneWeights = activeImportConfig->limitBoneWeights;
  2722. constructor->mOptions.joinIdenticalVerts = activeImportConfig->JoinIdenticalVerts;
  2723. constructor->mOptions.reverseWindingOrder = activeImportConfig->reverseWindingOrder;
  2724. constructor->mOptions.invertNormals = activeImportConfig->invertNormals;
  2725. constructor->mOptions.removeRedundantMats = activeImportConfig->removeRedundantMats;
  2726. S32 animTimingType;
  2727. if (activeImportConfig->animTiming.compare("FrameCount") == 0)
  2728. animTimingType = ColladaUtils::ImportOptions::eAnimTimingType::FrameCount;
  2729. else if (activeImportConfig->animTiming.compare("Seconds") == 0)
  2730. animTimingType = ColladaUtils::ImportOptions::eAnimTimingType::Seconds;
  2731. else// (activeImportConfig->animTiming.compare("Milliseconds") == 0)
  2732. animTimingType = ColladaUtils::ImportOptions::eAnimTimingType::Milliseconds;
  2733. constructor->mOptions.animTiming = (ColladaUtils::ImportOptions::eAnimTimingType)animTimingType;
  2734. constructor->mOptions.animFPS = activeImportConfig->animFPS;
  2735. constructor->mOptions.neverImportMat = neverImportMats;
  2736. PersistenceManager* constructorPersist = new PersistenceManager();
  2737. constructorPersist->registerObject();
  2738. constructorPersist->setDirty(constructor, constructorPath);
  2739. if (!constructorPersist->saveDirtyObject(constructor))
  2740. {
  2741. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Error! Failed to save shape constructor file to %s", constructorPath.c_str());
  2742. activityLog.push_back(importLogBuffer);
  2743. }
  2744. else
  2745. {
  2746. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Finished creating shape constructor file to %s", constructorPath.c_str());
  2747. activityLog.push_back(importLogBuffer);
  2748. }
  2749. constructorPersist->destroySelf();
  2750. }
  2751. //restore the cached version just in case we loaded a sis file
  2752. cachedConfig->CopyTo(activeImportConfig);
  2753. cachedConfig->deleteObject();
  2754. return tamlPath;
  2755. }
  2756. Torque::Path AssetImporter::importSoundAsset(AssetImportObject* assetItem)
  2757. {
  2758. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Beginning importing of Sound Asset: %s", assetItem->assetName.c_str());
  2759. activityLog.push_back(importLogBuffer);
  2760. SoundAsset* newAsset = new SoundAsset();
  2761. newAsset->registerObject();
  2762. StringTableEntry assetName = StringTable->insert(assetItem->assetName.c_str());
  2763. String soundFileName = assetItem->filePath.getFileName() + "." + assetItem->filePath.getExtension();
  2764. String assetPath = targetPath + "/" + soundFileName;
  2765. String tamlPath = targetPath + "/" + assetName + ".asset.taml";
  2766. String originalPath = assetItem->filePath.getFullPath().c_str();
  2767. char qualifiedFromFile[2048];
  2768. char qualifiedToFile[2048];
  2769. #ifndef TORQUE_SECURE_VFS
  2770. Platform::makeFullPathName(originalPath.c_str(), qualifiedFromFile, sizeof(qualifiedFromFile));
  2771. Platform::makeFullPathName(assetPath.c_str(), qualifiedToFile, sizeof(qualifiedToFile));
  2772. #else
  2773. dStrcpy(qualifiedFromFile, originalPath.c_str(), sizeof(qualifiedFromFile));
  2774. dStrcpy(qualifiedToFile, assetPath.c_str(), sizeof(qualifiedToFile));
  2775. #endif
  2776. newAsset->setAssetName(assetName);
  2777. newAsset->_setSoundFile(newAsset, "0", soundFileName.c_str());
  2778. //If it's not a re-import, check that the file isn't being in-place imported. If it isn't, store off the original
  2779. //file path for reimporting support later
  2780. if (!isReimport && String::compare(qualifiedFromFile, qualifiedToFile) && Torque::FS::IsFile(qualifiedFromFile))
  2781. {
  2782. newAsset->setDataField(StringTable->insert("originalFilePath"), nullptr, qualifiedFromFile);
  2783. }
  2784. Taml tamlWriter;
  2785. bool importSuccessful = tamlWriter.write(newAsset, tamlPath.c_str());
  2786. if (!importSuccessful)
  2787. {
  2788. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Error! Unable to write asset taml file %s", tamlPath.c_str());
  2789. activityLog.push_back(importLogBuffer);
  2790. return "";
  2791. }
  2792. if (!isReimport)
  2793. {
  2794. bool isInPlace = !String::compare(qualifiedFromFile, qualifiedToFile);
  2795. if (!isInPlace && !Torque::FS::CopyFile(qualifiedFromFile, qualifiedToFile, !isReimport))
  2796. {
  2797. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Error! Unable to copy file %s", assetItem->filePath.getFullPath().c_str());
  2798. activityLog.push_back(importLogBuffer);
  2799. return "";
  2800. }
  2801. }
  2802. return tamlPath;
  2803. }
  2804. Torque::Path AssetImporter::importShapeAnimationAsset(AssetImportObject* assetItem)
  2805. {
  2806. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Beginning importing of Shape Animation Asset: %s", assetItem->assetName.c_str());
  2807. activityLog.push_back(importLogBuffer);
  2808. ShapeAnimationAsset* newAsset = new ShapeAnimationAsset();
  2809. newAsset->registerObject();
  2810. StringTableEntry assetName = StringTable->insert(assetItem->assetName.c_str());
  2811. String imageFileName = assetItem->filePath.getFileName() + "." + assetItem->filePath.getExtension();
  2812. String assetPath = targetPath + "/" + imageFileName;
  2813. String tamlPath = targetPath + "/" + assetName + ".asset.taml";
  2814. String originalPath = assetItem->filePath.getFullPath().c_str();
  2815. char qualifiedFromFile[2048];
  2816. char qualifiedToFile[2048];
  2817. #ifndef TORQUE_SECURE_VFS
  2818. Platform::makeFullPathName(originalPath.c_str(), qualifiedFromFile, sizeof(qualifiedFromFile));
  2819. Platform::makeFullPathName(assetPath.c_str(), qualifiedToFile, sizeof(qualifiedToFile));
  2820. #else
  2821. dStrcpy(qualifiedFromFile, originalPath.c_str(), sizeof(qualifiedFromFile));
  2822. dStrcpy(qualifiedToFile, assetPath.c_str(), sizeof(qualifiedToFile));
  2823. #endif
  2824. newAsset->setAssetName(assetName);
  2825. newAsset->setAnimationFile(imageFileName.c_str());
  2826. //If it's not a re-import, check that the file isn't being in-place imported. If it isn't, store off the original
  2827. //file path for reimporting support later
  2828. if (!isReimport && String::compare(qualifiedFromFile, qualifiedToFile) && Torque::FS::IsFile(qualifiedFromFile))
  2829. {
  2830. newAsset->setDataField(StringTable->insert("originalFilePath"), nullptr, qualifiedFromFile);
  2831. }
  2832. Taml tamlWriter;
  2833. bool importSuccessful = tamlWriter.write(newAsset, tamlPath.c_str());
  2834. if (!importSuccessful)
  2835. {
  2836. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Error! Unable to write asset taml file %s", tamlPath.c_str());
  2837. activityLog.push_back(importLogBuffer);
  2838. return "";
  2839. }
  2840. if (!isReimport)
  2841. {
  2842. bool isInPlace = !String::compare(qualifiedFromFile, qualifiedToFile);
  2843. if (!isInPlace && !Torque::FS::CopyFile(qualifiedFromFile, qualifiedToFile, !isReimport))
  2844. {
  2845. dSprintf(importLogBuffer, sizeof(importLogBuffer), "Error! Unable to copy file %s", assetItem->filePath.getFullPath().c_str());
  2846. activityLog.push_back(importLogBuffer);
  2847. return "";
  2848. }
  2849. }
  2850. return tamlPath;
  2851. }