navMesh.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2014 Daniel Buckmaster
  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 "navMesh.h"
  23. #include "navContext.h"
  24. #include <DetourDebugDraw.h>
  25. #include <RecastDebugDraw.h>
  26. #include "math/mathUtils.h"
  27. #include "math/mRandom.h"
  28. #include "console/consoleTypes.h"
  29. #include "console/engineAPI.h"
  30. #include "console/typeValidators.h"
  31. #include "scene/sceneRenderState.h"
  32. #include "gfx/gfxDrawUtil.h"
  33. #include "renderInstance/renderPassManager.h"
  34. #include "gfx/primBuilder.h"
  35. #include "core/stream/bitStream.h"
  36. #include "math/mathIO.h"
  37. #include "core/stream/fileStream.h"
  38. extern bool gEditingMission;
  39. IMPLEMENT_CO_NETOBJECT_V1(NavMesh);
  40. const U32 NavMesh::mMaxVertsPerPoly = 3;
  41. SimObjectPtr<SimSet> NavMesh::smServerSet = NULL;
  42. ImplementEnumType(NavMeshWaterMethod,
  43. "The method used to include water surfaces in the NavMesh.\n")
  44. { NavMesh::Ignore, "Ignore", "Ignore all water surfaces.\n" },
  45. { NavMesh::Solid, "Solid", "Treat water surfaces as solid and walkable.\n" },
  46. { NavMesh::Impassable, "Impassable", "Treat water as an impassable obstacle.\n" },
  47. EndImplementEnumType;
  48. SimSet *NavMesh::getServerSet()
  49. {
  50. if(!smServerSet)
  51. {
  52. SimSet *set = NULL;
  53. if(Sim::findObject("ServerNavMeshSet", set))
  54. smServerSet = set;
  55. else
  56. {
  57. smServerSet = new SimSet();
  58. smServerSet->registerObject("ServerNavMeshSet");
  59. Sim::getRootGroup()->addObject(smServerSet);
  60. }
  61. }
  62. return smServerSet;
  63. }
  64. SimObjectPtr<EventManager> NavMesh::smEventManager = NULL;
  65. EventManager *NavMesh::getEventManager()
  66. {
  67. if(!smEventManager)
  68. {
  69. smEventManager = new EventManager();
  70. smEventManager->registerObject("NavEventManager");
  71. Sim::getRootGroup()->addObject(smEventManager);
  72. smEventManager->setMessageQueue("NavEventManagerQueue");
  73. smEventManager->registerEvent("NavMeshCreated");
  74. smEventManager->registerEvent("NavMeshRemoved");
  75. smEventManager->registerEvent("NavMeshStartUpdate");
  76. smEventManager->registerEvent("NavMeshUpdate");
  77. smEventManager->registerEvent("NavMeshTileUpdate");
  78. smEventManager->registerEvent("NavMeshUpdateBox");
  79. smEventManager->registerEvent("NavMeshObstacleAdded");
  80. smEventManager->registerEvent("NavMeshObstacleRemoved");
  81. }
  82. return smEventManager;
  83. }
  84. DefineEngineFunction(getNavMeshEventManager, S32, (),,
  85. "@brief Get the EventManager object for all NavMesh updates.")
  86. {
  87. return NavMesh::getEventManager()->getId();
  88. }
  89. DefineEngineFunction(NavMeshUpdateAll, void, (S32 objid, bool remove), (0, false),
  90. "@brief Update all NavMesh tiles that intersect the given object's world box.")
  91. {
  92. SceneObject *obj;
  93. if(!Sim::findObject(objid, obj))
  94. return;
  95. obj->mPathfindingIgnore = remove;
  96. SimSet *set = NavMesh::getServerSet();
  97. for(U32 i = 0; i < set->size(); i++)
  98. {
  99. NavMesh *m = dynamic_cast<NavMesh*>(set->at(i));
  100. if (m)
  101. {
  102. m->cancelBuild();
  103. m->buildTiles(obj->getWorldBox());
  104. }
  105. }
  106. }
  107. DefineEngineFunction(NavMeshUpdateAroundObject, void, (S32 objid, bool remove), (0, false),
  108. "@brief Update all NavMesh tiles that intersect the given object's world box.")
  109. {
  110. SceneObject *obj;
  111. if (!Sim::findObject(objid, obj))
  112. return;
  113. obj->mPathfindingIgnore = remove;
  114. SimSet *set = NavMesh::getServerSet();
  115. for (U32 i = 0; i < set->size(); i++)
  116. {
  117. NavMesh *m = dynamic_cast<NavMesh*>(set->at(i));
  118. if (m)
  119. {
  120. m->cancelBuild();
  121. m->buildTiles(obj->getWorldBox());
  122. }
  123. }
  124. }
  125. DefineEngineFunction(NavMeshIgnore, void, (S32 objid, bool _ignore), (0, true),
  126. "@brief Flag this object as not generating a navmesh result.")
  127. {
  128. SceneObject *obj;
  129. if(!Sim::findObject(objid, obj))
  130. return;
  131. obj->mPathfindingIgnore = _ignore;
  132. }
  133. DefineEngineFunction(NavMeshUpdateOne, void, (S32 meshid, S32 objid, bool remove), (0, 0, false),
  134. "@brief Update all tiles in a given NavMesh that intersect the given object's world box.")
  135. {
  136. NavMesh *mesh;
  137. SceneObject *obj;
  138. if(!Sim::findObject(meshid, mesh))
  139. {
  140. Con::errorf("NavMeshUpdateOne: cannot find NavMesh %d", meshid);
  141. return;
  142. }
  143. if(!Sim::findObject(objid, obj))
  144. {
  145. Con::errorf("NavMeshUpdateOne: cannot find SceneObject %d", objid);
  146. return;
  147. }
  148. if(remove)
  149. obj->disableCollision();
  150. mesh->buildTiles(obj->getWorldBox());
  151. if(remove)
  152. obj->enableCollision();
  153. }
  154. NavMesh::NavMesh()
  155. {
  156. mTypeMask |= StaticShapeObjectType | MarkerObjectType;
  157. mFileName = StringTable->EmptyString();
  158. mNetFlags.clear(Ghostable);
  159. mSaveIntermediates = false;
  160. nm = NULL;
  161. ctx = NULL;
  162. mWaterMethod = Ignore;
  163. dMemset(&cfg, 0, sizeof(cfg));
  164. mCellSize = mCellHeight = 0.2f;
  165. mWalkableHeight = 2.0f;
  166. mWalkableClimb = 0.3f;
  167. mWalkableRadius = 0.5f;
  168. mWalkableSlope = 40.0f;
  169. mBorderSize = 1;
  170. mDetailSampleDist = 6.0f;
  171. mDetailSampleMaxError = 1.0f;
  172. mMaxEdgeLen = 12;
  173. mMaxSimplificationError = 1.3f;
  174. mMinRegionArea = 8;
  175. mMergeRegionArea = 20;
  176. mTileSize = 10.0f;
  177. mMaxPolysPerTile = 128;
  178. mSmallCharacters = false;
  179. mRegularCharacters = true;
  180. mLargeCharacters = false;
  181. mVehicles = false;
  182. mCoverSet = StringTable->EmptyString();
  183. mInnerCover = false;
  184. mCoverDist = 1.0f;
  185. mPeekDist = 0.7f;
  186. mAlwaysRender = false;
  187. mBuilding = false;
  188. mCurLinkID = 0;
  189. }
  190. NavMesh::~NavMesh()
  191. {
  192. dtFreeNavMesh(nm);
  193. nm = NULL;
  194. delete ctx;
  195. ctx = NULL;
  196. }
  197. bool NavMesh::setProtectedDetailSampleDist(void *obj, const char *index, const char *data)
  198. {
  199. F32 dist = dAtof(data);
  200. if(dist == 0.0f || dist >= 0.9f)
  201. return true;
  202. if (dist > 0.0f && dist < 0.9f)
  203. {
  204. NavMesh* ptr = static_cast<NavMesh*>(obj);
  205. ptr->mDetailSampleDist = 0.9f;
  206. }
  207. Con::errorf("NavMesh::detailSampleDist must be 0 or greater than 0.9!");
  208. return false;
  209. }
  210. bool NavMesh::setProtectedAlwaysRender(void *obj, const char *index, const char *data)
  211. {
  212. NavMesh *mesh = static_cast<NavMesh*>(obj);
  213. bool always = dAtob(data);
  214. if(always)
  215. {
  216. if(!gEditingMission)
  217. mesh->mNetFlags.set(Ghostable);
  218. }
  219. else
  220. {
  221. if(!gEditingMission)
  222. mesh->mNetFlags.clear(Ghostable);
  223. }
  224. mesh->mAlwaysRender = always;
  225. mesh->setMaskBits(LoadFlag);
  226. return true;
  227. }
  228. FRangeValidator ValidCellSize(0.01f, 10.0f);
  229. void NavMesh::initPersistFields()
  230. {
  231. docsURL;
  232. addGroup("NavMesh Options");
  233. addField("fileName", TypeString, Offset(mFileName, NavMesh),
  234. "Name of the data file to store this navmesh in (relative to engine executable).");
  235. addField("waterMethod", TYPEID<NavMeshWaterMethod>(), Offset(mWaterMethod, NavMesh),
  236. "The method to use to handle water surfaces.");
  237. addFieldV("cellSize", TypeRangedF32, Offset(mCellSize, NavMesh), &ValidCellSize,
  238. "Length/width of a voxel.");
  239. addFieldV("cellHeight", TypeRangedF32, Offset(mCellHeight, NavMesh), &ValidCellSize,
  240. "Height of a voxel.");
  241. addFieldV("tileSize", TypeRangedF32, Offset(mTileSize, NavMesh), &CommonValidators::PositiveNonZeroFloat,
  242. "The horizontal size of tiles.");
  243. addFieldV("actorHeight", TypeRangedF32, Offset(mWalkableHeight, NavMesh), &CommonValidators::PositiveFloat,
  244. "Height of an actor.");
  245. addFieldV("actorClimb", TypeRangedF32, Offset(mWalkableClimb, NavMesh), &CommonValidators::PositiveFloat,
  246. "Maximum climbing height of an actor.");
  247. addFieldV("actorRadius", TypeRangedF32, Offset(mWalkableRadius, NavMesh), &CommonValidators::PositiveFloat,
  248. "Radius of an actor.");
  249. addFieldV("walkableSlope", TypeRangedF32, Offset(mWalkableSlope, NavMesh), &CommonValidators::ValidSlopeAngle,
  250. "Maximum walkable slope in degrees.");
  251. addField("smallCharacters", TypeBool, Offset(mSmallCharacters, NavMesh),
  252. "Is this NavMesh for smaller-than-usual characters?");
  253. addField("regularCharacters", TypeBool, Offset(mRegularCharacters, NavMesh),
  254. "Is this NavMesh for regular-sized characters?");
  255. addField("largeCharacters", TypeBool, Offset(mLargeCharacters, NavMesh),
  256. "Is this NavMesh for larger-than-usual characters?");
  257. addField("vehicles", TypeBool, Offset(mVehicles, NavMesh),
  258. "Is this NavMesh for characters driving vehicles?");
  259. endGroup("NavMesh Options");
  260. addGroup("NavMesh Annotations");
  261. addField("coverGroup", TypeString, Offset(mCoverSet, NavMesh),
  262. "Name of the SimGroup to store cover points in.");
  263. addField("innerCover", TypeBool, Offset(mInnerCover, NavMesh),
  264. "Add cover points everywhere, not just on corners?");
  265. addFieldV("coverDist", TypeRangedF32, Offset(mCoverDist, NavMesh), &CommonValidators::PositiveFloat,
  266. "Distance from the edge of the NavMesh to search for cover.");
  267. addFieldV("peekDist", TypeRangedF32, Offset(mPeekDist, NavMesh), &CommonValidators::PositiveFloat,
  268. "Distance to the side of each cover point that peeking happens.");
  269. endGroup("NavMesh Annotations");
  270. addGroup("NavMesh Rendering");
  271. addProtectedField("alwaysRender", TypeBool, Offset(mAlwaysRender, NavMesh),
  272. &setProtectedAlwaysRender, &defaultProtectedGetFn,
  273. "Display this NavMesh even outside the editor.");
  274. endGroup("NavMesh Rendering");
  275. addGroup("NavMesh Advanced Options");
  276. addFieldV("borderSize", TypeRangedS32, Offset(mBorderSize, NavMesh), &CommonValidators::PositiveInt,
  277. "Size of the non-walkable border around the navigation mesh (in voxels).");
  278. addProtectedFieldV("detailSampleDist", TypeRangedF32, Offset(mDetailSampleDist, NavMesh),
  279. &setProtectedDetailSampleDist, &defaultProtectedGetFn, &CommonValidators::PositiveFloat,
  280. "Sets the sampling distance to use when generating the detail mesh.");
  281. addFieldV("detailSampleError", TypeRangedF32, Offset(mDetailSampleMaxError, NavMesh), &CommonValidators::PositiveFloat,
  282. "The maximum distance the detail mesh surface should deviate from heightfield data.");
  283. addFieldV("maxEdgeLen", TypeRangedS32, Offset(mDetailSampleDist, NavMesh), &CommonValidators::PositiveInt,
  284. "The maximum allowed length for contour edges along the border of the mesh.");
  285. addFieldV("simplificationError", TypeRangedF32, Offset(mMaxSimplificationError, NavMesh), &CommonValidators::PositiveFloat,
  286. "The maximum distance a simplfied contour's border edges should deviate from the original raw contour.");
  287. addFieldV("minRegionArea", TypeRangedS32, Offset(mMinRegionArea, NavMesh), &CommonValidators::PositiveInt,
  288. "The minimum number of cells allowed to form isolated island areas.");
  289. addFieldV("mergeRegionArea", TypeRangedS32, Offset(mMergeRegionArea, NavMesh), &CommonValidators::PositiveInt,
  290. "Any regions with a span count smaller than this value will, if possible, be merged with larger regions.");
  291. addFieldV("maxPolysPerTile", TypeRangedS32, Offset(mMaxPolysPerTile, NavMesh), &CommonValidators::NaturalNumber,
  292. "The maximum number of polygons allowed in a tile.");
  293. endGroup("NavMesh Advanced Options");
  294. Parent::initPersistFields();
  295. }
  296. bool NavMesh::onAdd()
  297. {
  298. if(!Parent::onAdd())
  299. return false;
  300. mObjBox.set(Point3F(-0.5f, -0.5f, -0.5f),
  301. Point3F( 0.5f, 0.5f, 0.5f));
  302. resetWorldBox();
  303. addToScene();
  304. if(gEditingMission || mAlwaysRender)
  305. {
  306. mNetFlags.set(Ghostable);
  307. if(isClientObject())
  308. renderToDrawer();
  309. }
  310. if(isServerObject())
  311. {
  312. getServerSet()->addObject(this);
  313. ctx = new NavContext();
  314. setProcessTick(true);
  315. if(getEventManager())
  316. getEventManager()->postEvent("NavMeshCreated", getIdString());
  317. }
  318. load();
  319. return true;
  320. }
  321. void NavMesh::onRemove()
  322. {
  323. if(getEventManager())
  324. getEventManager()->postEvent("NavMeshRemoved", getIdString());
  325. removeFromScene();
  326. Parent::onRemove();
  327. }
  328. void NavMesh::setTransform(const MatrixF &mat)
  329. {
  330. Parent::setTransform(mat);
  331. }
  332. void NavMesh::setScale(const VectorF &scale)
  333. {
  334. Parent::setScale(scale);
  335. }
  336. S32 NavMesh::addLink(const Point3F &from, const Point3F &to, U32 flags)
  337. {
  338. Point3F rcFrom = DTStoRC(from), rcTo = DTStoRC(to);
  339. mLinkVerts.push_back(rcFrom.x);
  340. mLinkVerts.push_back(rcFrom.y);
  341. mLinkVerts.push_back(rcFrom.z);
  342. mLinkVerts.push_back(rcTo.x);
  343. mLinkVerts.push_back(rcTo.y);
  344. mLinkVerts.push_back(rcTo.z);
  345. mLinksUnsynced.push_back(true);
  346. mLinkRads.push_back(mWalkableRadius);
  347. mLinkDirs.push_back(0);
  348. mLinkAreas.push_back(OffMeshArea);
  349. if (flags == 0) {
  350. Point3F dir = to - from;
  351. F32 drop = -dir.z;
  352. dir.z = 0;
  353. // If we drop more than we travel horizontally, we're a drop link.
  354. if(drop > dir.len())
  355. mLinkFlags.push_back(DropFlag);
  356. else
  357. mLinkFlags.push_back(JumpFlag);
  358. }
  359. mLinkIDs.push_back(1000 + mCurLinkID);
  360. mLinkSelectStates.push_back(Unselected);
  361. mDeleteLinks.push_back(false);
  362. mCurLinkID++;
  363. return mLinkIDs.size() - 1;
  364. }
  365. DefineEngineMethod(NavMesh, addLink, S32, (Point3F from, Point3F to, U32 flags), (0),
  366. "Add a link to this NavMesh between two points.\n\n"
  367. "")
  368. {
  369. return object->addLink(from, to, flags);
  370. }
  371. S32 NavMesh::getLink(const Point3F &pos)
  372. {
  373. for(U32 i = 0; i < mLinkIDs.size(); i++)
  374. {
  375. if(mDeleteLinks[i])
  376. continue;
  377. SphereF start(getLinkStart(i), mLinkRads[i]);
  378. SphereF end(getLinkEnd(i), mLinkRads[i]);
  379. if(start.isContained(pos) || end.isContained(pos))
  380. return i;
  381. }
  382. return -1;
  383. }
  384. DefineEngineMethod(NavMesh, getLink, S32, (Point3F pos),,
  385. "Get the off-mesh link closest to a given world point.")
  386. {
  387. return object->getLink(pos);
  388. }
  389. S32 NavMesh::getLinkCount()
  390. {
  391. return mLinkIDs.size();
  392. }
  393. DefineEngineMethod(NavMesh, getLinkCount, S32, (),,
  394. "Return the number of links this mesh has.")
  395. {
  396. return object->getLinkCount();
  397. }
  398. LinkData NavMesh::getLinkFlags(U32 idx)
  399. {
  400. if(idx < mLinkIDs.size())
  401. {
  402. return LinkData(mLinkFlags[idx]);
  403. }
  404. return LinkData();
  405. }
  406. DefineEngineMethod(NavMesh, getLinkFlags, S32, (U32 id),,
  407. "Get the flags set for a particular off-mesh link.")
  408. {
  409. return object->getLinkFlags(id).getFlags();
  410. }
  411. void NavMesh::setLinkFlags(U32 idx, const LinkData &d)
  412. {
  413. if(idx < mLinkIDs.size())
  414. {
  415. mLinkFlags[idx] = d.getFlags();
  416. mLinksUnsynced[idx] = true;
  417. }
  418. }
  419. DefineEngineMethod(NavMesh, setLinkFlags, void, (U32 id, U32 flags),,
  420. "Set the flags of a particular off-mesh link.")
  421. {
  422. LinkData d(flags);
  423. object->setLinkFlags(id, d);
  424. }
  425. Point3F NavMesh::getLinkStart(U32 idx)
  426. {
  427. return RCtoDTS(Point3F(
  428. mLinkVerts[idx*6],
  429. mLinkVerts[idx*6 + 1],
  430. mLinkVerts[idx*6 + 2]));
  431. }
  432. DefineEngineMethod(NavMesh, getLinkStart, Point3F, (U32 id),,
  433. "Get the starting point of an off-mesh link.")
  434. {
  435. return object->getLinkStart(id);
  436. }
  437. Point3F NavMesh::getLinkEnd(U32 idx)
  438. {
  439. return RCtoDTS(Point3F(
  440. mLinkVerts[idx*6 + 3],
  441. mLinkVerts[idx*6 + 4],
  442. mLinkVerts[idx*6 + 5]));
  443. }
  444. DefineEngineMethod(NavMesh, getLinkEnd, Point3F, (U32 id),,
  445. "Get the ending point of an off-mesh link.")
  446. {
  447. return object->getLinkEnd(id);
  448. }
  449. void NavMesh::selectLink(U32 idx, bool select, bool hover)
  450. {
  451. if(idx < mLinkIDs.size())
  452. {
  453. if(!select)
  454. mLinkSelectStates[idx] = Unselected;
  455. else
  456. mLinkSelectStates[idx] = hover ? Hovered : Selected;
  457. }
  458. }
  459. void NavMesh::eraseLink(U32 i)
  460. {
  461. mLinkVerts.erase(i*6, 6);
  462. mLinksUnsynced.erase(i);
  463. mLinkRads.erase(i);
  464. mLinkDirs.erase(i);
  465. mLinkAreas.erase(i);
  466. mLinkFlags.erase(i);
  467. mLinkIDs.erase(i);
  468. mLinkSelectStates.erase(i);
  469. mDeleteLinks.erase(i);
  470. }
  471. void NavMesh::eraseLinks()
  472. {
  473. mLinkVerts.clear();
  474. mLinksUnsynced.clear();
  475. mLinkRads.clear();
  476. mLinkDirs.clear();
  477. mLinkAreas.clear();
  478. mLinkFlags.clear();
  479. mLinkIDs.clear();
  480. mLinkSelectStates.clear();
  481. mDeleteLinks.clear();
  482. }
  483. void NavMesh::setLinkCount(U32 c)
  484. {
  485. eraseLinks();
  486. mLinkVerts.setSize(c * 6);
  487. mLinksUnsynced.setSize(c);
  488. mLinkRads.setSize(c);
  489. mLinkDirs.setSize(c);
  490. mLinkAreas.setSize(c);
  491. mLinkFlags.setSize(c);
  492. mLinkIDs.setSize(c);
  493. mLinkSelectStates.setSize(c);
  494. mDeleteLinks.setSize(c);
  495. }
  496. void NavMesh::deleteLink(U32 idx)
  497. {
  498. if(idx < mLinkIDs.size())
  499. {
  500. mDeleteLinks[idx] = true;
  501. if(mLinksUnsynced[idx])
  502. eraseLink(idx);
  503. else
  504. mLinksUnsynced[idx] = true;
  505. }
  506. }
  507. DefineEngineMethod(NavMesh, deleteLink, void, (U32 id),,
  508. "Delete a given off-mesh link.")
  509. {
  510. object->deleteLink(id);
  511. }
  512. DefineEngineMethod(NavMesh, deleteLinks, void, (),,
  513. "Deletes all off-mesh links on this NavMesh.")
  514. {
  515. //object->eraseLinks();
  516. }
  517. bool NavMesh::build(bool background, bool saveIntermediates)
  518. {
  519. if(mBuilding)
  520. cancelBuild();
  521. else
  522. {
  523. if(getEventManager())
  524. getEventManager()->postEvent("NavMeshStartUpdate", getIdString());
  525. }
  526. mBuilding = true;
  527. ctx->startTimer(RC_TIMER_TOTAL);
  528. dtFreeNavMesh(nm);
  529. // Allocate a new navmesh.
  530. nm = dtAllocNavMesh();
  531. if(!nm)
  532. {
  533. Con::errorf("Could not allocate dtNavMesh for NavMesh %s", getIdString());
  534. return false;
  535. }
  536. updateConfig();
  537. // Build navmesh parameters from console members.
  538. dtNavMeshParams params;
  539. rcVcopy(params.orig, cfg.bmin);
  540. params.tileWidth = cfg.tileSize * mCellSize;
  541. params.tileHeight = cfg.tileSize * mCellSize;
  542. params.maxTiles = mCeil(getWorldBox().len_x() / params.tileWidth) * mCeil(getWorldBox().len_y() / params.tileHeight);
  543. params.maxPolys = mMaxPolysPerTile;
  544. // Initialise our navmesh.
  545. if(dtStatusFailed(nm->init(&params)))
  546. {
  547. Con::errorf("Could not init dtNavMesh for NavMesh %s", getIdString());
  548. return false;
  549. }
  550. // Update links to be deleted.
  551. for(U32 i = 0; i < mLinkIDs.size();)
  552. {
  553. if(mDeleteLinks[i])
  554. eraseLink(i);
  555. else
  556. i++;
  557. }
  558. mLinksUnsynced.fill(false);
  559. mCurLinkID = 0;
  560. mSaveIntermediates = saveIntermediates;
  561. updateTiles(true);
  562. if(!background)
  563. {
  564. while(!mDirtyTiles.empty())
  565. buildNextTile();
  566. }
  567. return true;
  568. }
  569. DefineEngineMethod(NavMesh, build, bool, (bool background, bool save), (true, false),
  570. "@brief Create a Recast nav mesh.")
  571. {
  572. return object->build(background, save);
  573. }
  574. void NavMesh::cancelBuild()
  575. {
  576. mDirtyTiles.clear();
  577. ctx->stopTimer(RC_TIMER_TOTAL);
  578. mBuilding = false;
  579. }
  580. DefineEngineMethod(NavMesh, cancelBuild, void, (),,
  581. "@brief Cancel the current NavMesh build.")
  582. {
  583. object->cancelBuild();
  584. }
  585. void NavMesh::inspectPostApply()
  586. {
  587. if(mBuilding)
  588. cancelBuild();
  589. }
  590. void NavMesh::updateConfig()
  591. {
  592. // Build rcConfig object from our console members.
  593. dMemset(&cfg, 0, sizeof(cfg));
  594. cfg.cs = mCellSize;
  595. cfg.ch = mCellHeight;
  596. Box3F box = DTStoRC(getWorldBox());
  597. rcVcopy(cfg.bmin, box.minExtents);
  598. rcVcopy(cfg.bmax, box.maxExtents);
  599. rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height);
  600. cfg.walkableHeight = mCeil(mWalkableHeight / mCellHeight);
  601. cfg.walkableClimb = mCeil(mWalkableClimb / mCellHeight);
  602. cfg.walkableRadius = mCeil(mWalkableRadius / mCellSize);
  603. cfg.walkableSlopeAngle = mWalkableSlope;
  604. cfg.borderSize = cfg.walkableRadius + 3;
  605. cfg.detailSampleDist = mDetailSampleDist;
  606. cfg.detailSampleMaxError = mDetailSampleMaxError;
  607. cfg.maxEdgeLen = mMaxEdgeLen;
  608. cfg.maxSimplificationError = mMaxSimplificationError;
  609. cfg.maxVertsPerPoly = mMaxVertsPerPoly;
  610. cfg.minRegionArea = mMinRegionArea;
  611. cfg.mergeRegionArea = mMergeRegionArea;
  612. cfg.tileSize = mTileSize / cfg.cs;
  613. }
  614. S32 NavMesh::getTile(const Point3F& pos)
  615. {
  616. if(mBuilding)
  617. return -1;
  618. for(U32 i = 0; i < mTiles.size(); i++)
  619. {
  620. if(mTiles[i].box.isContained(pos))
  621. return i;
  622. }
  623. return -1;
  624. }
  625. Box3F NavMesh::getTileBox(U32 id)
  626. {
  627. if(mBuilding || id >= mTiles.size())
  628. return Box3F::Invalid;
  629. return mTiles[id].box;
  630. }
  631. void NavMesh::updateTiles(bool dirty)
  632. {
  633. PROFILE_SCOPE(NavMesh_updateTiles);
  634. if(!isProperlyAdded())
  635. return;
  636. mTiles.clear();
  637. mTileData.clear();
  638. mDirtyTiles.clear();
  639. const Box3F &box = DTStoRC(getWorldBox());
  640. if(box.isEmpty())
  641. return;
  642. updateConfig();
  643. // Calculate tile dimensions.
  644. const U32 ts = cfg.tileSize;
  645. const U32 tw = (cfg.width + ts-1) / ts;
  646. const U32 th = (cfg.height + ts-1) / ts;
  647. const F32 tcs = cfg.tileSize * cfg.cs;
  648. // Iterate over tiles.
  649. F32 tileBmin[3], tileBmax[3];
  650. for(U32 y = 0; y < th; ++y)
  651. {
  652. for(U32 x = 0; x < tw; ++x)
  653. {
  654. tileBmin[0] = cfg.bmin[0] + x*tcs;
  655. tileBmin[1] = cfg.bmin[1];
  656. tileBmin[2] = cfg.bmin[2] + y*tcs;
  657. tileBmax[0] = cfg.bmin[0] + (x+1)*tcs;
  658. tileBmax[1] = cfg.bmax[1];
  659. tileBmax[2] = cfg.bmin[2] + (y+1)*tcs;
  660. mTiles.push_back(
  661. Tile(RCtoDTS(tileBmin, tileBmax),
  662. x, y,
  663. tileBmin, tileBmax));
  664. if(dirty)
  665. mDirtyTiles.push_back_unique(mTiles.size() - 1);
  666. if(mSaveIntermediates)
  667. mTileData.increment();
  668. }
  669. }
  670. }
  671. void NavMesh::processTick(const Move *move)
  672. {
  673. buildNextTile();
  674. }
  675. void NavMesh::buildNextTile()
  676. {
  677. PROFILE_SCOPE(NavMesh_buildNextTile);
  678. if(!mDirtyTiles.empty())
  679. {
  680. // Pop a single dirty tile and process it.
  681. U32 i = mDirtyTiles.front();
  682. mDirtyTiles.pop_front();
  683. const Tile &tile = mTiles[i];
  684. // Intermediate data for tile build.
  685. TileData tempdata;
  686. TileData &tdata = mSaveIntermediates ? mTileData[i] : tempdata;
  687. // Remove any previous data.
  688. nm->removeTile(nm->getTileRefAt(tile.x, tile.y, 0), 0, 0);
  689. // Generate navmesh for this tile.
  690. U32 dataSize = 0;
  691. unsigned char* data = buildTileData(tile, tdata, dataSize);
  692. if(data)
  693. {
  694. // Add new data (navmesh owns and deletes the data).
  695. dtStatus status = nm->addTile(data, dataSize, DT_TILE_FREE_DATA, 0, 0);
  696. int success = 1;
  697. if(dtStatusFailed(status))
  698. {
  699. success = 0;
  700. dtFree(data);
  701. }
  702. if(getEventManager())
  703. {
  704. String str = String::ToString("%d %d %d (%d, %d) %d %.3f %s",
  705. getId(),
  706. i, mTiles.size(),
  707. tile.x, tile.y,
  708. success,
  709. ctx->getAccumulatedTime(RC_TIMER_TOTAL) / 1000.0f,
  710. castConsoleTypeToString(tile.box));
  711. getEventManager()->postEvent("NavMeshTileUpdate", str.c_str());
  712. setMaskBits(LoadFlag);
  713. }
  714. }
  715. // Did we just build the last tile?
  716. if(mDirtyTiles.empty())
  717. {
  718. ctx->stopTimer(RC_TIMER_TOTAL);
  719. if(getEventManager())
  720. {
  721. String str = String::ToString("%d", getId());
  722. getEventManager()->postEvent("NavMeshUpdate", str.c_str());
  723. setMaskBits(LoadFlag);
  724. }
  725. mBuilding = false;
  726. }
  727. }
  728. }
  729. static void buildCallback(SceneObject* object,void *key)
  730. {
  731. SceneContainer::CallbackInfo* info = reinterpret_cast<SceneContainer::CallbackInfo*>(key);
  732. if (!object->mPathfindingIgnore)
  733. object->buildPolyList(info->context,info->polyList,info->boundingBox,info->boundingSphere);
  734. }
  735. unsigned char *NavMesh::buildTileData(const Tile &tile, TileData &data, U32 &dataSize)
  736. {
  737. // Push out tile boundaries a bit.
  738. F32 tileBmin[3], tileBmax[3];
  739. rcVcopy(tileBmin, tile.bmin);
  740. rcVcopy(tileBmax, tile.bmax);
  741. tileBmin[0] -= cfg.borderSize * cfg.cs;
  742. tileBmin[2] -= cfg.borderSize * cfg.cs;
  743. tileBmax[0] += cfg.borderSize * cfg.cs;
  744. tileBmax[2] += cfg.borderSize * cfg.cs;
  745. // Parse objects from level into RC-compatible format.
  746. Box3F box = RCtoDTS(tileBmin, tileBmax);
  747. SceneContainer::CallbackInfo info;
  748. info.context = PLC_Navigation;
  749. info.boundingBox = box;
  750. data.geom.clear();
  751. info.polyList = &data.geom;
  752. info.key = this;
  753. getContainer()->findObjects(box, StaticObjectType | DynamicShapeObjectType, buildCallback, &info);
  754. // Parse water objects into the same list, but remember how much geometry was /not/ water.
  755. U32 nonWaterVertCount = data.geom.getVertCount();
  756. U32 nonWaterTriCount = data.geom.getTriCount();
  757. if(mWaterMethod != Ignore)
  758. {
  759. getContainer()->findObjects(box, WaterObjectType, buildCallback, &info);
  760. }
  761. // Check for no geometry.
  762. if (!data.geom.getVertCount())
  763. {
  764. data.geom.clear();
  765. return NULL;
  766. }
  767. // Figure out voxel dimensions of this tile.
  768. U32 width = 0, height = 0;
  769. width = cfg.tileSize + cfg.borderSize * 2;
  770. height = cfg.tileSize + cfg.borderSize * 2;
  771. // Create a heightfield to voxelise our input geometry.
  772. data.hf = rcAllocHeightfield();
  773. if(!data.hf)
  774. {
  775. Con::errorf("Out of memory (rcHeightField) for NavMesh %s", getIdString());
  776. return NULL;
  777. }
  778. if(!rcCreateHeightfield(ctx, *data.hf, width, height, tileBmin, tileBmax, cfg.cs, cfg.ch))
  779. {
  780. Con::errorf("Could not generate rcHeightField for NavMesh %s", getIdString());
  781. return NULL;
  782. }
  783. unsigned char *areas = new unsigned char[data.geom.getTriCount()];
  784. dMemset(areas, 0, data.geom.getTriCount() * sizeof(unsigned char));
  785. // Mark walkable triangles with the appropriate area flags, and rasterize.
  786. if(mWaterMethod == Solid)
  787. {
  788. // Treat water as solid: i.e. mark areas as walkable based on angle.
  789. rcMarkWalkableTriangles(ctx, cfg.walkableSlopeAngle,
  790. data.geom.getVerts(), data.geom.getVertCount(),
  791. data.geom.getTris(), data.geom.getTriCount(), areas);
  792. }
  793. else
  794. {
  795. // Treat water as impassable: leave all area flags 0.
  796. rcMarkWalkableTriangles(ctx, cfg.walkableSlopeAngle,
  797. data.geom.getVerts(), nonWaterVertCount,
  798. data.geom.getTris(), nonWaterTriCount, areas);
  799. }
  800. rcRasterizeTriangles(ctx,
  801. data.geom.getVerts(), data.geom.getVertCount(),
  802. data.geom.getTris(), areas, data.geom.getTriCount(),
  803. *data.hf, cfg.walkableClimb);
  804. delete[] areas;
  805. // Filter out areas with low ceilings and other stuff.
  806. rcFilterLowHangingWalkableObstacles(ctx, cfg.walkableClimb, *data.hf);
  807. rcFilterLedgeSpans(ctx, cfg.walkableHeight, cfg.walkableClimb, *data.hf);
  808. rcFilterWalkableLowHeightSpans(ctx, cfg.walkableHeight, *data.hf);
  809. data.chf = rcAllocCompactHeightfield();
  810. if(!data.chf)
  811. {
  812. Con::errorf("Out of memory (rcCompactHeightField) for NavMesh %s", getIdString());
  813. return NULL;
  814. }
  815. if(!rcBuildCompactHeightfield(ctx, cfg.walkableHeight, cfg.walkableClimb, *data.hf, *data.chf))
  816. {
  817. Con::errorf("Could not generate rcCompactHeightField for NavMesh %s", getIdString());
  818. return NULL;
  819. }
  820. if(!rcErodeWalkableArea(ctx, cfg.walkableRadius, *data.chf))
  821. {
  822. Con::errorf("Could not erode walkable area for NavMesh %s", getIdString());
  823. return NULL;
  824. }
  825. //--------------------------
  826. // Todo: mark areas here.
  827. //const ConvexVolume* vols = m_geom->getConvexVolumes();
  828. //for (int i = 0; i < m_geom->getConvexVolumeCount(); ++i)
  829. //rcMarkConvexPolyArea(m_ctx, vols[i].verts, vols[i].nverts, vols[i].hmin, vols[i].hmax, (unsigned char)vols[i].area, *m_chf);
  830. //--------------------------
  831. if(false)
  832. {
  833. if(!rcBuildRegionsMonotone(ctx, *data.chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea))
  834. {
  835. Con::errorf("Could not build regions for NavMesh %s", getIdString());
  836. return NULL;
  837. }
  838. }
  839. else
  840. {
  841. if(!rcBuildDistanceField(ctx, *data.chf))
  842. {
  843. Con::errorf("Could not build distance field for NavMesh %s", getIdString());
  844. return NULL;
  845. }
  846. if(!rcBuildRegions(ctx, *data.chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea))
  847. {
  848. Con::errorf("Could not build regions for NavMesh %s", getIdString());
  849. return NULL;
  850. }
  851. }
  852. data.cs = rcAllocContourSet();
  853. if(!data.cs)
  854. {
  855. Con::errorf("Out of memory (rcContourSet) for NavMesh %s", getIdString());
  856. return NULL;
  857. }
  858. if(!rcBuildContours(ctx, *data.chf, cfg.maxSimplificationError, cfg.maxEdgeLen, *data.cs))
  859. {
  860. Con::errorf("Could not construct rcContourSet for NavMesh %s", getIdString());
  861. return NULL;
  862. }
  863. if(data.cs->nconts <= 0)
  864. {
  865. Con::errorf("No contours in rcContourSet for NavMesh %s", getIdString());
  866. return NULL;
  867. }
  868. data.pm = rcAllocPolyMesh();
  869. if(!data.pm)
  870. {
  871. Con::errorf("Out of memory (rcPolyMesh) for NavMesh %s", getIdString());
  872. return NULL;
  873. }
  874. if(!rcBuildPolyMesh(ctx, *data.cs, cfg.maxVertsPerPoly, *data.pm))
  875. {
  876. Con::errorf("Could not construct rcPolyMesh for NavMesh %s", getIdString());
  877. return NULL;
  878. }
  879. data.pmd = rcAllocPolyMeshDetail();
  880. if(!data.pmd)
  881. {
  882. Con::errorf("Out of memory (rcPolyMeshDetail) for NavMesh %s", getIdString());
  883. return NULL;
  884. }
  885. if(!rcBuildPolyMeshDetail(ctx, *data.pm, *data.chf, cfg.detailSampleDist, cfg.detailSampleMaxError, *data.pmd))
  886. {
  887. Con::errorf("Could not construct rcPolyMeshDetail for NavMesh %s", getIdString());
  888. return NULL;
  889. }
  890. if(data.pm->nverts >= 0xffff)
  891. {
  892. Con::errorf("Too many vertices in rcPolyMesh for NavMesh %s", getIdString());
  893. return NULL;
  894. }
  895. for(U32 i = 0; i < data.pm->npolys; i++)
  896. {
  897. if(data.pm->areas[i] == RC_WALKABLE_AREA)
  898. data.pm->areas[i] = GroundArea;
  899. if(data.pm->areas[i] == GroundArea)
  900. data.pm->flags[i] |= WalkFlag;
  901. if(data.pm->areas[i] == WaterArea)
  902. data.pm->flags[i] |= SwimFlag;
  903. }
  904. unsigned char* navData = 0;
  905. int navDataSize = 0;
  906. dtNavMeshCreateParams params;
  907. dMemset(&params, 0, sizeof(params));
  908. params.verts = data.pm->verts;
  909. params.vertCount = data.pm->nverts;
  910. params.polys = data.pm->polys;
  911. params.polyAreas = data.pm->areas;
  912. params.polyFlags = data.pm->flags;
  913. params.polyCount = data.pm->npolys;
  914. params.nvp = data.pm->nvp;
  915. params.detailMeshes = data.pmd->meshes;
  916. params.detailVerts = data.pmd->verts;
  917. params.detailVertsCount = data.pmd->nverts;
  918. params.detailTris = data.pmd->tris;
  919. params.detailTriCount = data.pmd->ntris;
  920. params.offMeshConVerts = mLinkVerts.address();
  921. params.offMeshConRad = mLinkRads.address();
  922. params.offMeshConDir = mLinkDirs.address();
  923. params.offMeshConAreas = mLinkAreas.address();
  924. params.offMeshConFlags = mLinkFlags.address();
  925. params.offMeshConUserID = mLinkIDs.address();
  926. params.offMeshConCount = mLinkIDs.size();
  927. params.walkableHeight = mWalkableHeight;
  928. params.walkableRadius = mWalkableRadius;
  929. params.walkableClimb = mWalkableClimb;
  930. params.tileX = tile.x;
  931. params.tileY = tile.y;
  932. params.tileLayer = 0;
  933. rcVcopy(params.bmin, data.pm->bmin);
  934. rcVcopy(params.bmax, data.pm->bmax);
  935. params.cs = cfg.cs;
  936. params.ch = cfg.ch;
  937. params.buildBvTree = true;
  938. if(!dtCreateNavMeshData(&params, &navData, &navDataSize))
  939. {
  940. Con::errorf("Could not create dtNavMeshData for tile (%d, %d) of NavMesh %s",
  941. tile.x, tile.y, getIdString());
  942. return NULL;
  943. }
  944. dataSize = navDataSize;
  945. return navData;
  946. }
  947. /// This method should never be called in a separate thread to the rendering
  948. /// or pathfinding logic. It directly replaces data in the dtNavMesh for
  949. /// this NavMesh object.
  950. void NavMesh::buildTiles(const Box3F &box)
  951. {
  952. PROFILE_SCOPE(NavMesh_buildTiles);
  953. // Make sure we've already built or loaded.
  954. if(!nm)
  955. return;
  956. // Iterate over tiles.
  957. for(U32 i = 0; i < mTiles.size(); i++)
  958. {
  959. const Tile &tile = mTiles[i];
  960. // Check tile box.
  961. if(!tile.box.isOverlapped(box))
  962. continue;
  963. // Mark as dirty.
  964. mDirtyTiles.push_back_unique(i);
  965. }
  966. if(mDirtyTiles.size())
  967. ctx->startTimer(RC_TIMER_TOTAL);
  968. }
  969. DefineEngineMethod(NavMesh, buildTiles, void, (Box3F box),,
  970. "@brief Rebuild the tiles overlapped by the input box.")
  971. {
  972. return object->buildTiles(box);
  973. }
  974. void NavMesh::buildTile(const U32 &tile)
  975. {
  976. PROFILE_SCOPE(NavMesh_buildTile);
  977. if(tile < mTiles.size())
  978. {
  979. mDirtyTiles.push_back_unique(tile);
  980. ctx->startTimer(RC_TIMER_TOTAL);
  981. }
  982. }
  983. void NavMesh::buildLinks()
  984. {
  985. // Make sure we've already built or loaded.
  986. if(!nm)
  987. return;
  988. // Iterate over tiles.
  989. for(U32 i = 0; i < mTiles.size(); i++)
  990. {
  991. const Tile &tile = mTiles[i];
  992. // Iterate over links
  993. for(U32 j = 0; j < mLinkIDs.size(); j++)
  994. {
  995. if (mLinksUnsynced[j])
  996. {
  997. if(tile.box.isContained(getLinkStart(j)) ||
  998. tile.box.isContained(getLinkEnd(j)))
  999. {
  1000. // Mark tile for build.
  1001. mDirtyTiles.push_back_unique(i);
  1002. // Delete link if necessary
  1003. if(mDeleteLinks[j])
  1004. {
  1005. eraseLink(j);
  1006. j--;
  1007. }
  1008. else
  1009. mLinksUnsynced[j] = false;
  1010. }
  1011. }
  1012. }
  1013. }
  1014. if(mDirtyTiles.size())
  1015. ctx->startTimer(RC_TIMER_TOTAL);
  1016. }
  1017. DefineEngineMethod(NavMesh, buildLinks, void, (),,
  1018. "@brief Build tiles of this mesh where there are unsynchronised links.")
  1019. {
  1020. object->buildLinks();
  1021. }
  1022. void NavMesh::deleteCoverPoints()
  1023. {
  1024. SimSet *set = NULL;
  1025. if(Sim::findObject(mCoverSet, set))
  1026. set->deleteAllObjects();
  1027. }
  1028. DefineEngineMethod(NavMesh, deleteCoverPoints, void, (),,
  1029. "@brief Remove all cover points for this NavMesh.")
  1030. {
  1031. object->deleteCoverPoints();
  1032. }
  1033. bool NavMesh::createCoverPoints()
  1034. {
  1035. if(!nm || !isServerObject())
  1036. return false;
  1037. SimSet *set = NULL;
  1038. if(Sim::findObject(mCoverSet, set))
  1039. {
  1040. set->deleteAllObjects();
  1041. }
  1042. else
  1043. {
  1044. set = new SimGroup();
  1045. if(set->registerObject(mCoverSet))
  1046. {
  1047. getGroup()->addObject(set);
  1048. }
  1049. else
  1050. {
  1051. delete set;
  1052. set = getGroup();
  1053. }
  1054. }
  1055. dtNavMeshQuery *query = dtAllocNavMeshQuery();
  1056. if(!query || dtStatusFailed(query->init(nm, 1)))
  1057. return false;
  1058. dtQueryFilter f;
  1059. // Iterate over all polys in our navmesh.
  1060. const int MAX_SEGS = 6;
  1061. for(U32 i = 0; i < nm->getMaxTiles(); ++i)
  1062. {
  1063. const dtMeshTile* tile = ((const dtNavMesh*)nm)->getTile(i);
  1064. if(!tile->header) continue;
  1065. const dtPolyRef base = nm->getPolyRefBase(tile);
  1066. for(U32 j = 0; j < tile->header->polyCount; ++j)
  1067. {
  1068. const dtPolyRef ref = base | j;
  1069. float segs[MAX_SEGS*6];
  1070. int nsegs = 0;
  1071. query->getPolyWallSegments(ref, &f, segs, NULL, &nsegs, MAX_SEGS);
  1072. for(int segIDx = 0; segIDx < nsegs; ++segIDx)
  1073. {
  1074. const float* sa = &segs[segIDx *6];
  1075. const float* sb = &segs[segIDx *6+3];
  1076. Point3F a = RCtoDTS(sa), b = RCtoDTS(sb);
  1077. F32 len = (b - a).len();
  1078. if(len < mWalkableRadius * 2)
  1079. continue;
  1080. Point3F edge = b - a;
  1081. edge.normalize();
  1082. // Number of points to try placing - for now, one at each end.
  1083. U32 pointCount = (len > mWalkableRadius * 4) ? 2 : 1;
  1084. for(U32 pointIDx = 0; pointIDx < pointCount; pointIDx++)
  1085. {
  1086. MatrixF mat;
  1087. Point3F pos;
  1088. // If we're only placing one point, put it in the middle.
  1089. if(pointCount == 1)
  1090. pos = a + edge * len / 2;
  1091. // Otherwise, stand off from edge ends.
  1092. else
  1093. {
  1094. if(pointIDx % 2)
  1095. pos = a + edge * (pointIDx /2+1) * mWalkableRadius;
  1096. else
  1097. pos = b - edge * (pointIDx /2+1) * mWalkableRadius;
  1098. }
  1099. CoverPointData data;
  1100. if(testEdgeCover(pos, edge, data))
  1101. {
  1102. CoverPoint *m = new CoverPoint();
  1103. if(!m->registerObject())
  1104. delete m;
  1105. else
  1106. {
  1107. m->setTransform(data.trans);
  1108. m->setSize(data.size);
  1109. m->setPeek(data.peek[0], data.peek[1], data.peek[2]);
  1110. if(set)
  1111. set->addObject(m);
  1112. }
  1113. }
  1114. }
  1115. }
  1116. }
  1117. }
  1118. return true;
  1119. }
  1120. DefineEngineMethod(NavMesh, createCoverPoints, bool, (),,
  1121. "@brief Create cover points for this NavMesh.")
  1122. {
  1123. return object->createCoverPoints();
  1124. }
  1125. bool NavMesh::testEdgeCover(const Point3F &pos, const VectorF &dir, CoverPointData &data)
  1126. {
  1127. data.peek[0] = data.peek[1] = data.peek[2] = false;
  1128. // Get the edge normal.
  1129. Point3F norm;
  1130. mCross(dir, Point3F(0, 0, 1), &norm);
  1131. RayInfo ray;
  1132. U32 hits = 0;
  1133. for(U32 j = 0; j < CoverPoint::NumSizes; j++)
  1134. {
  1135. Point3F test = pos + Point3F(0.0f, 0.0f, mWalkableHeight * j / (F32)CoverPoint::NumSizes);
  1136. if(getContainer()->castRay(test, test + norm * mCoverDist, StaticObjectType, &ray))
  1137. {
  1138. // Test peeking.
  1139. Point3F left = test + dir * mPeekDist;
  1140. data.peek[0] = !getContainer()->castRay(test, left, StaticObjectType, &ray)
  1141. && !getContainer()->castRay(left, left + norm * mCoverDist, StaticObjectType, &ray);
  1142. Point3F right = test - dir * mPeekDist;
  1143. data.peek[1] = !getContainer()->castRay(test, right, StaticObjectType, &ray)
  1144. && !getContainer()->castRay(right, right + norm * mCoverDist, StaticObjectType, &ray);
  1145. Point3F over = test + Point3F(0, 0, 1) * 0.2f;
  1146. data.peek[2] = !getContainer()->castRay(test, over, StaticObjectType, &ray)
  1147. && !getContainer()->castRay(over, over + norm * mCoverDist, StaticObjectType, &ray);
  1148. if(mInnerCover || data.peek[0] || data.peek[1] || data.peek[2])
  1149. hits++;
  1150. // If we couldn't peek here, we may be able to peek further up.
  1151. }
  1152. else
  1153. // No cover at this height - break off.
  1154. break;
  1155. }
  1156. if(hits > 0)
  1157. {
  1158. data.size = (CoverPoint::Size)(hits - 1);
  1159. data.trans = MathUtils::createOrientFromDir(norm);
  1160. data.trans.setPosition(pos);
  1161. }
  1162. return hits > 0;
  1163. }
  1164. void NavMesh::renderToDrawer()
  1165. {
  1166. mDbgDraw.clear();
  1167. // Recast debug draw
  1168. NetObject *no = getServerObject();
  1169. if(no)
  1170. {
  1171. NavMesh *n = static_cast<NavMesh*>(no);
  1172. if(n->nm)
  1173. {
  1174. mDbgDraw.beginGroup(0);
  1175. duDebugDrawNavMesh (&mDbgDraw, *n->nm, 0);
  1176. mDbgDraw.beginGroup(1);
  1177. duDebugDrawNavMeshPortals(&mDbgDraw, *n->nm);
  1178. mDbgDraw.beginGroup(2);
  1179. duDebugDrawNavMeshBVTree (&mDbgDraw, *n->nm);
  1180. }
  1181. }
  1182. }
  1183. void NavMesh::prepRenderImage(SceneRenderState *state)
  1184. {
  1185. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  1186. ri->renderDelegate.bind(this, &NavMesh::render);
  1187. ri->type = RenderPassManager::RIT_Object;
  1188. ri->translucentSort = true;
  1189. ri->defaultKey = 1;
  1190. state->getRenderPass()->addInst(ri);
  1191. }
  1192. void NavMesh::render(ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat)
  1193. {
  1194. if(overrideMat)
  1195. return;
  1196. if(state->isReflectPass())
  1197. return;
  1198. PROFILE_SCOPE(NavMesh_Render);
  1199. // Recast debug draw
  1200. NetObject *no = getServerObject();
  1201. if(no)
  1202. {
  1203. NavMesh *n = static_cast<NavMesh*>(no);
  1204. if(n->isSelected())
  1205. {
  1206. GFXDrawUtil *drawer = GFX->getDrawUtil();
  1207. GFXStateBlockDesc desc;
  1208. desc.setZReadWrite(true, false);
  1209. desc.setBlend(true);
  1210. desc.setCullMode(GFXCullNone);
  1211. drawer->drawCube(desc, getWorldBox(), n->mBuilding
  1212. ? ColorI(255, 0, 0, 80)
  1213. : ColorI(136, 228, 255, 45));
  1214. desc.setFillModeWireframe();
  1215. drawer->drawCube(desc, getWorldBox(), ColorI::BLACK);
  1216. }
  1217. if(n->mBuilding)
  1218. {
  1219. int alpha = 80;
  1220. if(!n->isSelected() || !Con::getBoolVariable("$Nav::EditorOpen"))
  1221. alpha = 20;
  1222. mDbgDraw.overrideColor(duRGBA(255, 0, 0, alpha));
  1223. }
  1224. else
  1225. {
  1226. mDbgDraw.cancelOverride();
  1227. }
  1228. if((!gEditingMission && n->mAlwaysRender) || (gEditingMission && Con::getBoolVariable("$Nav::Editor::renderMesh", 1))) mDbgDraw.renderGroup(0);
  1229. if(Con::getBoolVariable("$Nav::Editor::renderPortals")) mDbgDraw.renderGroup(1);
  1230. if(Con::getBoolVariable("$Nav::Editor::renderBVTree")) mDbgDraw.renderGroup(2);
  1231. }
  1232. }
  1233. void NavMesh::renderLinks(duDebugDraw &dd)
  1234. {
  1235. if(mBuilding)
  1236. return;
  1237. dd.depthMask(true);
  1238. dd.begin(DU_DRAW_LINES);
  1239. for(U32 i = 0; i < mLinkIDs.size(); i++)
  1240. {
  1241. U32 col = 0;
  1242. switch(mLinkSelectStates[i])
  1243. {
  1244. case Unselected: col = mLinksUnsynced[i] ? duRGBA(255, 0, 0, 200) : duRGBA(0, 0, 255, 255); break;
  1245. case Hovered: col = duRGBA(255, 255, 255, 255); break;
  1246. case Selected: col = duRGBA(0, 255, 0, 255); break;
  1247. }
  1248. F32 *s = &mLinkVerts[i*6];
  1249. F32 *e = &mLinkVerts[i*6 + 3];
  1250. if(!mDeleteLinks[i])
  1251. duAppendCircle(&dd, s[0], s[1], s[2], mLinkRads[i], col);
  1252. duAppendArc(&dd,
  1253. s[0], s[1], s[2],
  1254. e[0], e[1], e[2],
  1255. 0.3f,
  1256. 0.0f, mLinkFlags[i] == DropFlag ? 0.0f : 0.4f,
  1257. col);
  1258. if(!mDeleteLinks[i])
  1259. duAppendCircle(&dd, e[0], e[1], e[2], mLinkRads[i], col);
  1260. }
  1261. dd.end();
  1262. }
  1263. void NavMesh::renderTileData(duDebugDrawTorque &dd, U32 tile)
  1264. {
  1265. if(tile >= mTileData.size())
  1266. return;
  1267. if(nm)
  1268. {
  1269. dd.beginGroup(0);
  1270. if(mTileData[tile].chf) duDebugDrawCompactHeightfieldSolid(&dd, *mTileData[tile].chf);
  1271. dd.beginGroup(1);
  1272. int col = duRGBA(255, 0, 255, 255);
  1273. RecastPolyList &in = mTileData[tile].geom;
  1274. dd.begin(DU_DRAW_LINES);
  1275. const F32 *verts = in.getVerts();
  1276. const S32 *tris = in.getTris();
  1277. for(U32 t = 0; t < in.getTriCount(); t++)
  1278. {
  1279. dd.vertex(&verts[tris[t*3]*3], col);
  1280. dd.vertex(&verts[tris[t*3+1]*3], col);
  1281. dd.vertex(&verts[tris[t*3+1]*3], col);
  1282. dd.vertex(&verts[tris[t*3+2]*3], col);
  1283. dd.vertex(&verts[tris[t*3+2]*3], col);
  1284. dd.vertex(&verts[tris[t*3]*3], col);
  1285. }
  1286. dd.end();
  1287. }
  1288. }
  1289. void NavMesh::onEditorEnable()
  1290. {
  1291. mNetFlags.set(Ghostable);
  1292. if(isClientObject() && !mAlwaysRender)
  1293. addToScene();
  1294. }
  1295. void NavMesh::onEditorDisable()
  1296. {
  1297. if(!mAlwaysRender)
  1298. {
  1299. mNetFlags.clear(Ghostable);
  1300. if(isClientObject())
  1301. removeFromScene();
  1302. }
  1303. }
  1304. U32 NavMesh::packUpdate(NetConnection *conn, U32 mask, BitStream *stream)
  1305. {
  1306. U32 retMask = Parent::packUpdate(conn, mask, stream);
  1307. mathWrite(*stream, getTransform());
  1308. mathWrite(*stream, getScale());
  1309. stream->writeFlag(mAlwaysRender);
  1310. return retMask;
  1311. }
  1312. void NavMesh::unpackUpdate(NetConnection *conn, BitStream *stream)
  1313. {
  1314. Parent::unpackUpdate(conn, stream);
  1315. mathRead(*stream, &mObjToWorld);
  1316. mathRead(*stream, &mObjScale);
  1317. mAlwaysRender = stream->readFlag();
  1318. setTransform(mObjToWorld);
  1319. renderToDrawer();
  1320. }
  1321. static const int NAVMESHSET_MAGIC = 'M'<<24 | 'S'<<16 | 'E'<<8 | 'T'; //'MSET';
  1322. static const int NAVMESHSET_VERSION = 1;
  1323. struct NavMeshSetHeader
  1324. {
  1325. int magic;
  1326. int version;
  1327. int numTiles;
  1328. dtNavMeshParams params;
  1329. };
  1330. struct NavMeshTileHeader
  1331. {
  1332. dtTileRef tileRef;
  1333. int dataSize;
  1334. };
  1335. bool NavMesh::load()
  1336. {
  1337. if(!dStrlen(mFileName))
  1338. return false;
  1339. FileStream stream;
  1340. if(!stream.open(mFileName, Torque::FS::File::Read))
  1341. {
  1342. Con::errorf("Could not open file %s when loading navmesh %s.",
  1343. mFileName, getName() ? getName() : getIdString());
  1344. return false;
  1345. }
  1346. // Read header.
  1347. NavMeshSetHeader header;
  1348. stream.read(sizeof(NavMeshSetHeader), (char*)&header);
  1349. if(header.magic != NAVMESHSET_MAGIC)
  1350. {
  1351. stream.close();
  1352. Con::errorf("Navmesh magic incorrect when loading navmesh %s; possible corrupt navmesh file %s.",
  1353. getName() ? getName() : getIdString(), mFileName);
  1354. return false;
  1355. }
  1356. if(header.version != NAVMESHSET_VERSION)
  1357. {
  1358. stream.close();
  1359. Con::errorf("Navmesh version incorrect when loading navmesh %s; possible corrupt navmesh file %s.",
  1360. getName() ? getName() : getIdString(), mFileName);
  1361. return false;
  1362. }
  1363. if(nm)
  1364. dtFreeNavMesh(nm);
  1365. nm = dtAllocNavMesh();
  1366. if(!nm)
  1367. {
  1368. stream.close();
  1369. Con::errorf("Out of memory when loading navmesh %s.",
  1370. getName() ? getName() : getIdString());
  1371. return false;
  1372. }
  1373. dtStatus status = nm->init(&header.params);
  1374. if(dtStatusFailed(status))
  1375. {
  1376. stream.close();
  1377. Con::errorf("Failed to initialise navmesh params when loading navmesh %s.",
  1378. getName() ? getName() : getIdString());
  1379. return false;
  1380. }
  1381. // Read tiles.
  1382. for(U32 i = 0; i < header.numTiles; ++i)
  1383. {
  1384. NavMeshTileHeader tileHeader;
  1385. stream.read(sizeof(NavMeshTileHeader), (char*)&tileHeader);
  1386. if(!tileHeader.tileRef || !tileHeader.dataSize)
  1387. break;
  1388. unsigned char* data = (unsigned char*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM);
  1389. if(!data) break;
  1390. memset(data, 0, tileHeader.dataSize);
  1391. stream.read(tileHeader.dataSize, (char*)data);
  1392. nm->addTile(data, tileHeader.dataSize, DT_TILE_FREE_DATA, tileHeader.tileRef, 0);
  1393. }
  1394. S32 s;
  1395. stream.read(sizeof(S32), (char*)&s);
  1396. setLinkCount(s);
  1397. if (s > 0)
  1398. {
  1399. stream.read(sizeof(F32) * s * 6, (char*)const_cast<F32*>(mLinkVerts.address()));
  1400. stream.read(sizeof(F32) * s, (char*)const_cast<F32*>(mLinkRads.address()));
  1401. stream.read(sizeof(U8) * s, (char*)const_cast<U8*>(mLinkDirs.address()));
  1402. stream.read(sizeof(U8) * s, (char*)const_cast<U8*>(mLinkAreas.address()));
  1403. stream.read(sizeof(U16) * s, (char*)const_cast<U16*>(mLinkFlags.address()));
  1404. stream.read(sizeof(F32) * s, (char*)const_cast<U32*>(mLinkIDs.address()));
  1405. }
  1406. mLinksUnsynced.fill(false);
  1407. mLinkSelectStates.fill(Unselected);
  1408. mDeleteLinks.fill(false);
  1409. stream.close();
  1410. updateTiles();
  1411. if(isServerObject())
  1412. {
  1413. setMaskBits(LoadFlag);
  1414. if(getEventManager())
  1415. getEventManager()->postEvent("NavMeshUpdate", getIdString());
  1416. }
  1417. return true;
  1418. }
  1419. DefineEngineMethod(NavMesh, load, bool, (),,
  1420. "@brief Load this NavMesh from its file.")
  1421. {
  1422. return object->load();
  1423. }
  1424. bool NavMesh::save()
  1425. {
  1426. if(!dStrlen(mFileName) || !nm)
  1427. return false;
  1428. FileStream stream;
  1429. if(!stream.open(mFileName, Torque::FS::File::Write))
  1430. {
  1431. Con::errorf("Could not open file %s when saving navmesh %s.",
  1432. mFileName, getName() ? getName() : getIdString());
  1433. return false;
  1434. }
  1435. // Store header.
  1436. NavMeshSetHeader header;
  1437. header.magic = NAVMESHSET_MAGIC;
  1438. header.version = NAVMESHSET_VERSION;
  1439. header.numTiles = 0;
  1440. for(U32 i = 0; i < nm->getMaxTiles(); ++i)
  1441. {
  1442. const dtMeshTile* tile = ((const dtNavMesh*)nm)->getTile(i);
  1443. if (!tile || !tile->header || !tile->dataSize) continue;
  1444. header.numTiles++;
  1445. }
  1446. memcpy(&header.params, nm->getParams(), sizeof(dtNavMeshParams));
  1447. stream.write(sizeof(NavMeshSetHeader), (const char*)&header);
  1448. // Store tiles.
  1449. for(U32 i = 0; i < nm->getMaxTiles(); ++i)
  1450. {
  1451. const dtMeshTile* tile = ((const dtNavMesh*)nm)->getTile(i);
  1452. if(!tile || !tile->header || !tile->dataSize) continue;
  1453. NavMeshTileHeader tileHeader;
  1454. tileHeader.tileRef = nm->getTileRef(tile);
  1455. tileHeader.dataSize = tile->dataSize;
  1456. stream.write(sizeof(tileHeader), (const char*)&tileHeader);
  1457. stream.write(tile->dataSize, (const char*)tile->data);
  1458. }
  1459. S32 s = mLinkIDs.size();
  1460. stream.write(sizeof(S32), (const char*)&s);
  1461. if (s > 0)
  1462. {
  1463. stream.write(sizeof(F32) * s * 6, (const char*)mLinkVerts.address());
  1464. stream.write(sizeof(F32) * s, (const char*)mLinkRads.address());
  1465. stream.write(sizeof(U8) * s, (const char*)mLinkDirs.address());
  1466. stream.write(sizeof(U8) * s, (const char*)mLinkAreas.address());
  1467. stream.write(sizeof(U16) * s, (const char*)mLinkFlags.address());
  1468. stream.write(sizeof(U32) * s, (const char*)mLinkIDs.address());
  1469. }
  1470. stream.close();
  1471. return true;
  1472. }
  1473. DefineEngineMethod(NavMesh, save, void, (),,
  1474. "@brief Save this NavMesh to its file.")
  1475. {
  1476. object->save();
  1477. }
  1478. void NavMesh::write(Stream &stream, U32 tabStop, U32 flags)
  1479. {
  1480. save();
  1481. Parent::write(stream, tabStop, flags);
  1482. }