2
0

simObject.cpp 114 KB

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