Entity.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "T3D/Entity.h"
  24. #include "core/stream/bitStream.h"
  25. #include "console/consoleTypes.h"
  26. #include "console/consoleObject.h"
  27. #include "sim/netConnection.h"
  28. #include "scene/sceneRenderState.h"
  29. #include "scene/sceneManager.h"
  30. #include "T3D/gameBase/gameProcess.h"
  31. #include "console/engineAPI.h"
  32. #include "T3D/gameBase/gameConnection.h"
  33. #include "math/mathIO.h"
  34. #include "math/mTransform.h"
  35. #include "T3D/Components/coreInterfaces.h"
  36. #include "T3D/Components/render/renderComponentInterface.h"
  37. #include "T3D/Components/Collision/collisionInterfaces.h"
  38. #include "gui/controls/guiTreeViewCtrl.h"
  39. #include "console/consoleInternal.h"
  40. #include "T3D/gameBase/std/stdMoveList.h"
  41. #include "T3D/prefab.h"
  42. //
  43. #include "gfx/sim/debugDraw.h"
  44. //
  45. extern bool gEditingMission;
  46. // Client prediction
  47. static F32 sMinWarpTicks = 0.5f; // Fraction of tick at which instant warp occurs
  48. static S32 sMaxWarpTicks = 3; // Max warp duration in ticks
  49. static S32 sMaxPredictionTicks = 30; // Number of ticks to predict
  50. IMPLEMENT_CO_NETOBJECT_V1(Entity);
  51. ConsoleDocClass(Entity,
  52. "@brief Base Entity class.\n\n"
  53. "Entity is typically made up of a shape and up to two particle emitters. In most cases Entity objects are "
  54. "not created directly. They are usually produced automatically by other means, such as through the Explosion "
  55. "class. When an explosion goes off, its ExplosionData datablock determines what Entity to emit.\n"
  56. "@tsexample\n"
  57. "datablock ExplosionData(GrenadeLauncherExplosion)\n"
  58. "{\n"
  59. " // Assiging Entity data\n"
  60. " Entity = GrenadeEntity;\n\n"
  61. " // Adjust how Entity is ejected\n"
  62. " EntityThetaMin = 10;\n"
  63. " EntityThetaMax = 60;\n"
  64. " EntityNum = 4;\n"
  65. " EntityNumVariance = 2;\n"
  66. " EntityVelocity = 25;\n"
  67. " EntityVelocityVariance = 5;\n\n"
  68. " // Note: other ExplosionData properties are not listed for this example\n"
  69. "};\n"
  70. "@endtsexample\n\n"
  71. "@note Entity are client side only objects.\n"
  72. "@see EntityData\n"
  73. "@see ExplosionData\n"
  74. "@see Explosion\n"
  75. "@ingroup FX\n"
  76. );
  77. Entity::Entity()
  78. {
  79. //mTypeMask |= DynamicShapeObjectType | StaticObjectType | ;
  80. mTypeMask |= EntityObjectType;
  81. mNetFlags.set(Ghostable | ScopeAlways);
  82. mPos = Point3F(0, 0, 0);
  83. mRot = Point3F(0, 0, 0);
  84. mDelta.pos = mDelta.posVec = Point3F::Zero;
  85. mDelta.rot[0].identity();
  86. mDelta.rot[1].identity();
  87. mDelta.warpOffset.set(0.0f, 0.0f, 0.0f);
  88. mDelta.warpTicks = mDelta.warpCount = 0;
  89. mDelta.dt = 1.0f;
  90. mDelta.move = NullMove;
  91. mComponents.clear();
  92. mStartComponentUpdate = false;
  93. mInitialized = false;
  94. }
  95. Entity::~Entity()
  96. {
  97. }
  98. void Entity::initPersistFields()
  99. {
  100. Parent::initPersistFields();
  101. removeField("DataBlock");
  102. addGroup("Transform");
  103. removeField("Position");
  104. addProtectedField("Position", TypePoint3F, Offset(mPos, Entity), &_setPosition, &_getPosition, "Object world orientation.");
  105. removeField("Rotation");
  106. addProtectedField("Rotation", TypeRotationF, Offset(mRot, Entity), &_setRotation, &_getRotation, "Object world orientation.");
  107. //These are basically renamed mountPos/Rot. pretty much there for conveinence
  108. addField("LocalPosition", TypeMatrixPosition, Offset(mMount.xfm, Entity), "Position we are mounted at ( object space of our mount object ).");
  109. addField("LocalRotation", TypeMatrixRotation, Offset(mMount.xfm, Entity), "Rotation we are mounted at ( object space of our mount object ).");
  110. endGroup("Transform");
  111. }
  112. //
  113. bool Entity::_setPosition(void *object, const char *index, const char *data)
  114. {
  115. Entity* so = static_cast<Entity*>(object);
  116. if (so)
  117. {
  118. Point3F pos;
  119. if (!dStrcmp(data, ""))
  120. pos = Point3F(0, 0, 0);
  121. else
  122. Con::setData(TypePoint3F, &pos, 0, 1, &data);
  123. so->setTransform(pos, so->mRot);
  124. }
  125. return false;
  126. }
  127. const char * Entity::_getPosition(void* obj, const char* data)
  128. {
  129. Entity* so = static_cast<Entity*>(obj);
  130. if (so)
  131. {
  132. Point3F pos = so->getPosition();
  133. static const U32 bufSize = 256;
  134. char* returnBuffer = Con::getReturnBuffer(bufSize);
  135. dSprintf(returnBuffer, bufSize, "%g %g %g", pos.x, pos.y, pos.z);
  136. return returnBuffer;
  137. }
  138. return "0 0 0";
  139. }
  140. bool Entity::_setRotation(void *object, const char *index, const char *data)
  141. {
  142. Entity* so = static_cast<Entity*>(object);
  143. if (so)
  144. {
  145. RotationF rot;
  146. Con::setData(TypeRotationF, &rot, 0, 1, &data);
  147. //so->mRot = rot;
  148. //MatrixF mat = rot.asMatrixF();
  149. //mat.setPosition(so->getPosition());
  150. //so->setTransform(mat);
  151. so->setTransform(so->getPosition(), rot);
  152. }
  153. return false;
  154. }
  155. const char * Entity::_getRotation(void* obj, const char* data)
  156. {
  157. Entity* so = static_cast<Entity*>(obj);
  158. if (so)
  159. {
  160. EulerF eulRot = so->mRot.asEulerF();
  161. static const U32 bufSize = 256;
  162. char* returnBuffer = Con::getReturnBuffer(bufSize);
  163. dSprintf(returnBuffer, bufSize, "%g %g %g", mRadToDeg(eulRot.x), mRadToDeg(eulRot.y), mRadToDeg(eulRot.z));
  164. return returnBuffer;
  165. }
  166. return "0 0 0";
  167. }
  168. bool Entity::onAdd()
  169. {
  170. if (!Parent::onAdd())
  171. return false;
  172. mObjBox = Box3F(Point3F(-1, -1, -1), Point3F(1, 1, 1));
  173. resetWorldBox();
  174. setObjectBox(mObjBox);
  175. addToScene();
  176. //Make sure we get positioned
  177. setMaskBits(TransformMask);
  178. return true;
  179. }
  180. void Entity::onRemove()
  181. {
  182. clearComponents(false);
  183. removeFromScene();
  184. onDataSet.removeAll();
  185. Parent::onRemove();
  186. }
  187. void Entity::onPostAdd()
  188. {
  189. mInitialized = true;
  190. //everything's done and added. go ahead and initialize the components
  191. for (U32 i = 0; i < mComponents.size(); i++)
  192. {
  193. mComponents[i]->onComponentAdd();
  194. }
  195. if (isMethod("onAdd"))
  196. Con::executef(this, "onAdd");
  197. }
  198. void Entity::setDataField(StringTableEntry slotName, const char *array, const char *value)
  199. {
  200. Parent::setDataField(slotName, array, value);
  201. onDataSet.trigger(this, slotName, value);
  202. }
  203. void Entity::onStaticModified(const char* slotName, const char* newValue)
  204. {
  205. Parent::onStaticModified(slotName, newValue);
  206. onDataSet.trigger(this, slotName, newValue);
  207. }
  208. //Updating
  209. void Entity::processTick(const Move* move)
  210. {
  211. if (!isHidden())
  212. {
  213. if (mDelta.warpCount < mDelta.warpTicks)
  214. {
  215. mDelta.warpCount++;
  216. // Set new pos.
  217. mObjToWorld.getColumn(3, &mDelta.pos);
  218. mDelta.pos += mDelta.warpOffset;
  219. mDelta.rot[0] = mDelta.rot[1];
  220. mDelta.rot[1].interpolate(mDelta.warpRot[0], mDelta.warpRot[1], F32(mDelta.warpCount) / mDelta.warpTicks);
  221. setTransform(mDelta.pos, mDelta.rot[1]);
  222. // Pos backstepping
  223. mDelta.posVec.x = -mDelta.warpOffset.x;
  224. mDelta.posVec.y = -mDelta.warpOffset.y;
  225. mDelta.posVec.z = -mDelta.warpOffset.z;
  226. }
  227. else
  228. {
  229. if (isMounted())
  230. {
  231. MatrixF mat;
  232. mMount.object->getMountTransform(mMount.node, mMount.xfm, &mat);
  233. Parent::setTransform(mat);
  234. Parent::setRenderTransform(mat);
  235. }
  236. else
  237. {
  238. if (!move)
  239. {
  240. if (isGhost())
  241. {
  242. // If we haven't run out of prediction time,
  243. // predict using the last known move.
  244. if (mPredictionCount-- <= 0)
  245. return;
  246. move = &mDelta.move;
  247. }
  248. else
  249. {
  250. move = &NullMove;
  251. }
  252. }
  253. }
  254. }
  255. Move prevMove = lastMove;
  256. if (move != NULL)
  257. lastMove = *move;
  258. else
  259. lastMove = NullMove;
  260. if (move && isServerObject())
  261. {
  262. if ((move->y != 0 || prevMove.y != 0)
  263. || (move->x != 0 || prevMove.x != 0)
  264. || (move->z != 0 || prevMove.x != 0))
  265. {
  266. if (isMethod("moveVectorEvent"))
  267. Con::executef(this, "moveVectorEvent", move->x, move->y, move->z);
  268. }
  269. if (move->yaw != 0)
  270. {
  271. if (isMethod("moveYawEvent"))
  272. Con::executef(this, "moveYawEvent", move->yaw);
  273. }
  274. if (move->pitch != 0)
  275. {
  276. if (isMethod("movePitchEvent"))
  277. Con::executef(this, "movePitchEvent", move->pitch);
  278. }
  279. if (move->roll != 0)
  280. {
  281. if (isMethod("moveRollEvent"))
  282. Con::executef(this, "moveRollEvent", move->roll);
  283. }
  284. for (U32 i = 0; i < MaxTriggerKeys; i++)
  285. {
  286. if (move->trigger[i] != prevMove.trigger[i])
  287. {
  288. if (isMethod("moveTriggerEvent"))
  289. Con::executef(this, "moveTriggerEvent", i, move->trigger[i]);
  290. }
  291. }
  292. }
  293. if (isMethod("processTick"))
  294. Con::executef(this, "processTick");
  295. }
  296. }
  297. void Entity::advanceTime(F32 dt)
  298. {
  299. }
  300. void Entity::interpolateTick(F32 dt)
  301. {
  302. if (dt == 0.0f)
  303. {
  304. setRenderTransform(mDelta.pos, mDelta.rot[1]);
  305. }
  306. else
  307. {
  308. QuatF rot;
  309. rot.interpolate(mDelta.rot[1], mDelta.rot[0], dt);
  310. Point3F pos = mDelta.pos + mDelta.posVec * dt;
  311. setRenderTransform(pos, rot);
  312. }
  313. mDelta.dt = dt;
  314. }
  315. //Render
  316. void Entity::prepRenderImage(SceneRenderState *state)
  317. {
  318. }
  319. //Networking
  320. U32 Entity::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  321. {
  322. U32 retMask = Parent::packUpdate(con, mask, stream);
  323. if (stream->writeFlag(mask & TransformMask))
  324. {
  325. //mathWrite( *stream, getScale() );
  326. //stream->writeAffineTransform(mObjToWorld);
  327. //mathWrite(*stream, getPosition());
  328. mathWrite(*stream, mPos);
  329. //mathWrite(*stream, getRotation());
  330. mathWrite(*stream, getRotation().asEulerF());
  331. mDelta.move.pack(stream);
  332. stream->writeFlag(!(mask & NoWarpMask));
  333. }
  334. /*if (stream->writeFlag(mask & MountedMask))
  335. {
  336. mathWrite(*stream, mMount.xfm.getPosition());
  337. mathWrite(*stream, mMount.xfm.toEuler());
  338. }*/
  339. if (stream->writeFlag(mask & BoundsMask))
  340. {
  341. mathWrite(*stream, mObjBox);
  342. }
  343. //pass our behaviors around
  344. if (mask & ComponentsMask || mask & InitialUpdateMask)
  345. {
  346. stream->writeFlag(true);
  347. //now, we run through a list of our to-be-sent behaviors and begin sending them
  348. //if any fail, we keep our list and re-queue the mask
  349. S32 componentCount = mToLoadComponents.size();
  350. //build our 'ready' list
  351. //This requires both the instance and the instances' template to be prepped(if the template hasn't been ghosted,
  352. //then we know we shouldn't be passing the instance's ghosts around yet)
  353. U32 ghostedCompCnt = 0;
  354. for (U32 i = 0; i < componentCount; i++)
  355. {
  356. if (con->getGhostIndex(mToLoadComponents[i]) != -1)
  357. ghostedCompCnt++;
  358. }
  359. if (ghostedCompCnt != 0)
  360. {
  361. stream->writeFlag(true);
  362. stream->writeFlag(mStartComponentUpdate);
  363. //if not all the behaviors have been ghosted, we'll need another pass
  364. if (ghostedCompCnt != componentCount)
  365. retMask |= ComponentsMask;
  366. //write the currently ghosted behavior count
  367. stream->writeInt(ghostedCompCnt, 16);
  368. for (U32 i = 0; i < mToLoadComponents.size(); i++)
  369. {
  370. //now fetch them and pass the ghost
  371. S32 ghostIndex = con->getGhostIndex(mToLoadComponents[i]);
  372. if (ghostIndex != -1)
  373. {
  374. stream->writeInt(ghostIndex, NetConnection::GhostIdBitSize);
  375. mToLoadComponents.erase(i);
  376. i--;
  377. mStartComponentUpdate = false;
  378. }
  379. }
  380. }
  381. else if (componentCount)
  382. {
  383. //on the odd chance we have behaviors to ghost, but NONE of them have been yet, just set the flag now
  384. stream->writeFlag(false);
  385. retMask |= ComponentsMask;
  386. }
  387. else
  388. stream->writeFlag(false);
  389. }
  390. else
  391. stream->writeFlag(false);
  392. return retMask;
  393. }
  394. void Entity::unpackUpdate(NetConnection *con, BitStream *stream)
  395. {
  396. Parent::unpackUpdate(con, stream);
  397. if (stream->readFlag())
  398. {
  399. /*Point3F scale;
  400. mathRead( *stream, &scale );
  401. setScale( scale);*/
  402. //MatrixF objToWorld;
  403. //stream->readAffineTransform(&objToWorld);
  404. Point3F pos;
  405. mathRead(*stream, &pos);
  406. RotationF rot;
  407. EulerF eRot;
  408. mathRead(*stream, &eRot);
  409. rot = RotationF(eRot);
  410. mDelta.move.unpack(stream);
  411. if (stream->readFlag() && isProperlyAdded())
  412. {
  413. // Determine number of ticks to warp based on the average
  414. // of the client and server velocities.
  415. /*mDelta.warpOffset = pos - mDelta.pos;
  416. F32 dt = mDelta.warpOffset.len() / (0.5f * TickSec);
  417. mDelta.warpTicks = (S32)((dt > sMinWarpTicks) ? getMax(mFloor(dt + 0.5f), 1.0f) : 0.0f);
  418. //F32 as = (speed + mVelocity.len()) * 0.5f * TickSec;
  419. //F32 dt = (as > 0.00001f) ? mDelta.warpOffset.len() / as : sMaxWarpTicks;
  420. //mDelta.warpTicks = (S32)((dt > sMinWarpTicks) ? getMax(mFloor(dt + 0.5f), 1.0f) : 0.0f);
  421. //mDelta.warpTicks = (S32)((dt > sMinWarpTicks) ? getMax(mFloor(dt + 0.5f), 1.0f) : 0.0f);
  422. //mDelta.warpTicks = sMaxWarpTicks;
  423. mDelta.warpTicks = 0;
  424. if (mDelta.warpTicks)
  425. {
  426. // Setup the warp to start on the next tick.
  427. if (mDelta.warpTicks > sMaxWarpTicks)
  428. mDelta.warpTicks = sMaxWarpTicks;
  429. mDelta.warpOffset /= (F32)mDelta.warpTicks;
  430. mDelta.rot[0] = rot.asQuatF();
  431. mDelta.rot[1] = rot.asQuatF();
  432. mDelta.rotOffset = rot.asEulerF() - mDelta.rot.asEulerF();
  433. // Ignore small rotation differences
  434. if (mFabs(mDelta.rotOffset.x) < 0.001f)
  435. mDelta.rotOffset.x = 0;
  436. if (mFabs(mDelta.rotOffset.y) < 0.001f)
  437. mDelta.rotOffset.y = 0;
  438. if (mFabs(mDelta.rotOffset.z) < 0.001f)
  439. mDelta.rotOffset.z = 0;
  440. mDelta.rotOffset /= (F32)mDelta.warpTicks;
  441. }
  442. else
  443. {
  444. // Going to skip the warp, server and client are real close.
  445. // Adjust the frame interpolation to move smoothly to the
  446. // new position within the current tick.
  447. Point3F cp = mDelta.pos + mDelta.posVec * mDelta.dt;
  448. if (mDelta.dt == 0)
  449. {
  450. mDelta.posVec.set(0.0f, 0.0f, 0.0f);
  451. mDelta.rotVec.set(0.0f, 0.0f, 0.0f);
  452. }
  453. else
  454. {
  455. F32 dti = 1.0f / mDelta.dt;
  456. mDelta.posVec = (cp - pos) * dti;
  457. mDelta.rotVec.z = mRot.z - rot.z;
  458. mDelta.rotVec.z *= dti;
  459. }
  460. mDelta.pos = pos;
  461. mDelta.rot = rot;
  462. setTransform(pos, rot);
  463. }*/
  464. Point3F cp = mDelta.pos + mDelta.posVec * mDelta.dt;
  465. mDelta.warpOffset = pos - cp;
  466. // Calc the distance covered in one tick as the average of
  467. // the old speed and the new speed from the server.
  468. VectorF vel = pos - mDelta.pos;
  469. F32 dt, as = vel.len() * 0.5 * TickSec;
  470. // Cal how many ticks it will take to cover the warp offset.
  471. // If it's less than what's left in the current tick, we'll just
  472. // warp in the remaining time.
  473. if (!as || (dt = mDelta.warpOffset.len() / as) > sMaxWarpTicks)
  474. dt = mDelta.dt + sMaxWarpTicks;
  475. else
  476. dt = (dt <= mDelta.dt) ? mDelta.dt : mCeil(dt - mDelta.dt) + mDelta.dt;
  477. // Adjust current frame interpolation
  478. if (mDelta.dt)
  479. {
  480. mDelta.pos = cp + (mDelta.warpOffset * (mDelta.dt / dt));
  481. mDelta.posVec = (cp - mDelta.pos) / mDelta.dt;
  482. QuatF cr;
  483. cr.interpolate(mDelta.rot[1], mDelta.rot[0], mDelta.dt);
  484. mDelta.rot[1].interpolate(cr, pos, mDelta.dt / dt);
  485. mDelta.rot[0].extrapolate(mDelta.rot[1], cr, mDelta.dt);
  486. }
  487. // Calculated multi-tick warp
  488. mDelta.warpCount = 0;
  489. mDelta.warpTicks = (S32)(mFloor(dt));
  490. if (mDelta.warpTicks)
  491. {
  492. mDelta.warpOffset = pos - mDelta.pos;
  493. mDelta.warpOffset /= mDelta.warpTicks;
  494. mDelta.warpRot[0] = mDelta.rot[1];
  495. mDelta.warpRot[1] = rot.asQuatF();
  496. }
  497. }
  498. else
  499. {
  500. // Set the entity to the server position
  501. mDelta.dt = 0;
  502. mDelta.pos = pos;
  503. mDelta.posVec.set(0, 0, 0);
  504. mDelta.rot[1] = mDelta.rot[0] = rot.asQuatF();
  505. mDelta.warpCount = mDelta.warpTicks = 0;
  506. setTransform(pos, rot);
  507. }
  508. }
  509. /*if (stream->readFlag())
  510. {
  511. Point3F mountOffset;
  512. EulerF mountRot;
  513. mathRead(*stream, &mountOffset);
  514. mathRead(*stream, &mountRot);
  515. RotationF rot = RotationF(mountRot);
  516. mountRot = rot.asEulerF(RotationF::Degrees);
  517. setMountOffset(mountOffset);
  518. setMountRotation(mountRot);
  519. }*/
  520. if (stream->readFlag())
  521. {
  522. mathRead(*stream, &mObjBox);
  523. resetWorldBox();
  524. }
  525. if (stream->readFlag())
  526. {
  527. //are we passing any behaviors currently?
  528. if (stream->readFlag())
  529. {
  530. //if we've just started the update, clear our behaviors
  531. if (stream->readFlag())
  532. clearComponents(false);
  533. S32 componentCount = stream->readInt(16);
  534. for (U32 i = 0; i < componentCount; i++)
  535. {
  536. S32 gIndex = stream->readInt(NetConnection::GhostIdBitSize);
  537. addComponent(dynamic_cast<Component*>(con->resolveGhost(gIndex)));
  538. }
  539. }
  540. }
  541. }
  542. //Manipulation
  543. void Entity::setTransform(const MatrixF &mat)
  544. {
  545. //setMaskBits(TransformMask);
  546. setMaskBits(TransformMask | NoWarpMask);
  547. if (isMounted())
  548. {
  549. // Use transform from mounted object
  550. Point3F newPos = mat.getPosition();
  551. Point3F parentPos = mMount.object->getTransform().getPosition();
  552. Point3F newOffset = newPos - parentPos;
  553. if (!newOffset.isZero())
  554. {
  555. //setMountOffset(newOffset);
  556. mPos = newOffset;
  557. }
  558. Point3F matEul = mat.toEuler();
  559. //mRot = Point3F(mRadToDeg(matEul.x), mRadToDeg(matEul.y), mRadToDeg(matEul.z));
  560. if (matEul != Point3F(0, 0, 0))
  561. {
  562. Point3F mountEul = mMount.object->getTransform().toEuler();
  563. Point3F diff = matEul - mountEul;
  564. //setMountRotation(Point3F(mRadToDeg(diff.x), mRadToDeg(diff.y), mRadToDeg(diff.z)));
  565. mRot = diff;
  566. }
  567. else
  568. {
  569. //setMountRotation(Point3F(0, 0, 0));
  570. mRot = Point3F(0, 0, 0);
  571. }
  572. RotationF addRot = mRot + RotationF(mMount.object->getTransform());
  573. MatrixF transf = addRot.asMatrixF();
  574. transf.setPosition(mPos + mMount.object->getPosition());
  575. Parent::setTransform(transf);
  576. }
  577. else
  578. {
  579. //Are we part of a prefab?
  580. /*Prefab* p = Prefab::getPrefabByChild(this);
  581. if (p)
  582. {
  583. //just let our prefab know we moved
  584. p->childTransformUpdated(this, mat);
  585. }*/
  586. //else
  587. {
  588. //mRot.set(mat);
  589. //Parent::setTransform(mat);
  590. RotationF rot = RotationF(mat);
  591. EulerF tempRot = rot.asEulerF(RotationF::Degrees);
  592. Point3F pos;
  593. mat.getColumn(3,&pos);
  594. setTransform(pos, rot);
  595. }
  596. }
  597. }
  598. void Entity::setTransform(Point3F position, RotationF rotation)
  599. {
  600. if (isMounted())
  601. {
  602. mPos = position;
  603. mRot = rotation;
  604. RotationF addRot = mRot + RotationF(mMount.object->getTransform());
  605. MatrixF transf = addRot.asMatrixF();
  606. transf.setPosition(mPos + mMount.object->getPosition());
  607. Parent::setTransform(transf);
  608. setMaskBits(TransformMask);
  609. }
  610. else
  611. {
  612. /*MatrixF newMat, imat, xmat, ymat, zmat;
  613. Point3F radRot = Point3F(mDegToRad(rotation.x), mDegToRad(rotation.y), mDegToRad(rotation.z));
  614. xmat.set(EulerF(radRot.x, 0, 0));
  615. ymat.set(EulerF(0.0f, radRot.y, 0.0f));
  616. zmat.set(EulerF(0, 0, radRot.z));
  617. imat.mul(zmat, xmat);
  618. newMat.mul(imat, ymat);*/
  619. MatrixF newMat = rotation.asMatrixF();
  620. newMat.setColumn(3, position);
  621. mPos = position;
  622. mRot = rotation;
  623. setMaskBits(TransformMask);
  624. //if (isServerObject())
  625. // setMaskBits(TransformMask);
  626. //setTransform(temp);
  627. // This test is a bit expensive so turn it off in release.
  628. #ifdef TORQUE_DEBUG
  629. //AssertFatal( mat.isAffine(), "SceneObject::setTransform() - Bad transform (non affine)!" );
  630. #endif
  631. //PROFILE_SCOPE(Entity_setTransform);
  632. // Update the transforms.
  633. Parent::setTransform(newMat);
  634. onTransformSet.trigger(&newMat);
  635. /*mObjToWorld = mWorldToObj = newMat;
  636. mWorldToObj.affineInverse();
  637. // Update the world-space AABB.
  638. resetWorldBox();
  639. // If we're in a SceneManager, sync our scene state.
  640. if (mSceneManager != NULL)
  641. mSceneManager->notifyObjectDirty(this);
  642. setRenderTransform(newMat);*/
  643. }
  644. }
  645. void Entity::setRenderTransform(const MatrixF &mat)
  646. {
  647. Parent::setRenderTransform(mat);
  648. }
  649. void Entity::setRenderTransform(Point3F position, RotationF rotation)
  650. {
  651. if (isMounted())
  652. {
  653. mPos = position;
  654. mRot = rotation;
  655. RotationF addRot = mRot + RotationF(mMount.object->getTransform());
  656. MatrixF transf = addRot.asMatrixF();
  657. transf.setPosition(mPos + mMount.object->getPosition());
  658. Parent::setRenderTransform(transf);
  659. }
  660. else
  661. {
  662. MatrixF newMat = rotation.asMatrixF();
  663. newMat.setColumn(3, position);
  664. mPos = position;
  665. mRot = rotation;
  666. Parent::setRenderTransform(newMat);
  667. onTransformSet.trigger(&newMat);
  668. }
  669. }
  670. MatrixF Entity::getTransform()
  671. {
  672. if (isMounted())
  673. {
  674. MatrixF mat;
  675. //Use transform from mount
  676. mMount.object->getMountTransform(mMount.node, mMount.xfm, &mat);
  677. Point3F transPos = mat.getPosition() + mPos;
  678. mat.mul(mRot.asMatrixF());
  679. mat.setPosition(transPos);
  680. return mat;
  681. }
  682. else
  683. {
  684. return Parent::getTransform();
  685. }
  686. }
  687. void Entity::setMountOffset(Point3F posOffset)
  688. {
  689. if (isMounted())
  690. {
  691. mMount.xfm.setColumn(3, posOffset);
  692. //mPos = posOffset;
  693. setMaskBits(MountedMask);
  694. }
  695. }
  696. void Entity::setMountRotation(EulerF rotOffset)
  697. {
  698. if (isMounted())
  699. {
  700. MatrixF temp, imat, xmat, ymat, zmat;
  701. Point3F radRot = Point3F(mDegToRad(rotOffset.x), mDegToRad(rotOffset.y), mDegToRad(rotOffset.z));
  702. xmat.set(EulerF(radRot.x, 0, 0));
  703. ymat.set(EulerF(0.0f, radRot.y, 0.0f));
  704. zmat.set(EulerF(0, 0, radRot.z));
  705. imat.mul(zmat, xmat);
  706. temp.mul(imat, ymat);
  707. temp.setColumn(3, mMount.xfm.getPosition());
  708. mMount.xfm = temp;
  709. //mRot = RotationF(temp);
  710. setMaskBits(MountedMask);
  711. }
  712. }
  713. //
  714. void Entity::getCameraTransform(F32* pos, MatrixF* mat)
  715. {
  716. Vector<CameraInterface*> updaters = getComponents<CameraInterface>();
  717. for (Vector<CameraInterface*>::iterator it = updaters.begin(); it != updaters.end(); it++) {
  718. if ((*it)->getCameraTransform(pos, mat)) {
  719. return;
  720. }
  721. }
  722. }
  723. void Entity::getMountTransform(S32 index, const MatrixF &xfm, MatrixF *outMat)
  724. {
  725. RenderComponentInterface* renderInterface = getComponent<RenderComponentInterface>();
  726. if (renderInterface)
  727. {
  728. renderInterface->getShapeInstance()->animate();
  729. S32 nodeCount = renderInterface->getShapeInstance()->getShape()->nodes.size();
  730. if (index >= 0 && index < nodeCount)
  731. {
  732. MatrixF mountTransform = renderInterface->getShapeInstance()->mNodeTransforms[index];
  733. mountTransform.mul(xfm);
  734. const Point3F& scale = getScale();
  735. // The position of the mount point needs to be scaled.
  736. Point3F position = mountTransform.getPosition();
  737. position.convolve(scale);
  738. mountTransform.setPosition(position);
  739. // Also we would like the object to be scaled to the model.
  740. outMat->mul(mObjToWorld, mountTransform);
  741. return;
  742. }
  743. }
  744. // Then let SceneObject handle it.
  745. Parent::getMountTransform(index, xfm, outMat);
  746. }
  747. void Entity::getRenderMountTransform(F32 delta, S32 index, const MatrixF &xfm, MatrixF *outMat)
  748. {
  749. RenderComponentInterface* renderInterface = getComponent<RenderComponentInterface>();
  750. if (renderInterface && renderInterface->getShapeInstance())
  751. {
  752. renderInterface->getShapeInstance()->animate();
  753. S32 nodeCount = renderInterface->getShapeInstance()->getShape()->nodes.size();
  754. if (index >= 0 && index < nodeCount)
  755. {
  756. MatrixF mountTransform = renderInterface->getShapeInstance()->mNodeTransforms[index];
  757. mountTransform.mul(xfm);
  758. const Point3F& scale = getScale();
  759. // The position of the mount point needs to be scaled.
  760. Point3F position = mountTransform.getPosition();
  761. position.convolve(scale);
  762. mountTransform.setPosition(position);
  763. // Also we would like the object to be scaled to the model.
  764. outMat->mul(getRenderTransform(), mountTransform);
  765. return;
  766. }
  767. }
  768. // Then let SceneObject handle it.
  769. Parent::getMountTransform(index, xfm, outMat);
  770. }
  771. void Entity::setForwardVector(VectorF newForward, VectorF upVector)
  772. {
  773. MatrixF mat = getTransform();
  774. VectorF up(0.0f, 0.0f, 1.0f);
  775. VectorF axisX;
  776. VectorF axisY = newForward;
  777. VectorF axisZ;
  778. if (upVector != VectorF::Zero)
  779. up = upVector;
  780. // Validate and normalize input:
  781. F32 lenSq;
  782. lenSq = axisY.lenSquared();
  783. if (lenSq < 0.000001f)
  784. {
  785. axisY.set(0.0f, 1.0f, 0.0f);
  786. Con::errorf("Entity::setForwardVector() - degenerate forward vector");
  787. }
  788. else
  789. {
  790. axisY /= mSqrt(lenSq);
  791. }
  792. lenSq = up.lenSquared();
  793. if (lenSq < 0.000001f)
  794. {
  795. up.set(0.0f, 0.0f, 1.0f);
  796. Con::errorf("SceneObject::setForwardVector() - degenerate up vector - too small");
  797. }
  798. else
  799. {
  800. up /= mSqrt(lenSq);
  801. }
  802. if (fabsf(mDot(up, axisY)) > 0.9999f)
  803. {
  804. Con::errorf("SceneObject::setForwardVector() - degenerate up vector - same as forward");
  805. // i haven't really tested this, but i think it generates something which should be not parallel to the previous vector:
  806. F32 tmp = up.x;
  807. up.x = -up.y;
  808. up.y = up.z;
  809. up.z = tmp;
  810. }
  811. // construct the remaining axes:
  812. mCross(axisY, up, &axisX);
  813. mCross(axisX, axisY, &axisZ);
  814. mat.setColumn(0, axisX);
  815. mat.setColumn(1, axisY);
  816. mat.setColumn(2, axisZ);
  817. setTransform(mat);
  818. }
  819. //
  820. //These basically just redirect to any collision behaviors we have
  821. bool Entity::castRay(const Point3F &start, const Point3F &end, RayInfo* info)
  822. {
  823. Vector<CastRayInterface*> updaters = getComponents<CastRayInterface>();
  824. for (Vector<CastRayInterface*>::iterator it = updaters.begin(); it != updaters.end(); it++)
  825. {
  826. if ((*it)->castRay(start, end, info))
  827. {
  828. return true;
  829. }
  830. }
  831. return false;
  832. }
  833. bool Entity::castRayRendered(const Point3F &start, const Point3F &end, RayInfo *info)
  834. {
  835. Vector<CastRayRenderedInterface*> updaters = getComponents<CastRayRenderedInterface>();
  836. for (Vector<CastRayRenderedInterface*>::iterator it = updaters.begin(); it != updaters.end(); it++)
  837. {
  838. if ((*it)->castRayRendered(start, end, info))
  839. {
  840. return true;
  841. }
  842. }
  843. return false;
  844. }
  845. bool Entity::buildPolyList(PolyListContext context, AbstractPolyList* polyList, const Box3F &box, const SphereF &sphere)
  846. {
  847. Vector<BuildPolyListInterface*> updaters = getComponents<BuildPolyListInterface>();
  848. for (Vector<BuildPolyListInterface*>::iterator it = updaters.begin(); it != updaters.end(); it++)
  849. {
  850. return (*it)->buildPolyList(context, polyList, box, sphere);
  851. }
  852. return false;
  853. }
  854. void Entity::buildConvex(const Box3F& box, Convex* convex)
  855. {
  856. Vector<BuildConvexInterface*> updaters = getComponents<BuildConvexInterface>();
  857. for (Vector<BuildConvexInterface*>::iterator it = updaters.begin(); it != updaters.end(); it++)
  858. {
  859. (*it)->buildConvex(box, convex);
  860. }
  861. }
  862. //
  863. // Mounting and heirarchy manipulation
  864. void Entity::mountObject(SceneObject* objB, MatrixF txfm)
  865. {
  866. Parent::mountObject(objB, -1, txfm);
  867. Parent::addObject(objB);
  868. }
  869. void Entity::mountObject(SceneObject *obj, S32 node, const MatrixF &xfm)
  870. {
  871. Parent::mountObject(obj, node, xfm);
  872. }
  873. void Entity::onMount(SceneObject *obj, S32 node)
  874. {
  875. deleteNotify(obj);
  876. // Are we mounting to a GameBase object?
  877. Entity *entityObj = dynamic_cast<Entity*>(obj);
  878. if (entityObj && entityObj->getControlObject() != this)
  879. processAfter(entityObj);
  880. if (!isGhost()) {
  881. setMaskBits(MountedMask);
  882. //TODO implement this callback
  883. //onMount_callback( this, obj, node );
  884. }
  885. }
  886. void Entity::onUnmount(SceneObject *obj, S32 node)
  887. {
  888. clearNotify(obj);
  889. Entity *entityObj = dynamic_cast<Entity*>(obj);
  890. if (entityObj && entityObj->getControlObject() != this)
  891. clearProcessAfter();
  892. if (!isGhost()) {
  893. setMaskBits(MountedMask);
  894. //TODO implement this callback
  895. //onUnmount_callback( this, obj, node );
  896. }
  897. }
  898. //Heirarchy stuff
  899. void Entity::addObject(SimObject* object)
  900. {
  901. Component* component = dynamic_cast<Component*>(object);
  902. if (component)
  903. {
  904. addComponent(component);
  905. return;
  906. }
  907. Entity* e = dynamic_cast<Entity*>(object);
  908. if (e)
  909. {
  910. MatrixF offset;
  911. //offset.mul(getWorldTransform(), e->getWorldTransform());
  912. //check if we're mounting to a node on a shape we have
  913. String node = e->getDataField("mountNode", NULL);
  914. if (!node.isEmpty())
  915. {
  916. RenderComponentInterface *renderInterface = getComponent<RenderComponentInterface>();
  917. if (renderInterface)
  918. {
  919. TSShape* shape = renderInterface->getShape();
  920. S32 nodeIdx = shape->findNode(node);
  921. mountObject(e, nodeIdx, MatrixF::Identity);
  922. }
  923. else
  924. {
  925. mountObject(e, MatrixF::Identity);
  926. }
  927. }
  928. else
  929. {
  930. /*Point3F posOffset = mPos - e->getPosition();
  931. mPos = posOffset;
  932. RotationF rotOffset = mRot - e->getRotation();
  933. mRot = rotOffset;
  934. setMaskBits(TransformMask);
  935. mountObject(e, MatrixF::Identity);*/
  936. mountObject(e, MatrixF::Identity);
  937. }
  938. //e->setMountOffset(e->getPosition() - getPosition());
  939. //Point3F diff = getWorldTransform().toEuler() - e->getWorldTransform().toEuler();
  940. //e->setMountRotation(Point3F(mRadToDeg(diff.x),mRadToDeg(diff.y),mRadToDeg(diff.z)));
  941. //mountObject(e, offset);
  942. }
  943. else
  944. {
  945. SceneObject* so = dynamic_cast<SceneObject*>(object);
  946. if (so)
  947. {
  948. //get the difference and build it as our offset!
  949. Point3F posOffset = so->getPosition() - mPos;
  950. RotationF rotOffset = RotationF(so->getTransform()) - mRot;
  951. MatrixF offset = rotOffset.asMatrixF();
  952. offset.setPosition(posOffset);
  953. mountObject(so, offset);
  954. return;
  955. }
  956. }
  957. Parent::addObject(object);
  958. }
  959. void Entity::removeObject(SimObject* object)
  960. {
  961. Entity* e = dynamic_cast<Entity*>(object);
  962. if (e)
  963. {
  964. mPos = mPos + e->getPosition();
  965. mRot = mRot + e->getRotation();
  966. unmountObject(e);
  967. setMaskBits(TransformMask);
  968. }
  969. else
  970. {
  971. SceneObject* so = dynamic_cast<SceneObject*>(object);
  972. if (so)
  973. unmountObject(so);
  974. }
  975. Parent::removeObject(object);
  976. }
  977. bool Entity::addComponent(Component *comp)
  978. {
  979. if (comp == NULL || !comp->isProperlyAdded())
  980. return false;
  981. //double-check were not re-adding anything
  982. mComponents.push_back(comp);
  983. // Register the component with this owner.
  984. comp->setOwner(this);
  985. //if we've already been added and this is being added after the fact(at runtime),
  986. //then just go ahead and call it's onComponentAdd so it can get to work
  987. if (mInitialized)
  988. comp->onComponentAdd();
  989. onComponentAdded.trigger(comp);
  990. return true;
  991. }
  992. SimObject* Entity::findObjectByInternalName(StringTableEntry internalName, bool searchChildren)
  993. {
  994. for (U32 i = 0; i < mComponents.size(); i++)
  995. {
  996. if (mComponents[i]->getInternalName() == internalName)
  997. {
  998. return mComponents[i];
  999. }
  1000. }
  1001. return Parent::findObjectByInternalName(internalName, searchChildren);
  1002. }
  1003. //////////////////////////////////////////////////////////////////////////
  1004. bool Entity::removeComponent(Component *comp, bool deleteComponent)
  1005. {
  1006. if (comp == NULL)
  1007. return false;
  1008. if(mComponents.remove(comp))
  1009. {
  1010. AssertFatal(comp->isProperlyAdded(), "Don't know how but a component is not registered w/ the sim");
  1011. //setComponentsDirty();
  1012. onComponentRemoved.trigger(comp);
  1013. comp->setOwner(NULL);
  1014. comp->onComponentRemove(); //in case the behavior needs to do cleanup on the owner
  1015. if (deleteComponent)
  1016. comp->safeDeleteObject();
  1017. return true;
  1018. }
  1019. return false;
  1020. }
  1021. //////////////////////////////////////////////////////////////////////////
  1022. //NOTE:
  1023. //The actor class calls this and flags the deletion of the behaviors to false so that behaviors that should no longer be attached during
  1024. //a network update will indeed be removed from the object. The reason it doesn't delete them is because when clearing the local behavior
  1025. //list, it would delete them, purging the ghost, and causing a crash when the unpack update tried to fetch any existing behaviors' ghosts
  1026. //to re-add them. Need to implement a clean clear function that will clear the local list, and only delete unused behaviors during an update.
  1027. void Entity::clearComponents(bool deleteComponents)
  1028. {
  1029. bool srv = isServerObject();
  1030. if (!deleteComponents)
  1031. {
  1032. while (mComponents.size() > 0)
  1033. {
  1034. removeComponent(mComponents.first(), deleteComponents);
  1035. }
  1036. }
  1037. else
  1038. {
  1039. while (mComponents.size() > 0)
  1040. {
  1041. Component* comp = mComponents.first();
  1042. if (comp)
  1043. {
  1044. comp->onComponentRemove(); //in case the behavior needs to do cleanup on the owner
  1045. bool removed = mComponents.remove(comp);
  1046. //we only need to delete them on the server side. they'll be cleaned up on the client side
  1047. //via the ghosting system for us
  1048. if (isServerObject())
  1049. comp->deleteObject();
  1050. }
  1051. }
  1052. }
  1053. }
  1054. //////////////////////////////////////////////////////////////////////////
  1055. Component *Entity::getComponent(const U32 index) const
  1056. {
  1057. if (index < mComponents.size())
  1058. return mComponents[index];
  1059. return NULL;
  1060. }
  1061. Component *Entity::getComponent(String componentType)
  1062. {
  1063. for (U32 i = 0; i < mComponents.size(); i++)
  1064. {
  1065. Component* comp = mComponents[i];
  1066. /*String namespaceName = comp->getNamespace()->mName;
  1067. //check our namespace first
  1068. if (namespaceName == componentType)
  1069. {
  1070. return comp;
  1071. }
  1072. else
  1073. {*/
  1074. //lets scan up, just to be sure
  1075. Namespace *NS = comp->getNamespace();
  1076. //we shouldn't ever go past Component into net object, as we're no longer dealing with component classes
  1077. while (dStrcmp(NS->getName(), "NetObject"))
  1078. {
  1079. String namespaceName = NS->getName();
  1080. if (namespaceName == componentType)
  1081. {
  1082. return comp;
  1083. }
  1084. else
  1085. {
  1086. NS = NS->getParent();
  1087. }
  1088. }
  1089. //}
  1090. }
  1091. return NULL;
  1092. }
  1093. void Entity::onInspect()
  1094. {
  1095. Vector<EditorInspectInterface*> updaters = getComponents<EditorInspectInterface>();
  1096. for (Vector<EditorInspectInterface*>::iterator it = updaters.begin(); it != updaters.end(); it++) {
  1097. (*it)->onInspect();
  1098. }
  1099. GuiTreeViewCtrl *editorTree = dynamic_cast<GuiTreeViewCtrl*>(Sim::findObject("EditorTree"));
  1100. if (!editorTree)
  1101. return;
  1102. GuiTreeViewCtrl::Item *newItem, *parentItem;
  1103. parentItem = editorTree->getItem(editorTree->findItemByObjectId(getId()));
  1104. S32 componentID = editorTree->insertItem(parentItem->getID(), "Components");
  1105. newItem = editorTree->getItem(componentID);
  1106. newItem->mState.set(GuiTreeViewCtrl::Item::VirtualParent);
  1107. newItem->mState.set(GuiTreeViewCtrl::Item::DenyDrag);
  1108. //newItem->mState.set(GuiTreeViewCtrl::Item::InspectorData);
  1109. newItem->mState.set(GuiTreeViewCtrl::Item::ForceItemName);
  1110. //newItem->mInspectorInfo.mObject = this;
  1111. for (U32 i = 0; i < mComponents.size(); i++)
  1112. {
  1113. String compName = mComponents[i]->getFriendlyName();
  1114. S32 compID = editorTree->insertItem(componentID, compName);
  1115. newItem = editorTree->getItem(compID);
  1116. newItem->mInspectorInfo.mObject = mComponents[i];
  1117. newItem->mState.set(GuiTreeViewCtrl::Item::ForceItemName);
  1118. newItem->mState.set(GuiTreeViewCtrl::Item::DenyDrag);
  1119. newItem->mState.set(GuiTreeViewCtrl::Item::InspectorData);
  1120. }
  1121. editorTree->buildVisibleTree(true);
  1122. }
  1123. void Entity::onEndInspect()
  1124. {
  1125. Vector<EditorInspectInterface*> updaters = getComponents<EditorInspectInterface>();
  1126. for (Vector<EditorInspectInterface*>::iterator it = updaters.begin(); it != updaters.end(); it++) {
  1127. (*it)->onEndInspect();
  1128. }
  1129. GuiTreeViewCtrl *editorTree = dynamic_cast<GuiTreeViewCtrl*>(Sim::findObject("EditorTree"));
  1130. if (!editorTree)
  1131. return;
  1132. S32 componentItemIdx = editorTree->findItemByName("Components");
  1133. editorTree->removeItem(componentItemIdx, false);
  1134. }
  1135. static void writeTabs(Stream &stream, U32 count)
  1136. {
  1137. char tab[] = " ";
  1138. while (count--)
  1139. stream.write(3, (void*)tab);
  1140. }
  1141. void Entity::write(Stream &stream, U32 tabStop, U32 flags)
  1142. {
  1143. // Do *not* call parent on this
  1144. /*VectorPtr<ComponentObject *> &componentList = lockComponentList();
  1145. // export selected only?
  1146. if( ( flags & SelectedOnly ) && !isSelected() )
  1147. {
  1148. for( BehaviorObjectIterator i = componentList.begin(); i != componentList.end(); i++ )
  1149. (*i)->write(stream, tabStop, flags);
  1150. goto write_end;
  1151. }*/
  1152. //catch if we have any written behavior fields already in the file, and clear them. We don't need to double-up
  1153. //the entries for no reason.
  1154. /*if(getFieldDictionary())
  1155. {
  1156. //get our dynamic field count, then parse through them to see if they're a behavior or not
  1157. //reset it
  1158. SimFieldDictionary* fieldDictionary = getFieldDictionary();
  1159. SimFieldDictionaryIterator itr(fieldDictionary);
  1160. for (S32 i = 0; i < fieldDictionary->getNumFields(); i++)
  1161. {
  1162. if (!(*itr))
  1163. break;
  1164. SimFieldDictionary::Entry* entry = *itr;
  1165. if(strstr(entry->slotName, "_behavior"))
  1166. {
  1167. entry->slotName = "";
  1168. entry->value = "";
  1169. }
  1170. ++itr;
  1171. }
  1172. }*/
  1173. //all existing written behavior fields should be cleared. now write the object block
  1174. writeTabs(stream, tabStop);
  1175. char buffer[1024];
  1176. dSprintf(buffer, sizeof(buffer), "new %s(%s) {\r\n", getClassName(), getName() ? getName() : "");
  1177. stream.write(dStrlen(buffer), buffer);
  1178. writeFields(stream, tabStop + 1);
  1179. stream.write(1, "\n");
  1180. ////first, write out our behavior objects
  1181. // NOW we write the behavior fields proper
  1182. if (mComponents.size() > 0)
  1183. {
  1184. // Pack out the behaviors into fields
  1185. U32 i = 0;
  1186. for (U32 i = 0; i < mComponents.size(); i++)
  1187. {
  1188. writeTabs(stream, tabStop + 1);
  1189. char buffer[1024];
  1190. dSprintf(buffer, sizeof(buffer), "new %s() {\r\n", mComponents[i]->getClassName());
  1191. stream.write(dStrlen(buffer), buffer);
  1192. //bi->writeFields( stream, tabStop + 2 );
  1193. mComponents[i]->packToStream(stream, tabStop + 2, i - 1, flags);
  1194. writeTabs(stream, tabStop + 1);
  1195. stream.write(4, "};\r\n");
  1196. }
  1197. }
  1198. //
  1199. //if (size() > 0)
  1200. // stream.write(2, "\r\n");
  1201. for (U32 i = 0; i < size(); i++)
  1202. {
  1203. SimObject* child = (*this)[i];
  1204. if (child->getCanSave())
  1205. child->write(stream, tabStop + 1, flags);
  1206. }
  1207. //stream.write(2, "\r\n");
  1208. writeTabs(stream, tabStop);
  1209. stream.write(4, "};\r\n");
  1210. //write_end:
  1211. //unlockComponentList();
  1212. }
  1213. SimObject* Entity::getTamlChild(const U32 childIndex) const
  1214. {
  1215. // Sanity!
  1216. AssertFatal(childIndex < getTamlChildCount(), "SimSet::getTamlChild() - Child index is out of range.");
  1217. // For when the assert is not used.
  1218. if (childIndex >= getTamlChildCount())
  1219. return NULL;
  1220. //we always order components first, child objects second
  1221. if (childIndex >= getComponentCount())
  1222. return at(childIndex - getComponentCount());
  1223. else
  1224. return getComponent(childIndex);
  1225. }
  1226. //
  1227. void Entity::onCameraScopeQuery(NetConnection* connection, CameraScopeQuery* query)
  1228. {
  1229. // Object itself is in scope.
  1230. Parent::onCameraScopeQuery(connection, query);
  1231. if (CameraInterface* cI = getComponent<CameraInterface>())
  1232. {
  1233. cI->onCameraScopeQuery(connection, query);
  1234. }
  1235. }
  1236. //
  1237. void Entity::setObjectBox(Box3F objBox)
  1238. {
  1239. mObjBox = objBox;
  1240. resetWorldBox();
  1241. if (isServerObject())
  1242. setMaskBits(BoundsMask);
  1243. }
  1244. void Entity::updateContainer()
  1245. {
  1246. PROFILE_SCOPE(Entity_updateContainer);
  1247. // Update container drag and buoyancy properties
  1248. containerInfo.box = getWorldBox();
  1249. //containerInfo.mass = mMass;
  1250. getContainer()->findObjects(containerInfo.box, WaterObjectType | PhysicalZoneObjectType, findRouter, &containerInfo);
  1251. //mWaterCoverage = info.waterCoverage;
  1252. //mLiquidType = info.liquidType;
  1253. //mLiquidHeight = info.waterHeight;
  1254. //setCurrentWaterObject( info.waterObject );
  1255. // This value might be useful as a datablock value,
  1256. // This is what allows the player to stand in shallow water (below this coverage)
  1257. // without jiggling from buoyancy
  1258. /*if (info.waterCoverage >= 0.25f)
  1259. {
  1260. // water viscosity is used as drag for in water.
  1261. // ShapeBaseData drag is used for drag outside of water.
  1262. // Combine these two components to calculate this ShapeBase object's
  1263. // current drag.
  1264. mDrag = (info.waterCoverage * info.waterViscosity) +
  1265. (1.0f - info.waterCoverage) * mDrag;
  1266. //mBuoyancy = (info.waterDensity / mDataBlock->density) * info.waterCoverage;
  1267. }
  1268. //mAppliedForce = info.appliedForce;
  1269. mGravityMod = info.gravityScale;*/
  1270. }
  1271. //
  1272. void Entity::setComponentsDirty()
  1273. {
  1274. if (mToLoadComponents.empty())
  1275. mStartComponentUpdate = true;
  1276. //we need to build a list of behaviors that need to be pushed across the network
  1277. for (U32 i = 0; i < mComponents.size(); i++)
  1278. {
  1279. // We can do this because both are in the string table
  1280. Component *comp = mComponents[i];
  1281. if (comp->isNetworked())
  1282. {
  1283. bool unique = true;
  1284. for (U32 i = 0; i < mToLoadComponents.size(); i++)
  1285. {
  1286. if (mToLoadComponents[i]->getId() == comp->getId())
  1287. {
  1288. unique = false;
  1289. break;
  1290. }
  1291. }
  1292. if (unique)
  1293. mToLoadComponents.push_back(comp);
  1294. }
  1295. }
  1296. setMaskBits(ComponentsMask);
  1297. }
  1298. void Entity::setComponentDirty(Component *comp, bool forceUpdate)
  1299. {
  1300. bool found = false;
  1301. for (U32 i = 0; i < mComponents.size(); i++)
  1302. {
  1303. if (mComponents[i]->getId() == comp->getId())
  1304. {
  1305. mComponents[i]->setOwner(this);
  1306. return;
  1307. }
  1308. }
  1309. if (!found)
  1310. return;
  1311. //if(mToLoadComponents.empty())
  1312. // mStartComponentUpdate = true;
  1313. /*if (comp->isNetworked() || forceUpdate)
  1314. {
  1315. bool unique = true;
  1316. for (U32 i = 0; i < mToLoadComponents.size(); i++)
  1317. {
  1318. if (mToLoadComponents[i]->getId() == comp->getId())
  1319. {
  1320. unique = false;
  1321. break;
  1322. }
  1323. }
  1324. if (unique)
  1325. mToLoadComponents.push_back(comp);
  1326. }
  1327. setMaskBits(ComponentsMask);*/
  1328. }
  1329. DefineEngineMethod(Entity, mountObject, bool,
  1330. (SceneObject* objB, TransformF txfm), (MatrixF::Identity),
  1331. "@brief Mount objB to this object at the desired slot with optional transform.\n\n"
  1332. "@param objB Object to mount onto us\n"
  1333. "@param slot Mount slot ID\n"
  1334. "@param txfm (optional) mount offset transform\n"
  1335. "@return true if successful, false if failed (objB is not valid)")
  1336. {
  1337. if (objB)
  1338. {
  1339. //BUG: Unsure how it broke, but atm the default transform passed in here is rotated 180 degrees. This doesn't happen
  1340. //for the SceneObject mountobject method. Hackish, but for now, just default to a clean MatrixF::Identity
  1341. object->mountObject(objB, /*MatrixF::Identity*/txfm.getMatrix());
  1342. return true;
  1343. }
  1344. return false;
  1345. }
  1346. DefineEngineMethod(Entity, setMountOffset, void,
  1347. (Point3F posOffset), (Point3F(0, 0, 0)),
  1348. "@brief Mount objB to this object at the desired slot with optional transform.\n\n"
  1349. "@param objB Object to mount onto us\n"
  1350. "@param slot Mount slot ID\n"
  1351. "@param txfm (optional) mount offset transform\n"
  1352. "@return true if successful, false if failed (objB is not valid)")
  1353. {
  1354. object->setMountOffset(posOffset);
  1355. }
  1356. DefineEngineMethod(Entity, setMountRotation, void,
  1357. (EulerF rotOffset), (EulerF(0, 0, 0)),
  1358. "@brief Mount objB to this object at the desired slot with optional transform.\n\n"
  1359. "@param objB Object to mount onto us\n"
  1360. "@param slot Mount slot ID\n"
  1361. "@param txfm (optional) mount offset transform\n"
  1362. "@return true if successful, false if failed (objB is not valid)")
  1363. {
  1364. object->setMountRotation(rotOffset);
  1365. }
  1366. DefineEngineMethod(Entity, getMountTransform, TransformF, (), ,
  1367. "@brief Mount objB to this object at the desired slot with optional transform.\n\n"
  1368. "@param objB Object to mount onto us\n"
  1369. "@param slot Mount slot ID\n"
  1370. "@param txfm (optional) mount offset transform\n"
  1371. "@return true if successful, false if failed (objB is not valid)")
  1372. {
  1373. MatrixF mat;
  1374. object->getMountTransform(0, MatrixF::Identity, &mat);
  1375. return mat;
  1376. }
  1377. DefineEngineMethod(Entity, setBox, void,
  1378. (Point3F box), (Point3F(1, 1, 1)),
  1379. "@brief Mount objB to this object at the desired slot with optional transform.\n\n"
  1380. "@param objB Object to mount onto us\n"
  1381. "@param slot Mount slot ID\n"
  1382. "@param txfm (optional) mount offset transform\n"
  1383. "@return true if successful, false if failed (objB is not valid)")
  1384. {
  1385. object->setObjectBox(Box3F(-box, box));
  1386. }
  1387. /*DefineConsoleMethod(Entity, callOnComponents, void, (const char* functionName), ,
  1388. "Get the number of static fields on the object.\n"
  1389. "@return The number of static fields defined on the object.")
  1390. {
  1391. object->callOnComponents(functionName);
  1392. }
  1393. ConsoleMethod(Entity, callMethod, void, 3, 64, "(methodName, argi) Calls script defined method\n"
  1394. "@param methodName The method's name as a string\n"
  1395. "@param argi Any arguments to pass to the method\n"
  1396. "@return No return value"
  1397. "@note %obj.callMethod( %methodName, %arg1, %arg2, ... );\n")
  1398. {
  1399. object->callMethodArgList(argc - 1, argv + 2);
  1400. }
  1401. ConsoleMethod(Entity, addComponents, void, 2, 2, "() - Add all fielded behaviors\n"
  1402. "@return No return value")
  1403. {
  1404. object->addComponents();
  1405. }*/
  1406. ConsoleMethod(Entity, addComponent, bool, 3, 3, "(ComponentInstance bi) - Add a behavior to the object\n"
  1407. "@param bi The behavior instance to add"
  1408. "@return (bool success) Whether or not the behavior was successfully added")
  1409. {
  1410. Component *comp = dynamic_cast<Component *>(Sim::findObject(argv[2]));
  1411. if (comp != NULL)
  1412. {
  1413. bool success = object->addComponent(comp);
  1414. if (success)
  1415. {
  1416. //Placed here so we can differentiate against adding a new behavior during runtime, or when we load all
  1417. //fielded behaviors on mission load. This way, we can ensure that we only call the callback
  1418. //once everything is loaded. This avoids any problems with looking for behaviors that haven't been added yet, etc.
  1419. if (comp->isMethod("onBehaviorAdd"))
  1420. Con::executef(comp, "onBehaviorAdd");
  1421. return true;
  1422. }
  1423. }
  1424. return false;
  1425. }
  1426. ConsoleMethod(Entity, removeComponent, bool, 3, 4, "(ComponentInstance bi, [bool deleteBehavior = true])\n"
  1427. "@param bi The behavior instance to remove\n"
  1428. "@param deleteBehavior Whether or not to delete the behavior\n"
  1429. "@return (bool success) Whether the behavior was successfully removed")
  1430. {
  1431. bool deleteComponent = true;
  1432. if (argc > 3)
  1433. deleteComponent = dAtob(argv[3]);
  1434. return object->removeComponent(dynamic_cast<Component *>(Sim::findObject(argv[2])), deleteComponent);
  1435. }
  1436. ConsoleMethod(Entity, clearComponents, void, 2, 2, "() - Clear all behavior instances\n"
  1437. "@return No return value")
  1438. {
  1439. object->clearComponents();
  1440. }
  1441. ConsoleMethod(Entity, getComponentByIndex, S32, 3, 3, "(int index) - Gets a particular behavior\n"
  1442. "@param index The index of the behavior to get\n"
  1443. "@return (ComponentInstance bi) The behavior instance you requested")
  1444. {
  1445. Component *comp = object->getComponent(dAtoi(argv[2]));
  1446. return (comp != NULL) ? comp->getId() : 0;
  1447. }
  1448. DefineConsoleMethod(Entity, getComponent, S32, (String componentName), (""),
  1449. "Get the number of static fields on the object.\n"
  1450. "@return The number of static fields defined on the object.")
  1451. {
  1452. Component *comp = object->getComponent(componentName);
  1453. return (comp != NULL) ? comp->getId() : 0;
  1454. return 0;
  1455. }
  1456. /*ConsoleMethod(Entity, getBehaviorByType, S32, 3, 3, "(string BehaviorTemplateName) - gets a behavior\n"
  1457. "@param BehaviorTemplateName The name of the template of the behavior instance you want\n"
  1458. "@return (ComponentInstance bi) The behavior instance you requested")
  1459. {
  1460. ComponentInstance *bInstance = object->getComponentByType(StringTable->insert(argv[2]));
  1461. return (bInstance != NULL) ? bInstance->getId() : 0;
  1462. }*/
  1463. /*ConsoleMethod(Entity, reOrder, bool, 3, 3, "(ComponentInstance inst, [int desiredIndex = 0])\n"
  1464. "@param inst The behavior instance you want to reorder\n"
  1465. "@param desiredIndex The index you want the behavior instance to be reordered to\n"
  1466. "@return (bool success) Whether or not the behavior instance was successfully reordered")
  1467. {
  1468. Component *inst = dynamic_cast<Component *>(Sim::findObject(argv[1]));
  1469. if (inst == NULL)
  1470. return false;
  1471. U32 idx = 0;
  1472. if (argc > 2)
  1473. idx = dAtoi(argv[2]);
  1474. return object->reOrder(inst, idx);
  1475. }*/
  1476. ConsoleMethod(Entity, getComponentCount, S32, 2, 2, "() - Get the count of behaviors on an object\n"
  1477. "@return (int count) The number of behaviors on an object")
  1478. {
  1479. return object->getComponentCount();
  1480. }
  1481. DefineConsoleMethod(Entity, setComponentDirty, void, (S32 componentID, bool forceUpdate), (0, false),
  1482. "Get the number of static fields on the object.\n"
  1483. "@return The number of static fields defined on the object.")
  1484. {
  1485. /*Component* comp;
  1486. if (Sim::findObject(componentID, comp))
  1487. object->setComponentDirty(comp, forceUpdate);*/
  1488. }
  1489. DefineConsoleMethod(Entity, getMoveVector, VectorF, (),,
  1490. "Get the number of static fields on the object.\n"
  1491. "@return The number of static fields defined on the object.")
  1492. {
  1493. if (object->getControllingClient() != NULL)
  1494. {
  1495. //fetch our last move
  1496. if (object->lastMove.x != 0 || object->lastMove.y != 0 || object->lastMove.z != 0)
  1497. return VectorF(object->lastMove.x, object->lastMove.y, object->lastMove.z);
  1498. }
  1499. return VectorF::Zero;
  1500. }
  1501. DefineConsoleMethod(Entity, getMoveRotation, VectorF, (), ,
  1502. "Get the number of static fields on the object.\n"
  1503. "@return The number of static fields defined on the object.")
  1504. {
  1505. if(object->getControllingClient() != NULL)
  1506. {
  1507. //fetch our last move
  1508. if (object->lastMove.pitch != 0 || object->lastMove.roll != 0 || object->lastMove.yaw != 0)
  1509. return VectorF(object->lastMove.pitch, object->lastMove.roll, object->lastMove.yaw);
  1510. }
  1511. return VectorF::Zero;
  1512. }
  1513. DefineConsoleMethod(Entity, getMoveTrigger, bool, (S32 triggerNum), (0),
  1514. "Get the number of static fields on the object.\n"
  1515. "@return The number of static fields defined on the object.")
  1516. {
  1517. if (object->getControllingClient() != NULL && triggerNum < MaxTriggerKeys)
  1518. {
  1519. return object->lastMove.trigger[triggerNum];
  1520. }
  1521. return false;
  1522. }
  1523. DefineConsoleMethod(Entity, setForwardVector, void, (VectorF newForward), (VectorF(0,0,0)),
  1524. "Get the number of static fields on the object.\n"
  1525. "@return The number of static fields defined on the object.")
  1526. {
  1527. object->setForwardVector(newForward);
  1528. }
  1529. DefineConsoleMethod(Entity, lookAt, void, (Point3F lookPosition),,
  1530. "Get the number of static fields on the object.\n"
  1531. "@return The number of static fields defined on the object.")
  1532. {
  1533. //object->setForwardVector(newForward);
  1534. }
  1535. DefineConsoleMethod(Entity, rotateTo, void, (Point3F lookPosition, F32 degreePerSecond), (1.0),
  1536. "Get the number of static fields on the object.\n"
  1537. "@return The number of static fields defined on the object.")
  1538. {
  1539. //object->setForwardVector(newForward);
  1540. }