EditorImport.as 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. // Urho3D editor import functions
  2. String importOptions = "-t";
  3. class ParentAssignment
  4. {
  5. uint childID;
  6. String parentName;
  7. }
  8. class AssetMapping
  9. {
  10. String assetName;
  11. String fullAssetName;
  12. }
  13. Array<AssetMapping> assetMappings;
  14. void ImportModel(const String&in fileName)
  15. {
  16. if (fileName.empty)
  17. return;
  18. ui.cursor.shape = CS_BUSY;
  19. String modelName = "Models/" + GetFileName(fileName) + ".mdl";
  20. String outFileName = sceneResourcePath + modelName;
  21. fileSystem.CreateDir(sceneResourcePath + "Models");
  22. Array<String> args;
  23. args.Push("model");
  24. args.Push("\"" + fileName + "\"");
  25. args.Push("\"" + outFileName + "\"");
  26. args.Push("-p \"" + sceneResourcePath + "\"");
  27. Array<String> options = importOptions.Trimmed().Split(' ');
  28. for (uint i = 0; i < options.length; ++i)
  29. args.Push(options[i]);
  30. // If material lists are to be applied, make sure the option to create them exists
  31. if (applyMaterialList)
  32. args.Push("-l");
  33. if (fileSystem.SystemRun(fileSystem.programDir + "AssetImporter", args) == 0)
  34. {
  35. Node@ newNode = editorScene.CreateChild(GetFileName(fileName));
  36. StaticModel@ newModel = newNode.CreateComponent("StaticModel");
  37. newNode.position = GetNewNodePosition();
  38. newModel.model = cache.GetResource("Model", modelName);
  39. newModel.ApplyMaterialList(); // Setup default materials if possible
  40. // Create an undo action for the create
  41. CreateNodeAction action;
  42. action.Define(newNode);
  43. SaveEditAction(action);
  44. SetSceneModified();
  45. FocusNode(newNode);
  46. }
  47. }
  48. void ImportScene(const String&in fileName)
  49. {
  50. if (fileName.empty)
  51. return;
  52. ui.cursor.shape = CS_BUSY;
  53. // Handle Tundra scene files here in code, otherwise via AssetImporter
  54. if (GetExtension(fileName) == ".txml")
  55. ImportTundraScene(fileName);
  56. else
  57. {
  58. // Export scene to a temp file, then load and delete it if successful
  59. String tempSceneName = sceneResourcePath + TEMP_SCENE_NAME;
  60. Array<String> args;
  61. args.Push("scene");
  62. args.Push("\"" + fileName + "\"");
  63. args.Push("\"" + tempSceneName + "\"");
  64. args.Push("-p \"" + sceneResourcePath + "\"");
  65. Array<String> options = importOptions.Trimmed().Split(' ');
  66. for (uint i = 0; i < options.length; ++i)
  67. args.Push(options[i]);
  68. if (applyMaterialList)
  69. args.Push("-l");
  70. if (fileSystem.SystemRun(fileSystem.programDir + "AssetImporter", args) == 0)
  71. {
  72. skipMruScene = true; // set to avoid adding tempscene to mru
  73. LoadScene(tempSceneName);
  74. fileSystem.Delete(tempSceneName);
  75. UpdateWindowTitle();
  76. }
  77. }
  78. }
  79. void ImportTundraScene(const String&in fileName)
  80. {
  81. fileSystem.CreateDir(sceneResourcePath + "Materials");
  82. fileSystem.CreateDir(sceneResourcePath + "Models");
  83. fileSystem.CreateDir(sceneResourcePath + "Textures");
  84. XMLFile source;
  85. source.Load(File(fileName, FILE_READ));
  86. String filePath = GetPath(fileName);
  87. XMLElement sceneElem = source.root;
  88. XMLElement entityElem = sceneElem.GetChild("entity");
  89. Array<String> convertedMaterials;
  90. Array<String> convertedMeshes;
  91. Array<ParentAssignment> parentAssignments;
  92. // Read the scene directory structure recursively to get assetname to full assetname mappings
  93. Array<String> fileNames = fileSystem.ScanDir(filePath, "*.*", SCAN_FILES, true);
  94. for (uint i = 0; i < fileNames.length; ++i)
  95. {
  96. AssetMapping mapping;
  97. mapping.assetName = GetFileNameAndExtension(fileNames[i]);
  98. mapping.fullAssetName = fileNames[i];
  99. assetMappings.Push(mapping);
  100. }
  101. // Clear old scene, then create a zone and a directional light first
  102. ResetScene();
  103. // Set standard gravity
  104. editorScene.physicsWorld.gravity = Vector3(0, -9.81, 0);
  105. // Create zone & global light
  106. Node@ zoneNode = editorScene.CreateChild("Zone");
  107. Zone@ zone = zoneNode.CreateComponent("Zone");
  108. zone.boundingBox = BoundingBox(-1000, 1000);
  109. zone.ambientColor = Color(0.364, 0.364, 0.364);
  110. zone.fogColor = Color(0.707792, 0.770537, 0.831373);
  111. zone.fogStart = 100.0;
  112. zone.fogEnd = 500.0;
  113. Node@ lightNode = editorScene.CreateChild("GlobalLight");
  114. Light@ light = lightNode.CreateComponent("Light");
  115. lightNode.rotation = Quaternion(60, 30, 0);
  116. light.lightType = LIGHT_DIRECTIONAL;
  117. light.color = Color(0.639, 0.639, 0.639);
  118. light.castShadows = true;
  119. light.shadowCascade = CascadeParameters(5, 15.0, 50.0, 0.0, 0.9);
  120. // Loop through scene entities
  121. while (!entityElem.isNull)
  122. {
  123. String nodeName;
  124. String meshName;
  125. String parentName;
  126. Vector3 meshPos;
  127. Vector3 meshRot;
  128. Vector3 meshScale(1, 1, 1);
  129. Vector3 pos;
  130. Vector3 rot;
  131. Vector3 scale(1, 1, 1);
  132. bool castShadows = false;
  133. float drawDistance = 0;
  134. Array<String> materialNames;
  135. int shapeType = -1;
  136. float mass = 0.0f;
  137. Vector3 bodySize;
  138. bool phantom = false;
  139. bool kinematic = false;
  140. uint collisionLayer;
  141. uint collisionMask;
  142. String collisionMeshName;
  143. XMLElement compElem = entityElem.GetChild("component");
  144. while (!compElem.isNull)
  145. {
  146. String compType = compElem.GetAttribute("type");
  147. if (compType == "EC_Mesh" || compType == "Mesh")
  148. {
  149. Array<String> coords = GetComponentAttribute(compElem, "Transform").Split(',');
  150. meshPos = GetVector3FromStrings(coords, 0);
  151. meshPos.z = -meshPos.z; // Convert to lefthanded
  152. meshRot = GetVector3FromStrings(coords, 3);
  153. meshScale = GetVector3FromStrings(coords, 6);
  154. meshName = GetComponentAttribute(compElem, "Mesh ref");
  155. castShadows = GetComponentAttribute(compElem, "Cast shadows").ToBool();
  156. drawDistance = GetComponentAttribute(compElem, "Draw distance").ToFloat();
  157. materialNames = GetComponentAttribute(compElem, "Mesh materials").Split(';');
  158. ProcessRef(meshName);
  159. for (uint i = 0; i < materialNames.length; ++i)
  160. ProcessRef(materialNames[i]);
  161. }
  162. if (compType == "EC_Name" || compType == "Name")
  163. nodeName = GetComponentAttribute(compElem, "name");
  164. if (compType == "EC_Placeable" || compType == "Placeable")
  165. {
  166. Array<String> coords = GetComponentAttribute(compElem, "Transform").Split(',');
  167. pos = GetVector3FromStrings(coords, 0);
  168. pos.z = -pos.z; // Convert to lefthanded
  169. rot = GetVector3FromStrings(coords, 3);
  170. scale = GetVector3FromStrings(coords, 6);
  171. parentName = GetComponentAttribute(compElem, "Parent entity ref");
  172. }
  173. if (compType == "EC_RigidBody" || compType == "RigidBody")
  174. {
  175. shapeType = GetComponentAttribute(compElem, "Shape type").ToInt();
  176. mass = GetComponentAttribute(compElem, "Mass").ToFloat();
  177. bodySize = GetComponentAttribute(compElem, "Size").ToVector3();
  178. collisionMeshName = GetComponentAttribute(compElem, "Collision mesh ref");
  179. phantom = GetComponentAttribute(compElem, "Phantom").ToBool();
  180. kinematic = GetComponentAttribute(compElem, "Kinematic").ToBool();
  181. collisionLayer = GetComponentAttribute(compElem, "Collision Layer").ToInt();
  182. collisionMask = GetComponentAttribute(compElem, "Collision Mask").ToInt();
  183. ProcessRef(collisionMeshName);
  184. }
  185. compElem = compElem.GetNext("component");
  186. }
  187. // If collision mesh not specified for the rigid body, assume same as the visible mesh
  188. if ((shapeType == 4 || shapeType == 6) && collisionMeshName.Trimmed().empty)
  189. collisionMeshName = meshName;
  190. if (!meshName.empty || shapeType >= 0)
  191. {
  192. for (uint i = 0; i < materialNames.length; ++i)
  193. ConvertMaterial(materialNames[i], filePath, convertedMaterials);
  194. ConvertModel(meshName, filePath, convertedMeshes);
  195. ConvertModel(collisionMeshName, filePath, convertedMeshes);
  196. Node@ newNode = editorScene.CreateChild(nodeName);
  197. // Calculate final transform in an Ogre-like fashion
  198. Quaternion quat = GetTransformQuaternion(rot);
  199. Quaternion meshQuat = GetTransformQuaternion(meshRot);
  200. Quaternion finalQuat = quat * meshQuat;
  201. Vector3 finalScale = scale * meshScale;
  202. Vector3 finalPos = pos + quat * (scale * meshPos);
  203. newNode.SetTransform(finalPos, finalQuat, finalScale);
  204. // Create model
  205. if (!meshName.empty)
  206. {
  207. StaticModel@ model = newNode.CreateComponent("StaticModel");
  208. model.model = cache.GetResource("Model", GetOutModelName(meshName));
  209. model.drawDistance = drawDistance;
  210. model.castShadows = castShadows;
  211. // Set default grey material to match Tundra defaults
  212. model.material = cache.GetResource("Material", "Materials/DefaultGrey.xml");
  213. // Then try to assign the actual materials
  214. for (uint i = 0; i < materialNames.length; ++i)
  215. {
  216. Material@ mat = cache.GetResource("Material", GetOutMaterialName(materialNames[i]));
  217. if (mat !is null)
  218. model.materials[i] = mat;
  219. }
  220. }
  221. // Create rigidbody & collision shape
  222. if (shapeType >= 0)
  223. {
  224. RigidBody@ body = newNode.CreateComponent("RigidBody");
  225. // If mesh has scaling, undo it for the collision shape
  226. bodySize.x /= meshScale.x;
  227. bodySize.y /= meshScale.y;
  228. bodySize.z /= meshScale.z;
  229. CollisionShape@ shape = newNode.CreateComponent("CollisionShape");
  230. switch (shapeType)
  231. {
  232. case 0:
  233. shape.SetBox(bodySize);
  234. break;
  235. case 1:
  236. shape.SetSphere(bodySize.x);
  237. break;
  238. case 2:
  239. shape.SetCylinder(bodySize.x, bodySize.y);
  240. break;
  241. case 3:
  242. shape.SetCapsule(bodySize.x, bodySize.y);
  243. break;
  244. case 4:
  245. shape.SetTriangleMesh(cache.GetResource("Model", GetOutModelName(collisionMeshName)), 0, bodySize);
  246. break;
  247. case 6:
  248. shape.SetConvexHull(cache.GetResource("Model", GetOutModelName(collisionMeshName)), 0, bodySize);
  249. break;
  250. }
  251. body.collisionLayer = collisionLayer;
  252. body.collisionMask = collisionMask;
  253. body.phantom = phantom;
  254. body.mass = mass;
  255. }
  256. // Store pending parent assignment if necessary
  257. if (!parentName.empty)
  258. {
  259. ParentAssignment assignment;
  260. assignment.childID = newNode.id;
  261. assignment.parentName = parentName;
  262. parentAssignments.Push(assignment);
  263. }
  264. }
  265. entityElem = entityElem.GetNext("entity");
  266. }
  267. // Process any parent assignments now
  268. for (uint i = 0; i < parentAssignments.length; ++i)
  269. {
  270. Node@ childNode = editorScene.GetNode(parentAssignments[i].childID);
  271. Node@ parentNode = editorScene.GetChild(parentAssignments[i].parentName, true);
  272. if (childNode !is null && parentNode !is null)
  273. childNode.parent = parentNode;
  274. }
  275. UpdateHierarchyItem(editorScene, true);
  276. UpdateWindowTitle();
  277. assetMappings.Clear();
  278. }
  279. String GetFullAssetName(const String& assetName)
  280. {
  281. for (uint i = 0; i < assetMappings.length; ++i)
  282. {
  283. if (assetMappings[i].assetName == assetName)
  284. return assetMappings[i].fullAssetName;
  285. }
  286. return assetName;
  287. }
  288. Quaternion GetTransformQuaternion(Vector3 rotEuler)
  289. {
  290. // Convert rotation to lefthanded
  291. Quaternion rotateX(-rotEuler.x, Vector3(1, 0, 0));
  292. Quaternion rotateY(-rotEuler.y, Vector3(0, 1, 0));
  293. Quaternion rotateZ(-rotEuler.z, Vector3(0, 0, -1));
  294. return rotateZ * rotateY * rotateX;
  295. }
  296. String GetComponentAttribute(XMLElement compElem, const String&in name)
  297. {
  298. XMLElement attrElem = compElem.GetChild("attribute");
  299. while (!attrElem.isNull)
  300. {
  301. if (attrElem.GetAttribute("name") == name)
  302. return attrElem.GetAttribute("value");
  303. attrElem = attrElem.GetNext("attribute");
  304. }
  305. return "";
  306. }
  307. Vector3 GetVector3FromStrings(Array<String>@ coords, uint startIndex)
  308. {
  309. return Vector3(coords[startIndex].ToFloat(), coords[startIndex + 1].ToFloat(), coords[startIndex + 2].ToFloat());
  310. }
  311. void ProcessRef(String& ref)
  312. {
  313. if (ref.StartsWith("local://"))
  314. ref = ref.Substring(8);
  315. if (ref.StartsWith("file://"))
  316. ref = ref.Substring(7);
  317. }
  318. String GetOutModelName(const String&in ref)
  319. {
  320. return "Models/" + GetFullAssetName(ref).Replaced('/', '_').Replaced(".mesh", ".mdl");
  321. }
  322. String GetOutMaterialName(const String&in ref)
  323. {
  324. return "Materials/" + GetFullAssetName(ref).Replaced('/', '_').Replaced(".material", ".xml");
  325. }
  326. String GetOutTextureName(const String&in ref)
  327. {
  328. return "Textures/" + GetFullAssetName(ref).Replaced('/', '_');
  329. }
  330. void ConvertModel(const String&in modelName, const String&in filePath, Array<String>@ convertedModels)
  331. {
  332. if (modelName.Trimmed().empty)
  333. return;
  334. for (uint i = 0; i < convertedModels.length; ++i)
  335. {
  336. if (convertedModels[i] == modelName)
  337. return;
  338. }
  339. String meshFileName = filePath + GetFullAssetName(modelName);
  340. String xmlFileName = filePath + GetFullAssetName(modelName) + ".xml";
  341. String outFileName = sceneResourcePath + GetOutModelName(modelName);
  342. // Convert .mesh to .mesh.xml
  343. String cmdLine = "ogrexmlconverter \"" + meshFileName + "\" \"" + xmlFileName + "\"";
  344. if (!fileSystem.FileExists(xmlFileName))
  345. fileSystem.SystemCommand(cmdLine.Replaced('/', '\\'));
  346. if (!fileSystem.FileExists(outFileName))
  347. {
  348. // Convert .mesh.xml to .mdl
  349. Array<String> args;
  350. args.Push("\"" + xmlFileName + "\"");
  351. args.Push("\"" + outFileName + "\"");
  352. args.Push("-a");
  353. fileSystem.SystemRun(fileSystem.programDir + "OgreImporter", args);
  354. }
  355. convertedModels.Push(modelName);
  356. }
  357. void ConvertMaterial(const String&in materialName, const String&in filePath, Array<String>@ convertedMaterials)
  358. {
  359. if (materialName.Trimmed().empty)
  360. return;
  361. for (uint i = 0; i < convertedMaterials.length; ++i)
  362. {
  363. if (convertedMaterials[i] == materialName)
  364. return;
  365. }
  366. String fileName = filePath + GetFullAssetName(materialName);
  367. String outFileName = sceneResourcePath + GetOutMaterialName(materialName);
  368. if (!fileSystem.FileExists(fileName))
  369. return;
  370. bool mask = false;
  371. bool twoSided = false;
  372. bool uvScaleSet = false;
  373. String textureName;
  374. Vector2 uvScale(1, 1);
  375. Color diffuse(1, 1, 1, 1);
  376. File file(fileName, FILE_READ);
  377. while (!file.eof)
  378. {
  379. String line = file.ReadLine().Trimmed();
  380. if (line.StartsWith("alpha_rejection") || line.StartsWith("scene_blend alpha_blend"))
  381. mask = true;
  382. if (line.StartsWith("cull_hardware none"))
  383. twoSided = true;
  384. // Todo: handle multiple textures per material
  385. if (textureName.empty && line.StartsWith("texture "))
  386. {
  387. textureName = line.Substring(8);
  388. ProcessRef(textureName);
  389. }
  390. if (!uvScaleSet && line.StartsWith("scale "))
  391. {
  392. uvScale = line.Substring(6).ToVector2();
  393. uvScaleSet = true;
  394. }
  395. if (line.StartsWith("diffuse "))
  396. diffuse = line.Substring(8).ToColor();
  397. }
  398. XMLFile outMat;
  399. XMLElement rootElem = outMat.CreateRoot("material");
  400. XMLElement techniqueElem = rootElem.CreateChild("technique");
  401. if (twoSided)
  402. {
  403. XMLElement cullElem = rootElem.CreateChild("cull");
  404. cullElem.SetAttribute("value", "none");
  405. XMLElement shadowCullElem = rootElem.CreateChild("shadowcull");
  406. shadowCullElem.SetAttribute("value", "none");
  407. }
  408. if (!textureName.empty)
  409. {
  410. techniqueElem.SetAttribute("name", mask ? "Techniques/DiffAlphaMask.xml" : "Techniques/Diff.xml");
  411. String outTextureName = GetOutTextureName(textureName);
  412. XMLElement textureElem = rootElem.CreateChild("texture");
  413. textureElem.SetAttribute("unit", "diffuse");
  414. textureElem.SetAttribute("name", outTextureName);
  415. fileSystem.Copy(filePath + GetFullAssetName(textureName), sceneResourcePath + outTextureName);
  416. }
  417. else
  418. techniqueElem.SetAttribute("name", "NoTexture.xml");
  419. if (uvScale != Vector2(1, 1))
  420. {
  421. XMLElement uScaleElem = rootElem.CreateChild("parameter");
  422. uScaleElem.SetAttribute("name", "UOffset");
  423. uScaleElem.SetVector3("value", Vector3(1 / uvScale.x, 0, 0));
  424. XMLElement vScaleElem = rootElem.CreateChild("parameter");
  425. vScaleElem.SetAttribute("name", "VOffset");
  426. vScaleElem.SetVector3("value", Vector3(0, 1 / uvScale.y, 0));
  427. }
  428. if (diffuse != Color(1, 1, 1, 1))
  429. {
  430. XMLElement diffuseElem = rootElem.CreateChild("parameter");
  431. diffuseElem.SetAttribute("name", "MatDiffColor");
  432. diffuseElem.SetColor("value", diffuse);
  433. }
  434. File outFile(outFileName, FILE_WRITE);
  435. outMat.Save(outFile);
  436. outFile.Close();
  437. convertedMaterials.Push(materialName);
  438. }