assetImporter.cpp 133 KB

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