trigger.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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/trigger.h"
  24. #include "scene/sceneRenderState.h"
  25. #include "console/consoleTypes.h"
  26. #include "console/engineAPI.h"
  27. #include "collision/boxConvex.h"
  28. #include "core/stream/bitStream.h"
  29. #include "math/mathIO.h"
  30. #include "gfx/gfxTransformSaver.h"
  31. #include "renderInstance/renderPassManager.h"
  32. #include "gfx/gfxDrawUtil.h"
  33. #include "T3D/physics/physicsPlugin.h"
  34. #include "T3D/physics/physicsBody.h"
  35. #include "T3D/physics/physicsCollision.h"
  36. bool Trigger::smRenderTriggers = false;
  37. //-----------------------------------------------------------------------------
  38. //----------------------------------------------------------------------------
  39. IMPLEMENT_CO_DATABLOCK_V1(TriggerData);
  40. ConsoleDocClass( TriggerData,
  41. "@brief Defines shared properties for Trigger objects.\n\n"
  42. "The primary focus of the TriggerData datablock is the callbacks it provides when an object is "
  43. "within or leaves the Trigger bounds.\n"
  44. "@see Trigger.\n"
  45. "@ingroup gameObjects\n"
  46. "@ingroup Datablocks\n"
  47. );
  48. IMPLEMENT_CALLBACK( TriggerData, onEnterTrigger, void, ( Trigger* trigger, GameBase* obj ), ( trigger, obj ),
  49. "@brief Called when an object enters the volume of the Trigger instance using this TriggerData.\n\n"
  50. "@param trigger the Trigger instance whose volume the object entered\n"
  51. "@param obj the object that entered the volume of the Trigger instance\n" );
  52. IMPLEMENT_CALLBACK( TriggerData, onTickTrigger, void, ( Trigger* trigger ), ( trigger ),
  53. "@brief Called every tickPeriodMS number of milliseconds (as specified in the TriggerData) whenever "
  54. "one or more objects are inside the volume of the trigger.\n\n"
  55. "The Trigger has methods to retrieve the objects that are within the Trigger's bounds if you "
  56. "want to do something with them in this callback.\n"
  57. "@param trigger the Trigger instance whose volume the object is inside\n"
  58. "@see tickPeriodMS\n"
  59. "@see Trigger::getNumObjects()\n"
  60. "@see Trigger::getObject()\n");
  61. IMPLEMENT_CALLBACK( TriggerData, onLeaveTrigger, void, ( Trigger* trigger, GameBase* obj ), ( trigger, obj ),
  62. "@brief Called when an object leaves the volume of the Trigger instance using this TriggerData.\n\n"
  63. "@param trigger the Trigger instance whose volume the object left\n"
  64. "@param obj the object that left the volume of the Trigger instance\n" );
  65. TriggerData::TriggerData()
  66. {
  67. tickPeriodMS = 100;
  68. isClientSide = false;
  69. }
  70. bool TriggerData::onAdd()
  71. {
  72. if (!Parent::onAdd())
  73. return false;
  74. return true;
  75. }
  76. void TriggerData::initPersistFields()
  77. {
  78. docsURL;
  79. addGroup("Callbacks");
  80. addField( "tickPeriodMS", TypeS32, Offset( tickPeriodMS, TriggerData ),
  81. "@brief Time in milliseconds between calls to onTickTrigger() while at least one object is within a Trigger's bounds.\n\n"
  82. "@see onTickTrigger()\n");
  83. addField( "clientSide", TypeBool, Offset( isClientSide, TriggerData ),
  84. "Forces Trigger callbacks to only be called on clients.");
  85. endGroup("Callbacks");
  86. Parent::initPersistFields();
  87. }
  88. //--------------------------------------------------------------------------
  89. void TriggerData::packData(BitStream* stream)
  90. {
  91. Parent::packData(stream);
  92. stream->write(tickPeriodMS);
  93. stream->write(isClientSide);
  94. }
  95. void TriggerData::unpackData(BitStream* stream)
  96. {
  97. Parent::unpackData(stream);
  98. stream->read(&tickPeriodMS);
  99. stream->read(&isClientSide);
  100. }
  101. //--------------------------------------------------------------------------
  102. IMPLEMENT_CO_NETOBJECT_V1(Trigger);
  103. ConsoleDocClass( Trigger,
  104. "@brief A Trigger is a volume of space that initiates script callbacks "
  105. "when objects pass through the Trigger.\n\n"
  106. "TriggerData provides the callbacks for the Trigger when an object enters, stays inside "
  107. "or leaves the Trigger's volume.\n\n"
  108. "@see TriggerData\n"
  109. "@ingroup gameObjects\n"
  110. );
  111. IMPLEMENT_CALLBACK( Trigger, onAdd, void, ( U32 objectId ), ( objectId ),
  112. "@brief Called when the Trigger is being created.\n\n"
  113. "@param objectId the object id of the Trigger being created\n" );
  114. IMPLEMENT_CALLBACK( Trigger, onRemove, void, ( U32 objectId ), ( objectId ),
  115. "@brief Called just before the Trigger is deleted.\n\n"
  116. "@param objectId the object id of the Trigger being deleted\n" );
  117. Trigger::Trigger()
  118. {
  119. // Don't ghost by default.
  120. mNetFlags.set(Ghostable | ScopeAlways);
  121. mTypeMask |= TriggerObjectType;
  122. mObjScale.set(1, 1, 1);
  123. mObjToWorld.identity();
  124. mWorldToObj.identity();
  125. mDataBlock = NULL;
  126. mLastThink = 0;
  127. mCurrTick = 0;
  128. mConvexList = new Convex;
  129. mPhysicsRep = NULL;
  130. mTripOnce = false;
  131. mTrippedBy = 0xFFFFFFFF;
  132. mTripCondition = "";
  133. //Default up a basic square
  134. Point3F vecs[3] = { Point3F(1.0, 0.0, 0.0),
  135. Point3F(0.0, -1.0, 0.0),
  136. Point3F(0.0, 0.0, 1.0) };
  137. mTriggerPolyhedron = Polyhedron(Point3F(-0.5, 0.5, 0.0), vecs);
  138. }
  139. Trigger::~Trigger()
  140. {
  141. delete mConvexList;
  142. mConvexList = NULL;
  143. SAFE_DELETE( mPhysicsRep );
  144. }
  145. bool Trigger::castRay(const Point3F &start, const Point3F &end, RayInfo* info)
  146. {
  147. // Collide against bounding box
  148. F32 st,et,fst = 0,fet = 1;
  149. F32 *bmin = &mObjBox.minExtents.x;
  150. F32 *bmax = &mObjBox.maxExtents.x;
  151. F32 const *si = &start.x;
  152. F32 const *ei = &end.x;
  153. for (S32 i = 0; i < 3; i++)
  154. {
  155. if (*si < *ei)
  156. {
  157. if (*si > *bmax || *ei < *bmin)
  158. return false;
  159. F32 di = *ei - *si;
  160. st = (*si < *bmin)? (*bmin - *si) / di: 0;
  161. et = (*ei > *bmax)? (*bmax - *si) / di: 1;
  162. }
  163. else
  164. {
  165. if (*ei > *bmax || *si < *bmin)
  166. return false;
  167. F32 di = *ei - *si;
  168. st = (*si > *bmax)? (*bmax - *si) / di: 0;
  169. et = (*ei < *bmin)? (*bmin - *si) / di: 1;
  170. }
  171. if (st > fst) fst = st;
  172. if (et < fet) fet = et;
  173. if (fet < fst)
  174. return false;
  175. bmin++; bmax++;
  176. si++; ei++;
  177. }
  178. info->normal = start - end;
  179. info->normal.normalizeSafe();
  180. getTransform().mulV( info->normal );
  181. info->t = fst;
  182. info->object = this;
  183. info->point.interpolate(start,end,fst);
  184. info->material = 0;
  185. return true;
  186. }
  187. //--------------------------------------------------------------------------
  188. /* Console polyhedron data type exporter
  189. The polyhedron type is really a quadrilateral and consists of a corner
  190. point follow by three vectors representing the edges extending from the
  191. corner.
  192. */
  193. DECLARE_STRUCT( Polyhedron );
  194. IMPLEMENT_STRUCT( Polyhedron, Polyhedron,,
  195. "" )
  196. FIELD(mPointList, pointList, 1, "")
  197. FIELD(mPlaneList, planeList, 1, "")
  198. FIELD(mEdgeList, edgeList, 1, "")
  199. END_IMPLEMENT_STRUCT;
  200. ConsoleType(floatList, TypeTriggerPolyhedron, Polyhedron, "")
  201. ConsoleGetType( TypeTriggerPolyhedron )
  202. {
  203. U32 i;
  204. Polyhedron* pPoly = reinterpret_cast<Polyhedron*>(dptr);
  205. // First point is corner, need to find the three vectors...`
  206. Point3F origin = pPoly->mPointList[0];
  207. U32 currVec = 0;
  208. Point3F vecs[3];
  209. for (i = 0; i < pPoly->mEdgeList.size(); i++) {
  210. const U32 *vertex = pPoly->mEdgeList[i].vertex;
  211. if (vertex[0] == 0)
  212. vecs[currVec++] = pPoly->mPointList[vertex[1]] - origin;
  213. else
  214. if (vertex[1] == 0)
  215. vecs[currVec++] = pPoly->mPointList[vertex[0]] - origin;
  216. }
  217. AssertFatal(currVec == 3, "Internal error: Bad trigger polyhedron");
  218. // Build output string.
  219. static const U32 bufSize = 1024;
  220. char* retBuf = Con::getReturnBuffer(bufSize);
  221. dSprintf(retBuf, bufSize, "%7.7f %7.7f %7.7f %7.7f %7.7f %7.7f %7.7f %7.7f %7.7f %7.7f %7.7f %7.7f",
  222. origin.x, origin.y, origin.z,
  223. vecs[0].x, vecs[0].y, vecs[0].z,
  224. vecs[2].x, vecs[2].y, vecs[2].z,
  225. vecs[1].x, vecs[1].y, vecs[1].z);
  226. return retBuf;
  227. }
  228. /* Console polyhedron data type loader
  229. The polyhedron type is really a quadrilateral and consists of an corner
  230. point follow by three vectors representing the edges extending from the
  231. corner.
  232. */
  233. ConsoleSetType( TypeTriggerPolyhedron )
  234. {
  235. if (argc != 1) {
  236. Con::printf("(TypeTriggerPolyhedron) multiple args not supported for polyhedra");
  237. return;
  238. }
  239. Point3F origin;
  240. Point3F vecs[3];
  241. U32 numArgs = dSscanf(argv[0], "%g %g %g %g %g %g %g %g %g %g %g %g",
  242. &origin.x, &origin.y, &origin.z,
  243. &vecs[0].x, &vecs[0].y, &vecs[0].z,
  244. &vecs[1].x, &vecs[1].y, &vecs[1].z,
  245. &vecs[2].x, &vecs[2].y, &vecs[2].z);
  246. if (numArgs != 12) {
  247. Con::printf("Bad polyhedron!");
  248. return;
  249. }
  250. Polyhedron* pPoly = reinterpret_cast<Polyhedron*>(dptr);
  251. // This setup goes against conventions for Polyhedrons in that it a) sets up
  252. // edges with CCW instead of CW order for face[0] and that it b) lets plane
  253. // normals face outwards rather than inwards.
  254. pPoly->mPointList.setSize(8);
  255. pPoly->mPointList[0] = origin;
  256. pPoly->mPointList[1] = origin + vecs[0];
  257. pPoly->mPointList[2] = origin + vecs[1];
  258. pPoly->mPointList[3] = origin + vecs[2];
  259. pPoly->mPointList[4] = origin + vecs[0] + vecs[1];
  260. pPoly->mPointList[5] = origin + vecs[0] + vecs[2];
  261. pPoly->mPointList[6] = origin + vecs[1] + vecs[2];
  262. pPoly->mPointList[7] = origin + vecs[0] + vecs[1] + vecs[2];
  263. Point3F normal;
  264. pPoly->mPlaneList.setSize(6);
  265. mCross(vecs[2], vecs[0], &normal);
  266. pPoly->mPlaneList[0].set(origin, normal);
  267. mCross(vecs[0], vecs[1], &normal);
  268. pPoly->mPlaneList[1].set(origin, normal);
  269. mCross(vecs[1], vecs[2], &normal);
  270. pPoly->mPlaneList[2].set(origin, normal);
  271. mCross(vecs[1], vecs[0], &normal);
  272. pPoly->mPlaneList[3].set(pPoly->mPointList[7], normal);
  273. mCross(vecs[2], vecs[1], &normal);
  274. pPoly->mPlaneList[4].set(pPoly->mPointList[7], normal);
  275. mCross(vecs[0], vecs[2], &normal);
  276. pPoly->mPlaneList[5].set(pPoly->mPointList[7], normal);
  277. pPoly->mEdgeList.setSize(12);
  278. pPoly->mEdgeList[0].vertex[0] = 0; pPoly->mEdgeList[0].vertex[1] = 1; pPoly->mEdgeList[0].face[0] = 0; pPoly->mEdgeList[0].face[1] = 1;
  279. pPoly->mEdgeList[1].vertex[0] = 1; pPoly->mEdgeList[1].vertex[1] = 5; pPoly->mEdgeList[1].face[0] = 0; pPoly->mEdgeList[1].face[1] = 4;
  280. pPoly->mEdgeList[2].vertex[0] = 5; pPoly->mEdgeList[2].vertex[1] = 3; pPoly->mEdgeList[2].face[0] = 0; pPoly->mEdgeList[2].face[1] = 3;
  281. pPoly->mEdgeList[3].vertex[0] = 3; pPoly->mEdgeList[3].vertex[1] = 0; pPoly->mEdgeList[3].face[0] = 0; pPoly->mEdgeList[3].face[1] = 2;
  282. pPoly->mEdgeList[4].vertex[0] = 3; pPoly->mEdgeList[4].vertex[1] = 6; pPoly->mEdgeList[4].face[0] = 3; pPoly->mEdgeList[4].face[1] = 2;
  283. pPoly->mEdgeList[5].vertex[0] = 6; pPoly->mEdgeList[5].vertex[1] = 2; pPoly->mEdgeList[5].face[0] = 2; pPoly->mEdgeList[5].face[1] = 5;
  284. pPoly->mEdgeList[6].vertex[0] = 2; pPoly->mEdgeList[6].vertex[1] = 0; pPoly->mEdgeList[6].face[0] = 2; pPoly->mEdgeList[6].face[1] = 1;
  285. pPoly->mEdgeList[7].vertex[0] = 1; pPoly->mEdgeList[7].vertex[1] = 4; pPoly->mEdgeList[7].face[0] = 4; pPoly->mEdgeList[7].face[1] = 1;
  286. pPoly->mEdgeList[8].vertex[0] = 4; pPoly->mEdgeList[8].vertex[1] = 2; pPoly->mEdgeList[8].face[0] = 1; pPoly->mEdgeList[8].face[1] = 5;
  287. pPoly->mEdgeList[9].vertex[0] = 4; pPoly->mEdgeList[9].vertex[1] = 7; pPoly->mEdgeList[9].face[0] = 4; pPoly->mEdgeList[9].face[1] = 5;
  288. pPoly->mEdgeList[10].vertex[0] = 5; pPoly->mEdgeList[10].vertex[1] = 7; pPoly->mEdgeList[10].face[0] = 3; pPoly->mEdgeList[10].face[1] = 4;
  289. pPoly->mEdgeList[11].vertex[0] = 7; pPoly->mEdgeList[11].vertex[1] = 6; pPoly->mEdgeList[11].face[0] = 3; pPoly->mEdgeList[11].face[1] = 5;
  290. }
  291. //-----------------------------------------------------------------------------
  292. void Trigger::consoleInit()
  293. {
  294. Con::addVariable( "$Trigger::renderTriggers", TypeBool, &smRenderTriggers,
  295. "@brief Forces all Trigger's to render.\n\n"
  296. "Used by the Tools and debug render modes.\n"
  297. "@ingroup gameObjects" );
  298. }
  299. void Trigger::initPersistFields()
  300. {
  301. docsURL;
  302. addField("polyhedron", TypeTriggerPolyhedron, Offset(mTriggerPolyhedron, Trigger),
  303. "@brief Defines a non-rectangular area for the trigger.\n\n"
  304. "Rather than the standard rectangular bounds, this optional parameter defines a quadrilateral "
  305. "trigger area. The quadrilateral is defined as a corner point followed by three vectors "
  306. "representing the edges extending from the corner.\n");
  307. addField("TripOnce", TypeBool, Offset(mTripOnce, Trigger),"Do we trigger callacks just the once?");
  308. addField("TripCondition", TypeRealString, Offset(mTripCondition, Trigger),"evaluation condition to trip callbacks (true/false)");
  309. addField("TrippedBy", TypeS32, Offset(mTrippedBy, Trigger), "typemask filter");
  310. addProtectedField("enterCommand", TypeCommand, Offset(mEnterCommand, Trigger), &setEnterCmd, &defaultProtectedGetFn,
  311. "The command to execute when an object enters this trigger. Object id stored in %%obj. Maximum 1023 characters." );
  312. addProtectedField("leaveCommand", TypeCommand, Offset(mLeaveCommand, Trigger), &setLeaveCmd, &defaultProtectedGetFn,
  313. "The command to execute when an object leaves this trigger. Object id stored in %%obj. Maximum 1023 characters." );
  314. addProtectedField("tickCommand", TypeCommand, Offset(mTickCommand, Trigger), &setTickCmd, &defaultProtectedGetFn,
  315. "The command to execute while an object is inside this trigger. Maximum 1023 characters." );
  316. Parent::initPersistFields();
  317. }
  318. bool Trigger::setEnterCmd( void *object, const char *index, const char *data )
  319. {
  320. static_cast<Trigger*>(object)->setMaskBits(EnterCmdMask);
  321. return true; // to update the actual field
  322. }
  323. bool Trigger::setLeaveCmd(void *object, const char *index, const char *data)
  324. {
  325. static_cast<Trigger*>(object)->setMaskBits(LeaveCmdMask);
  326. return true; // to update the actual field
  327. }
  328. bool Trigger::setTickCmd(void *object, const char *index, const char *data)
  329. {
  330. static_cast<Trigger*>(object)->setMaskBits(TickCmdMask);
  331. return true; // to update the actual field
  332. }
  333. //------------------------------------------------------------------------------
  334. void Trigger::testObjects()
  335. {
  336. Vector<SceneObject*> foundobjs;
  337. foundobjs.clear();
  338. if (getSceneManager() && getSceneManager()->getContainer() && getSceneManager()->getZoneManager())
  339. getSceneManager()->getContainer()->findObjectList(getWorldBox(), mTrippedBy, &foundobjs);
  340. else return;
  341. for (S32 i = 0; i < foundobjs.size(); i++)
  342. {
  343. GameBase* so = dynamic_cast<GameBase*>(foundobjs[i]);
  344. if (so)
  345. potentialEnterObject(so);
  346. }
  347. }
  348. //--------------------------------------------------------------------------
  349. bool Trigger::onAdd()
  350. {
  351. if(!Parent::onAdd())
  352. return false;
  353. onAdd_callback( getId() );
  354. Polyhedron temp = mTriggerPolyhedron;
  355. setTriggerPolyhedron(temp);
  356. mTripped = false;
  357. addToScene();
  358. if (isServerObject())
  359. scriptOnAdd();
  360. testObjects();
  361. return true;
  362. }
  363. void Trigger::onRemove()
  364. {
  365. onRemove_callback( getId() );
  366. mConvexList->nukeList();
  367. removeFromScene();
  368. Parent::onRemove();
  369. }
  370. bool Trigger::onNewDataBlock( GameBaseData *dptr, bool reload )
  371. {
  372. mDataBlock = dynamic_cast<TriggerData*>( dptr );
  373. if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) )
  374. return false;
  375. scriptOnNewDataBlock();
  376. return true;
  377. }
  378. void Trigger::onDeleteNotify( SimObject *obj )
  379. {
  380. GameBase* pScene = dynamic_cast<GameBase*>( obj );
  381. if ( pScene != NULL && mDataBlock != NULL )
  382. {
  383. for ( U32 i = 0; i < mObjects.size(); i++ )
  384. {
  385. if ( pScene == mObjects[i] )
  386. {
  387. mObjects.erase(i);
  388. if (mDataBlock)
  389. mDataBlock->onLeaveTrigger_callback( this, NULL );
  390. break;
  391. }
  392. }
  393. }
  394. Parent::onDeleteNotify( obj );
  395. }
  396. void Trigger::inspectPostApply()
  397. {
  398. setTriggerPolyhedron(mTriggerPolyhedron);
  399. setMaskBits(PolyMask);
  400. Parent::inspectPostApply();
  401. }
  402. //--------------------------------------------------------------------------
  403. void Trigger::buildConvex(const Box3F& box, Convex* convex)
  404. {
  405. // These should really come out of a pool
  406. mConvexList->collectGarbage();
  407. Box3F realBox = box;
  408. mWorldToObj.mul(realBox);
  409. realBox.minExtents.convolveInverse(mObjScale);
  410. realBox.maxExtents.convolveInverse(mObjScale);
  411. if (realBox.isOverlapped(getObjBox()) == false)
  412. return;
  413. // Just return a box convex for the entire shape...
  414. Convex* cc = 0;
  415. CollisionWorkingList& wl = convex->getWorkingList();
  416. for (CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext) {
  417. if (itr->mConvex->getType() == BoxConvexType &&
  418. itr->mConvex->getObject() == this) {
  419. cc = itr->mConvex;
  420. break;
  421. }
  422. }
  423. if (cc)
  424. return;
  425. // Create a new convex.
  426. BoxConvex* cp = new BoxConvex;
  427. mConvexList->registerObject(cp);
  428. convex->addToWorkingList(cp);
  429. cp->init(this);
  430. mObjBox.getCenter(&cp->mCenter);
  431. cp->mSize.x = mObjBox.len_x() / 2.0f;
  432. cp->mSize.y = mObjBox.len_y() / 2.0f;
  433. cp->mSize.z = mObjBox.len_z() / 2.0f;
  434. }
  435. //------------------------------------------------------------------------------
  436. void Trigger::setTransform(const MatrixF & mat)
  437. {
  438. Parent::setTransform(mat);
  439. if ( mPhysicsRep )
  440. mPhysicsRep->setTransform( mat );
  441. if (isServerObject()) {
  442. MatrixF base(true);
  443. base.scale(Point3F(1.0/mObjScale.x,
  444. 1.0/mObjScale.y,
  445. 1.0/mObjScale.z));
  446. base.mul(mWorldToObj);
  447. mClippedList.setBaseTransform(base);
  448. setMaskBits(TransformMask | ScaleMask);
  449. }
  450. testObjects();
  451. }
  452. void Trigger::onUnmount( SceneObject *obj, S32 node )
  453. {
  454. Parent::onUnmount( obj, node );
  455. // Make sure the client get's the final server pos.
  456. setMaskBits(TransformMask | ScaleMask);
  457. }
  458. void Trigger::prepRenderImage( SceneRenderState *state )
  459. {
  460. // only render if selected or render flag is set
  461. if ( !smRenderTriggers && !isSelected() )
  462. return;
  463. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  464. ri->renderDelegate.bind( this, &Trigger::renderObject );
  465. ri->type = RenderPassManager::RIT_Editor;
  466. ri->translucentSort = true;
  467. ri->defaultKey = 1;
  468. state->getRenderPass()->addInst( ri );
  469. }
  470. void Trigger::renderObject( ObjectRenderInst *ri,
  471. SceneRenderState *state,
  472. BaseMatInstance *overrideMat )
  473. {
  474. if(overrideMat)
  475. return;
  476. GFXStateBlockDesc desc;
  477. desc.setZReadWrite( true, false );
  478. desc.setBlend( true );
  479. // Trigger polyhedrons are set up with outward facing normals and CCW ordering
  480. // so can't enable backface culling.
  481. desc.setCullMode( GFXCullNone );
  482. GFXTransformSaver saver;
  483. MatrixF mat = getRenderTransform();
  484. mat.scale( getScale() );
  485. GFX->multWorld( mat );
  486. GFXDrawUtil *drawer = GFX->getDrawUtil();
  487. drawer->drawPolyhedron( desc, mTriggerPolyhedron, ColorI( 255, 192, 0, 45 ) );
  488. // Render wireframe.
  489. desc.setFillModeWireframe();
  490. drawer->drawPolyhedron( desc, mTriggerPolyhedron, ColorI::BLACK );
  491. }
  492. void Trigger::setTriggerPolyhedron(const Polyhedron& rPolyhedron)
  493. {
  494. mTriggerPolyhedron = rPolyhedron;
  495. if (mTriggerPolyhedron.mPointList.size() != 0) {
  496. mObjBox.minExtents.set(1e10, 1e10, 1e10);
  497. mObjBox.maxExtents.set(-1e10, -1e10, -1e10);
  498. for (U32 i = 0; i < mTriggerPolyhedron.mPointList.size(); i++) {
  499. mObjBox.minExtents.setMin(mTriggerPolyhedron.mPointList[i]);
  500. mObjBox.maxExtents.setMax(mTriggerPolyhedron.mPointList[i]);
  501. }
  502. } else {
  503. mObjBox.minExtents.set(-0.5, -0.5, -0.5);
  504. mObjBox.maxExtents.set( 0.5, 0.5, 0.5);
  505. }
  506. MatrixF xform = getTransform();
  507. setTransform(xform);
  508. mClippedList.clear();
  509. mClippedList.mPlaneList = mTriggerPolyhedron.mPlaneList;
  510. // for (U32 i = 0; i < mClippedList.mPlaneList.size(); i++)
  511. // mClippedList.mPlaneList[i].neg();
  512. MatrixF base(true);
  513. base.scale(Point3F(1.0/mObjScale.x,
  514. 1.0/mObjScale.y,
  515. 1.0/mObjScale.z));
  516. base.mul(mWorldToObj);
  517. mClippedList.setBaseTransform(base);
  518. SAFE_DELETE( mPhysicsRep );
  519. if ( PHYSICSMGR )
  520. {
  521. PhysicsCollision *colShape = PHYSICSMGR->createCollision();
  522. MatrixF colMat( true );
  523. colMat.displace( Point3F( 0, 0, mObjBox.getExtents().z * 0.5f * mObjScale.z ) );
  524. colShape->addBox( mObjBox.getExtents() * 0.5f * mObjScale, colMat );
  525. //MatrixF colMat( true );
  526. //colMat.scale( mObjScale );
  527. //colShape->addConvex( mTriggerPolyhedron.pointList.address(), mTriggerPolyhedron.pointList.size(), colMat );
  528. PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  529. mPhysicsRep = PHYSICSMGR->createBody();
  530. mPhysicsRep->init( colShape, 0, PhysicsBody::BF_TRIGGER | PhysicsBody::BF_KINEMATIC, this, world );
  531. mPhysicsRep->setTransform( getTransform() );
  532. }
  533. }
  534. //--------------------------------------------------------------------------
  535. bool Trigger::testObject(GameBase* enter)
  536. {
  537. if (mTriggerPolyhedron.mPointList.size() == 0)
  538. return false;
  539. if (!(enter->getTypeMask() & mTrippedBy))
  540. return false; //not the right type of object
  541. mClippedList.clear();
  542. SphereF sphere;
  543. sphere.center = (mWorldBox.minExtents + mWorldBox.maxExtents) * 0.5;
  544. VectorF bv = mWorldBox.maxExtents - sphere.center;
  545. sphere.radius = bv.len();
  546. enter->buildPolyList(PLC_Collision, &mClippedList, mWorldBox, sphere);
  547. return mClippedList.isEmpty() == false;
  548. }
  549. bool Trigger::testTrippable()
  550. {
  551. if ((mTripOnce == true) && (mTripped == true))
  552. return false; // we've already fired the once
  553. return true;
  554. }
  555. bool Trigger::testCondition()
  556. {
  557. if (mTripCondition.isEmpty())
  558. return true; //we've got no tests to run so just do it
  559. //test the mapper plugged in condition line
  560. String resVar = getIdString() + String(".result");
  561. Con::setBoolVariable(resVar.c_str(), false);
  562. String command = resVar + "=" + mTripCondition + ";";
  563. Con::evaluatef(command.c_str());
  564. if (Con::getBoolVariable(resVar.c_str()) == 1)
  565. {
  566. return true;
  567. }
  568. return false;
  569. }
  570. bool Trigger::evalCmD(String* cmd)
  571. {
  572. if (!testTrippable()) return false;
  573. if (cmd && cmd->isNotEmpty())//do we have a callback?
  574. {
  575. return testCondition();
  576. }
  577. return false;
  578. }
  579. void Trigger::potentialEnterObject(GameBase* enter)
  580. {
  581. if( (!mDataBlock || mDataBlock->isClientSide) && isServerObject() )
  582. return;
  583. if( (mDataBlock && !mDataBlock->isClientSide) && isGhost() )
  584. return;
  585. for (U32 i = 0; i < mObjects.size(); i++) {
  586. if (mObjects[i] == enter)
  587. return;
  588. }
  589. if (testObject(enter) == true) {
  590. mObjects.push_back(enter);
  591. deleteNotify(enter);
  592. if(evalCmD(&mEnterCommand))
  593. {
  594. String command = String("%obj = ") + enter->getIdString() + ";";
  595. command = command + String("%this = ") + getIdString() + ";" + mEnterCommand;
  596. Con::evaluate(command.c_str());
  597. }
  598. if( mDataBlock && testTrippable() && testCondition())
  599. mDataBlock->onEnterTrigger_callback( this, enter );
  600. mTripped = true;
  601. }
  602. }
  603. void Trigger::processTick(const Move* move)
  604. {
  605. Parent::processTick(move);
  606. if (!mDataBlock)
  607. return;
  608. if (mDataBlock->isClientSide && isServerObject())
  609. return;
  610. if (!mDataBlock->isClientSide && isClientObject())
  611. return;
  612. if (isMounted()) {
  613. MatrixF mat;
  614. mMount.object->getMountTransform( mMount.node, mMount.xfm, &mat );
  615. setTransform(mat);
  616. setRenderTransform(mat);
  617. }
  618. //
  619. if (mObjects.size() == 0)
  620. return;
  621. if (mLastThink + mDataBlock->tickPeriodMS < mCurrTick)
  622. {
  623. mCurrTick = 0;
  624. mLastThink = 0;
  625. for (S32 i = S32(mObjects.size() - 1); i >= 0; i--)
  626. {
  627. if (testObject(mObjects[i]) == false)
  628. {
  629. GameBase* remove = mObjects[i];
  630. mObjects.erase(i);
  631. clearNotify(remove);
  632. if (evalCmD(&mLeaveCommand))
  633. {
  634. String command = String("%obj = ") + remove->getIdString() + ";";
  635. command = command + String("%this = ") + getIdString() + ";" + mLeaveCommand;
  636. Con::evaluate(command.c_str());
  637. }
  638. if (testTrippable() && testCondition())
  639. mDataBlock->onLeaveTrigger_callback( this, remove );
  640. mTripped = true;
  641. }
  642. }
  643. if (evalCmD(&mTickCommand))
  644. Con::evaluate(mTickCommand.c_str());
  645. if (mObjects.size() != 0 && testTrippable() && testCondition())
  646. mDataBlock->onTickTrigger_callback( this );
  647. }
  648. else
  649. {
  650. mCurrTick += TickMs;
  651. }
  652. }
  653. void Trigger::interpolateTick(F32 delta)
  654. {
  655. if (isMounted()) {
  656. MatrixF mat;
  657. mMount.object->getRenderMountTransform( delta, mMount.node, mMount.xfm, &mat );
  658. setRenderTransform(mat);
  659. }
  660. }
  661. //--------------------------------------------------------------------------
  662. U32 Trigger::packUpdate(NetConnection* con, U32 mask, BitStream* stream)
  663. {
  664. U32 i;
  665. U32 retMask = Parent::packUpdate(con, mask, stream);
  666. if( stream->writeFlag( mask & TransformMask ) )
  667. {
  668. stream->writeAffineTransform(mObjToWorld);
  669. }
  670. // Write the polyhedron
  671. if( stream->writeFlag( mask & PolyMask ) )
  672. {
  673. stream->write(mTriggerPolyhedron.mPointList.size());
  674. for (i = 0; i < mTriggerPolyhedron.mPointList.size(); i++)
  675. mathWrite(*stream, mTriggerPolyhedron.mPointList[i]);
  676. stream->write(mTriggerPolyhedron.mPlaneList.size());
  677. for (i = 0; i < mTriggerPolyhedron.mPlaneList.size(); i++)
  678. mathWrite(*stream, mTriggerPolyhedron.mPlaneList[i]);
  679. stream->write(mTriggerPolyhedron.mEdgeList.size());
  680. for (i = 0; i < mTriggerPolyhedron.mEdgeList.size(); i++) {
  681. const Polyhedron::Edge& rEdge = mTriggerPolyhedron.mEdgeList[i];
  682. stream->write(rEdge.face[0]);
  683. stream->write(rEdge.face[1]);
  684. stream->write(rEdge.vertex[0]);
  685. stream->write(rEdge.vertex[1]);
  686. }
  687. }
  688. if( stream->writeFlag( mask & EnterCmdMask ) )
  689. stream->writeLongString(CMD_SIZE-1, mEnterCommand.c_str());
  690. if( stream->writeFlag( mask & LeaveCmdMask ) )
  691. stream->writeLongString(CMD_SIZE-1, mLeaveCommand.c_str());
  692. if( stream->writeFlag( mask & TickCmdMask ) )
  693. stream->writeLongString(CMD_SIZE-1, mTickCommand.c_str());
  694. return retMask;
  695. }
  696. void Trigger::unpackUpdate(NetConnection* con, BitStream* stream)
  697. {
  698. Parent::unpackUpdate(con, stream);
  699. U32 i, size;
  700. // Transform
  701. if( stream->readFlag() )
  702. {
  703. MatrixF temp;
  704. stream->readAffineTransform(&temp);
  705. setTransform(temp);
  706. }
  707. // Read the polyhedron
  708. if( stream->readFlag() )
  709. {
  710. Polyhedron tempPH;
  711. stream->read(&size);
  712. tempPH.mPointList.setSize(size);
  713. for (i = 0; i < tempPH.mPointList.size(); i++)
  714. mathRead(*stream, &tempPH.mPointList[i]);
  715. stream->read(&size);
  716. tempPH.mPlaneList.setSize(size);
  717. for (i = 0; i < tempPH.mPlaneList.size(); i++)
  718. mathRead(*stream, &tempPH.mPlaneList[i]);
  719. stream->read(&size);
  720. tempPH.mEdgeList.setSize(size);
  721. for (i = 0; i < tempPH.mEdgeList.size(); i++) {
  722. Polyhedron::Edge& rEdge = tempPH.mEdgeList[i];
  723. stream->read(&rEdge.face[0]);
  724. stream->read(&rEdge.face[1]);
  725. stream->read(&rEdge.vertex[0]);
  726. stream->read(&rEdge.vertex[1]);
  727. }
  728. setTriggerPolyhedron(tempPH);
  729. }
  730. if( stream->readFlag() )
  731. {
  732. char buf[CMD_SIZE];
  733. stream->readLongString(CMD_SIZE-1, buf);
  734. mEnterCommand = buf;
  735. }
  736. if( stream->readFlag() )
  737. {
  738. char buf[CMD_SIZE];
  739. stream->readLongString(CMD_SIZE-1, buf);
  740. mLeaveCommand = buf;
  741. }
  742. if( stream->readFlag() )
  743. {
  744. char buf[CMD_SIZE];
  745. stream->readLongString(CMD_SIZE-1, buf);
  746. mTickCommand = buf;
  747. }
  748. }
  749. //ConsoleMethod( Trigger, getNumObjects, S32, 2, 2, "")
  750. DefineEngineMethod( Trigger, getNumObjects, S32, (),,
  751. "@brief Get the number of objects that are within the Trigger's bounds.\n\n"
  752. "@see getObject()\n")
  753. {
  754. return object->getNumTriggeringObjects();
  755. }
  756. //ConsoleMethod( Trigger, getObject, S32, 3, 3, "(int idx)")
  757. DefineEngineMethod( Trigger, getObject, S32, ( S32 index ),,
  758. "@brief Retrieve the requested object that is within the Trigger's bounds.\n\n"
  759. "@param index Index of the object to get (range is 0 to getNumObjects()-1)\n"
  760. "@returns The SimObjectID of the object, or -1 if the requested index is invalid.\n"
  761. "@see getNumObjects()\n")
  762. {
  763. if (index >= object->getNumTriggeringObjects() || index < 0)
  764. return -1;
  765. else
  766. return object->getObject(U32(index))->getId();
  767. }