simObject.cpp 112 KB

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