simObject.cpp 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 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. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  26. #include "platform/platform.h"
  27. #include "platform/platformMemory.h"
  28. #include "console/simObject.h"
  29. #include "console/console.h"
  30. #include "console/consoleInternal.h"
  31. #include "console/engineAPI.h"
  32. #include "console/simFieldDictionary.h"
  33. #include "console/simPersistID.h"
  34. #include "console/typeValidators.h"
  35. #include "console/arrayObject.h"
  36. #include "console/codeBlock.h"
  37. #include "core/frameAllocator.h"
  38. #include "core/stream/fileStream.h"
  39. #include "core/fileObject.h"
  40. #include "persistence/taml/tamlCustom.h"
  41. IMPLEMENT_CONOBJECT( SimObject );
  42. // See full description in the new CHM manual
  43. ConsoleDocClass( SimObject,
  44. "@brief Base class for almost all objects involved in the simulation.\n\n"
  45. "@ingroup Console\n"
  46. );
  47. bool SimObject::smForceId = false;
  48. SimObjectId SimObject::smForcedId = 0;
  49. namespace Sim
  50. {
  51. // Defined in simManager.cpp
  52. extern SimGroup *gRootGroup;
  53. extern SimManagerNameDictionary *gNameDictionary;
  54. extern SimIdDictionary *gIdDictionary;
  55. extern U32 gNextObjectId;
  56. }
  57. //-----------------------------------------------------------------------------
  58. SimObject::SimObject()
  59. {
  60. objectName = NULL;
  61. mOriginalName = NULL;
  62. mInternalName = NULL;
  63. nextNameObject = (SimObject*)-1;
  64. nextManagerNameObject = (SimObject*)-1;
  65. nextIdObject = NULL;
  66. mFilename = NULL;
  67. mDeclarationLine = -1;
  68. mId = 0;
  69. mIdString[ 0 ] = '\0';
  70. mGroup = 0;
  71. mNameSpace = NULL;
  72. mNotifyList = NULL;
  73. mFlags.set( ModStaticFields | ModDynamicFields );
  74. mFieldDictionary = NULL;
  75. mCanSaveFieldDictionary = true;
  76. mClassName = NULL;
  77. mSuperClassName = NULL;
  78. mCopySource = NULL;
  79. mPersistentId = NULL;
  80. }
  81. //-----------------------------------------------------------------------------
  82. SimObject::~SimObject()
  83. {
  84. if( mFieldDictionary )
  85. {
  86. delete mFieldDictionary;
  87. mFieldDictionary = NULL;
  88. }
  89. // Release persistent ID.
  90. if( mPersistentId )
  91. {
  92. mPersistentId->unresolve();
  93. mPersistentId->decRefCount();
  94. mPersistentId = NULL;
  95. }
  96. if( mCopySource )
  97. mCopySource->unregisterReference( &mCopySource );
  98. AssertFatal(nextNameObject == (SimObject*)-1,avar(
  99. "SimObject::~SimObject: Not removed from dictionary: name %s, id %i",
  100. objectName, mId));
  101. AssertFatal(nextManagerNameObject == (SimObject*)-1,avar(
  102. "SimObject::~SimObject: Not removed from manager dictionary: name %s, id %i",
  103. objectName,mId));
  104. AssertFatal(mFlags.test(Added) == 0, "SimObject::object "
  105. "missing call to SimObject::onRemove");
  106. }
  107. //-----------------------------------------------------------------------------
  108. bool SimObject::processArguments(S32 argc, ConsoleValueRef *argv)
  109. {
  110. return argc == 0;
  111. }
  112. //-----------------------------------------------------------------------------
  113. void SimObject::initPersistFields()
  114. {
  115. addGroup( "Ungrouped" );
  116. addProtectedField( "name", TypeName, Offset(objectName, SimObject), &setProtectedName, &defaultProtectedGetFn,
  117. "Optional global name of this object." );
  118. endGroup( "Ungrouped" );
  119. addGroup( "Object" );
  120. addField( "internalName", TypeString, Offset(mInternalName, SimObject),
  121. "Optional name that may be used to lookup this object within a SimSet.");
  122. addProtectedField( "parentGroup", TYPEID< SimObject >(), Offset(mGroup, SimObject), &setProtectedParent, &defaultProtectedGetFn,
  123. "Group hierarchy parent of the object." );
  124. addProtectedField( "class", TypeString, Offset(mClassName, SimObject), &setClass, &defaultProtectedGetFn,
  125. "Script class of object." );
  126. addProtectedField( "superClass", TypeString, Offset(mSuperClassName, SimObject), &setSuperClass, &defaultProtectedGetFn,
  127. "Script super-class of object." );
  128. // For legacy support
  129. addProtectedField( "className", TypeString, Offset(mClassName, SimObject), &setClass, &defaultProtectedGetFn,
  130. "Script class of object.", AbstractClassRep::FIELD_HideInInspectors );
  131. endGroup( "Object" );
  132. addGroup( "Editing" );
  133. addProtectedField( "hidden", TypeBool, NULL,
  134. &_setHidden, &_getHidden,
  135. "Whether the object is visible." );
  136. addProtectedField( "locked", TypeBool, NULL,
  137. &_setLocked, &_getLocked,
  138. "Whether the object can be edited." );
  139. endGroup( "Editing" );
  140. addGroup( "Persistence" );
  141. addProtectedField( "canSave", TypeBool, Offset( mFlags, SimObject ),
  142. &_setCanSave, &_getCanSave,
  143. "Whether the object can be saved out. If false, the object is purely transient in nature." );
  144. addField( "canSaveDynamicFields", TypeBool, Offset(mCanSaveFieldDictionary, SimObject),
  145. "True if dynamic fields (added at runtime) should be saved. Defaults to true." );
  146. addProtectedField( "persistentId", TypePID, Offset( mPersistentId, SimObject ),
  147. &_setPersistentID, &defaultProtectedGetFn,
  148. "The universally unique identifier for the object." );
  149. endGroup( "Persistence" );
  150. Parent::initPersistFields();
  151. }
  152. //-----------------------------------------------------------------------------
  153. String SimObject::describeSelf() const
  154. {
  155. String desc = Parent::describeSelf();
  156. if( mId != 0 )
  157. desc = avar( "%s|id: %i", desc.c_str(), mId );
  158. if( objectName )
  159. desc = avar( "%s|name: %s", desc.c_str(), objectName );
  160. if( mInternalName )
  161. desc = avar( "%s|internal: %s", desc.c_str(), mInternalName );
  162. if( mNameSpace )
  163. desc = avar( "%s|nspace: %s", desc.c_str(), mNameSpace->mName );
  164. if( mGroup )
  165. desc = avar( "%s|group: %s", desc.c_str(), mGroup->getName() );
  166. if( mCopySource )
  167. desc = avar( "%s|copy: %s", desc.c_str(), mCopySource->getName() );
  168. if( mPersistentId )
  169. desc = avar( "%s|pid: %s", desc.c_str(), mPersistentId->getUUID().toString().c_str() );
  170. return desc;
  171. }
  172. //=============================================================================
  173. // Persistence.
  174. //=============================================================================
  175. // MARK: ---- Persistence ----
  176. //-----------------------------------------------------------------------------
  177. bool SimObject::writeField(StringTableEntry fieldname, const char* value)
  178. {
  179. // Don't write empty fields.
  180. if (!value || !*value)
  181. return false;
  182. // Don't write owner field for components
  183. static StringTableEntry sOwner = StringTable->insert( "owner" );
  184. if( fieldname == sOwner )
  185. return false;
  186. // Don't write ParentGroup
  187. static StringTableEntry sParentGroup = StringTable->insert( "parentGroup" );
  188. if( fieldname == sParentGroup )
  189. return false;
  190. // Don't write name, is within the parenthesis already
  191. static StringTableEntry sName = StringTable->insert( "name" );
  192. if( fieldname == sName )
  193. return false;
  194. // Don't write className, it is read for legacy support but we
  195. // write it out as class.
  196. static StringTableEntry sClassName = StringTable->insert( "className" );
  197. if( fieldname == sClassName )
  198. return false;
  199. // Write persistent ID only if present.
  200. static StringTableEntry sPersistentId = StringTable->insert( "persistentId" );
  201. if( fieldname == sPersistentId && ( !value || !value[ 0 ] ) )
  202. return false;
  203. // Don't write hidden and locked flags if they are at their default value.
  204. static StringTableEntry sHidden = StringTable->insert( "hidden" );
  205. static StringTableEntry sLocked = StringTable->insert( "locked" );
  206. if( fieldname == sHidden && !dAtob( value ) )
  207. return false;
  208. if( fieldname == sLocked && !dAtob( value ) )
  209. return false;
  210. return true;
  211. }
  212. //-----------------------------------------------------------------------------
  213. void SimObject::writeFields(Stream &stream, U32 tabStop)
  214. {
  215. // Write static fields.
  216. const AbstractClassRep::FieldList &list = getFieldList();
  217. for(U32 i = 0; i < list.size(); i++)
  218. {
  219. const AbstractClassRep::Field* f = &list[i];
  220. // Skip the special field types.
  221. if ( f->type >= AbstractClassRep::ARCFirstCustomField )
  222. continue;
  223. for(U32 j = 0; S32(j) < f->elementCount; j++)
  224. {
  225. char array[8];
  226. dSprintf( array, 8, "%d", j );
  227. const char *val = getDataField(StringTable->insert( f->pFieldname ), array );
  228. // Make a copy for the field check.
  229. if (!val)
  230. continue;
  231. U32 nBufferSize = dStrlen( val ) + 1;
  232. FrameTemp<char> valCopy( nBufferSize );
  233. dStrcpy( (char *)valCopy, val );
  234. if (!writeField(f->pFieldname, valCopy))
  235. continue;
  236. val = valCopy;
  237. U32 expandedBufferSize = ( nBufferSize * 2 ) + dStrlen(f->pFieldname) + 32;
  238. FrameTemp<char> expandedBuffer( expandedBufferSize );
  239. if(f->elementCount == 1)
  240. dSprintf(expandedBuffer, expandedBufferSize, "%s = \"", f->pFieldname);
  241. else
  242. dSprintf(expandedBuffer, expandedBufferSize, "%s[%d] = \"", f->pFieldname, j);
  243. // detect and collapse relative path information
  244. char fnBuf[1024];
  245. if (f->type == TypeFilename ||
  246. f->type == TypeStringFilename ||
  247. f->type == TypeImageFilename ||
  248. f->type == TypePrefabFilename ||
  249. f->type == TypeShapeFilename)
  250. {
  251. Con::collapseScriptFilename(fnBuf, 1024, val);
  252. val = fnBuf;
  253. }
  254. expandEscape((char*)expandedBuffer + dStrlen(expandedBuffer), val);
  255. dStrcat(expandedBuffer, "\";\r\n");
  256. stream.writeTabs(tabStop);
  257. stream.write(dStrlen(expandedBuffer),expandedBuffer);
  258. }
  259. }
  260. // Write dynamic fields, if enabled.
  261. if(mFieldDictionary && mCanSaveFieldDictionary)
  262. mFieldDictionary->writeFields(this, stream, tabStop);
  263. }
  264. //-----------------------------------------------------------------------------
  265. void SimObject::write(Stream &stream, U32 tabStop, U32 flags)
  266. {
  267. if( !getCanSave() && !( flags & IgnoreCanSave ) )
  268. return;
  269. // Only output selected objects if they want that.
  270. if((flags & SelectedOnly) && !isSelected())
  271. return;
  272. stream.writeTabs(tabStop);
  273. char buffer[1024];
  274. dSprintf(buffer, sizeof(buffer), "new %s(%s) {\r\n", getClassName(), getName() && !(flags & NoName) ? getName() : "");
  275. stream.write(dStrlen(buffer), buffer);
  276. writeFields(stream, tabStop + 1);
  277. stream.writeTabs(tabStop);
  278. stream.write(4, "};\r\n");
  279. }
  280. //-----------------------------------------------------------------------------
  281. bool SimObject::save(const char *pcFileName, bool bOnlySelected, const char *preappend)
  282. {
  283. static const char *beginMessage = "//--- OBJECT WRITE BEGIN ---";
  284. static const char *endMessage = "//--- OBJECT WRITE END ---";
  285. FileStream *stream;
  286. FileObject f;
  287. f.readMemory(pcFileName);
  288. // check for flags <selected, ...>
  289. U32 writeFlags = 0;
  290. if(bOnlySelected)
  291. writeFlags |= SimObject::SelectedOnly;
  292. if((stream = FileStream::createAndOpen( pcFileName, Torque::FS::File::Write )) == NULL)
  293. return false;
  294. char docRoot[256];
  295. char modRoot[256];
  296. dStrcpy(docRoot, pcFileName);
  297. char *p = dStrrchr(docRoot, '/');
  298. if (p) *++p = '\0';
  299. else docRoot[0] = '\0';
  300. dStrcpy(modRoot, pcFileName);
  301. p = dStrchr(modRoot, '/');
  302. if (p) *++p = '\0';
  303. else modRoot[0] = '\0';
  304. Con::setVariable("$DocRoot", docRoot);
  305. Con::setVariable("$ModRoot", modRoot);
  306. const char *buffer;
  307. while(!f.isEOF())
  308. {
  309. buffer = (const char *) f.readLine();
  310. if(!dStrcmp(buffer, beginMessage))
  311. break;
  312. stream->write(dStrlen(buffer), buffer);
  313. stream->write(2, "\r\n");
  314. }
  315. stream->write(dStrlen(beginMessage), beginMessage);
  316. stream->write(2, "\r\n");
  317. if ( preappend != NULL )
  318. stream->write(dStrlen(preappend),preappend);
  319. write(*stream, 0, writeFlags);
  320. stream->write(dStrlen(endMessage), endMessage);
  321. stream->write(2, "\r\n");
  322. while(!f.isEOF())
  323. {
  324. buffer = (const char *) f.readLine();
  325. if(!dStrcmp(buffer, endMessage))
  326. break;
  327. }
  328. while(!f.isEOF())
  329. {
  330. buffer = (const char *) f.readLine();
  331. stream->write(dStrlen(buffer), buffer);
  332. stream->write(2, "\r\n");
  333. }
  334. Con::setVariable("$DocRoot", NULL);
  335. Con::setVariable("$ModRoot", NULL);
  336. delete stream;
  337. return true;
  338. }
  339. //-----------------------------------------------------------------------------
  340. SimPersistID* SimObject::getOrCreatePersistentId()
  341. {
  342. if( !mPersistentId )
  343. {
  344. mPersistentId = SimPersistID::create( this );
  345. mPersistentId->incRefCount();
  346. }
  347. return mPersistentId;
  348. }
  349. void SimObject::onTamlCustomRead(TamlCustomNodes const& customNodes)
  350. {
  351. // Debug Profiling.
  352. //PROFILE_SCOPE(SimObject_OnTamlCustomRead);
  353. // Fetch field list.
  354. const AbstractClassRep::FieldList& fieldList = getFieldList();
  355. const U32 fieldCount = fieldList.size();
  356. for (U32 index = 0; index < fieldCount; ++index)
  357. {
  358. // Fetch field.
  359. const AbstractClassRep::Field* pField = &fieldList[index];
  360. // Ignore if field not appropriate.
  361. if (pField->type == AbstractClassRep::StartArrayFieldType || pField->elementCount > 1)
  362. {
  363. // Find cell custom node.
  364. const TamlCustomNode* pCustomCellNodes = NULL;
  365. if (pField->pGroupname != NULL)
  366. pCustomCellNodes = customNodes.findNode(pField->pGroupname);
  367. if (!pCustomCellNodes)
  368. {
  369. char* niceFieldName = const_cast<char *>(pField->pFieldname);
  370. niceFieldName[0] = dToupper(niceFieldName[0]);
  371. String str_niceFieldName = String(niceFieldName);
  372. pCustomCellNodes = customNodes.findNode(str_niceFieldName + "s");
  373. }
  374. // Continue if we have explicit cells.
  375. if (pCustomCellNodes != NULL)
  376. {
  377. // Fetch children cell nodes.
  378. const TamlCustomNodeVector& cellNodes = pCustomCellNodes->getChildren();
  379. U8 idx = 0;
  380. // Iterate cells.
  381. for (TamlCustomNodeVector::const_iterator cellNodeItr = cellNodes.begin(); cellNodeItr != cellNodes.end(); ++cellNodeItr)
  382. {
  383. char buf[5];
  384. dSprintf(buf, 5, "%d", idx);
  385. // Fetch cell node.
  386. TamlCustomNode* pCellNode = *cellNodeItr;
  387. // Fetch node name.
  388. StringTableEntry nodeName = pCellNode->getNodeName();
  389. // Is this a valid alias?
  390. if (nodeName != pField->pFieldname)
  391. {
  392. // No, so warn.
  393. Con::warnf("SimObject::onTamlCustomRead() - Encountered an unknown custom name of '%s'. Only '%s' is valid.", nodeName, pField->pFieldname);
  394. continue;
  395. }
  396. // Fetch fields.
  397. const TamlCustomFieldVector& fields = pCellNode->getFields();
  398. // Iterate property fields.
  399. for (TamlCustomFieldVector::const_iterator fieldItr = fields.begin(); fieldItr != fields.end(); ++fieldItr)
  400. {
  401. // Fetch field.
  402. const TamlCustomField* pField = *fieldItr;
  403. // Fetch field name.
  404. StringTableEntry fieldName = pField->getFieldName();
  405. const AbstractClassRep::Field* field = findField(fieldName);
  406. // Check common fields.
  407. if (field)
  408. {
  409. setDataField(fieldName, buf, pField->getFieldValue());
  410. }
  411. else
  412. {
  413. // Unknown name so warn.
  414. Con::warnf("SimObject::onTamlCustomRead() - Encountered an unknown custom field name of '%s'.", fieldName);
  415. continue;
  416. }
  417. }
  418. idx++;
  419. }
  420. }
  421. }
  422. }
  423. }
  424. //-----------------------------------------------------------------------------
  425. bool SimObject::_setPersistentID( void* object, const char* index, const char* data )
  426. {
  427. SimObject* simObject = reinterpret_cast< SimObject* >( object );
  428. // Make sure we don't already have a PID.
  429. if( simObject->getPersistentId() )
  430. {
  431. Con::errorf( "SimObject::_setPersistentID - cannot set a persistent ID on an object that already has a persistent ID assigned." );
  432. return false;
  433. }
  434. SimPersistID* pid;
  435. Con::setData( TypePID, &pid, 0, 1, &data );
  436. if ( !pid )
  437. return false;
  438. // Make sure it's not already bound to an object.
  439. if( pid->getObject() )
  440. {
  441. AssertWarn( pid->getObject() != simObject, "Sim::_setPersistentID - PID is bound to this object yet not assigned to it!" );
  442. SimObject* otherObj = pid->getObject();
  443. Con::errorf( "SimObject::_setPersistentID - UUID is already used by another object: '%s' -> %i:%s (%s)",
  444. data, otherObj->getId(), otherObj->getClassName(), otherObj->getName() );
  445. return false;
  446. }
  447. pid->resolve( simObject );
  448. pid->incRefCount();
  449. simObject->mPersistentId = pid;
  450. return false;
  451. }
  452. //-----------------------------------------------------------------------------
  453. void SimObject::setFilename( const char* file )
  454. {
  455. if( file )
  456. mFilename = StringTable->insert( file );
  457. else
  458. mFilename = StringTable->EmptyString();
  459. }
  460. //-----------------------------------------------------------------------------
  461. void SimObject::setDeclarationLine(U32 lineNumber)
  462. {
  463. mDeclarationLine = lineNumber;
  464. }
  465. //=============================================================================
  466. // Management.
  467. //=============================================================================
  468. // MARK: ---- Management ----
  469. //-----------------------------------------------------------------------------
  470. bool SimObject::registerObject()
  471. {
  472. AssertFatal( !mFlags.test( Added ), "reigsterObject - Object already registered!");
  473. mFlags.clear(Deleted | Removed);
  474. if(smForceId)
  475. {
  476. setId(smForcedId);
  477. smForceId = false;
  478. }
  479. if( !mId )
  480. {
  481. mId = Sim::gNextObjectId++;
  482. dSprintf( mIdString, sizeof( mIdString ), "%u", mId );
  483. }
  484. AssertFatal(Sim::gIdDictionary && Sim::gNameDictionary,
  485. "SimObject::registerObject - tried to register an object before Sim::init()!");
  486. Sim::gIdDictionary->insert(this);
  487. Sim::gNameDictionary->insert(this);
  488. // Notify object
  489. bool ret = onAdd();
  490. if(!ret)
  491. unregisterObject();
  492. AssertFatal(!ret || isProperlyAdded(), "Object did not call SimObject::onAdd()");
  493. return ret;
  494. }
  495. //-----------------------------------------------------------------------------
  496. void SimObject::unregisterObject()
  497. {
  498. mFlags.set(Removed);
  499. // Notify object first
  500. onRemove();
  501. // Clear out any pending notifications before
  502. // we call our own, just in case they delete
  503. // something that we have referenced.
  504. clearAllNotifications();
  505. // Notify all objects that are waiting for delete
  506. // messages
  507. if (getGroup())
  508. getGroup()->removeObject(this);
  509. processDeleteNotifies();
  510. // Do removals from the Sim.
  511. Sim::gNameDictionary->remove(this);
  512. Sim::gIdDictionary->remove(this);
  513. Sim::cancelPendingEvents(this);
  514. }
  515. //-----------------------------------------------------------------------------
  516. void SimObject::deleteObject()
  517. {
  518. Parent::destroySelf();
  519. }
  520. //-----------------------------------------------------------------------------
  521. void SimObject::_destroySelf()
  522. {
  523. AssertFatal( !isDeleted(), "SimObject::destroySelf - Object has already been deleted" );
  524. AssertFatal( !isRemoved(), "SimObject::destroySelf - Object in the process of being removed" );
  525. mFlags.set( Deleted );
  526. if( mFlags.test( Added ) )
  527. unregisterObject();
  528. Parent::_destroySelf();
  529. }
  530. //-----------------------------------------------------------------------------
  531. void SimObject::destroySelf()
  532. {
  533. // When using the legacy console interop, we don't delete objects
  534. // when their reference count drops to zero but rather defer their
  535. // deletion until deleteObject() is called.
  536. if( engineAPI::gUseConsoleInterop )
  537. return;
  538. Parent::destroySelf();
  539. }
  540. //-----------------------------------------------------------------------------
  541. class SimObjectDeleteEvent : public SimEvent
  542. {
  543. public:
  544. void process(SimObject *object)
  545. {
  546. object->deleteObject();
  547. }
  548. };
  549. void SimObject::safeDeleteObject()
  550. {
  551. Sim::postEvent( this, new SimObjectDeleteEvent, Sim::getCurrentTime() + 1 );
  552. }
  553. //-----------------------------------------------------------------------------
  554. void SimObject::setId(SimObjectId newId)
  555. {
  556. if(!mFlags.test(Added))
  557. mId = newId;
  558. else
  559. {
  560. // get this object out of the id dictionary if it's in it
  561. Sim::gIdDictionary->remove(this);
  562. // Free current Id.
  563. // Assign new one.
  564. mId = newId ? newId : Sim::gNextObjectId++;
  565. Sim::gIdDictionary->insert(this);
  566. }
  567. dSprintf( mIdString, sizeof( mIdString ), "%u", mId );
  568. }
  569. //-----------------------------------------------------------------------------
  570. void SimObject::assignName(const char *name)
  571. {
  572. if( objectName && !isNameChangeAllowed() )
  573. {
  574. Con::errorf( "SimObject::assignName - not allowed to change name of object '%s'", objectName );
  575. return;
  576. }
  577. // Added this assert 3/30/2007 because it is dumb to try to name
  578. // a SimObject the same thing as it's class name -patw
  579. //AssertFatal( dStricmp( getClassName(), name ), "Attempted to assign a name to a SimObject which matches it's type name." );
  580. if( dStricmp( getClassName(), name ) == 0 )
  581. Con::errorf( "SimObject::assignName - Assigning name '%s' to instance of object with type '%s'."
  582. " This can cause namespace linking issues.", getClassName(), name );
  583. StringTableEntry newName = NULL;
  584. if(name[0])
  585. newName = StringTable->insert(name);
  586. onNameChange( newName );
  587. if( mGroup )
  588. mGroup->mNameDictionary.remove( this );
  589. if( isProperlyAdded() )
  590. {
  591. unlinkNamespaces();
  592. Sim::gNameDictionary->remove( this );
  593. }
  594. objectName = newName;
  595. if( mGroup )
  596. mGroup->mNameDictionary.insert( this );
  597. if( isProperlyAdded() )
  598. {
  599. Sim::gNameDictionary->insert( this );
  600. linkNamespaces();
  601. }
  602. }
  603. //-----------------------------------------------------------------------------
  604. bool SimObject::registerObject(U32 id)
  605. {
  606. setId(id);
  607. return registerObject();
  608. }
  609. //-----------------------------------------------------------------------------
  610. bool SimObject::registerObject(const char *name)
  611. {
  612. assignName(name);
  613. return registerObject();
  614. }
  615. //-----------------------------------------------------------------------------
  616. bool SimObject::registerObject(const char *name, U32 id)
  617. {
  618. setId(id);
  619. assignName(name);
  620. return registerObject();
  621. }
  622. //=============================================================================
  623. // Introspection.
  624. //=============================================================================
  625. // MARK: ---- Introspection ----
  626. //-----------------------------------------------------------------------------
  627. bool SimObject::isMethod( const char* methodName )
  628. {
  629. if( !methodName || !methodName[0] )
  630. return false;
  631. StringTableEntry stname = StringTable->insert( methodName );
  632. if( getNamespace() )
  633. return ( getNamespace()->lookup( stname ) != NULL );
  634. return false;
  635. }
  636. //-----------------------------------------------------------------------------
  637. bool SimObject::isField( const char* fieldName, bool includeStatic, bool includeDynamic )
  638. {
  639. const char* strFieldName = StringTable->insert( fieldName );
  640. if( includeStatic && getClassRep()->findField( strFieldName ) )
  641. return true;
  642. if( includeDynamic && getFieldDictionary() && getFieldDictionary()->findDynamicField( strFieldName ) )
  643. return true;
  644. return false;
  645. }
  646. //-----------------------------------------------------------------------------
  647. void SimObject::assignDynamicFieldsFrom(SimObject* parent)
  648. {
  649. if(parent->mFieldDictionary)
  650. {
  651. if( mFieldDictionary == NULL )
  652. mFieldDictionary = new SimFieldDictionary;
  653. mFieldDictionary->assignFrom(parent->mFieldDictionary);
  654. }
  655. }
  656. //-----------------------------------------------------------------------------
  657. void SimObject::assignFieldsFrom(SimObject *parent)
  658. {
  659. // Only allow field assigns from objects of the same class or
  660. // a superclass.
  661. if( getClassRep()->isClass( parent->getClassRep() ) )
  662. {
  663. const AbstractClassRep::FieldList &list = parent->getFieldList();
  664. // copy out all the fields:
  665. for(U32 i = 0; i < list.size(); i++)
  666. {
  667. const AbstractClassRep::Field* f = &list[i];
  668. // Skip the special field types.
  669. if ( f->type >= AbstractClassRep::ARCFirstCustomField )
  670. continue;
  671. // Skip certain fields that we don't want to see copied so we don't
  672. // get error messages from their setters.
  673. static StringTableEntry sName = StringTable->insert( "name" );
  674. static StringTableEntry sPersistentId = StringTable->insert( "persistentId" );
  675. if( f->pFieldname == sName || f->pFieldname == sPersistentId )
  676. continue;
  677. S32 lastField = f->elementCount - 1;
  678. for(S32 j = 0; j <= lastField; j++)
  679. {
  680. const char* fieldVal = (*f->getDataFn)( parent, Con::getData(f->type, (void *) (((const char *)parent) + f->offset), j, f->table, f->flag));
  681. // Don't assign the field is the pointer is null or if
  682. // the field is not empty and writing it was disallowed.
  683. if ( !fieldVal || ( fieldVal[0] && !writeField( f->pFieldname, fieldVal ) ) )
  684. continue;
  685. // code copied from SimObject::setDataField().
  686. // TODO: paxorr: abstract this into a better setData / getData that considers prot fields.
  687. FrameTemp<char> buffer(2048);
  688. FrameTemp<char> bufferSecure(2048); // This buffer is used to make a copy of the data
  689. ConsoleBaseType *cbt = ConsoleBaseType::getType( f->type );
  690. const char* szBuffer = cbt->prepData( fieldVal, buffer, 2048 );
  691. dMemset( bufferSecure, 0, 2048 );
  692. dMemcpy( bufferSecure, szBuffer, dStrlen( szBuffer ) );
  693. if((*f->setDataFn)( this, NULL, bufferSecure ) )
  694. Con::setData(f->type, (void *) (((const char *)this) + f->offset), j, 1, &fieldVal, f->table);
  695. }
  696. }
  697. }
  698. else
  699. {
  700. Con::errorf( "SimObject::assignFieldsFrom() - cannot assigned fields from object of type '%s' to object of type '%s'",
  701. parent->getClassName(), getClassName()
  702. );
  703. }
  704. assignDynamicFieldsFrom(parent);
  705. }
  706. //-----------------------------------------------------------------------------
  707. void SimObject::setDataField(StringTableEntry slotName, const char *array, const char *value)
  708. {
  709. // first search the static fields if enabled
  710. if(mFlags.test(ModStaticFields))
  711. {
  712. const AbstractClassRep::Field *fld = findField(slotName);
  713. if(fld)
  714. {
  715. // Skip the special field types as they are not data.
  716. if ( fld->type >= AbstractClassRep::ARCFirstCustomField )
  717. return;
  718. S32 array1 = array ? dAtoi(array) : 0;
  719. // Here we check to see if <this> is a datablock and if <value>
  720. // starts with "$$". If both true than save value as a runtime substitution.
  721. if (dynamic_cast<SimDataBlock*>(this) && value[0] == '$' && value[1] == '$')
  722. {
  723. if (!this->allowSubstitutions())
  724. {
  725. Con::errorf("Substitution Error: %s datablocks do not allow \"$$\" field substitutions. [%s]",
  726. this->getClassName(), this->getName());
  727. return;
  728. }
  729. if (fld->doNotSubstitute)
  730. {
  731. Con::errorf("Substitution Error: field \"%s\" of datablock %s prohibits \"$$\" field substitutions. [%s]",
  732. slotName, this->getClassName(), this->getName());
  733. return;
  734. }
  735. // add the substitution
  736. ((SimDataBlock*)this)->addSubstitution(slotName, array1, value);
  737. return;
  738. }
  739. if(array1 >= 0 && array1 < fld->elementCount && fld->elementCount >= 1)
  740. {
  741. // If the set data notify callback returns true, then go ahead and
  742. // set the data, otherwise, assume the set notify callback has either
  743. // already set the data, or has deemed that the data should not
  744. // be set at all.
  745. FrameTemp<char> buffer(2048);
  746. FrameTemp<char> bufferSecure(2048); // This buffer is used to make a copy of the data
  747. // so that if the prep functions or any other functions use the string stack, the data
  748. // is not corrupted.
  749. ConsoleBaseType *cbt = ConsoleBaseType::getType( fld->type );
  750. AssertFatal( cbt != NULL, "Could not resolve Type Id." );
  751. const char* szBuffer = cbt->prepData( value, buffer, 2048 );
  752. dMemset( bufferSecure, 0, 2048 );
  753. dMemcpy( bufferSecure, szBuffer, dStrlen( szBuffer ) );
  754. if( (*fld->setDataFn)( this, array, bufferSecure ) )
  755. Con::setData(fld->type, (void *) (((const char *)this) + fld->offset), array1, 1, &value, fld->table);
  756. if(fld->validator)
  757. fld->validator->validateType(this, (void *) (((const char *)this) + fld->offset));
  758. onStaticModified( slotName, value );
  759. return;
  760. }
  761. if(fld->validator)
  762. fld->validator->validateType(this, (void *) (((const char *)this) + fld->offset));
  763. onStaticModified( slotName, value );
  764. return;
  765. }
  766. }
  767. if(mFlags.test(ModDynamicFields))
  768. {
  769. if(!mFieldDictionary)
  770. mFieldDictionary = new SimFieldDictionary;
  771. if(!array)
  772. {
  773. mFieldDictionary->setFieldValue(slotName, value);
  774. onDynamicModified( slotName, value );
  775. }
  776. else
  777. {
  778. char buf[256];
  779. dStrcpy(buf, slotName);
  780. dStrcat(buf, array);
  781. StringTableEntry permanentSlotName = StringTable->insert(buf);
  782. mFieldDictionary->setFieldValue(permanentSlotName, value);
  783. onDynamicModified( permanentSlotName, value );
  784. }
  785. }
  786. }
  787. //-----------------------------------------------------------------------------
  788. const char *SimObject::getDataField(StringTableEntry slotName, const char *array)
  789. {
  790. if(mFlags.test(ModStaticFields))
  791. {
  792. S32 array1 = array ? dAtoi(array) : -1;
  793. const AbstractClassRep::Field *fld = findField(slotName);
  794. if(fld)
  795. {
  796. if(array1 == -1 && fld->elementCount == 1)
  797. return (*fld->getDataFn)( this, Con::getData(fld->type, (void *) (((const char *)this) + fld->offset), 0, fld->table, fld->flag) );
  798. if(array1 >= 0 && array1 < fld->elementCount)
  799. return (*fld->getDataFn)( this, Con::getData(fld->type, (void *) (((const char *)this) + fld->offset), array1, fld->table, fld->flag) );// + typeSizes[fld.type] * array1));
  800. return "";
  801. }
  802. }
  803. if(mFlags.test(ModDynamicFields))
  804. {
  805. if(!mFieldDictionary)
  806. return "";
  807. if(!array)
  808. {
  809. if (const char* val = mFieldDictionary->getFieldValue(slotName))
  810. return val;
  811. }
  812. else
  813. {
  814. static char buf[256];
  815. dStrcpy(buf, slotName);
  816. dStrcat(buf, array);
  817. if (const char* val = mFieldDictionary->getFieldValue(StringTable->insert(buf)))
  818. return val;
  819. }
  820. }
  821. return "";
  822. }
  823. const char *SimObject::getPrefixedDataField(StringTableEntry fieldName, const char *array)
  824. {
  825. // Sanity!
  826. AssertFatal(fieldName != NULL, "Cannot get field value with NULL field name.");
  827. // Fetch field value.
  828. const char* pFieldValue = getDataField(fieldName, array);
  829. // Sanity.
  830. //AssertFatal(pFieldValue != NULL, "Field value cannot be NULL.");
  831. if (!pFieldValue)
  832. return NULL;
  833. // Return without the prefix if there's no value.
  834. if (*pFieldValue == 0)
  835. return StringTable->EmptyString();
  836. // Fetch the field prefix.
  837. StringTableEntry fieldPrefix = getDataFieldPrefix(fieldName);
  838. // Sanity!
  839. AssertFatal(fieldPrefix != NULL, "Field prefix cannot be NULL.");
  840. // Calculate a buffer size including prefix.
  841. const U32 valueBufferSize = dStrlen(fieldPrefix) + dStrlen(pFieldValue) + 1;
  842. // Fetch a buffer.
  843. char* pValueBuffer = Con::getReturnBuffer(valueBufferSize);
  844. // Format the value buffer.
  845. dSprintf(pValueBuffer, valueBufferSize, "%s%s", fieldPrefix, pFieldValue);
  846. return pValueBuffer;
  847. }
  848. //-----------------------------------------------------------------------------
  849. void SimObject::setPrefixedDataField(StringTableEntry fieldName, const char *array, const char *value)
  850. {
  851. // Sanity!
  852. AssertFatal(fieldName != NULL, "Cannot set object field value with NULL field name.");
  853. AssertFatal(value != NULL, "Field value cannot be NULL.");
  854. // Set value without prefix if there's no value.
  855. if (*value == 0)
  856. {
  857. setDataField(fieldName, NULL, value);
  858. return;
  859. }
  860. // Fetch the field prefix.
  861. StringTableEntry fieldPrefix = getDataFieldPrefix(fieldName);
  862. // Sanity.
  863. AssertFatal(fieldPrefix != NULL, "Field prefix cannot be NULL.");
  864. // Do we have a field prefix?
  865. if (fieldPrefix == StringTable->EmptyString())
  866. {
  867. // No, so set the data field in the usual way.
  868. setDataField(fieldName, NULL, value);
  869. return;
  870. }
  871. // Yes, so fetch the length of the field prefix.
  872. const U32 fieldPrefixLength = dStrlen(fieldPrefix);
  873. // Yes, so does it start with the object field prefix?
  874. if (dStrnicmp(value, fieldPrefix, fieldPrefixLength) != 0)
  875. {
  876. // No, so set the data field in the usual way.
  877. setDataField(fieldName, NULL, value);
  878. return;
  879. }
  880. // Yes, so set the data excluding the prefix.
  881. setDataField(fieldName, NULL, value + fieldPrefixLength);
  882. }
  883. //-----------------------------------------------------------------------------
  884. const char *SimObject::getPrefixedDynamicDataField(StringTableEntry fieldName, const char *array, const S32 fieldType)
  885. {
  886. // Sanity!
  887. AssertFatal(fieldName != NULL, "Cannot get field value with NULL field name.");
  888. // Fetch field value.
  889. const char* pFieldValue = getDataField(fieldName, array);
  890. // Sanity.
  891. AssertFatal(pFieldValue != NULL, "Field value cannot be NULL.");
  892. // Return the field if no field type is specified.
  893. if (fieldType == -1)
  894. return pFieldValue;
  895. // Return without the prefix if there's no value.
  896. if (*pFieldValue == 0)
  897. return StringTable->EmptyString();
  898. // Fetch the console base type.
  899. ConsoleBaseType* pConsoleBaseType = ConsoleBaseType::getType(fieldType);
  900. // Did we find the console base type?
  901. if (pConsoleBaseType == NULL)
  902. {
  903. // No, so warn.
  904. Con::warnf("getPrefixedDynamicDataField() - Invalid field type '%d' specified for field '%s' with value '%s'.",
  905. fieldType, fieldName, pFieldValue);
  906. }
  907. // Fetch the field prefix.
  908. StringTableEntry fieldPrefix = pConsoleBaseType->getTypePrefix();
  909. // Sanity!
  910. AssertFatal(fieldPrefix != NULL, "Field prefix cannot be NULL.");
  911. // Calculate a buffer size including prefix.
  912. const U32 valueBufferSize = dStrlen(fieldPrefix) + dStrlen(pFieldValue) + 1;
  913. // Fetch a buffer.
  914. char* pValueBuffer = Con::getReturnBuffer(valueBufferSize);
  915. // Format the value buffer.
  916. dSprintf(pValueBuffer, valueBufferSize, "%s%s", fieldPrefix, pFieldValue);
  917. return pValueBuffer;
  918. }
  919. //-----------------------------------------------------------------------------
  920. void SimObject::setPrefixedDynamicDataField(StringTableEntry fieldName, const char *array, const char *value, const S32 fieldType)
  921. {
  922. // Sanity!
  923. AssertFatal(fieldName != NULL, "Cannot set object field value with NULL field name.");
  924. AssertFatal(value != NULL, "Field value cannot be NULL.");
  925. // Set value without prefix if no field type was specified.
  926. if (fieldType == -1)
  927. {
  928. setDataField(fieldName, NULL, value);
  929. return;
  930. }
  931. // Fetch the console base type.
  932. ConsoleBaseType* pConsoleBaseType = ConsoleBaseType::getType(fieldType);
  933. // Did we find the console base type?
  934. if (pConsoleBaseType == NULL)
  935. {
  936. // No, so warn.
  937. Con::warnf("setPrefixedDynamicDataField() - Invalid field type '%d' specified for field '%s' with value '%s'.",
  938. fieldType, fieldName, value);
  939. }
  940. // Set value without prefix if there's no value or we didn't find the console base type.
  941. if (*value == 0 || pConsoleBaseType == NULL)
  942. {
  943. setDataField(fieldName, NULL, value);
  944. return;
  945. }
  946. // Fetch the field prefix.
  947. StringTableEntry fieldPrefix = pConsoleBaseType->getTypePrefix();
  948. // Sanity.
  949. AssertFatal(fieldPrefix != NULL, "Field prefix cannot be NULL.");
  950. // Do we have a field prefix?
  951. if (fieldPrefix == StringTable->EmptyString())
  952. {
  953. // No, so set the data field in the usual way.
  954. setDataField(fieldName, NULL, value);
  955. return;
  956. }
  957. // Yes, so fetch the length of the field prefix.
  958. const U32 fieldPrefixLength = dStrlen(fieldPrefix);
  959. // Yes, so does it start with the object field prefix?
  960. if (dStrnicmp(value, fieldPrefix, fieldPrefixLength) != 0)
  961. {
  962. // No, so set the data field in the usual way.
  963. setDataField(fieldName, NULL, value);
  964. return;
  965. }
  966. // Yes, so set the data excluding the prefix.
  967. setDataField(fieldName, NULL, value + fieldPrefixLength);
  968. }
  969. //-----------------------------------------------------------------------------
  970. StringTableEntry SimObject::getDataFieldPrefix(StringTableEntry fieldName)
  971. {
  972. // Sanity!
  973. AssertFatal(fieldName != NULL, "Cannot get field prefix with NULL field name.");
  974. // Find the field.
  975. const AbstractClassRep::Field* pField = findField(fieldName);
  976. // Return nothing if field was not found.
  977. if (pField == NULL)
  978. return StringTable->EmptyString();
  979. // Yes, so fetch the console base type.
  980. ConsoleBaseType* pConsoleBaseType = ConsoleBaseType::getType(pField->type);
  981. // Fetch the type prefix.
  982. return pConsoleBaseType->getTypePrefix();
  983. }
  984. //-----------------------------------------------------------------------------
  985. U32 SimObject::getDataFieldType( StringTableEntry slotName, const char* array )
  986. {
  987. const AbstractClassRep::Field* field = findField( slotName );
  988. if(field)
  989. return field->type;
  990. // Check dynamic fields
  991. if(!mFieldDictionary)
  992. return 0;
  993. if(array == NULL || *array == 0)
  994. return mFieldDictionary->getFieldType( slotName );
  995. else
  996. {
  997. static char buf[256];
  998. dStrcpy( buf, slotName );
  999. dStrcat( buf, array );
  1000. return mFieldDictionary->getFieldType( StringTable->insert( buf ) );
  1001. }
  1002. }
  1003. //-----------------------------------------------------------------------------
  1004. void SimObject::setDataFieldType(const U32 fieldTypeId, StringTableEntry slotName, const char *array)
  1005. {
  1006. // This only works on dynamic fields, bail if we have no field dictionary
  1007. if(!mFieldDictionary)
  1008. return;
  1009. if(array == NULL || *array == 0)
  1010. {
  1011. mFieldDictionary->setFieldType( slotName, fieldTypeId );
  1012. onDynamicModified( slotName, mFieldDictionary->getFieldValue(slotName) );
  1013. }
  1014. else
  1015. {
  1016. static char buf[256];
  1017. dStrcpy( buf, slotName );
  1018. dStrcat( buf, array );
  1019. mFieldDictionary->setFieldType( StringTable->insert( buf ), fieldTypeId );
  1020. onDynamicModified( slotName, mFieldDictionary->getFieldValue(slotName) );
  1021. }
  1022. }
  1023. //-----------------------------------------------------------------------------
  1024. void SimObject::setDataFieldType(const char *typeName, StringTableEntry slotName, const char *array)
  1025. {
  1026. // This only works on dynamic fields, bail if we have no field dictionary
  1027. if(!mFieldDictionary)
  1028. return;
  1029. if(array == NULL || *array == 0)
  1030. mFieldDictionary->setFieldType( slotName, typeName );
  1031. else
  1032. {
  1033. static char buf[256];
  1034. dStrcpy( buf, slotName );
  1035. dStrcat( buf, array );
  1036. StringTableEntry permanentSlotName = StringTable->insert(buf);
  1037. mFieldDictionary->setFieldType( permanentSlotName, typeName );
  1038. onDynamicModified( permanentSlotName, mFieldDictionary->getFieldValue(permanentSlotName) );
  1039. }
  1040. }
  1041. //-----------------------------------------------------------------------------
  1042. void SimObject::dumpClassHierarchy()
  1043. {
  1044. AbstractClassRep* pRep = getClassRep();
  1045. while(pRep)
  1046. {
  1047. Con::warnf("%s ->", pRep->getClassName());
  1048. pRep = pRep->getParentClass();
  1049. }
  1050. }
  1051. //-----------------------------------------------------------------------------
  1052. SimObject* SimObject::clone()
  1053. {
  1054. if( !getClassRep() )
  1055. return NULL;
  1056. ConsoleObject* conObject = getClassRep()->create();
  1057. if( !conObject )
  1058. return NULL;
  1059. SimObject* simObject = dynamic_cast< SimObject* >( conObject );
  1060. if( !simObject )
  1061. {
  1062. delete conObject;
  1063. return NULL;
  1064. }
  1065. simObject->assignFieldsFrom( this );
  1066. String name = Sim::getUniqueName( getName() );
  1067. if( !simObject->registerObject( name ) )
  1068. {
  1069. delete simObject;
  1070. return NULL;
  1071. }
  1072. if( getGroup() )
  1073. getGroup()->addObject( simObject );
  1074. return simObject;
  1075. }
  1076. //-----------------------------------------------------------------------------
  1077. SimObject* SimObject::deepClone()
  1078. {
  1079. return clone();
  1080. }
  1081. //=============================================================================
  1082. // Grouping.
  1083. //=============================================================================
  1084. // MARK: ---- Grouping ----
  1085. //-----------------------------------------------------------------------------
  1086. SimObject* SimObject::findObject( const char* )
  1087. {
  1088. return NULL;
  1089. }
  1090. //-----------------------------------------------------------------------------
  1091. bool SimObject::isChildOfGroup(SimGroup* pGroup)
  1092. {
  1093. if(!pGroup)
  1094. return false;
  1095. //if we *are* the group in question,
  1096. //return true:
  1097. if(pGroup == dynamic_cast<SimGroup*>(this))
  1098. return true;
  1099. SimGroup* temp = mGroup;
  1100. while(temp)
  1101. {
  1102. if(temp == pGroup)
  1103. return true;
  1104. temp = temp->mGroup;
  1105. }
  1106. return false;
  1107. }
  1108. //-----------------------------------------------------------------------------
  1109. bool SimObject::addToSet(SimObjectId spid)
  1110. {
  1111. if (mFlags.test(Added) == false)
  1112. return false;
  1113. SimObject* ptr = Sim::findObject(spid);
  1114. if (ptr)
  1115. {
  1116. SimSet* sp = dynamic_cast<SimSet*>(ptr);
  1117. AssertFatal(sp != 0,
  1118. "SimObject::addToSet: "
  1119. "ObjectId does not refer to a set object");
  1120. sp->addObject(this);
  1121. return true;
  1122. }
  1123. return false;
  1124. }
  1125. //-----------------------------------------------------------------------------
  1126. bool SimObject::addToSet(const char *ObjectName)
  1127. {
  1128. if (mFlags.test(Added) == false)
  1129. return false;
  1130. SimObject* ptr = Sim::findObject(ObjectName);
  1131. if (ptr)
  1132. {
  1133. SimSet* sp = dynamic_cast<SimSet*>(ptr);
  1134. AssertFatal(sp != 0,
  1135. "SimObject::addToSet: "
  1136. "ObjectName does not refer to a set object");
  1137. sp->addObject(this);
  1138. return true;
  1139. }
  1140. return false;
  1141. }
  1142. //-----------------------------------------------------------------------------
  1143. bool SimObject::removeFromSet(SimObjectId sid)
  1144. {
  1145. if (mFlags.test(Added) == false)
  1146. return false;
  1147. SimSet *set;
  1148. if(Sim::findObject(sid, set))
  1149. {
  1150. set->removeObject(this);
  1151. return true;
  1152. }
  1153. return false;
  1154. }
  1155. //-----------------------------------------------------------------------------
  1156. bool SimObject::removeFromSet(const char *objectName)
  1157. {
  1158. if (mFlags.test(Added) == false)
  1159. return false;
  1160. SimSet *set;
  1161. if(Sim::findObject(objectName, set))
  1162. {
  1163. set->removeObject(this);
  1164. return true;
  1165. }
  1166. return false;
  1167. }
  1168. //-----------------------------------------------------------------------------
  1169. void SimObject::dumpGroupHierarchy()
  1170. {
  1171. String className( getClassName() );
  1172. String objectName( getName() );
  1173. Con::warnf( "[%i] %s - %s ->", getId(), className.c_str(), objectName.c_str() );
  1174. if ( mGroup )
  1175. mGroup->dumpGroupHierarchy();
  1176. }
  1177. //=============================================================================
  1178. // Events.
  1179. //=============================================================================
  1180. // MARK: ---- Events ----
  1181. //-----------------------------------------------------------------------------
  1182. bool SimObject::onAdd()
  1183. {
  1184. mFlags.set(Added);
  1185. linkNamespaces();
  1186. return true;
  1187. }
  1188. //-----------------------------------------------------------------------------
  1189. void SimObject::onRemove()
  1190. {
  1191. mFlags.clear(Added);
  1192. unlinkNamespaces();
  1193. }
  1194. //-----------------------------------------------------------------------------
  1195. void SimObject::onGroupAdd()
  1196. {
  1197. }
  1198. //-----------------------------------------------------------------------------
  1199. void SimObject::onGroupRemove()
  1200. {
  1201. }
  1202. //-----------------------------------------------------------------------------
  1203. void SimObject::onDeleteNotify(SimObject*)
  1204. {
  1205. }
  1206. //-----------------------------------------------------------------------------
  1207. void SimObject::onNameChange(const char*)
  1208. {
  1209. }
  1210. //-----------------------------------------------------------------------------
  1211. void SimObject::onStaticModified(const char* slotName, const char* newValue)
  1212. {
  1213. }
  1214. //-----------------------------------------------------------------------------
  1215. void SimObject::onDynamicModified(const char* slotName, const char* newValue)
  1216. {
  1217. }
  1218. //=============================================================================
  1219. // Notifications.
  1220. //=============================================================================
  1221. // MARK: ---- Notifications ----
  1222. static Chunker<SimObject::Notify> notifyChunker(128000);
  1223. SimObject::Notify *SimObject::mNotifyFreeList = NULL;
  1224. //-----------------------------------------------------------------------------
  1225. SimObject::Notify *SimObject::allocNotify()
  1226. {
  1227. if(mNotifyFreeList)
  1228. {
  1229. SimObject::Notify *ret = mNotifyFreeList;
  1230. mNotifyFreeList = ret->next;
  1231. return ret;
  1232. }
  1233. return notifyChunker.alloc();
  1234. }
  1235. //-----------------------------------------------------------------------------
  1236. void SimObject::freeNotify(SimObject::Notify* note)
  1237. {
  1238. AssertFatal(note->type != SimObject::Notify::Invalid, "Invalid notify");
  1239. note->type = SimObject::Notify::Invalid;
  1240. note->next = mNotifyFreeList;
  1241. mNotifyFreeList = note;
  1242. }
  1243. //-----------------------------------------------------------------------------
  1244. SimObject::Notify* SimObject::removeNotify(void *ptr, SimObject::Notify::Type type)
  1245. {
  1246. Notify **list = &mNotifyList;
  1247. while(*list)
  1248. {
  1249. if((*list)->ptr == ptr && (*list)->type == type)
  1250. {
  1251. SimObject::Notify *ret = *list;
  1252. *list = ret->next;
  1253. return ret;
  1254. }
  1255. list = &((*list)->next);
  1256. }
  1257. return NULL;
  1258. }
  1259. //-----------------------------------------------------------------------------
  1260. void SimObject::deleteNotify(SimObject* obj)
  1261. {
  1262. AssertFatal(!obj->isDeleted(),
  1263. "SimManager::deleteNotify: Object is being deleted");
  1264. Notify *note = allocNotify();
  1265. note->ptr = (void *) this;
  1266. note->next = obj->mNotifyList;
  1267. note->type = Notify::DeleteNotify;
  1268. obj->mNotifyList = note;
  1269. note = allocNotify();
  1270. note->ptr = (void *) obj;
  1271. note->next = mNotifyList;
  1272. note->type = Notify::ClearNotify;
  1273. mNotifyList = note;
  1274. //obj->deleteNotifyList.pushBack(this);
  1275. //clearNotifyList.pushBack(obj);
  1276. }
  1277. //-----------------------------------------------------------------------------
  1278. void SimObject::registerReference(SimObject **ptr)
  1279. {
  1280. Notify *note = allocNotify();
  1281. note->ptr = (void *) ptr;
  1282. note->next = mNotifyList;
  1283. note->type = Notify::ObjectRef;
  1284. mNotifyList = note;
  1285. }
  1286. //-----------------------------------------------------------------------------
  1287. void SimObject::unregisterReference(SimObject **ptr)
  1288. {
  1289. Notify *note = removeNotify((void *) ptr, Notify::ObjectRef);
  1290. if(note)
  1291. {
  1292. freeNotify(note);
  1293. if( mFlags.test( AutoDelete ) )
  1294. {
  1295. for( Notify* n = mNotifyList; n != NULL; n = n->next )
  1296. if( n->type == Notify::ObjectRef )
  1297. return;
  1298. deleteObject();
  1299. }
  1300. }
  1301. }
  1302. //-----------------------------------------------------------------------------
  1303. void SimObject::clearNotify(SimObject* obj)
  1304. {
  1305. Notify *note = obj->removeNotify((void *) this, Notify::DeleteNotify);
  1306. if(note)
  1307. freeNotify(note);
  1308. note = removeNotify((void *) obj, Notify::ClearNotify);
  1309. if(note)
  1310. freeNotify(note);
  1311. }
  1312. //-----------------------------------------------------------------------------
  1313. void SimObject::processDeleteNotifies()
  1314. {
  1315. // clear out any delete notifies and
  1316. // object refs.
  1317. while(mNotifyList)
  1318. {
  1319. Notify *note = mNotifyList;
  1320. mNotifyList = note->next;
  1321. AssertFatal(note->type != Notify::ClearNotify, "Clear notes should be all gone.");
  1322. if(note->type == Notify::DeleteNotify)
  1323. {
  1324. SimObject *obj = (SimObject *) note->ptr;
  1325. Notify *cnote = obj->removeNotify((void *)this, Notify::ClearNotify);
  1326. obj->onDeleteNotify(this);
  1327. freeNotify(cnote);
  1328. }
  1329. else
  1330. {
  1331. // it must be an object ref - a pointer refs this object
  1332. *((SimObject **) note->ptr) = NULL;
  1333. }
  1334. freeNotify(note);
  1335. }
  1336. }
  1337. //-----------------------------------------------------------------------------
  1338. void SimObject::clearAllNotifications()
  1339. {
  1340. for(Notify **cnote = &mNotifyList; *cnote; )
  1341. {
  1342. Notify *temp = *cnote;
  1343. if(temp->type == Notify::ClearNotify)
  1344. {
  1345. *cnote = temp->next;
  1346. Notify *note = ((SimObject *) temp->ptr)->removeNotify((void *) this, Notify::DeleteNotify);
  1347. freeNotify(temp);
  1348. if ( note )
  1349. freeNotify(note);
  1350. }
  1351. else
  1352. cnote = &(temp->next);
  1353. }
  1354. }
  1355. //=============================================================================
  1356. // Namespaces.
  1357. //=============================================================================
  1358. // MARK: ---- Namespaces ----
  1359. //-----------------------------------------------------------------------------
  1360. void SimObject::linkNamespaces()
  1361. {
  1362. // Don't link if we already have a namespace linkage in place.
  1363. // If you want to change namespace linking, first call unlinkNamespaces()
  1364. // while still having the class namespace fields matching the current
  1365. // setup.
  1366. if (mNameSpace)
  1367. {
  1368. Con::warnf("SimObject::linkNamespaces -- Namespace linkage already in place %s", mNameSpace->getName());
  1369. return;
  1370. }
  1371. // Get the namespace for the C++ class.
  1372. Namespace* cppNamespace = getClassRep()->getNameSpace();
  1373. // Parent namespace defaults to namespace of C++ class.
  1374. Namespace* parentNamespace = cppNamespace;
  1375. // Perform superclass linking, if requested.
  1376. if( mSuperClassName && mSuperClassName[ 0 ] )
  1377. {
  1378. // Look up the superclass namespace.
  1379. Namespace* superClassNamespace = Con::lookupNamespace( mSuperClassName );
  1380. // If packages are active and adding to the superclass namespace, then we will
  1381. // have multiple packages in a parent chain that all have the same name.
  1382. // Con::lookupNamespace returns the bottom-most package in the chain to us so
  1383. // in order to properly link namespace here without conflicting with the package
  1384. // mechanism, we need to properly link child namespaces to the bottom-most namespace
  1385. // while linking parent namespaces to the topmost namespace. To find the latter
  1386. // one, we walk up the hierarchy here.
  1387. Namespace* superClassNamespacePackageRoot = superClassNamespace->getPackageRoot();
  1388. // Link the superclass namespace to the C++ class namespace.
  1389. if( superClassNamespacePackageRoot->getParent() == NULL )
  1390. {
  1391. // The superclass namespace isn't linked yet so we just
  1392. // link it to the C++ class namespace and make that our parent.
  1393. // No increasing parent reference counts is needed in this case.
  1394. bool ok = superClassNamespacePackageRoot->classLinkTo( cppNamespace );
  1395. AssertFatal( ok, "SimObject::linkNamespaces - failed to link new namespace to c++ class name" );
  1396. parentNamespace = superClassNamespace;
  1397. }
  1398. else
  1399. {
  1400. // In debug builds, make sure the namespace hierarchy that's been
  1401. // put into place actually makes sense and leads back to the C++
  1402. // class namespace.
  1403. #ifdef TORQUE_DEBUG
  1404. bool foundClassNameNS = false;
  1405. for( Namespace* linkWalk = superClassNamespacePackageRoot->getParent(); linkWalk != NULL;
  1406. linkWalk = linkWalk->getParent() )
  1407. {
  1408. if( linkWalk == cppNamespace )
  1409. {
  1410. foundClassNameNS = true;
  1411. break;
  1412. }
  1413. }
  1414. if( !foundClassNameNS )
  1415. {
  1416. // C++ class namespace not in parent link chain. Warn about it.
  1417. Con::errorf(
  1418. "SimObject::linkNamespaces - cannot link object to superclass %s because c++ class %s is not in the parent namespace chain. Linking object to c++ class.",
  1419. mSuperClassName,
  1420. getClassName()
  1421. );
  1422. // Clear out superclass name so we don't come across it during
  1423. // unlinking.
  1424. mSuperClassName = NULL;
  1425. }
  1426. else
  1427. #endif
  1428. {
  1429. // Super link is ok.
  1430. parentNamespace = superClassNamespace;
  1431. // Now increase the reference count of all namespaces in the parent hierarchy
  1432. // (up to the C++ class).
  1433. for( Namespace* linkWalk = parentNamespace;
  1434. linkWalk != NULL && linkWalk != cppNamespace && linkWalk->getParent() != NULL;
  1435. linkWalk = linkWalk->getParent() )
  1436. {
  1437. // Skip namespaces coming from packages.
  1438. if( linkWalk->getPackage() != NULL )
  1439. continue;
  1440. linkWalk->incRefCountToParent();
  1441. }
  1442. }
  1443. }
  1444. }
  1445. // If class name is set, link it in as the new parent
  1446. // which itself inherits from the current parent.
  1447. if( mClassName && mClassName[ 0 ] )
  1448. {
  1449. Namespace* classNamespace = Con::lookupNamespace( mClassName );
  1450. if( classNamespace && classNamespace->classLinkTo( parentNamespace ) )
  1451. {
  1452. parentNamespace = classNamespace;
  1453. }
  1454. else
  1455. {
  1456. // Clear out class name so we don't perform a bogus unlink
  1457. // in unlinkNamespaces().
  1458. mClassName = NULL;
  1459. }
  1460. }
  1461. // Finally, if we have an object name, link its namespace
  1462. // as the child to the current parent namespace and let it
  1463. // become the final namespace of this object.
  1464. StringTableEntry objectName = getName();
  1465. if( objectName && objectName[ 0 ] )
  1466. {
  1467. Namespace* objectNamespace = Con::lookupNamespace( objectName );
  1468. if( objectNamespace && objectNamespace->classLinkTo( parentNamespace ) )
  1469. {
  1470. parentNamespace = objectNamespace;
  1471. }
  1472. }
  1473. // Store our namespace.
  1474. mNameSpace = parentNamespace;
  1475. }
  1476. //-----------------------------------------------------------------------------
  1477. void SimObject::unlinkNamespaces()
  1478. {
  1479. if( !mNameSpace )
  1480. return;
  1481. Namespace* cppNamespace = getClassRep()->getNameSpace();
  1482. Namespace* parentNamespace = cppNamespace;
  1483. // Handle superclass.
  1484. if( mSuperClassName && mSuperClassName[ 0 ] )
  1485. {
  1486. // Get the superclass namespace.
  1487. Namespace* superClassNamespace = Con::lookupNamespace( mSuperClassName );
  1488. // Make it the parent namespace.
  1489. parentNamespace = superClassNamespace;
  1490. // Decrease parent refcounts on the superclass hierarchy.
  1491. for( Namespace* linkWalk = superClassNamespace;
  1492. linkWalk != NULL && linkWalk != cppNamespace && linkWalk->getParent() != NULL; )
  1493. {
  1494. // Store the parent link since it may disappear once we
  1495. // decrease the reference count.
  1496. Namespace* parent = linkWalk->getParent();
  1497. // Decrease the refcount.
  1498. if( linkWalk->getPackage() == NULL ) // Skip namespaces coming from packages.
  1499. linkWalk->decRefCountToParent();
  1500. // Walk up.
  1501. linkWalk = parent;
  1502. }
  1503. }
  1504. // Handle class.
  1505. if( mClassName && mClassName[ 0 ] )
  1506. {
  1507. Namespace* classNamespace = Con::lookupNamespace( mClassName );
  1508. if( classNamespace )
  1509. {
  1510. classNamespace->decRefCountToParent();
  1511. parentNamespace = classNamespace;
  1512. }
  1513. }
  1514. // Handle object name.
  1515. StringTableEntry objectName = getName();
  1516. if( objectName && objectName[ 0 ] )
  1517. mNameSpace->decRefCountToParent();
  1518. mNameSpace = NULL;
  1519. }
  1520. //-----------------------------------------------------------------------------
  1521. void SimObject::setClassNamespace( const char *classNamespace )
  1522. {
  1523. StringTableEntry oldClassNamespace = mClassName;
  1524. StringTableEntry newClassNamespace = StringTable->insert( classNamespace );
  1525. if( oldClassNamespace == newClassNamespace )
  1526. return;
  1527. if( isProperlyAdded() )
  1528. unlinkNamespaces();
  1529. mClassName = newClassNamespace;
  1530. if( isProperlyAdded() )
  1531. {
  1532. linkNamespaces();
  1533. // Restore old namespace setup if linkage failed.
  1534. if( mClassName != newClassNamespace )
  1535. {
  1536. mClassName = oldClassNamespace;
  1537. linkNamespaces();
  1538. }
  1539. }
  1540. }
  1541. //-----------------------------------------------------------------------------
  1542. void SimObject::setSuperClassNamespace( const char *superClassNamespace )
  1543. {
  1544. StringTableEntry oldSuperClassNamespace = mSuperClassName;
  1545. StringTableEntry newSuperClassNamespace = StringTable->insert( superClassNamespace );
  1546. if( oldSuperClassNamespace == newSuperClassNamespace )
  1547. return;
  1548. if( isProperlyAdded() )
  1549. unlinkNamespaces();
  1550. mSuperClassName = newSuperClassNamespace;
  1551. if( isProperlyAdded() )
  1552. {
  1553. linkNamespaces();
  1554. // Restore old setup if linkage failed.
  1555. if( mSuperClassName != newSuperClassNamespace )
  1556. {
  1557. mSuperClassName = oldSuperClassNamespace;
  1558. linkNamespaces();
  1559. }
  1560. }
  1561. }
  1562. //=============================================================================
  1563. // Misc.
  1564. //=============================================================================
  1565. // MARK: ---- Misc ----
  1566. //-----------------------------------------------------------------------------
  1567. void SimObject::setInternalName( const char* newname )
  1568. {
  1569. if( newname )
  1570. mInternalName = StringTable->insert( newname );
  1571. else
  1572. mInternalName = StringTable->EmptyString();
  1573. }
  1574. //-----------------------------------------------------------------------------
  1575. void SimObject::setOriginalName( const char* originalName )
  1576. {
  1577. if( originalName )
  1578. mOriginalName = StringTable->insert( originalName );
  1579. else
  1580. mOriginalName = StringTable->EmptyString();
  1581. }
  1582. //-----------------------------------------------------------------------------
  1583. const char *SimObject::tabComplete(const char *prevText, S32 baseLen, bool fForward)
  1584. {
  1585. return mNameSpace->tabComplete(prevText, baseLen, fForward);
  1586. }
  1587. //-----------------------------------------------------------------------------
  1588. void SimObject::setSelected( bool sel )
  1589. {
  1590. if( mFlags.test( Selected ) == sel )
  1591. return; // No change.
  1592. if( sel )
  1593. {
  1594. mFlags.set( Selected );
  1595. _onSelected();
  1596. }
  1597. else
  1598. {
  1599. mFlags.clear( Selected );
  1600. _onUnselected();
  1601. }
  1602. }
  1603. //-----------------------------------------------------------------------------
  1604. bool SimObject::isSelectedRecursive() const
  1605. {
  1606. const SimObject *walk = this;
  1607. while ( walk )
  1608. {
  1609. if ( walk->isSelected() )
  1610. return true;
  1611. walk = walk->getGroup();
  1612. }
  1613. return false;
  1614. }
  1615. //-----------------------------------------------------------------------------
  1616. void SimObject::setLocked( bool b )
  1617. {
  1618. if( b )
  1619. mFlags.set( Locked );
  1620. else
  1621. mFlags.clear( Locked );
  1622. }
  1623. //-----------------------------------------------------------------------------
  1624. void SimObject::setHidden( bool b )
  1625. {
  1626. if( b )
  1627. mFlags.set( Hidden );
  1628. else
  1629. mFlags.clear( Hidden );
  1630. }
  1631. //-----------------------------------------------------------------------------
  1632. void SimObject::setCopySource( SimObject* object )
  1633. {
  1634. if( mCopySource )
  1635. mCopySource->unregisterReference( &mCopySource );
  1636. mCopySource = object;
  1637. if( mCopySource )
  1638. mCopySource->registerReference( &mCopySource );
  1639. }
  1640. //---------------------------------------------------------------------------
  1641. bool SimObject::_setCanSave( void* object, const char* index, const char* data )
  1642. {
  1643. SimObject* obj = reinterpret_cast< SimObject* >( object );
  1644. obj->setCanSave( dAtob( data ) );
  1645. return false;
  1646. }
  1647. //-----------------------------------------------------------------------------
  1648. const char* SimObject::_getCanSave( void* object, const char* data )
  1649. {
  1650. SimObject* obj = reinterpret_cast< SimObject* >( object );
  1651. if( obj->getCanSave() )
  1652. return "1";
  1653. else
  1654. return "0";
  1655. }
  1656. //---------------------------------------------------------------------------
  1657. // Copy SimObject to another SimObject (Originally designed for T2D).
  1658. void SimObject::copyTo( SimObject* object )
  1659. {
  1660. object->mClassName = mClassName;
  1661. object->mSuperClassName = mSuperClassName;
  1662. linkNamespaces();
  1663. }
  1664. //-----------------------------------------------------------------------------
  1665. bool SimObject::setProtectedParent( void *obj, const char *index, const char *data )
  1666. {
  1667. SimGroup *parent = NULL;
  1668. SimObject *object = static_cast<SimObject*>(obj);
  1669. if(Sim::findObject(data, parent))
  1670. parent->addObject(object);
  1671. // always return false, because we've set mGroup when we called addObject
  1672. return false;
  1673. }
  1674. //-----------------------------------------------------------------------------
  1675. bool SimObject::setProtectedName(void *obj, const char *index, const char *data)
  1676. {
  1677. SimObject *object = static_cast<SimObject*>(obj);
  1678. if ( object->isProperlyAdded() )
  1679. object->assignName( data );
  1680. // always return false because we assign the name here
  1681. return false;
  1682. }
  1683. //-----------------------------------------------------------------------------
  1684. void SimObject::inspectPreApply()
  1685. {
  1686. }
  1687. //-----------------------------------------------------------------------------
  1688. void SimObject::inspectPostApply()
  1689. {
  1690. }
  1691. //-----------------------------------------------------------------------------
  1692. String SimObject::_getLogMessage(const char* fmt, va_list args) const
  1693. {
  1694. String objClass = "UnknownClass";
  1695. if(getClassRep())
  1696. objClass = getClassRep()->getClassName();
  1697. String objName = getName();
  1698. if(objName.isEmpty())
  1699. objName = "Unnamed";
  1700. String formattedMessage = String::VToString(fmt, args);
  1701. return String::ToString("%s - %s(%i) - %s",
  1702. objClass.c_str(), objName.c_str(), getId(), formattedMessage.c_str());
  1703. }
  1704. //=============================================================================
  1705. // API.
  1706. //=============================================================================
  1707. // MARK: ---- API ----
  1708. //-----------------------------------------------------------------------------
  1709. DefineEngineMethod( SimObject, dumpGroupHierarchy, void, (),,
  1710. "Dump the hierarchy of this object up to RootGroup to the console." )
  1711. {
  1712. object->dumpGroupHierarchy();
  1713. }
  1714. //-----------------------------------------------------------------------------
  1715. DefineConsoleMethod( SimObject, isMethod, bool, ( const char* methodName ),,
  1716. "Test whether the given method is defined on this object.\n"
  1717. "@param The name of the method.\n"
  1718. "@return True if the object implements the given method." )
  1719. {
  1720. return object->isMethod( methodName );
  1721. }
  1722. //-----------------------------------------------------------------------------
  1723. DefineEngineMethod( SimObject, isChildOfGroup, bool, ( SimGroup* group ),,
  1724. "Test whether the object belongs directly or indirectly to the given group.\n"
  1725. "@param group The SimGroup object.\n"
  1726. "@return True if the object is a child of the given group or a child of a group that the given group is directly or indirectly a child to." )
  1727. {
  1728. return object->isChildOfGroup( group );
  1729. }
  1730. //-----------------------------------------------------------------------------
  1731. DefineConsoleMethod( SimObject, getClassNamespace, const char*, (),,
  1732. "Get the name of the class namespace assigned to this object.\n"
  1733. "@return The name of the 'class' namespace." )
  1734. {
  1735. return object->getClassNamespace();
  1736. }
  1737. //-----------------------------------------------------------------------------
  1738. DefineConsoleMethod( SimObject, getSuperClassNamespace, const char*, (),,
  1739. "Get the name of the superclass namespace assigned to this object.\n"
  1740. "@return The name of the 'superClass' namespace." )
  1741. {
  1742. return object->getSuperClassNamespace();
  1743. }
  1744. //-----------------------------------------------------------------------------
  1745. DefineConsoleMethod( SimObject, setClassNamespace, void, ( const char* name ),,
  1746. "Assign a class namespace to this object.\n"
  1747. "@param name The name of the 'class' namespace for this object." )
  1748. {
  1749. object->setClassNamespace( name );
  1750. }
  1751. //-----------------------------------------------------------------------------
  1752. DefineConsoleMethod( SimObject, setSuperClassNamespace, void, ( const char* name ),,
  1753. "Assign a superclass namespace to this object.\n"
  1754. "@param name The name of the 'superClass' namespace for this object." )
  1755. {
  1756. object->setSuperClassNamespace( name );
  1757. }
  1758. //-----------------------------------------------------------------------------
  1759. DefineEngineMethod( SimObject, isSelected, bool, (),,
  1760. "Get whether the object has been marked as selected. (in editor)\n"
  1761. "@return True if the object is currently selected." )
  1762. {
  1763. return object->isSelected();
  1764. }
  1765. //-----------------------------------------------------------------------------
  1766. DefineEngineMethod( SimObject, setIsSelected, void, ( bool state ), ( true ),
  1767. "Set whether the object has been marked as selected. (in editor)\n"
  1768. "@param state True if object is to be marked selected; false if not." )
  1769. {
  1770. object->setSelected( state );
  1771. }
  1772. //-----------------------------------------------------------------------------
  1773. DefineConsoleMethod( SimObject, isExpanded, bool, (),,
  1774. "Get whether the object has been marked as expanded. (in editor)\n"
  1775. "@return True if the object is marked expanded." )
  1776. {
  1777. return object->isExpanded();
  1778. }
  1779. //-----------------------------------------------------------------------------
  1780. DefineConsoleMethod( SimObject, setIsExpanded, void, ( bool state ), ( true ),
  1781. "Set whether the object has been marked as expanded. (in editor)\n"
  1782. "@param state True if the object is to be marked expanded; false if not." )
  1783. {
  1784. object->setExpanded( state );
  1785. }
  1786. //-----------------------------------------------------------------------------
  1787. DefineConsoleMethod( SimObject, getFilename, const char*, (),,
  1788. "Returns the filename the object is attached to.\n"
  1789. "@return The name of the file the object is associated with; usually the file the object was loaded from." )
  1790. {
  1791. return object->getFilename();
  1792. }
  1793. //-----------------------------------------------------------------------------
  1794. DefineConsoleMethod( SimObject, setFilename, void, ( const char* fileName ),,
  1795. "Sets the object's file name and path\n"
  1796. "@param fileName The name of the file to associate this object with." )
  1797. {
  1798. return object->setFilename( fileName );
  1799. }
  1800. //-----------------------------------------------------------------------------
  1801. DefineConsoleMethod( SimObject, getDeclarationLine, S32, (),,
  1802. "Get the line number at which the object is defined in its file.\n\n"
  1803. "@return The line number of the object's definition in script.\n"
  1804. "@see getFilename()")
  1805. {
  1806. return object->getDeclarationLine();
  1807. }
  1808. //-----------------------------------------------------------------------------
  1809. #ifdef TORQUE_DEBUG
  1810. static const char* sEnumCallbackFunction;
  1811. static void sEnumCallback( EngineObject* object )
  1812. {
  1813. SimObject* simObject = dynamic_cast< SimObject* >( object );
  1814. if( !simObject )
  1815. return;
  1816. Con::evaluatef( "%s( %i );", sEnumCallbackFunction, simObject->getId() );
  1817. }
  1818. DefineEngineFunction( debugEnumInstances, void, ( const char* className, const char* functionName ),,
  1819. "Call the given function for each instance of the given class.\n"
  1820. "@param className Name of the class for which to enumerate instances.\n"
  1821. "@param functionName Name of function to call and pass each instance of the given class.\n"
  1822. "@note This function is only available in debug builds and primarily meant as an aid in debugging."
  1823. "@ingroup Console")
  1824. {
  1825. sEnumCallbackFunction = functionName;
  1826. ConsoleObject::debugEnumInstances( className, sEnumCallback );
  1827. }
  1828. #endif
  1829. //-----------------------------------------------------------------------------
  1830. DefineConsoleMethod( SimObject, assignFieldsFrom, void, ( SimObject* fromObject ),,
  1831. "Copy fields from another object onto this one. The objects must "
  1832. "be of same type. Everything from the object will overwrite what's "
  1833. "in this object; extra fields in this object will remain. This "
  1834. "includes dynamic fields.\n"
  1835. "@param fromObject The object from which to copy fields." )
  1836. {
  1837. if( fromObject )
  1838. object->assignFieldsFrom( fromObject );
  1839. }
  1840. //-----------------------------------------------------------------------------
  1841. DefineEngineMethod( SimObject, assignPersistentId, void, (),,
  1842. "Assign a persistent ID to the object if it does not already have one." )
  1843. {
  1844. object->getOrCreatePersistentId();
  1845. }
  1846. //-----------------------------------------------------------------------------
  1847. DefineConsoleMethod( SimObject, getCanSave, bool, (),,
  1848. "Get whether the object will be included in saves.\n"
  1849. "@return True if the object will be saved; false otherwise." )
  1850. {
  1851. return object->getCanSave();
  1852. }
  1853. //-----------------------------------------------------------------------------
  1854. DefineConsoleMethod( SimObject, setCanSave, void, ( bool value ), ( true ),
  1855. "Set whether the object will be included in saves.\n"
  1856. "@param value If true, the object will be included in saves; if false, it will be excluded." )
  1857. {
  1858. object->setCanSave( value );
  1859. }
  1860. //-----------------------------------------------------------------------------
  1861. DefineEngineMethod( SimObject, isEditorOnly, bool, (),,
  1862. "Return true if the object is only used by the editor.\n"
  1863. "@return True if this object exists only for the sake of editing." )
  1864. {
  1865. return object->isEditorOnly();
  1866. }
  1867. //-----------------------------------------------------------------------------
  1868. DefineEngineMethod( SimObject, setEditorOnly, void, ( bool value ), ( true ),
  1869. "Set/clear the editor-only flag on this object.\n"
  1870. "@param value If true, the object is marked as existing only for the editor." )
  1871. {
  1872. object->setEditorOnly( value );
  1873. }
  1874. //-----------------------------------------------------------------------------
  1875. DefineEngineMethod( SimObject, isNameChangeAllowed, bool, (),,
  1876. "Get whether this object may be renamed.\n"
  1877. "@return True if this object can be renamed; false otherwise." )
  1878. {
  1879. return object->isNameChangeAllowed();
  1880. }
  1881. //-----------------------------------------------------------------------------
  1882. DefineEngineMethod( SimObject, setNameChangeAllowed, void, ( bool value ), ( true ),
  1883. "Set whether this object can be renamed from its first name.\n"
  1884. "@param value If true, renaming is allowed for this object; if false, trying to change the name of the object will generate a console error." )
  1885. {
  1886. object->setNameChangeAllowed( value );
  1887. }
  1888. //-----------------------------------------------------------------------------
  1889. DefineEngineMethod( SimObject, clone, SimObject*, (),,
  1890. "Create a copy of this object.\n"
  1891. "@return An exact duplicate of this object." )
  1892. {
  1893. return object->clone();
  1894. }
  1895. //-----------------------------------------------------------------------------
  1896. DefineEngineMethod( SimObject, deepClone, SimObject*, (),,
  1897. "Create a copy of this object and all its subobjects.\n"
  1898. "@return An exact duplicate of this object and all objects it references." )
  1899. {
  1900. return object->deepClone();
  1901. }
  1902. //-----------------------------------------------------------------------------
  1903. DefineEngineMethod( SimObject, setLocked, void, ( bool value ), ( true ),
  1904. "Lock/unlock the object in the editor.\n"
  1905. "@param value If true, the object will be locked; if false, the object will be unlocked." )
  1906. {
  1907. object->setLocked( value );
  1908. }
  1909. //-----------------------------------------------------------------------------
  1910. DefineEngineMethod( SimObject, setHidden, void, ( bool value ), ( true ),
  1911. "Hide/unhide the object.\n"
  1912. "@param value If true, the object will be hidden; if false, the object will be unhidden." )
  1913. {
  1914. object->setHidden( value );
  1915. }
  1916. //-----------------------------------------------------------------------------
  1917. DefineConsoleMethod( SimObject, dumpMethods, ArrayObject*, (),,
  1918. "List the methods defined on this object.\n\n"
  1919. "Each description is a newline-separated vector with the following elements:\n"
  1920. "- Minimum number of arguments.\n"
  1921. "- Maximum number of arguments.\n"
  1922. "- Prototype string.\n"
  1923. "- Full script file path (if script method).\n"
  1924. "- Line number of method definition in script (if script method).\n\n"
  1925. "- Documentation string (not including prototype). This takes up the remainder of the vector.\n"
  1926. "@return An ArrayObject populated with (name,description) pairs of all methods defined on the object." )
  1927. {
  1928. Namespace *ns = object->getNamespace();
  1929. if( !ns )
  1930. return 0;
  1931. ArrayObject* dictionary = new ArrayObject();
  1932. dictionary->registerObject();
  1933. VectorPtr<Namespace::Entry *> vec(__FILE__, __LINE__);
  1934. ns->getEntryList(&vec);
  1935. for(Vector< Namespace::Entry* >::iterator j = vec.begin(); j != vec.end(); j++)
  1936. {
  1937. Namespace::Entry* e = *j;
  1938. if( e->mType < 0 )
  1939. continue;
  1940. StringBuilder str;
  1941. str.append( String::ToString( e->mMinArgs ) );
  1942. str.append( '\n' );
  1943. str.append( String::ToString( e->mMaxArgs ) );
  1944. str.append( '\n' );
  1945. str.append( e->getPrototypeString() );
  1946. str.append( '\n' );
  1947. if( e->mCode && e->mCode->fullPath )
  1948. str.append( e->mCode->fullPath );
  1949. str.append( '\n' );
  1950. if( e->mCode )
  1951. str.append( String::ToString( e->mFunctionLineNumber ) );
  1952. str.append( '\n' );
  1953. String docs = e->getDocString();
  1954. if( !docs.isEmpty() )
  1955. str.append( docs );
  1956. dictionary->push_back( e->mFunctionName, str.end() );
  1957. }
  1958. return dictionary;
  1959. }
  1960. //-----------------------------------------------------------------------------
  1961. namespace {
  1962. S32 QSORT_CALLBACK compareFields( const void* a,const void* b )
  1963. {
  1964. const AbstractClassRep::Field* fa = *((const AbstractClassRep::Field**)a);
  1965. const AbstractClassRep::Field* fb = *((const AbstractClassRep::Field**)b);
  1966. return dStricmp(fa->pFieldname, fb->pFieldname);
  1967. }
  1968. struct DocString
  1969. {
  1970. char mPadding[ 8 ];
  1971. String mPrototype;
  1972. String mDescription;
  1973. const char* mReturnType;
  1974. DocString( Namespace::Entry* entry )
  1975. : mPrototype( entry->getArgumentsString() ),
  1976. mDescription( entry->getBriefDescription() )
  1977. {
  1978. mReturnType = " ";
  1979. mPadding[ 0 ] = 0;
  1980. if( entry->mType == -4 )
  1981. {
  1982. //TODO: need to have script callbacks set up proper return type info
  1983. }
  1984. else
  1985. {
  1986. switch( entry->mType )
  1987. {
  1988. case Namespace::Entry::StringCallbackType:
  1989. mReturnType = "string";
  1990. mPadding[ 0 ] = ' ';
  1991. mPadding[ 1 ] = ' ';
  1992. mPadding[ 2 ] = 0;
  1993. break;
  1994. case Namespace::Entry::IntCallbackType:
  1995. mReturnType = "int";
  1996. mPadding[ 0 ] = ' ';
  1997. mPadding[ 1 ] = ' ';
  1998. mPadding[ 2 ] = ' ';
  1999. mPadding[ 3 ] = ' ';
  2000. mPadding[ 4 ] = ' ';
  2001. mPadding[ 5 ] = 0;
  2002. break;
  2003. case Namespace::Entry::FloatCallbackType:
  2004. mReturnType = "float";
  2005. mPadding[ 0 ] = ' ';
  2006. mPadding[ 1 ] = ' ';
  2007. mPadding[ 2 ] = ' ';
  2008. mPadding[ 3 ] = 0;
  2009. break;
  2010. case Namespace::Entry::VoidCallbackType:
  2011. mReturnType = "void";
  2012. mPadding[ 0 ] = ' ';
  2013. mPadding[ 1 ] = ' ';
  2014. mPadding[ 2 ] = ' ';
  2015. mPadding[ 3 ] = ' ';
  2016. mPadding[ 4 ] = 0;
  2017. break;
  2018. case Namespace::Entry::BoolCallbackType:
  2019. mReturnType = "bool";
  2020. mPadding[ 0 ] = ' ';
  2021. mPadding[ 1 ] = ' ';
  2022. mPadding[ 2 ] = ' ';
  2023. mPadding[ 3 ] = ' ';
  2024. mPadding[ 4 ] = 0;
  2025. break;
  2026. }
  2027. }
  2028. }
  2029. };
  2030. }
  2031. DefineEngineMethod( SimObject, dump, void, ( bool detailed ), ( false ),
  2032. "Dump a description of all fields and methods defined on this object to the console.\n"
  2033. "@param detailed Whether to print detailed information about members." )
  2034. {
  2035. Con::printf( "Class: %s", object->getClassName() );
  2036. const AbstractClassRep::FieldList &list = object->getFieldList();
  2037. char expandedBuffer[4096];
  2038. Con::printf( "Static Fields:" );
  2039. Vector<const AbstractClassRep::Field *> flist(__FILE__, __LINE__);
  2040. for(U32 i = 0; i < list.size(); i++)
  2041. flist.push_back(&list[i]);
  2042. dQsort(flist.address(),flist.size(),sizeof(AbstractClassRep::Field *),compareFields);
  2043. for(Vector<const AbstractClassRep::Field *>::iterator itr = flist.begin(); itr != flist.end(); itr++)
  2044. {
  2045. const AbstractClassRep::Field* f = *itr;
  2046. // The special field types can be skipped.
  2047. if ( f->type >= AbstractClassRep::ARCFirstCustomField )
  2048. continue;
  2049. for(U32 j = 0; S32(j) < f->elementCount; j++)
  2050. {
  2051. // [neo, 07/05/2007 - #3000]
  2052. // Some objects use dummy vars and projected fields so make sure we call the get functions
  2053. //const char *val = Con::getData(f->type, (void *) (((const char *)object) + f->offset), j, f->table, f->flag);
  2054. const char *val = (*f->getDataFn)( object, Con::getData(f->type, (void *) (((const char *)object) + f->offset), j, f->table, f->flag) );// + typeSizes[fld.type] * array1));
  2055. ConsoleBaseType* conType = ConsoleBaseType::getType( f->type );
  2056. const char* conTypeName = "<unknown>";
  2057. if( conType )
  2058. conTypeName = conType->getTypeClassName();
  2059. if( !val /*|| !*val*/ )
  2060. continue;
  2061. if( f->elementCount == 1 )
  2062. dSprintf( expandedBuffer, sizeof( expandedBuffer ), " %s %s = \"", conTypeName, f->pFieldname );
  2063. else
  2064. dSprintf( expandedBuffer, sizeof( expandedBuffer ), " %s %s[ %d ] = \"", conTypeName, f->pFieldname, j );
  2065. expandEscape( expandedBuffer + dStrlen(expandedBuffer), val);
  2066. Con::printf( "%s\"", expandedBuffer );
  2067. if( detailed && f->pFieldDocs && f->pFieldDocs[ 0 ] )
  2068. Con::printf( " %s", f->pFieldDocs );
  2069. }
  2070. }
  2071. // If the object is a datablock with substitution statements,
  2072. // they get printed out as part of the dump.
  2073. if (dynamic_cast<SimDataBlock*>(object))
  2074. {
  2075. if (((SimDataBlock*)object)->getSubstitutionCount() > 0)
  2076. {
  2077. Con::printf("Substitution Fields:");
  2078. ((SimDataBlock*)object)->printSubstitutions();
  2079. }
  2080. }
  2081. Con::printf( "Dynamic Fields:" );
  2082. if(object->getFieldDictionary())
  2083. object->getFieldDictionary()->printFields(object);
  2084. Con::printf( "Methods:" );
  2085. Namespace *ns = object->getNamespace();
  2086. VectorPtr<Namespace::Entry *> vec(__FILE__, __LINE__);
  2087. if(ns)
  2088. ns->getEntryList(&vec);
  2089. bool sawCBs = false;
  2090. for(Vector<Namespace::Entry *>::iterator j = vec.begin(); j != vec.end(); j++)
  2091. {
  2092. Namespace::Entry *e = *j;
  2093. if(e->mType == Namespace::Entry::ScriptCallbackType)
  2094. sawCBs = true;
  2095. if(e->mType < 0)
  2096. continue;
  2097. DocString doc( e );
  2098. Con::printf( " %s%s%s%s", doc.mReturnType, doc.mPadding, e->mFunctionName, doc.mPrototype.c_str() );
  2099. if( detailed && !doc.mDescription.isEmpty() )
  2100. Con::printf( " %s", doc.mDescription.c_str() );
  2101. }
  2102. if( sawCBs )
  2103. {
  2104. Con::printf( "Callbacks:" );
  2105. for(Vector<Namespace::Entry *>::iterator j = vec.begin(); j != vec.end(); j++)
  2106. {
  2107. Namespace::Entry *e = *j;
  2108. if(e->mType != Namespace::Entry::ScriptCallbackType)
  2109. continue;
  2110. DocString doc( e );
  2111. Con::printf( " %s%s%s%s", doc.mReturnType, doc.mPadding, e->cb.mCallbackName, doc.mPrototype.c_str() );
  2112. if( detailed && !doc.mDescription.isEmpty() )
  2113. Con::printf( " %s", doc.mDescription.c_str() );
  2114. }
  2115. }
  2116. }
  2117. //-----------------------------------------------------------------------------
  2118. DefineConsoleMethod( SimObject, save, bool, ( const char* fileName, bool selectedOnly, const char* preAppendString ), ( false, "" ),
  2119. "Save out the object to the given file.\n"
  2120. "@param fileName The name of the file to save to."
  2121. "@param selectedOnly If true, only objects marked as selected will be saved out.\n"
  2122. "@param preAppendString Text which will be preprended directly to the object serialization.\n"
  2123. "@param True on success, false on failure." )
  2124. {
  2125. return object->save( fileName, selectedOnly, preAppendString );
  2126. }
  2127. //-----------------------------------------------------------------------------
  2128. DefineEngineMethod( SimObject, setName, void, ( const char* newName ),,
  2129. "Set the global name of the object.\n"
  2130. "@param newName The new global name to assign to the object.\n"
  2131. "@note If name changing is disallowed on the object, the method will fail with a console error." )
  2132. {
  2133. object->assignName( newName );
  2134. }
  2135. //-----------------------------------------------------------------------------
  2136. DefineEngineMethod( SimObject, getName, const char*, (),,
  2137. "Get the global name of the object.\n"
  2138. "@return The global name assigned to the object." )
  2139. {
  2140. const char *ret = object->getName();
  2141. return ret ? ret : "";
  2142. }
  2143. //-----------------------------------------------------------------------------
  2144. DefineConsoleMethod( SimObject, getClassName, const char*, (),,
  2145. "Get the name of the C++ class which the object is an instance of.\n"
  2146. "@return The name of the C++ class of the object." )
  2147. {
  2148. const char *ret = object->getClassName();
  2149. return ret ? ret : "";
  2150. }
  2151. //-----------------------------------------------------------------------------
  2152. DefineConsoleMethod( SimObject, isField, bool, ( const char* fieldName ),,
  2153. "Test whether the given field is defined on this object.\n"
  2154. "@param fieldName The name of the field.\n"
  2155. "@return True if the object implements the given field." )
  2156. {
  2157. return object->isField( fieldName );
  2158. }
  2159. //-----------------------------------------------------------------------------
  2160. DefineConsoleMethod( SimObject, getFieldValue, const char*, ( const char* fieldName, S32 index ), ( -1 ),
  2161. "Return the value of the given field on this object.\n"
  2162. "@param fieldName The name of the field. If it includes a field index, the index is parsed out.\n"
  2163. "@param index Optional parameter to specify the index of an array field separately.\n"
  2164. "@return The value of the given field or \"\" if undefined." )
  2165. {
  2166. char fieldNameBuffer[ 1024 ];
  2167. char arrayIndexBuffer[ 64 ];
  2168. // Parse out index if the field is given in the form of 'name[index]'.
  2169. const char* arrayIndex = NULL;
  2170. const U32 nameLen = dStrlen( fieldName );
  2171. if( fieldName[ nameLen - 1 ] == ']' )
  2172. {
  2173. const char* leftBracket = dStrchr( fieldName, '[' );
  2174. const char* rightBracket = &fieldName[ nameLen - 1 ];
  2175. const U32 fieldNameLen = getMin( U32( leftBracket - fieldName ), sizeof( fieldNameBuffer ) - 1 );
  2176. const U32 arrayIndexLen = getMin( U32( rightBracket - leftBracket - 1 ), sizeof( arrayIndexBuffer ) - 1 );
  2177. dMemcpy( fieldNameBuffer, fieldName, fieldNameLen );
  2178. dMemcpy( arrayIndexBuffer, leftBracket + 1, arrayIndexLen );
  2179. fieldNameBuffer[ fieldNameLen ] = '\0';
  2180. arrayIndexBuffer[ arrayIndexLen ] = '\0';
  2181. fieldName = fieldNameBuffer;
  2182. arrayIndex = arrayIndexBuffer;
  2183. }
  2184. fieldName = StringTable->insert( fieldName );
  2185. if( index != -1 )
  2186. {
  2187. dSprintf( arrayIndexBuffer, sizeof( arrayIndexBuffer ), "%i", index );
  2188. arrayIndex = arrayIndexBuffer;
  2189. }
  2190. return object->getDataField( fieldName, arrayIndex );
  2191. }
  2192. //-----------------------------------------------------------------------------
  2193. DefineConsoleMethod( SimObject, setFieldValue, bool, ( const char* fieldName, const char* value, S32 index ), ( -1 ),
  2194. "Set the value of the given field on this object.\n"
  2195. "@param fieldName The name of the field to assign to. If it includes an array index, the index will be parsed out.\n"
  2196. "@param value The new value to assign to the field.\n"
  2197. "@param index Optional argument to specify an index for an array field.\n"
  2198. "@return True." )
  2199. {
  2200. char fieldNameBuffer[ 1024 ];
  2201. char arrayIndexBuffer[ 64 ];
  2202. // Parse out index if the field is given in the form of 'name[index]'.
  2203. const char* arrayIndex = NULL;
  2204. const U32 nameLen = dStrlen( fieldName );
  2205. if( fieldName[ nameLen - 1 ] == ']' )
  2206. {
  2207. const char* leftBracket = dStrchr( fieldName, '[' );
  2208. const char* rightBracket = &fieldName[ nameLen - 1 ];
  2209. const U32 fieldNameLen = getMin( U32( leftBracket - fieldName ), sizeof( fieldNameBuffer ) - 1 );
  2210. const U32 arrayIndexLen = getMin( U32( rightBracket - leftBracket - 1 ), sizeof( arrayIndexBuffer ) - 1 );
  2211. dMemcpy( fieldNameBuffer, fieldName, fieldNameLen );
  2212. dMemcpy( arrayIndexBuffer, leftBracket + 1, arrayIndexLen );
  2213. fieldNameBuffer[ fieldNameLen ] = '\0';
  2214. arrayIndexBuffer[ arrayIndexLen ] = '\0';
  2215. fieldName = fieldNameBuffer;
  2216. arrayIndex = arrayIndexBuffer;
  2217. }
  2218. fieldName = StringTable->insert( fieldName );
  2219. if( index != -1 )
  2220. {
  2221. dSprintf( arrayIndexBuffer, sizeof( arrayIndexBuffer ), "%i", index );
  2222. arrayIndex = arrayIndexBuffer;
  2223. }
  2224. object->setDataField( fieldName, arrayIndex, value );
  2225. return true;
  2226. }
  2227. //-----------------------------------------------------------------------------
  2228. DefineConsoleMethod( SimObject, getFieldType, const char*, ( const char* fieldName ),,
  2229. "Get the console type code of the given field.\n"
  2230. "@return The numeric type code for the underlying console type of the given field." )
  2231. {
  2232. U32 typeID = object->getDataFieldType( StringTable->insert( fieldName ), NULL );
  2233. ConsoleBaseType* type = ConsoleBaseType::getType( typeID );
  2234. if( type )
  2235. return type->getTypeName();
  2236. return "";
  2237. }
  2238. //-----------------------------------------------------------------------------
  2239. DefineConsoleMethod( SimObject, setFieldType, void, ( const char* fieldName, const char* type ),,
  2240. "Set the console type code for the given field.\n"
  2241. "@param fieldName The name of the dynamic field to change to type for.\n"
  2242. "@param type The name of the console type.\n"
  2243. "@note This only works for dynamic fields. Types of static fields cannot be changed." )
  2244. {
  2245. object->setDataFieldType( type, StringTable->insert( fieldName ), NULL );
  2246. }
  2247. //-----------------------------------------------------------------------------
  2248. ConsoleMethod( SimObject, call, const char*, 3, 0, "( string method, string args... ) Dynamically call a method on an object.\n"
  2249. "@param method Name of method to call.\n"
  2250. "@param args Zero or more arguments for the method.\n"
  2251. "@return The result of the method call." )
  2252. {
  2253. argv[1] = argv[2];
  2254. return Con::execute( object, argc - 1, argv + 1 );
  2255. }
  2256. //-----------------------------------------------------------------------------
  2257. DefineEngineMethod( SimObject, setInternalName, void, ( const char* newInternalName ),,
  2258. "Set the internal name of the object.\n"
  2259. "@param newInternalName The new internal name for the object." )
  2260. {
  2261. object->setInternalName( newInternalName );
  2262. }
  2263. //-----------------------------------------------------------------------------
  2264. DefineEngineMethod( SimObject, getInternalName, const char*, (),,
  2265. "Get the internal name of the object.\n"
  2266. "@return The internal name of the object." )
  2267. {
  2268. return object->getInternalName();
  2269. }
  2270. //-----------------------------------------------------------------------------
  2271. DefineConsoleMethod( SimObject, dumpClassHierarchy, void, (),,
  2272. "Dump the native C++ class hierarchy of this object's C++ class to the console." )
  2273. {
  2274. object->dumpClassHierarchy();
  2275. }
  2276. //-----------------------------------------------------------------------------
  2277. DefineConsoleMethod( SimObject, isMemberOfClass, bool, ( const char* className ),,
  2278. "Test whether this object is a member of the specified class.\n"
  2279. "@param className Name of a native C++ class.\n"
  2280. "@return True if this object is an instance of the given C++ class or any of its super classes." )
  2281. {
  2282. AbstractClassRep* pRep = object->getClassRep();
  2283. while(pRep)
  2284. {
  2285. if( !dStricmp(pRep->getClassName(), className ) )
  2286. {
  2287. //matches
  2288. return true;
  2289. }
  2290. pRep = pRep->getParentClass();
  2291. }
  2292. return false;
  2293. }
  2294. //-----------------------------------------------------------------------------
  2295. DefineConsoleMethod( SimObject, isInNamespaceHierarchy, bool, ( const char* name ),,
  2296. "Test whether the namespace of this object is a direct or indirect child to the given namespace.\n"
  2297. "@param name The name of a namespace.\n"
  2298. "@return True if the given namespace name is within the namespace hierarchy of this object." )
  2299. {
  2300. Namespace* nspace = object->getNamespace();
  2301. while( nspace && dStricmp( nspace->mName, name ) != 0 )
  2302. nspace = nspace->mParent;
  2303. return ( nspace != NULL );
  2304. }
  2305. //-----------------------------------------------------------------------------
  2306. DefineEngineMethod( SimObject, getId, S32, (),,
  2307. "Get the underlying unique numeric ID of the object.\n"
  2308. "@note Object IDs are unique only during single engine runs.\n"
  2309. "@return The unique numeric ID of the object." )
  2310. {
  2311. return object->getId();
  2312. }
  2313. //-----------------------------------------------------------------------------
  2314. DefineEngineMethod( SimObject, getGroup, SimGroup*, (),,
  2315. "Get the group that this object is contained in.\n"
  2316. "@note If not assigned to particular SimGroup, an object belongs to RootGroup.\n"
  2317. "@return The SimGroup object to which the object belongs." )
  2318. {
  2319. return object->getGroup();
  2320. }
  2321. //-----------------------------------------------------------------------------
  2322. DefineConsoleMethod( SimObject, delete, void, (),,
  2323. "Delete and remove the object." )
  2324. {
  2325. object->deleteObject();
  2326. }
  2327. //-----------------------------------------------------------------------------
  2328. ConsoleMethod( SimObject,schedule, S32, 4, 0, "( float time, string method, string args... ) Delay an invocation of a method.\n"
  2329. "@param time The number of milliseconds after which to invoke the method. This is a soft limit.\n"
  2330. "@param method The method to call.\n"
  2331. "@param args The arguments with which to call the method.\n"
  2332. "@return The numeric ID of the created schedule. Can be used to cancel the call.\n" )
  2333. {
  2334. U32 timeDelta = U32(dAtof(argv[2]));
  2335. argv[2] = argv[3];
  2336. argv[3] = argv[1];
  2337. SimConsoleEvent *evt = new SimConsoleEvent(argc - 2, argv + 2, true);
  2338. S32 ret = Sim::postEvent(object, evt, Sim::getCurrentTime() + timeDelta);
  2339. // #ifdef DEBUG
  2340. // Con::printf("obj %s schedule(%s) = %d", argv[3], argv[2], ret);
  2341. // Con::executef( "backtrace");
  2342. // #endif
  2343. return ret;
  2344. }
  2345. //-----------------------------------------------------------------------------
  2346. DefineConsoleMethod( SimObject, getDynamicFieldCount, S32, (),,
  2347. "Get the number of dynamic fields defined on the object.\n"
  2348. "@return The number of dynamic fields defined on the object." )
  2349. {
  2350. S32 count = 0;
  2351. SimFieldDictionary* fieldDictionary = object->getFieldDictionary();
  2352. for (SimFieldDictionaryIterator itr(fieldDictionary); *itr; ++itr)
  2353. count++;
  2354. return count;
  2355. }
  2356. //-----------------------------------------------------------------------------
  2357. DefineConsoleMethod( SimObject, getDynamicField, const char*, ( S32 index ),,
  2358. "Get a value of a dynamic field by index.\n"
  2359. "@param index The index of the dynamic field.\n"
  2360. "@return The value of the dynamic field at the given index or \"\"." )
  2361. {
  2362. SimFieldDictionary* fieldDictionary = object->getFieldDictionary();
  2363. SimFieldDictionaryIterator itr(fieldDictionary);
  2364. for (S32 i = 0; i < index; i++)
  2365. {
  2366. if (!(*itr))
  2367. {
  2368. Con::warnf("Invalid dynamic field index passed to SimObject::getDynamicField!");
  2369. return NULL;
  2370. }
  2371. ++itr;
  2372. }
  2373. static const U32 bufSize = 256;
  2374. char* buffer = Con::getReturnBuffer(bufSize);
  2375. if (*itr)
  2376. {
  2377. SimFieldDictionary::Entry* entry = *itr;
  2378. dSprintf(buffer, bufSize, "%s\t%s", entry->slotName, entry->value);
  2379. return buffer;
  2380. }
  2381. Con::warnf("Invalid dynamic field index passed to SimObject::getDynamicField!");
  2382. return NULL;
  2383. }
  2384. //-----------------------------------------------------------------------------
  2385. DefineConsoleMethod( SimObject, getFieldCount, S32, (),,
  2386. "Get the number of static fields on the object.\n"
  2387. "@return The number of static fields defined on the object." )
  2388. {
  2389. const AbstractClassRep::FieldList &list = object->getFieldList();
  2390. const AbstractClassRep::Field* f;
  2391. U32 numDummyEntries = 0;
  2392. for(S32 i = 0; i < list.size(); i++)
  2393. {
  2394. f = &list[i];
  2395. // The special field types do not need to be counted.
  2396. if ( f->type >= AbstractClassRep::ARCFirstCustomField )
  2397. numDummyEntries++;
  2398. }
  2399. return list.size() - numDummyEntries;
  2400. }
  2401. //-----------------------------------------------------------------------------
  2402. DefineConsoleMethod( SimObject, getField, const char*, ( S32 index ),,
  2403. "Retrieve the value of a static field by index.\n"
  2404. "@param index The index of the static field.\n"
  2405. "@return The value of the static field with the given index or \"\"." )
  2406. {
  2407. const AbstractClassRep::FieldList &list = object->getFieldList();
  2408. if( ( index < 0 ) || ( index >= list.size() ) )
  2409. return "";
  2410. const AbstractClassRep::Field* f;
  2411. S32 currentField = 0;
  2412. for ( U32 i = 0; i < list.size() && currentField <= index; i++ )
  2413. {
  2414. f = &list[i];
  2415. // The special field types can be skipped.
  2416. if ( f->type >= AbstractClassRep::ARCFirstCustomField )
  2417. continue;
  2418. if(currentField == index)
  2419. return f->pFieldname;
  2420. currentField++;
  2421. }
  2422. // if we found nada, return nada.
  2423. return "";
  2424. }
  2425. //-----------------------------------------------------------------------------
  2426. #ifdef TORQUE_DEBUG
  2427. DefineEngineMethod( SimObject, getDebugInfo, ArrayObject*, (),,
  2428. "Return some behind-the-scenes information on the object.\n"
  2429. "@return An ArrayObject filled with internal information about the object." )
  2430. {
  2431. ArrayObject* array = new ArrayObject();
  2432. array->registerObject();
  2433. array->push_back( "C++|Address", String::ToString( "0x%x", object ) );
  2434. array->push_back( "C++|Size", String::ToString( object->getClassRep()->getSizeof() ) );
  2435. array->push_back( "Object|Description", object->describeSelf() );
  2436. array->push_back( "Object|FileName", object->getFilename() );
  2437. array->push_back( "Object|DeclarationLine", String::ToString( object->getDeclarationLine() ) );
  2438. array->push_back( "Object|CopySource", object->getCopySource() ?
  2439. String::ToString( "%i:%s (%s)", object->getCopySource()->getId(), object->getCopySource()->getClassName(), object->getCopySource()->getName() ) : "" );
  2440. array->push_back( "Flag|EditorOnly", object->isEditorOnly() ? "true" : "false" );
  2441. array->push_back( "Flag|NameChangeAllowed", object->isNameChangeAllowed() ? "true" : "false" );
  2442. array->push_back( "Flag|AutoDelete", object->isAutoDeleted() ? "true" : "false" );
  2443. array->push_back( "Flag|Selected", object->isSelected() ? "true" : "false" );
  2444. array->push_back( "Flag|Expanded", object->isExpanded() ? "true" : "false" );
  2445. array->push_back( "Flag|ModStaticFields", object->canModStaticFields() ? "true" : "false" );
  2446. array->push_back( "Flag|ModDynamicFields", object->canModDynamicFields() ? "true" : "false" );
  2447. array->push_back( "Flag|CanSave", object->getCanSave() ? "true" : "false" );
  2448. #ifndef TORQUE_DISABLE_MEMORY_MANAGER
  2449. Memory::Info memInfo;
  2450. Memory::getMemoryInfo( object, memInfo );
  2451. array->push_back( "Memory|AllocNumber", String::ToString( memInfo.mAllocNumber ) );
  2452. array->push_back( "Memory|AllocSize", String::ToString( memInfo.mAllocSize ) );
  2453. array->push_back( "Memory|AllocFile", memInfo.mFileName );
  2454. array->push_back( "Memory|AllocLine", String::ToString( memInfo.mLineNumber ) );
  2455. array->push_back( "Memory|IsGlobal", memInfo.mIsGlobal ? "true" : "false" );
  2456. array->push_back( "Memory|IsStatic", memInfo.mIsStatic ? "true" : "false" );
  2457. #endif
  2458. return array;
  2459. }
  2460. #endif