simObject.cpp 105 KB

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