simObject.cpp 100 KB

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