taml.cpp 59 KB

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