assetImporter.cpp 147 KB

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