simObject.cpp 86 KB

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