simObject.cpp 99 KB

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