taml.cpp 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2013 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "taml.h"
  23. #ifndef _TAML_XMLWRITER_H_
  24. #include "persistence/taml/xml/tamlXmlWriter.h"
  25. #endif
  26. #ifndef _TAML_XMLREADER_H_
  27. #include "persistence/taml/xml/tamlXmlReader.h"
  28. #endif
  29. #ifndef _TAML_XMLPARSER_H_
  30. #include "persistence/taml/xml/tamlXmlParser.h"
  31. #endif
  32. #ifndef _TAML_BINARYWRITER_H_
  33. #include "persistence/taml/binary/tamlBinaryWriter.h"
  34. #endif
  35. #ifndef _TAML_BINARYREADER_H_
  36. #include "persistence/taml/binary/tamlBinaryReader.h"
  37. #endif
  38. /*#ifndef _TAML_JSONWRITER_H_
  39. #include "taml/json/tamlJSONWriter.h"
  40. #endif
  41. #ifndef _TAML_JSONREADER_H_
  42. #include "taml/json/tamlJSONReader.h"
  43. #endif
  44. #ifndef _TAML_JSONPARSER_H_
  45. #include "taml/json/tamlJSONParser.h"
  46. #endif*/
  47. #ifndef _FRAMEALLOCATOR_H_
  48. #include "core/frameAllocator.h"
  49. #endif
  50. #ifndef _SIMBASE_H_
  51. #include "console/simBase.h"
  52. #endif
  53. #ifndef _MATHTYPES_H_
  54. #include "math/mathTypes.h"
  55. #endif
  56. #ifndef _MPOINT2_H_
  57. #include "math/mPoint2.h"
  58. #endif
  59. #ifndef _ASSET_BASE_H_
  60. #include "assets/assetBase.h"
  61. #endif
  62. // Script bindings.
  63. #include "taml_ScriptBinding.h"
  64. // Debug Profiling.
  65. #include "platform/profiler.h"
  66. //-----------------------------------------------------------------------------
  67. IMPLEMENT_CONOBJECT(Taml);
  68. //-----------------------------------------------------------------------------
  69. StringTableEntry tamlRefIdName = StringTable->insert("TamlId");
  70. StringTableEntry tamlRefToIdName = StringTable->insert("TamlRefId");
  71. StringTableEntry tamlNamedObjectName = StringTable->insert("Name");
  72. //-----------------------------------------------------------------------------
  73. typedef Taml::TamlFormatMode _TamlFormatMode;
  74. ImplementEnumType(_TamlFormatMode,
  75. "")
  76. {
  77. Taml::XmlFormat, "xml"
  78. },
  79. { Taml::BinaryFormat, "binary" }//,
  80. //{ Taml::JSONFormat, "json" }
  81. EndImplementEnumType;
  82. //-----------------------------------------------------------------------------
  83. Taml::TamlFormatMode Taml::getFormatModeEnum(const char* label)
  84. {
  85. // Search for Mnemonic.
  86. for (U32 i = 0; i < (sizeof(__TamlFormatMode::_sEnums) / sizeof(EnumTable::Value)); i++)
  87. {
  88. if (dStricmp(__TamlFormatMode::_sEnumTable[i].getName(), label) == 0)
  89. return (TamlFormatMode)__TamlFormatMode::_sEnumTable[i].getInt();
  90. }
  91. // Warn.
  92. Con::warnf("Taml::getFormatModeEnum() - Invalid format of '%s'.", label);
  93. return Taml::InvalidFormat;
  94. }
  95. //-----------------------------------------------------------------------------
  96. const char* Taml::getFormatModeDescription(const Taml::TamlFormatMode formatMode)
  97. {
  98. // Search for Mnemonic.
  99. for (U32 i = 0; i < (sizeof(__TamlFormatMode::_sEnums) / sizeof(EnumTable::Value)); i++)
  100. {
  101. if (__TamlFormatMode::_sEnumTable[i].getInt() == (S32)formatMode)
  102. return __TamlFormatMode::_sEnumTable[i].getName();
  103. }
  104. // Warn.
  105. Con::warnf("Taml::getFormatModeDescription() - Invalid format mode.");
  106. return StringTable->EmptyString();
  107. }
  108. //-----------------------------------------------------------------------------
  109. // The string-table-entries are set to string literals below because Taml is used in a static scope and the string-table cannot currently be used like that.
  110. Taml::Taml() :
  111. mFormatMode(XmlFormat),
  112. mJSONStrict(true),
  113. mBinaryCompression(true),
  114. mWriteDefaults(false),
  115. mAutoFormatXmlExtension("taml"),
  116. mAutoFormat(true),
  117. mProgenitorUpdate(true),
  118. mAutoFormatBinaryExtension("baml"),
  119. mAutoFormatJSONExtension("json")
  120. {
  121. // Reset the file-path buffer.
  122. mFilePathBuffer[0] = 0;
  123. }
  124. //-----------------------------------------------------------------------------
  125. void Taml::initPersistFields()
  126. {
  127. // Call parent.
  128. Parent::initPersistFields();
  129. addField("Format", TYPEID<_TamlFormatMode>(), Offset(mFormatMode, Taml), "The read/write format that should be used.");
  130. addField("JSONStrict", TypeBool, Offset(mBinaryCompression, Taml), "Whether to write JSON that is strictly compatible with RFC4627 or not.\n");
  131. addField("BinaryCompression", TypeBool, Offset(mBinaryCompression, Taml), "Whether ZIP compression is used on binary formatting or not.\n");
  132. addField("WriteDefaults", TypeBool, Offset(mWriteDefaults, Taml), "Whether to write static fields that are at their default or not.\n");
  133. addField("ProgenitorUpdate", TypeBool, Offset(mProgenitorUpdate, Taml), "Whether to update each type instances file-progenitor or not.\n");
  134. addField("AutoFormat", TypeBool, Offset(mAutoFormat, Taml), "Whether the format type is automatically determined by the filename extension or not.\n");
  135. addField("AutoFormatXmlExtension", TypeString, Offset(mAutoFormatXmlExtension, Taml), "When using auto-format, this is the extension (end of filename) used to detect the XML format.\n");
  136. addField("AutoFormatBinaryExtension", TypeString, Offset(mAutoFormatBinaryExtension, Taml), "When using auto-format, this is the extension (end of filename) used to detect the BINARY format.\n");
  137. addField("AutoFormatJSONExtension", TypeString, Offset(mAutoFormatJSONExtension, Taml), "When using auto-format, this is the extension (end of filename) used to detect the JSON format.\n");
  138. }
  139. //-----------------------------------------------------------------------------
  140. bool Taml::onAdd()
  141. {
  142. // Call parent.
  143. if (!Parent::onAdd())
  144. return false;
  145. // Set JSON strict mode.
  146. mJSONStrict = Con::getBoolVariable(TAML_JSON_STRICT_VARIBLE, true);
  147. // Reset the compilation.
  148. resetCompilation();
  149. return true;
  150. }
  151. //-----------------------------------------------------------------------------
  152. void Taml::onRemove()
  153. {
  154. // Reset the compilation.
  155. resetCompilation();
  156. // Call parent.
  157. Parent::onRemove();
  158. }
  159. //-----------------------------------------------------------------------------
  160. bool Taml::write(SimObject* pSimObject, const char* pFilename)
  161. {
  162. // Debug Profiling.
  163. PROFILE_SCOPE(Taml_Write);
  164. // Sanity!
  165. AssertFatal(pSimObject != NULL, "Cannot write a NULL object.");
  166. AssertFatal(pFilename != NULL, "Cannot write to a NULL filename.");
  167. // Expand the file-name into the file-path buffer.
  168. Con::expandToolScriptFilename(mFilePathBuffer, sizeof(mFilePathBuffer), pFilename);
  169. FileStream stream;
  170. // File opened?
  171. if (!stream.open(mFilePathBuffer, Torque::FS::File::Write))
  172. {
  173. // No, so warn.
  174. Con::warnf("Taml::writeFile() - Could not open filename '%s' for write.", mFilePathBuffer);
  175. return false;
  176. }
  177. // Get the file auto-format mode.
  178. const TamlFormatMode formatMode = getFileAutoFormatMode(mFilePathBuffer);
  179. // Reset the compilation.
  180. resetCompilation();
  181. // Write object.
  182. const bool status = write(stream, pSimObject, formatMode);
  183. // Close file.
  184. stream.close();
  185. // Reset the compilation.
  186. resetCompilation();
  187. return status;
  188. }
  189. //-----------------------------------------------------------------------------
  190. SimObject* Taml::read(const char* pFilename)
  191. {
  192. // Debug Profiling.
  193. PROFILE_SCOPE(Taml_Read);
  194. // Sanity!
  195. AssertFatal(pFilename != NULL, "Cannot read from a NULL filename.");
  196. // Expand the file-name into the file-path buffer.
  197. Con::expandToolScriptFilename(mFilePathBuffer, sizeof(mFilePathBuffer), pFilename);
  198. FileStream stream;
  199. // File opened?
  200. if (!stream.open(mFilePathBuffer, Torque::FS::File::Read))
  201. {
  202. // No, so warn.
  203. Con::warnf("Taml::read() - Could not open filename '%s' for read.", mFilePathBuffer);
  204. return NULL;
  205. }
  206. // Get the file auto-format mode.
  207. const TamlFormatMode formatMode = getFileAutoFormatMode(mFilePathBuffer);
  208. // Reset the compilation.
  209. resetCompilation();
  210. // Write object.
  211. SimObject* pSimObject = read(stream, formatMode);
  212. // Close file.
  213. stream.close();
  214. // Reset the compilation.
  215. resetCompilation();
  216. // Did we generate an object?
  217. if (pSimObject == NULL)
  218. {
  219. // No, so warn.
  220. Con::warnf("Taml::read() - Failed to load an object from the file '%s'.", mFilePathBuffer);
  221. }
  222. else
  223. {
  224. pSimObject->onPostAdd();
  225. }
  226. return pSimObject;
  227. }
  228. //-----------------------------------------------------------------------------
  229. bool Taml::write(FileStream& stream, SimObject* pSimObject, const TamlFormatMode formatMode)
  230. {
  231. // Sanity!
  232. AssertFatal(pSimObject != NULL, "Cannot write a NULL object.");
  233. // Compile nodes.
  234. TamlWriteNode* pRootNode = compileObject(pSimObject);
  235. // Format appropriately.
  236. switch (formatMode)
  237. {
  238. /// Xml.
  239. case XmlFormat:
  240. {
  241. // Create writer.
  242. TamlXmlWriter writer(this);
  243. // Write.
  244. return writer.write(stream, pRootNode);
  245. }
  246. /// Binary.
  247. case BinaryFormat:
  248. {
  249. // Create writer.
  250. TamlBinaryWriter writer(this);
  251. // Write.
  252. return writer.write(stream, pRootNode, mBinaryCompression);
  253. }
  254. /// JSON.
  255. case JSONFormat:
  256. {
  257. // Create writer.
  258. //TamlJSONWriter writer( this );
  259. // Write.
  260. //return writer.write( stream, pRootNode );
  261. return NULL;
  262. }
  263. /// Invalid.
  264. case InvalidFormat:
  265. {
  266. // Warn.
  267. Con::warnf("Taml::write() - Cannot write, invalid format.");
  268. return false;
  269. }
  270. }
  271. // Warn.
  272. Con::warnf("Taml::write() - Unknown format.");
  273. return false;
  274. }
  275. //-----------------------------------------------------------------------------
  276. SimObject* Taml::read(FileStream& stream, const TamlFormatMode formatMode)
  277. {
  278. // Format appropriately.
  279. switch (formatMode)
  280. {
  281. /// Xml.
  282. case XmlFormat:
  283. {
  284. // Create reader.
  285. TamlXmlReader reader(this);
  286. // Read.
  287. return reader.read(stream);
  288. }
  289. /// Binary.
  290. case BinaryFormat:
  291. {
  292. // Create reader.
  293. TamlBinaryReader reader(this);
  294. // Read.
  295. return reader.read(stream);
  296. }
  297. /// JSON.
  298. case JSONFormat:
  299. {
  300. // Create reader.
  301. //TamlJSONReader reader( this );
  302. // Read.
  303. //return reader.read( stream );
  304. return NULL;
  305. }
  306. /// Invalid.
  307. case InvalidFormat:
  308. {
  309. // Warn.
  310. Con::warnf("Taml::read() - Cannot read, invalid format.");
  311. return NULL;
  312. }
  313. }
  314. // Warn.
  315. Con::warnf("Taml::read() - Unknown format.");
  316. return NULL;
  317. }
  318. //-----------------------------------------------------------------------------
  319. bool Taml::parse(const char* pFilename, TamlVisitor& visitor)
  320. {
  321. // Debug Profiling.
  322. PROFILE_SCOPE(Taml_Parse);
  323. // Sanity!
  324. AssertFatal(pFilename != NULL, "Taml::parse() - Cannot parse a NULL filename.");
  325. // Fetch format mode.
  326. const TamlFormatMode formatMode = getFileAutoFormatMode(pFilename);
  327. // Handle format mode appropriately.
  328. switch (formatMode)
  329. {
  330. case XmlFormat:
  331. {
  332. // Parse with the visitor.
  333. TamlXmlParser parser;
  334. // Are property changes needed but not supported?
  335. if (visitor.wantsPropertyChanges() && !parser.canChangeProperty())
  336. {
  337. // Yes, so warn.
  338. Con::warnf("Taml::parse() - Cannot parse '%s' file-type for filename '%s' as a specified visitor requires property changes which are not supported by the parser.", getFormatModeDescription(formatMode), pFilename);
  339. return false;
  340. }
  341. return parser.accept(pFilename, visitor);
  342. }
  343. case JSONFormat:
  344. {
  345. // Parse with the visitor.
  346. /*TamlJSONParser parser;
  347. // Are property changes needed but not supported?
  348. if ( visitor.wantsPropertyChanges() && !parser.canChangeProperty() )
  349. {
  350. // Yes, so warn.
  351. Con::warnf( "Taml::parse() - Cannot parse '%s' file-type for filename '%s' as a specified visitor requires property changes which are not supported by the parser.", getFormatModeDescription(formatMode), pFilename );
  352. return false;
  353. }
  354. return parser.accept( pFilename, visitor ); */
  355. return false;
  356. }
  357. case BinaryFormat:
  358. default:
  359. break;
  360. }
  361. // Warn.
  362. Con::warnf("Taml::parse() - Cannot parse '%s' file-type for filename '%s' as a required parser is not available.", getFormatModeDescription(formatMode), pFilename);
  363. return false;
  364. }
  365. //-----------------------------------------------------------------------------
  366. void Taml::resetCompilation(void)
  367. {
  368. // Debug Profiling.
  369. PROFILE_SCOPE(Taml_ResetCompilation);
  370. // Clear compiled nodes.
  371. for (typeNodeVector::iterator itr = mCompiledNodes.begin(); itr != mCompiledNodes.end(); ++itr)
  372. {
  373. // Fetch node.
  374. TamlWriteNode* pNode = (*itr);
  375. // Reset node.
  376. pNode->resetNode();
  377. // Delete node.
  378. delete pNode;
  379. }
  380. mCompiledNodes.clear();
  381. // Clear compiled objects.
  382. mCompiledObjects.clear();
  383. // Reset master node Id.
  384. mMasterNodeId = 0;
  385. }
  386. //-----------------------------------------------------------------------------
  387. Taml::TamlFormatMode Taml::getFileAutoFormatMode(const char* pFilename)
  388. {
  389. // Sanity!
  390. AssertFatal(pFilename != NULL, "Taml::getFileAutoFormatMode() - Cannot auto-format using a NULL filename.");
  391. // Is auto-format active?
  392. if (mAutoFormat)
  393. {
  394. // Yes, so fetch the extension lengths.
  395. const U32 xmlExtensionLength = dStrlen(mAutoFormatXmlExtension);
  396. const U32 binaryExtensionLength = dStrlen(mAutoFormatBinaryExtension);
  397. const U32 jsonExtensionLength = dStrlen(mAutoFormatJSONExtension);
  398. // Fetch filename length.
  399. const U32 filenameLength = dStrlen(pFilename);
  400. // Fetch end of filename,
  401. const char* pEndOfFilename = pFilename + filenameLength;
  402. // Check for the XML format.
  403. if (xmlExtensionLength <= filenameLength && dStricmp(pEndOfFilename - xmlExtensionLength, mAutoFormatXmlExtension) == 0)
  404. return Taml::XmlFormat;
  405. // Check for the Binary format.
  406. if (binaryExtensionLength <= filenameLength && dStricmp(pEndOfFilename - xmlExtensionLength, mAutoFormatBinaryExtension) == 0)
  407. return Taml::BinaryFormat;
  408. // Check for the XML format.
  409. if (jsonExtensionLength <= filenameLength && dStricmp(pEndOfFilename - jsonExtensionLength, mAutoFormatJSONExtension) == 0)
  410. return Taml::JSONFormat;
  411. }
  412. // Use the explicitly specified format mode.
  413. return mFormatMode;
  414. }
  415. //-----------------------------------------------------------------------------
  416. TamlWriteNode* Taml::compileObject(SimObject* pSimObject, const bool forceId)
  417. {
  418. // Debug Profiling.
  419. PROFILE_SCOPE(Taml_CompileObject);
  420. // Sanity!
  421. AssertFatal(pSimObject != NULL, "Taml::compileObject() - Cannot compile a NULL object.");
  422. // Fetch object Id.
  423. const SimObjectId objectId = pSimObject->getId();
  424. // Find a previously compiled node.
  425. typeCompiledHash::Iterator compiledItr = mCompiledObjects.find(objectId);
  426. // Have we already compiled this?
  427. if (compiledItr != mCompiledObjects.end())
  428. {
  429. // Yes, so sanity!
  430. AssertFatal(mCompiledNodes.size() != 0, "Taml::compileObject() - Found a compiled node at the root.");
  431. // Yes, so fetch node.
  432. TamlWriteNode* compiledNode = compiledItr->value;
  433. // Is a reference Id already present?
  434. if (compiledNode->mRefId == 0)
  435. {
  436. // No, so allocate one.
  437. compiledNode->mRefId = ++mMasterNodeId;
  438. }
  439. // Create write node.
  440. TamlWriteNode* pNewNode = new TamlWriteNode();
  441. pNewNode->set(pSimObject);
  442. // Set reference node.
  443. pNewNode->mRefToNode = compiledNode;
  444. // Push new node.
  445. mCompiledNodes.push_back(pNewNode);
  446. return pNewNode;
  447. }
  448. // No, so create write node.
  449. TamlWriteNode* pNewNode = new TamlWriteNode();
  450. pNewNode->set(pSimObject);
  451. // Is an Id being forced for this object?
  452. if (forceId)
  453. {
  454. // Yes, so allocate one.
  455. pNewNode->mRefId = ++mMasterNodeId;
  456. }
  457. // Push new node.
  458. mCompiledNodes.push_back(pNewNode);
  459. // Insert compiled object.
  460. mCompiledObjects.insertUnique(objectId, pNewNode);
  461. // Are there any Taml callbacks?
  462. if (pNewNode->mpTamlCallbacks != NULL)
  463. {
  464. // Yes, so call it.
  465. tamlPreWrite(pNewNode->mpTamlCallbacks);
  466. }
  467. // Compile static and dynamic fields.
  468. compileStaticFields(pNewNode);
  469. compileDynamicFields(pNewNode);
  470. // Compile children.
  471. compileChildren(pNewNode);
  472. // Compile custom state.
  473. compileCustomState(pNewNode);
  474. // Are there any Taml callbacks?
  475. if (pNewNode->mpTamlCallbacks != NULL)
  476. {
  477. // Yes, so call it.
  478. tamlPostWrite(pNewNode->mpTamlCallbacks);
  479. }
  480. return pNewNode;
  481. }
  482. //-----------------------------------------------------------------------------
  483. void Taml::compileStaticFields(TamlWriteNode* pTamlWriteNode)
  484. {
  485. // Debug Profiling.
  486. PROFILE_SCOPE(Taml_CompileStaticFields);
  487. // Sanity!
  488. AssertFatal(pTamlWriteNode != NULL, "Cannot compile static fields on a NULL node.");
  489. AssertFatal(pTamlWriteNode->mpSimObject != NULL, "Cannot compile static fields on a node with no object.");
  490. // Fetch object.
  491. SimObject* pSimObject = pTamlWriteNode->mpSimObject;
  492. // Fetch field list.
  493. const AbstractClassRep::FieldList& fieldList = pSimObject->getFieldList();
  494. // Fetch field count.
  495. const U32 fieldCount = fieldList.size();
  496. // Iterate fields.
  497. U8 arrayDepth = 0;
  498. TamlCustomNode* currentArrayNode;
  499. for (U32 index = 0; index < fieldCount; ++index)
  500. {
  501. // Fetch field.
  502. const AbstractClassRep::Field* pField = &fieldList[index];
  503. // Ignore if field not appropriate.
  504. if (pField->type == AbstractClassRep::DeprecatedFieldType ||
  505. pField->type == AbstractClassRep::StartGroupFieldType ||
  506. pField->type == AbstractClassRep::EndGroupFieldType)
  507. continue;
  508. if (pField->type == AbstractClassRep::StartArrayFieldType)
  509. {
  510. TamlCustomNodes& pCustomNodes = pTamlWriteNode->mCustomNodes;
  511. currentArrayNode = pCustomNodes.addNode(pField->pGroupname);
  512. for (U16 idx = 0; idx < pField->elementCount; idx++)
  513. currentArrayNode->addNode(pField->pFieldname);
  514. arrayDepth++;
  515. continue;
  516. }
  517. if (pField->type == AbstractClassRep::EndArrayFieldType)
  518. {
  519. arrayDepth--;
  520. continue;
  521. }
  522. if (arrayDepth == 0 && pField->elementCount > 1)
  523. {
  524. TamlCustomNodes& pCustomNodes = pTamlWriteNode->mCustomNodes;
  525. char* niceFieldName = const_cast<char *>(pField->pFieldname);
  526. niceFieldName[0] = dToupper(niceFieldName[0]);
  527. String str_niceFieldName = String(niceFieldName);
  528. currentArrayNode = pCustomNodes.addNode(str_niceFieldName + "s");
  529. for (U16 idx = 0; idx < pField->elementCount; idx++)
  530. currentArrayNode->addNode(str_niceFieldName);
  531. }
  532. // Fetch fieldname.
  533. StringTableEntry fieldName = StringTable->insert(pField->pFieldname);
  534. // Fetch element count.
  535. const U32 elementCount = pField->elementCount;
  536. // Skip if the field should not be written.
  537. // For now, we only deal with non-array fields.
  538. if (elementCount == 1 &&
  539. pField->setDataFn != NULL &&
  540. (!getWriteDefaults() && pField->writeDataFn(pSimObject, fieldName) == false))
  541. continue;
  542. // Iterate elements.
  543. for (U32 elementIndex = 0; elementIndex < elementCount; ++elementIndex)
  544. {
  545. char indexBuffer[8];
  546. dSprintf(indexBuffer, 8, "%d", elementIndex);
  547. // Fetch object field value.
  548. const char* pFieldValue = pSimObject->getPrefixedDataField(fieldName, indexBuffer);
  549. if (!pFieldValue)
  550. pFieldValue = StringTable->EmptyString();
  551. if (pField->type == TypeBool)
  552. pFieldValue = dAtob(pFieldValue) ? "true" : "false";
  553. U32 nBufferSize = dStrlen(pFieldValue) + 1;
  554. FrameTemp<char> valueCopy(nBufferSize);
  555. dStrcpy((char *)valueCopy, pFieldValue, nBufferSize);
  556. // Skip if field should not be written.
  557. if (!pSimObject->writeField(fieldName, valueCopy))
  558. continue;
  559. // Reassign field value.
  560. pFieldValue = valueCopy;
  561. // Detect and collapse relative path information
  562. char fnBuf[1024];
  563. if ((S32)pField->type == TypeFilename)
  564. {
  565. Con::collapseScriptFilename(fnBuf, 1024, pFieldValue);
  566. pFieldValue = fnBuf;
  567. }
  568. // Save field/value.
  569. if (arrayDepth > 0 || pField->elementCount > 1)
  570. currentArrayNode->getChildren()[elementIndex]->addField(fieldName, pFieldValue);
  571. else
  572. {
  573. TamlWriteNode::FieldValuePair* pFieldValuePair = new TamlWriteNode::FieldValuePair(fieldName, pFieldValue);
  574. pTamlWriteNode->mFields.push_back(pFieldValuePair);
  575. }
  576. }
  577. }
  578. }
  579. //-----------------------------------------------------------------------------
  580. static S32 QSORT_CALLBACK compareFieldEntries(const void* a, const void* b)
  581. {
  582. // Debug Profiling.
  583. PROFILE_SCOPE(Taml_CompareFieldEntries);
  584. SimFieldDictionary::Entry *fa = *((SimFieldDictionary::Entry **)a);
  585. SimFieldDictionary::Entry *fb = *((SimFieldDictionary::Entry **)b);
  586. return dStricmp(fa->slotName, fb->slotName);
  587. }
  588. //-----------------------------------------------------------------------------
  589. void Taml::compileDynamicFields(TamlWriteNode* pTamlWriteNode)
  590. {
  591. // Debug Profiling.
  592. PROFILE_SCOPE(Taml_CompileDynamicFields);
  593. // Sanity!
  594. AssertFatal(pTamlWriteNode != NULL, "Cannot compile dynamic fields on a NULL node.");
  595. AssertFatal(pTamlWriteNode->mpSimObject != NULL, "Cannot compile dynamic fields on a node with no object.");
  596. // Fetch object.
  597. SimObject* pSimObject = pTamlWriteNode->mpSimObject;
  598. // Fetch field dictionary.
  599. SimFieldDictionary* pFieldDictionary = pSimObject->getFieldDictionary();
  600. // Ignore if not writing dynamic fields.
  601. if (!pFieldDictionary || !pSimObject->getCanSaveDynamicFields())
  602. return;
  603. // Fetch field list.
  604. const AbstractClassRep::FieldList& fieldList = pSimObject->getFieldList();
  605. // Fetch field count.
  606. const U32 fieldCount = fieldList.size();
  607. Vector<SimFieldDictionary::Entry*> dynamicFieldList(__FILE__, __LINE__);
  608. // Ensure the dynamic field doesn't conflict with static field.
  609. for (U32 hashIndex = 0; hashIndex < SimFieldDictionary::HashTableSize; ++hashIndex)
  610. {
  611. for (SimFieldDictionary::Entry* pEntry = pFieldDictionary->mHashTable[hashIndex]; pEntry; pEntry = pEntry->next)
  612. {
  613. // Iterate static fields.
  614. U32 fieldIndex;
  615. for (fieldIndex = 0; fieldIndex < fieldCount; ++fieldIndex)
  616. {
  617. if (fieldList[fieldIndex].pFieldname == pEntry->slotName)
  618. break;
  619. }
  620. // Skip if found.
  621. if (fieldIndex != (U32)fieldList.size())
  622. continue;
  623. // Skip if not writing field.
  624. if (!pSimObject->writeField(pEntry->slotName, pEntry->value))
  625. continue;
  626. dynamicFieldList.push_back(pEntry);
  627. }
  628. }
  629. // Sort Entries to prevent version control conflicts
  630. if (dynamicFieldList.size() > 1)
  631. dQsort(dynamicFieldList.address(), dynamicFieldList.size(), sizeof(SimFieldDictionary::Entry*), compareFieldEntries);
  632. // Save the fields.
  633. for (Vector<SimFieldDictionary::Entry*>::iterator entryItr = dynamicFieldList.begin(); entryItr != dynamicFieldList.end(); ++entryItr)
  634. {
  635. // Fetch entry.
  636. SimFieldDictionary::Entry* pEntry = *entryItr;
  637. // Save field/value.
  638. TamlWriteNode::FieldValuePair* pFieldValuePair = new TamlWriteNode::FieldValuePair(pEntry->slotName, pEntry->value);
  639. pTamlWriteNode->mFields.push_back(pFieldValuePair);
  640. }
  641. }
  642. //-----------------------------------------------------------------------------
  643. void Taml::compileChildren(TamlWriteNode* pTamlWriteNode)
  644. {
  645. // Debug Profiling.
  646. PROFILE_SCOPE(Taml_CompileChildren);
  647. // Sanity!
  648. AssertFatal(pTamlWriteNode != NULL, "Cannot compile children on a NULL node.");
  649. AssertFatal(pTamlWriteNode->mpSimObject != NULL, "Cannot compile children on a node with no object.");
  650. // Fetch object.
  651. SimObject* pSimObject = pTamlWriteNode->mpSimObject;
  652. // Fetch the Taml children.
  653. TamlChildren* pChildren = dynamic_cast<TamlChildren*>(pSimObject);
  654. // Finish if object does not contain Taml children.
  655. if (pChildren == NULL || pChildren->getTamlChildCount() == 0)
  656. return;
  657. // Create children vector.
  658. pTamlWriteNode->mChildren = new typeNodeVector();
  659. // Fetch the child count.
  660. const U32 childCount = pChildren->getTamlChildCount();
  661. // Iterate children.
  662. for (U32 childIndex = 0; childIndex < childCount; childIndex++)
  663. {
  664. // Compile object.
  665. TamlWriteNode* pChildTamlWriteNode = compileObject(pChildren->getTamlChild(childIndex));
  666. // Save node.
  667. pTamlWriteNode->mChildren->push_back(pChildTamlWriteNode);
  668. }
  669. }
  670. //-----------------------------------------------------------------------------
  671. void Taml::compileCustomState(TamlWriteNode* pTamlWriteNode)
  672. {
  673. // Debug Profiling.
  674. PROFILE_SCOPE(Taml_CompileCustomProperties);
  675. // Sanity!
  676. AssertFatal(pTamlWriteNode != NULL, "Cannot compile custom state on a NULL node.");
  677. AssertFatal(pTamlWriteNode->mpSimObject != NULL, "Cannot compile custom state on a node with no object.");
  678. // Fetch the custom node on the write node.
  679. TamlCustomNodes& customNodes = pTamlWriteNode->mCustomNodes;
  680. // Are there any Taml callbacks?
  681. if (pTamlWriteNode->mpTamlCallbacks != NULL)
  682. {
  683. // Yes, so call it.
  684. tamlCustomWrite(pTamlWriteNode->mpTamlCallbacks, customNodes);
  685. }
  686. // Fetch custom nodes.
  687. const TamlCustomNodeVector& nodes = customNodes.getNodes();
  688. // Finish if no custom nodes to process.
  689. if (nodes.size() == 0)
  690. return;
  691. // Iterate custom properties.
  692. for (TamlCustomNodeVector::const_iterator customNodesItr = nodes.begin(); customNodesItr != nodes.end(); ++customNodesItr)
  693. {
  694. // Fetch the custom node.
  695. TamlCustomNode* pCustomNode = *customNodesItr;
  696. // Compile custom node state.
  697. compileCustomNodeState(pCustomNode);
  698. }
  699. }
  700. //-----------------------------------------------------------------------------
  701. void Taml::compileCustomNodeState(TamlCustomNode* pCustomNode)
  702. {
  703. // Sanity!
  704. AssertFatal(pCustomNode != NULL, "Taml: Cannot compile NULL custom node state.");
  705. // Fetch children.
  706. const TamlCustomNodeVector& children = pCustomNode->getChildren();
  707. // Fetch proxy object.
  708. SimObject* pProxyObject = pCustomNode->getProxyObject<SimObject>(false);
  709. // Do we have a proxy object?
  710. if (pProxyObject != NULL)
  711. {
  712. // Yes, so sanity!
  713. AssertFatal(children.size() == 0, "Taml: Cannot compile a proxy object on a custom node that has children.");
  714. // Yes, so compile it.
  715. // NOTE: We force an Id for custom compiled objects so we guarantee an Id. The reason for this is fairly
  716. // weak in that the XML parser currently has no way of distinguishing between a compiled object node
  717. // and a custom node. If the node has an Id or an Id-Ref then it's obviously an object and should be parsed as such.
  718. pCustomNode->setWriteNode(compileObject(pProxyObject, true));
  719. return;
  720. }
  721. // Finish if no children.
  722. if (children.size() == 0)
  723. return;
  724. // Iterate children.
  725. for (TamlCustomNodeVector::const_iterator childItr = children.begin(); childItr != children.end(); ++childItr)
  726. {
  727. // Fetch shape node.
  728. TamlCustomNode* pChildNode = *childItr;
  729. // Compile the child.
  730. compileCustomNodeState(pChildNode);
  731. }
  732. }
  733. //-----------------------------------------------------------------------------
  734. SimObject* Taml::createType(StringTableEntry typeName, const Taml* pTaml, const char* pProgenitorSuffix)
  735. {
  736. // Debug Profiling.
  737. PROFILE_SCOPE(Taml_CreateType);
  738. typedef HashTable<StringTableEntry, AbstractClassRep*> typeClassHash;
  739. static typeClassHash mClassMap;
  740. // Sanity!
  741. AssertFatal(typeName != NULL, "Taml: Type cannot be NULL");
  742. // Find type.
  743. typeClassHash::Iterator typeItr = mClassMap.find(typeName);
  744. // Found type?
  745. if (typeItr == mClassMap.end())
  746. {
  747. // No, so find type.
  748. AbstractClassRep* pClassRep = AbstractClassRep::getClassList();
  749. while (pClassRep)
  750. {
  751. // Is this the type?
  752. if (dStricmp(pClassRep->getClassName(), typeName) == 0)
  753. {
  754. // Yes, so insert it.
  755. typeItr = mClassMap.insertUnique(typeName, pClassRep);
  756. break;
  757. }
  758. // Next type.
  759. pClassRep = pClassRep->getNextClass();
  760. }
  761. // Did we find the type?
  762. if (typeItr == mClassMap.end())
  763. {
  764. // No, so warn and fail.
  765. Con::warnf("Taml: Failed to create type '%s' as such a registered type could not be found.", typeName);
  766. return NULL;
  767. }
  768. }
  769. // Create the object.
  770. ConsoleObject* pConsoleObject = typeItr->value->create();
  771. // NOTE: It is important that we don't register the object here as many objects rely on the fact that
  772. // fields are set prior to the object being registered. Registering here will invalid those assumptions.
  773. // Fetch the SimObject.
  774. SimObject* pSimObject = dynamic_cast<SimObject*>(pConsoleObject);
  775. // Was it a SimObject?
  776. if (pSimObject == NULL)
  777. {
  778. // No, so warn.
  779. Con::warnf("Taml: Failed to create type '%s' as it is not a SimObject.", typeName);
  780. // Destroy object and fail.
  781. delete pConsoleObject;
  782. return NULL;
  783. }
  784. // Are we updating the file-progenitor?
  785. if (pTaml->getProgenitorUpdate())
  786. {
  787. // Yes, so do we have a progenitor suffix?
  788. if (pProgenitorSuffix == NULL)
  789. {
  790. // No, so just set it to the progenitor file.
  791. pSimObject->setProgenitorFile(pTaml->getFilePathBuffer());
  792. }
  793. else
  794. {
  795. // Yes, so format the progenitor buffer.
  796. char progenitorBuffer[2048];
  797. dSprintf(progenitorBuffer, sizeof(progenitorBuffer), "%s,%s", pTaml->getFilePathBuffer(), pProgenitorSuffix);
  798. // Set the progenitor file.
  799. pSimObject->setProgenitorFile(progenitorBuffer);
  800. }
  801. }
  802. return pSimObject;
  803. }
  804. //-----------------------------------------------------------------------------
  805. bool Taml::generateTamlSchema()
  806. {
  807. // Fetch any TAML Schema file reference.
  808. const char* pTamlSchemaFile = Con::getVariable(TAML_SCHEMA_VARIABLE);
  809. // Do we have a schema file reference?
  810. if (pTamlSchemaFile == NULL || *pTamlSchemaFile == 0)
  811. {
  812. // No, so warn.
  813. Con::warnf("Taml::generateTamlSchema() - Cannot write a TAML schema as no schema variable is set ('%s').", TAML_SCHEMA_VARIABLE);
  814. return false;
  815. }
  816. // Expand the file-name into the file-path buffer.
  817. char filePathBuffer[1024];
  818. Con::expandToolScriptFilename(filePathBuffer, sizeof(filePathBuffer), pTamlSchemaFile);
  819. FileStream stream;
  820. // File opened?
  821. /*if ( !stream.open( filePathBuffer, Torque::FS::File::Write ) )
  822. {
  823. // No, so warn.
  824. Con::warnf("Taml::GenerateTamlSchema() - Could not open filename '%s' for write.", filePathBuffer );
  825. return false;
  826. }*/
  827. // Create document.
  828. TiXmlDocument schemaDocument;
  829. // Add declaration.
  830. TiXmlDeclaration schemaDeclaration("1.0", "iso-8859-1", "no");
  831. schemaDocument.InsertEndChild(schemaDeclaration);
  832. // Add schema element.
  833. TiXmlElement* pSchemaElement = new TiXmlElement("xs:schema");
  834. pSchemaElement->SetAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
  835. schemaDocument.LinkEndChild(pSchemaElement);
  836. // Fetch class-rep root.
  837. AbstractClassRep* pRootType = AbstractClassRep::getClassList();
  838. // Fetch SimObject class rep.
  839. AbstractClassRep* pSimObjectType = AbstractClassRep::findClassRep("SimObject");
  840. // Sanity!
  841. AssertFatal(pSimObjectType != NULL, "Taml::GenerateTamlSchema() - Could not find SimObject class rep.");
  842. // Reset scratch state.
  843. char buffer[1024];
  844. HashTable<AbstractClassRep*, StringTableEntry> childGroups;
  845. // *************************************************************
  846. // Generate console type elements.
  847. // *************************************************************
  848. // Vector2.
  849. TiXmlComment* pVector2Comment = new TiXmlComment("Vector2 Console Type");
  850. pSchemaElement->LinkEndChild(pVector2Comment);
  851. TiXmlElement* pVector2TypeElement = new TiXmlElement("xs:simpleType");
  852. pVector2TypeElement->SetAttribute("name", "Vector2_ConsoleType");
  853. pSchemaElement->LinkEndChild(pVector2TypeElement);
  854. TiXmlElement* pVector2ElementA = new TiXmlElement("xs:restriction");
  855. pVector2ElementA->SetAttribute("base", "xs:string");
  856. pVector2TypeElement->LinkEndChild(pVector2ElementA);
  857. TiXmlElement* pVector2ElementB = new TiXmlElement("xs:pattern");
  858. pVector2ElementB->SetAttribute("value", "([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b");
  859. pVector2ElementA->LinkEndChild(pVector2ElementB);
  860. // Point2F.
  861. TiXmlComment* pPoint2FComment = new TiXmlComment("Point2F Console Type");
  862. pSchemaElement->LinkEndChild(pPoint2FComment);
  863. TiXmlElement* pPoint2FTypeElement = new TiXmlElement("xs:simpleType");
  864. pPoint2FTypeElement->SetAttribute("name", "Point2F_ConsoleType");
  865. pSchemaElement->LinkEndChild(pPoint2FTypeElement);
  866. TiXmlElement* pPoint2FElementA = new TiXmlElement("xs:restriction");
  867. pPoint2FElementA->SetAttribute("base", "xs:string");
  868. pPoint2FTypeElement->LinkEndChild(pPoint2FElementA);
  869. TiXmlElement* pPoint2FElementB = new TiXmlElement("xs:pattern");
  870. pPoint2FElementB->SetAttribute("value", "([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b");
  871. pPoint2FElementA->LinkEndChild(pPoint2FElementB);
  872. // Point2I.
  873. TiXmlComment* pPoint2IComment = new TiXmlComment("Point2I Console Type");
  874. pSchemaElement->LinkEndChild(pPoint2IComment);
  875. TiXmlElement* pPoint2ITypeElement = new TiXmlElement("xs:simpleType");
  876. pPoint2ITypeElement->SetAttribute("name", "Point2I_ConsoleType");
  877. pSchemaElement->LinkEndChild(pPoint2ITypeElement);
  878. TiXmlElement* pPoint2IElementA = new TiXmlElement("xs:restriction");
  879. pPoint2IElementA->SetAttribute("base", "xs:string");
  880. pPoint2ITypeElement->LinkEndChild(pPoint2IElementA);
  881. TiXmlElement* pPoint2IElementB = new TiXmlElement("xs:pattern");
  882. pPoint2IElementB->SetAttribute("value", "[-]?[0-9]* [-]?[0-9]*");
  883. pPoint2IElementA->LinkEndChild(pPoint2IElementB);
  884. // b2AABB.
  885. TiXmlComment* pb2AABBComment = new TiXmlComment("b2AABB Console Type");
  886. pSchemaElement->LinkEndChild(pb2AABBComment);
  887. TiXmlElement* pb2AABBTypeElement = new TiXmlElement("xs:simpleType");
  888. pb2AABBTypeElement->SetAttribute("name", "b2AABB_ConsoleType");
  889. pSchemaElement->LinkEndChild(pb2AABBTypeElement);
  890. TiXmlElement* pb2AABBElementA = new TiXmlElement("xs:restriction");
  891. pb2AABBElementA->SetAttribute("base", "xs:string");
  892. pb2AABBTypeElement->LinkEndChild(pb2AABBElementA);
  893. TiXmlElement* pb2AABBElementB = new TiXmlElement("xs:pattern");
  894. pb2AABBElementB->SetAttribute("value", "([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b");
  895. pb2AABBElementA->LinkEndChild(pb2AABBElementB);
  896. // RectI.
  897. TiXmlComment* pRectIComment = new TiXmlComment("RectI Console Type");
  898. pSchemaElement->LinkEndChild(pRectIComment);
  899. TiXmlElement* pRectITypeElement = new TiXmlElement("xs:simpleType");
  900. pRectITypeElement->SetAttribute("name", "RectI_ConsoleType");
  901. pSchemaElement->LinkEndChild(pRectITypeElement);
  902. TiXmlElement* pRectIElementA = new TiXmlElement("xs:restriction");
  903. pRectIElementA->SetAttribute("base", "xs:string");
  904. pRectITypeElement->LinkEndChild(pRectIElementA);
  905. TiXmlElement* pRectIElementB = new TiXmlElement("xs:pattern");
  906. pRectIElementB->SetAttribute("value", "[-]?[0-9]* [-]?[0-9]* [-]?[0-9]* [-]?[0-9]*");
  907. pRectIElementA->LinkEndChild(pRectIElementB);
  908. // RectF.
  909. TiXmlComment* pRectFComment = new TiXmlComment("RectF Console Type");
  910. pSchemaElement->LinkEndChild(pRectFComment);
  911. TiXmlElement* pRectFTypeElement = new TiXmlElement("xs:simpleType");
  912. pRectFTypeElement->SetAttribute("name", "RectF_ConsoleType");
  913. pSchemaElement->LinkEndChild(pRectFTypeElement);
  914. TiXmlElement* pRectFElementA = new TiXmlElement("xs:restriction");
  915. pRectFElementA->SetAttribute("base", "xs:string");
  916. pRectFTypeElement->LinkEndChild(pRectFElementA);
  917. TiXmlElement* pRectFElementB = new TiXmlElement("xs:pattern");
  918. pRectFElementB->SetAttribute("value", "(\\b[-]?(b[0-9]+)?\\.)?[0-9]+\\b");
  919. pRectFElementA->LinkEndChild(pRectFElementB);
  920. // AssetId.
  921. TiXmlComment* pAssetIdComment = new TiXmlComment("AssetId Console Type");
  922. pSchemaElement->LinkEndChild(pAssetIdComment);
  923. TiXmlElement* pAssetIdTypeElement = new TiXmlElement("xs:simpleType");
  924. pAssetIdTypeElement->SetAttribute("name", "AssetId_ConsoleType");
  925. pSchemaElement->LinkEndChild(pAssetIdTypeElement);
  926. TiXmlElement* pAssetIdElementA = new TiXmlElement("xs:restriction");
  927. pAssetIdElementA->SetAttribute("base", "xs:string");
  928. pAssetIdTypeElement->LinkEndChild(pAssetIdElementA);
  929. TiXmlElement* pAssetIdElementB = new TiXmlElement("xs:pattern");
  930. dSprintf(buffer, sizeof(buffer), "(%s)?\\b[a-zA-Z0-9]+\\b%s\\b[a-zA-Z0-9]+\\b", ASSET_ID_FIELD_PREFIX, ASSET_SCOPE_TOKEN);
  931. pAssetIdElementB->SetAttribute("value", buffer);
  932. pAssetIdElementA->LinkEndChild(pAssetIdElementB);
  933. // Color Enums.
  934. TiXmlComment* pColorEnumsComment = new TiXmlComment("Color Enums");
  935. pSchemaElement->LinkEndChild(pColorEnumsComment);
  936. TiXmlElement* pColorEnumsTypeElement = new TiXmlElement("xs:simpleType");
  937. pColorEnumsTypeElement->SetAttribute("name", "Color_Enums");
  938. pSchemaElement->LinkEndChild(pColorEnumsTypeElement);
  939. TiXmlElement* pColorEnumsRestrictionElement = new TiXmlElement("xs:restriction");
  940. pColorEnumsRestrictionElement->SetAttribute("base", "xs:string");
  941. pColorEnumsTypeElement->LinkEndChild(pColorEnumsRestrictionElement);
  942. const S32 ColorEnumsCount = StockColor::getCount();
  943. for (S32 index = 0; index < ColorEnumsCount; ++index)
  944. {
  945. // Add enumeration element.
  946. TiXmlElement* pColorEnumsAttributeEnumerationElement = new TiXmlElement("xs:enumeration");
  947. pColorEnumsAttributeEnumerationElement->SetAttribute("value", StockColor::getColorItem(index)->getColorName());
  948. pColorEnumsRestrictionElement->LinkEndChild(pColorEnumsAttributeEnumerationElement);
  949. }
  950. // LinearColorF.
  951. TiXmlComment* pColorFValuesComment = new TiXmlComment("LinearColorF Values");
  952. pSchemaElement->LinkEndChild(pColorFValuesComment);
  953. TiXmlElement* pColorFValuesTypeElement = new TiXmlElement("xs:simpleType");
  954. pColorFValuesTypeElement->SetAttribute("name", "ColorF_Values");
  955. pSchemaElement->LinkEndChild(pColorFValuesTypeElement);
  956. TiXmlElement* pColorFValuesElementA = new TiXmlElement("xs:restriction");
  957. pColorFValuesElementA->SetAttribute("base", "xs:string");
  958. pColorFValuesTypeElement->LinkEndChild(pColorFValuesElementA);
  959. TiXmlElement* pColorFValuesElementB = new TiXmlElement("xs:pattern");
  960. pColorFValuesElementB->SetAttribute("value", "([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b");
  961. pColorFValuesElementA->LinkEndChild(pColorFValuesElementB);
  962. TiXmlComment* pColorFComment = new TiXmlComment("LinearColorF Console Type");
  963. pSchemaElement->LinkEndChild(pColorFComment);
  964. TiXmlElement* pColorFTypeElement = new TiXmlElement("xs:simpleType");
  965. pColorFTypeElement->SetAttribute("name", "ColorF_ConsoleType");
  966. pSchemaElement->LinkEndChild(pColorFTypeElement);
  967. TiXmlElement* pColorFUnionElement = new TiXmlElement("xs:union");
  968. pColorFUnionElement->SetAttribute("memberTypes", "ColorF_Values Color_Enums");
  969. pColorFTypeElement->LinkEndChild(pColorFUnionElement);
  970. // ColorI.
  971. TiXmlComment* pColorIValuesComment = new TiXmlComment("ColorI Values");
  972. pSchemaElement->LinkEndChild(pColorIValuesComment);
  973. TiXmlElement* pColorIValuesTypeElement = new TiXmlElement("xs:simpleType");
  974. pColorIValuesTypeElement->SetAttribute("name", "ColorI_Values");
  975. pSchemaElement->LinkEndChild(pColorIValuesTypeElement);
  976. TiXmlElement* pColorIValuesElementA = new TiXmlElement("xs:restriction");
  977. pColorIValuesElementA->SetAttribute("base", "xs:string");
  978. pColorIValuesTypeElement->LinkEndChild(pColorIValuesElementA);
  979. TiXmlElement* pColorIValuesElementB = new TiXmlElement("xs:pattern");
  980. pColorIValuesElementB->SetAttribute("value", "[-]?[0-9]* [-]?[0-9]* [-]?[0-9]* [-]?[0-9]*");
  981. pColorIValuesElementA->LinkEndChild(pColorIValuesElementB);
  982. TiXmlComment* pColorIComment = new TiXmlComment("ColorI Console Type");
  983. pSchemaElement->LinkEndChild(pColorIComment);
  984. TiXmlElement* pColorITypeElement = new TiXmlElement("xs:simpleType");
  985. pColorITypeElement->SetAttribute("name", "ColorI_ConsoleType");
  986. pSchemaElement->LinkEndChild(pColorITypeElement);
  987. TiXmlElement* pColorIUnionElement = new TiXmlElement("xs:union");
  988. pColorIUnionElement->SetAttribute("memberTypes", "ColorI_Values Color_Enums");
  989. pColorITypeElement->LinkEndChild(pColorIUnionElement);
  990. // *************************************************************
  991. // Generate engine type elements.
  992. // *************************************************************
  993. // Generate the engine type elements.
  994. TiXmlComment* tComment = new TiXmlComment("Type Elements");
  995. pSchemaElement->LinkEndChild(tComment);
  996. for (AbstractClassRep* pType = pRootType; pType != NULL; pType = pType->getNextClass())
  997. {
  998. // Add type.
  999. TiXmlElement* pTypeElement = new TiXmlElement("xs:element");
  1000. pTypeElement->SetAttribute("name", pType->getClassName());
  1001. dSprintf(buffer, sizeof(buffer), "%s_Type", pType->getClassName());
  1002. pTypeElement->SetAttribute("type", buffer);
  1003. pSchemaElement->LinkEndChild(pTypeElement);
  1004. }
  1005. // *************************************************************
  1006. // Generate the engine complex types.
  1007. // *************************************************************
  1008. for (AbstractClassRep* pType = pRootType; pType != NULL; pType = pType->getNextClass())
  1009. {
  1010. // Add complex type comment.
  1011. dSprintf(buffer, sizeof(buffer), " %s Type ", pType->getClassName());
  1012. TiXmlComment* ctComment = new TiXmlComment(buffer);
  1013. pSchemaElement->LinkEndChild(ctComment);
  1014. // Add complex type.
  1015. TiXmlElement* pComplexTypeElement = new TiXmlElement("xs:complexType");
  1016. dSprintf(buffer, sizeof(buffer), "%s_Type", pType->getClassName());
  1017. pComplexTypeElement->SetAttribute("name", buffer);
  1018. pSchemaElement->LinkEndChild(pComplexTypeElement);
  1019. // Add sequence.
  1020. TiXmlElement* pSequenceElement = new TiXmlElement("xs:sequence");
  1021. pComplexTypeElement->LinkEndChild(pSequenceElement);
  1022. // Fetch container child class.
  1023. AbstractClassRep* pContainerChildClass = pType->getContainerChildClass(true);
  1024. // Is the type allowed children?
  1025. if (pContainerChildClass != NULL)
  1026. {
  1027. // Yes, so add choice element.
  1028. TiXmlElement* pChoiceElement = new TiXmlElement("xs:choice");
  1029. pChoiceElement->SetAttribute("minOccurs", 0);
  1030. pChoiceElement->SetAttribute("maxOccurs", "unbounded");
  1031. pSequenceElement->LinkEndChild(pChoiceElement);
  1032. // Find child group.
  1033. HashTable<AbstractClassRep*, StringTableEntry>::Iterator childGroupItr = childGroups.find(pContainerChildClass);
  1034. // Does the group exist?
  1035. if (childGroupItr == childGroups.end())
  1036. {
  1037. // No, so format group name.
  1038. dSprintf(buffer, sizeof(buffer), "%s_ChildrenTypes", pContainerChildClass->getClassName());
  1039. // Insert into child group hash.
  1040. childGroupItr = childGroups.insertUnique(pContainerChildClass, StringTable->insert(buffer));
  1041. // Add the group.
  1042. TiXmlElement* pChildrenGroupElement = new TiXmlElement("xs:group");
  1043. pChildrenGroupElement->SetAttribute("name", buffer);
  1044. pSchemaElement->LinkEndChild(pChildrenGroupElement);
  1045. // Add choice element.
  1046. TiXmlElement* pChildreGroupChoiceElement = new TiXmlElement("xs:choice");
  1047. pChildrenGroupElement->LinkEndChild(pChildreGroupChoiceElement);
  1048. // Add choice members.
  1049. for (AbstractClassRep* pChoiceType = pRootType; pChoiceType != NULL; pChoiceType = pChoiceType->getNextClass())
  1050. {
  1051. // Skip if not derived from the container child class.
  1052. if (!pChoiceType->isClass(pContainerChildClass))
  1053. continue;
  1054. // Add choice member.
  1055. TiXmlElement* pChildrenMemberElement = new TiXmlElement("xs:element");
  1056. pChildrenMemberElement->SetAttribute("name", pChoiceType->getClassName());
  1057. dSprintf(buffer, sizeof(buffer), "%s_Type", pChoiceType->getClassName());
  1058. pChildrenMemberElement->SetAttribute("type", buffer);
  1059. pChildreGroupChoiceElement->LinkEndChild(pChildrenMemberElement);
  1060. }
  1061. }
  1062. // Reference the child group.
  1063. TiXmlElement* pChoiceGroupReferenceElement = new TiXmlElement("xs:group");
  1064. pChoiceGroupReferenceElement->SetAttribute("ref", childGroupItr->value);
  1065. pChoiceGroupReferenceElement->SetAttribute("minOccurs", 0);
  1066. pChoiceElement->LinkEndChild(pChoiceGroupReferenceElement);
  1067. }
  1068. // Generate the custom Taml schema.
  1069. for (AbstractClassRep* pCustomSchemaType = pType; pCustomSchemaType != NULL; pCustomSchemaType = pCustomSchemaType->getParentClass())
  1070. {
  1071. // Fetch the types custom TAML schema function.
  1072. AbstractClassRep::WriteCustomTamlSchema customSchemaFn = pCustomSchemaType->getCustomTamlSchema();
  1073. // Skip if no function avilable.
  1074. if (customSchemaFn == NULL)
  1075. continue;
  1076. // Call schema generation function.
  1077. customSchemaFn(pType, pSequenceElement);
  1078. }
  1079. // Generate field attribute group.
  1080. TiXmlElement* pFieldAttributeGroupElement = new TiXmlElement("xs:attributeGroup");
  1081. dSprintf(buffer, sizeof(buffer), "%s_Fields", pType->getClassName());
  1082. pFieldAttributeGroupElement->SetAttribute("name", buffer);
  1083. pSchemaElement->LinkEndChild(pFieldAttributeGroupElement);
  1084. // Fetch field list.
  1085. const AbstractClassRep::FieldList& fields = pType->mFieldList;
  1086. // Fetcj field count.
  1087. const S32 fieldCount = fields.size();
  1088. // Iterate static fields (in reverse as most types are organized from the root-fields up).
  1089. for (S32 index = fieldCount - 1; index > 0; --index)
  1090. {
  1091. // Fetch field.
  1092. const AbstractClassRep::Field& field = fields[index];
  1093. // Skip if not a data field.
  1094. if (field.type == AbstractClassRep::DeprecatedFieldType ||
  1095. field.type == AbstractClassRep::StartGroupFieldType ||
  1096. field.type == AbstractClassRep::EndGroupFieldType)
  1097. continue;
  1098. // Skip if the field root is not this type.
  1099. if (pType->findFieldRoot(field.pFieldname) != pType)
  1100. continue;
  1101. // Add attribute element.
  1102. TiXmlElement* pAttributeElement = new TiXmlElement("xs:attribute");
  1103. pAttributeElement->SetAttribute("name", field.pFieldname);
  1104. // Handle the console type appropriately.
  1105. const S32 fieldType = (S32)field.type;
  1106. /*
  1107. // Is the field an enumeration?
  1108. if ( fieldType == TypeEnum )
  1109. {
  1110. // Yes, so add attribute type.
  1111. TiXmlElement* pAttributeSimpleTypeElement = new TiXmlElement( "xs:simpleType" );
  1112. pAttributeElement->LinkEndChild( pAttributeSimpleTypeElement );
  1113. // Add restriction element.
  1114. TiXmlElement* pAttributeRestrictionElement = new TiXmlElement( "xs:restriction" );
  1115. pAttributeRestrictionElement->SetAttribute( "base", "xs:string" );
  1116. pAttributeSimpleTypeElement->LinkEndChild( pAttributeRestrictionElement );
  1117. // Yes, so fetch enumeration count.
  1118. const S32 enumCount = field.table->size;
  1119. // Iterate enumeration.
  1120. for( S32 index = 0; index < enumCount; ++index )
  1121. {
  1122. // Add enumeration element.
  1123. TiXmlElement* pAttributeEnumerationElement = new TiXmlElement( "xs:enumeration" );
  1124. pAttributeEnumerationElement->SetAttribute( "value", field.table->table[index].label );
  1125. pAttributeRestrictionElement->LinkEndChild( pAttributeEnumerationElement );
  1126. }
  1127. }
  1128. else
  1129. {*/
  1130. // No, so assume it's a string type initially.
  1131. const char* pFieldTypeDescription = "xs:string";
  1132. // Handle known types.
  1133. if (fieldType == TypeF32)
  1134. {
  1135. pFieldTypeDescription = "xs:float";
  1136. }
  1137. else if (fieldType == TypeS8 || fieldType == TypeS32)
  1138. {
  1139. pFieldTypeDescription = "xs:int";
  1140. }
  1141. else if (fieldType == TypeBool || fieldType == TypeFlag)
  1142. {
  1143. pFieldTypeDescription = "xs:boolean";
  1144. }
  1145. else if (fieldType == TypePoint2F)
  1146. {
  1147. pFieldTypeDescription = "Point2F_ConsoleType";
  1148. }
  1149. else if (fieldType == TypePoint2I)
  1150. {
  1151. pFieldTypeDescription = "Point2I_ConsoleType";
  1152. }
  1153. else if (fieldType == TypeRectI)
  1154. {
  1155. pFieldTypeDescription = "RectI_ConsoleType";
  1156. }
  1157. else if (fieldType == TypeRectF)
  1158. {
  1159. pFieldTypeDescription = "RectF_ConsoleType";
  1160. }
  1161. else if (fieldType == TypeColorF)
  1162. {
  1163. pFieldTypeDescription = "ColorF_ConsoleType";
  1164. }
  1165. else if (fieldType == TypeColorI)
  1166. {
  1167. pFieldTypeDescription = "ColorI_ConsoleType";
  1168. }
  1169. else if (fieldType == TypeAssetId/* ||
  1170. fieldType == TypeImageAssetPtr ||
  1171. fieldType == TypeAnimationAssetPtr ||
  1172. fieldType == TypeAudioAssetPtr*/)
  1173. {
  1174. pFieldTypeDescription = "AssetId_ConsoleType";
  1175. }
  1176. // Set attribute type.
  1177. pAttributeElement->SetAttribute("type", pFieldTypeDescription);
  1178. //}
  1179. pAttributeElement->SetAttribute("use", "optional");
  1180. pFieldAttributeGroupElement->LinkEndChild(pAttributeElement);
  1181. }
  1182. // Is this the SimObject Type?
  1183. if (pType == pSimObjectType)
  1184. {
  1185. // Yes, so add reserved Taml field attributes here...
  1186. // Add Taml "Name" attribute element.
  1187. TiXmlElement* pNameAttributeElement = new TiXmlElement("xs:attribute");
  1188. pNameAttributeElement->SetAttribute("name", tamlNamedObjectName);
  1189. pNameAttributeElement->SetAttribute("type", "xs:normalizedString");
  1190. pFieldAttributeGroupElement->LinkEndChild(pNameAttributeElement);
  1191. // Add Taml "TamlId" attribute element.
  1192. TiXmlElement* pTamlIdAttributeElement = new TiXmlElement("xs:attribute");
  1193. pTamlIdAttributeElement->SetAttribute("name", tamlRefIdName);
  1194. pTamlIdAttributeElement->SetAttribute("type", "xs:nonNegativeInteger");
  1195. pFieldAttributeGroupElement->LinkEndChild(pTamlIdAttributeElement);
  1196. // Add Taml "TamlRefId" attribute element.
  1197. TiXmlElement* pTamlRefIdAttributeElement = new TiXmlElement("xs:attribute");
  1198. pTamlRefIdAttributeElement->SetAttribute("name", tamlRefToIdName);
  1199. pTamlRefIdAttributeElement->SetAttribute("type", "xs:nonNegativeInteger");
  1200. pFieldAttributeGroupElement->LinkEndChild(pTamlRefIdAttributeElement);
  1201. }
  1202. // Add attribute group types.
  1203. for (AbstractClassRep* pAttributeGroupsType = pType; pAttributeGroupsType != NULL; pAttributeGroupsType = pAttributeGroupsType->getParentClass())
  1204. {
  1205. TiXmlElement* pFieldAttributeGroupRefElement = new TiXmlElement("xs:attributeGroup");
  1206. dSprintf(buffer, sizeof(buffer), "%s_Fields", pAttributeGroupsType->getClassName());
  1207. pFieldAttributeGroupRefElement->SetAttribute("ref", buffer);
  1208. pComplexTypeElement->LinkEndChild(pFieldAttributeGroupRefElement);
  1209. }
  1210. // Add "any" attribute element (dynamic fields).
  1211. TiXmlElement* pAnyAttributeElement = new TiXmlElement("xs:anyAttribute");
  1212. pAnyAttributeElement->SetAttribute("processContents", "skip");
  1213. pComplexTypeElement->LinkEndChild(pAnyAttributeElement);
  1214. }
  1215. // Write the schema document.
  1216. schemaDocument.SaveFile(filePathBuffer);
  1217. // Close file.
  1218. stream.close();
  1219. return true;
  1220. }
  1221. //-----------------------------------------------------------------------------
  1222. void Taml::WriteUnrestrictedCustomTamlSchema(const char* pCustomNodeName, const AbstractClassRep* pClassRep, TiXmlElement* pParentElement)
  1223. {
  1224. // Sanity!
  1225. AssertFatal(pCustomNodeName != NULL, "Taml::WriteDefaultCustomTamlSchema() - Node name cannot be NULL.");
  1226. AssertFatal(pClassRep != NULL, "Taml::WriteDefaultCustomTamlSchema() - ClassRep cannot be NULL.");
  1227. AssertFatal(pParentElement != NULL, "Taml::WriteDefaultCustomTamlSchema() - Parent Element cannot be NULL.");
  1228. char buffer[1024];
  1229. // Add custom type element.
  1230. TiXmlElement* pCustomElement = new TiXmlElement("xs:element");
  1231. dSprintf(buffer, sizeof(buffer), "%s.%s", pClassRep->getClassName(), pCustomNodeName);
  1232. pCustomElement->SetAttribute("name", buffer);
  1233. pCustomElement->SetAttribute("minOccurs", 0);
  1234. pCustomElement->SetAttribute("maxOccurs", 1);
  1235. pParentElement->LinkEndChild(pCustomElement);
  1236. // Add complex type element.
  1237. TiXmlElement* pComplexTypeElement = new TiXmlElement("xs:complexType");
  1238. pCustomElement->LinkEndChild(pComplexTypeElement);
  1239. // Add choice element.
  1240. TiXmlElement* pChoiceElement = new TiXmlElement("xs:choice");
  1241. pChoiceElement->SetAttribute("minOccurs", 0);
  1242. pChoiceElement->SetAttribute("maxOccurs", "unbounded");
  1243. pComplexTypeElement->LinkEndChild(pChoiceElement);
  1244. // Add sequence element.
  1245. TiXmlElement* pSequenceElement = new TiXmlElement("xs:sequence");
  1246. pChoiceElement->LinkEndChild(pSequenceElement);
  1247. // Add "any" element.
  1248. TiXmlElement* pAnyElement = new TiXmlElement("xs:any");
  1249. pAnyElement->SetAttribute("processContents", "skip");
  1250. pSequenceElement->LinkEndChild(pAnyElement);
  1251. }