terrData.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  26. #include "platform/platform.h"
  27. #include "terrain/terrData.h"
  28. #include "terrain/terrCollision.h"
  29. #include "terrain/terrCell.h"
  30. #include "terrain/terrRender.h"
  31. #include "terrain/terrMaterial.h"
  32. #include "terrain/terrCellMaterial.h"
  33. #include "gui/worldEditor/terrainEditor.h"
  34. #include "math/mathIO.h"
  35. #include "core/stream/fileStream.h"
  36. #include "core/stream/bitStream.h"
  37. #include "console/consoleTypes.h"
  38. #include "sim/netConnection.h"
  39. #include "core/util/safeDelete.h"
  40. #include "T3D/objectTypes.h"
  41. #include "renderInstance/renderPassManager.h"
  42. #include "scene/sceneRenderState.h"
  43. #include "materials/materialManager.h"
  44. #include "materials/baseMatInstance.h"
  45. #include "gfx/gfxTextureManager.h"
  46. #include "gfx/gfxCardProfile.h"
  47. #include "gfx/gfxAPI.h"
  48. #include "core/resourceManager.h"
  49. #include "T3D/physics/physicsPlugin.h"
  50. #include "T3D/physics/physicsBody.h"
  51. #include "T3D/physics/physicsCollision.h"
  52. #include "console/engineAPI.h"
  53. #include "core/util/safeRelease.h"
  54. #include "T3D/assets/TerrainMaterialAsset.h"
  55. using namespace Torque;
  56. IMPLEMENT_CO_NETOBJECT_V1(TerrainBlock);
  57. ConsoleDocClass( TerrainBlock,
  58. "@brief Represent a terrain object in a Torque 3D level\n\n"
  59. "@tsexample\n"
  60. "new TerrainBlock(theTerrain)\n"
  61. "{\n"
  62. " terrainFile = \"art/terrains/Deathball Desert_0.ter\";\n"
  63. " squareSize = \"2\";\n"
  64. " tile = \"0\";\n"
  65. " baseTexSize = \"1024\";\n"
  66. " screenError = \"16\";\n"
  67. " position = \"-1024 -1024 179.978\";\n"
  68. " rotation = \"1 0 0 0\";\n"
  69. " scale = \"1 1 1\";\n"
  70. " isRenderEnabled = \"true\";\n"
  71. " canSaveDynamicFields = \"1\";\n"
  72. "};\n"
  73. "@endtsexample\n\n"
  74. "@see TerrainMaterial\n\n"
  75. "@ingroup Terrain\n"
  76. );
  77. Signal<void(U32,TerrainBlock*,const Point2I& ,const Point2I&)> TerrainBlock::smUpdateSignal;
  78. F32 TerrainBlock::smLODScale = 1.0f;
  79. F32 TerrainBlock::smDetailScale = 1.0f;
  80. //RBP - Global function declared in Terrdata.h
  81. TerrainBlock* getTerrainUnderWorldPoint(const Point3F & wPos)
  82. {
  83. // Cast a ray straight down from the world position and see which
  84. // Terrain is the closest to our starting point
  85. Point3F startPnt = wPos;
  86. Point3F endPnt = wPos + Point3F(0.0f, 0.0f, -10000.0f);
  87. S32 blockIndex = -1;
  88. F32 nearT = 1.0f;
  89. SimpleQueryList queryList;
  90. gServerContainer.findObjects( TerrainObjectType, SimpleQueryList::insertionCallback, &queryList);
  91. for (U32 i = 0; i < queryList.mList.size(); i++)
  92. {
  93. Point3F tStartPnt, tEndPnt;
  94. TerrainBlock* terrBlock = dynamic_cast<TerrainBlock*>(queryList.mList[i]);
  95. terrBlock->getWorldTransform().mulP(startPnt, &tStartPnt);
  96. terrBlock->getWorldTransform().mulP(endPnt, &tEndPnt);
  97. RayInfo ri;
  98. if (terrBlock->castRayI(tStartPnt, tEndPnt, &ri, true))
  99. {
  100. if (ri.t < nearT)
  101. {
  102. blockIndex = i;
  103. nearT = ri.t;
  104. }
  105. }
  106. }
  107. if (blockIndex > -1)
  108. return (TerrainBlock*)(queryList.mList[blockIndex]);
  109. return NULL;
  110. }
  111. ConsoleDocFragment _getTerrainUnderWorldPoint1(
  112. "@brief Gets the terrain block that is located under the given world point\n\n"
  113. "@param position The world space coordinate you wish to query at. Formatted as (\"x y z\")\n\n"
  114. "@return Returns the ID of the requested terrain block (0 if not found).\n\n"
  115. "@ingroup Terrain",
  116. NULL,
  117. "bool getTerrainUnderWorldPoint( Point3F position );"
  118. );
  119. ConsoleDocFragment _getTerrainUnderWorldPoint2(
  120. "@brief Takes a world point and find the \"highest\" terrain underneath it\n\n"
  121. "@param x The X coordinate in world space\n"
  122. "@param y The Y coordinate in world space\n\n"
  123. "@param z The Z coordinate in world space\n\n"
  124. "@return Returns the ID of the requested terrain block (0 if not found).\n\n"
  125. "@ingroup Terrain",
  126. NULL,
  127. "bool getTerrainUnderWorldPoint( F32 x, F32 y, F32 z);"
  128. );
  129. DefineEngineFunction( getTerrainUnderWorldPoint, S32, (const char* ptOrX, const char* y, const char* z), ("", ""),
  130. "(Point3F x/y/z) Gets the terrain block that is located under the given world point.\n"
  131. "@param x/y/z The world coordinates (floating point values) you wish to query at. "
  132. "These can be formatted as either a string (\"x y z\") or separately as (x, y, z)\n"
  133. "@return Returns the ID of the requested terrain block (0 if not found).\n\n"
  134. "@hide")
  135. {
  136. Point3F pos;
  137. if(!String::isEmpty(ptOrX) && String::isEmpty(y) && String::isEmpty(z))
  138. dSscanf(ptOrX, "%f %f %f", &pos.x, &pos.y, &pos.z);
  139. else if(!String::isEmpty(ptOrX) && !String::isEmpty(y) && !String::isEmpty(z))
  140. {
  141. pos.x = dAtof(ptOrX);
  142. pos.y = dAtof(y);
  143. pos.z = dAtof(z);
  144. }
  145. TerrainBlock* terrain = getTerrainUnderWorldPoint(pos);
  146. if(terrain != NULL)
  147. {
  148. return terrain->getId();
  149. }
  150. return 0;
  151. }
  152. typedef TerrainBlock::BaseTexFormat baseTexFormat;
  153. DefineEnumType(baseTexFormat);
  154. ImplementEnumType(baseTexFormat,
  155. "Description\n"
  156. "@ingroup ?\n\n")
  157. { TerrainBlock::NONE, "NONE", "No cached terrain.\n" },
  158. { TerrainBlock::DDS, "DDS", "Cache the terrain in a DDS format.\n" },
  159. { TerrainBlock::PNG, "PNG", "Cache the terrain in a PNG format.\n" },
  160. EndImplementEnumType;
  161. TerrainBlock::TerrainBlock()
  162. : mLightMap( NULL ),
  163. mLightMapSize( 256 ),
  164. mCRC( 0 ),
  165. mMaxDetailDistance( 0.0f ),
  166. mBaseTexScaleConst( NULL ),
  167. mBaseTexIdConst( NULL ),
  168. mBaseLayerSizeConst(NULL),
  169. mDetailsDirty( false ),
  170. mLayerTexDirty( false ),
  171. mBaseTexSize( 1024 ),
  172. mBaseTexFormat( TerrainBlock::DDS ),
  173. mCell( NULL ),
  174. mBaseMaterial( NULL ),
  175. mDefaultMatInst( NULL ),
  176. mSquareSize( 1.0f ),
  177. mPhysicsRep( NULL ),
  178. mScreenError( 16 ),
  179. mCastShadows( true ),
  180. mZoningDirty( false ),
  181. mUpdateBasetex ( true ),
  182. mDetailTextureArray( NULL ),
  183. mMacroTextureArray( NULL ),
  184. mOrmTextureArray( NULL ),
  185. mNormalTextureArray( NULL )
  186. {
  187. mTypeMask = TerrainObjectType | StaticObjectType | StaticShapeObjectType;
  188. mNetFlags.set(Ghostable | ScopeAlways);
  189. mIgnoreZodiacs = false;
  190. zode_primBuffer = 0;
  191. mTerrainAsset = StringTable->EmptyString();
  192. mTerrainAssetId = StringTable->EmptyString();
  193. }
  194. extern Convex sTerrainConvexList;
  195. TerrainBlock::~TerrainBlock()
  196. {
  197. // Kill collision
  198. sTerrainConvexList.nukeList();
  199. SAFE_DELETE(mLightMap);
  200. mLightMapTex = NULL;
  201. #ifdef TORQUE_TOOLS
  202. TerrainEditor* editor = dynamic_cast<TerrainEditor*>(Sim::findObject("ETerrainEditor"));
  203. if (editor)
  204. editor->detachTerrain(this);
  205. #endif
  206. deleteZodiacPrimitiveBuffer();
  207. SAFE_RELEASE(mDetailTextureArray);
  208. SAFE_RELEASE(mMacroTextureArray);
  209. SAFE_RELEASE(mNormalTextureArray);
  210. SAFE_RELEASE(mOrmTextureArray);
  211. }
  212. void TerrainBlock::_onTextureEvent( GFXTexCallbackCode code )
  213. {
  214. if ( code == GFXZombify )
  215. {
  216. if ( mBaseTex.isValid() &&
  217. mBaseTex->isRenderTarget() )
  218. mBaseTex = NULL;
  219. mLayerTex = NULL;
  220. mLightMapTex = NULL;
  221. }
  222. }
  223. bool TerrainBlock::_setSquareSize( void *obj, const char *index, const char *data )
  224. {
  225. TerrainBlock *terrain = static_cast<TerrainBlock*>( obj );
  226. F32 newSqaureSize = dAtof( data );
  227. if ( !mIsEqual( terrain->mSquareSize, newSqaureSize ) )
  228. {
  229. terrain->mSquareSize = newSqaureSize;
  230. if ( terrain->isServerObject() && terrain->isProperlyAdded() )
  231. terrain->_updateBounds();
  232. terrain->setMaskBits( HeightMapChangeMask | SizeMask );
  233. }
  234. return false;
  235. }
  236. bool TerrainBlock::_setBaseTexSize( void *obj, const char *index, const char *data )
  237. {
  238. TerrainBlock *terrain = static_cast<TerrainBlock*>( obj );
  239. // NOTE: We're limiting the base texture size to
  240. // 2048 as anything greater in size becomes too
  241. // large to generate for many cards.
  242. //
  243. // If you want to remove this limit feel free, but
  244. // prepare for problems if you don't ship the baked
  245. // base texture with your installer.
  246. //
  247. S32 texSize = mClamp( dAtoi( data ), 0, 2048 );
  248. if ( terrain->mBaseTexSize != texSize )
  249. {
  250. terrain->mBaseTexSize = texSize;
  251. terrain->setMaskBits( MaterialMask );
  252. }
  253. return false;
  254. }
  255. bool TerrainBlock::_setBaseTexFormat(void *obj, const char *index, const char *data)
  256. {
  257. TerrainBlock *terrain = static_cast<TerrainBlock*>(obj);
  258. EngineEnumTable eTable = _baseTexFormat::_sEnumTable;
  259. for (U8 i = 0; i < eTable.getNumValues(); i++)
  260. {
  261. if (strcasecmp(eTable[i].mName, data) == 0)
  262. {
  263. terrain->mBaseTexFormat = (BaseTexFormat)eTable[i].mInt;
  264. terrain->_updateMaterials();
  265. if (terrain->isServerObject()) return false;
  266. terrain->_updateLayerTexture();
  267. // If the cached base texture is older that the terrain file or
  268. // it doesn't exist then generate and cache it.
  269. String baseCachePath = terrain->_getBaseTexCacheFileName();
  270. if (Platform::compareModifiedTimes(baseCachePath, terrain->mTerrainAsset->getTerrainFilePath()) < 0 && terrain->mUpdateBasetex)
  271. terrain->_updateBaseTexture(true);
  272. break;
  273. }
  274. }
  275. return false;
  276. }
  277. bool TerrainBlock::_setLightMapSize( void *obj, const char *index, const char *data )
  278. {
  279. TerrainBlock *terrain = static_cast<TerrainBlock*>(obj);
  280. // Handle inspector value decrements correctly
  281. U32 mapSize = dAtoi( data );
  282. if ( mapSize == terrain->mLightMapSize-1 )
  283. mapSize = terrain->mLightMapSize/2;
  284. // Limit the lightmap size, and ensure it is a power of 2
  285. const U32 maxTextureSize = GFX->getCardProfiler()->queryProfile( "maxTextureSize", 1024 );
  286. mapSize = mClamp( getNextPow2( mapSize ), 0, maxTextureSize );
  287. if ( terrain->mLightMapSize != mapSize )
  288. {
  289. terrain->mLightMapSize = mapSize;
  290. terrain->setMaskBits( MaterialMask );
  291. }
  292. return false;
  293. }
  294. bool TerrainBlock::setFile( const FileName &terrFileName )
  295. {
  296. if ( mTerrainAsset && mTerrainAsset->getTerrainFilePath() == terrFileName )
  297. return mFile != NULL;
  298. Resource<TerrainFile> file = ResourceManager::get().load( terrFileName );
  299. if( !file )
  300. return false;
  301. setFile( file );
  302. setMaskBits( FileMask | HeightMapChangeMask );
  303. return true;
  304. }
  305. void TerrainBlock::setFile(const Resource<TerrainFile>& terr)
  306. {
  307. if (mFile)
  308. {
  309. GFXTextureManager::removeEventDelegate(this, &TerrainBlock::_onTextureEvent);
  310. MATMGR->getFlushSignal().remove(this, &TerrainBlock::_onFlushMaterials);
  311. }
  312. mFile = terr;
  313. if (!mFile)
  314. {
  315. Con::errorf("TerrainBlock::setFile() - No valid terrain file!");
  316. return;
  317. }
  318. if (terr->mNeedsResaving)
  319. {
  320. if (Platform::messageBox("Update Terrain File", "You appear to have a Terrain file in an older format. Do you want Torque to update it?", MBOkCancel, MIQuestion) == MROk)
  321. {
  322. mFile->save(terr->mFilePath.getFullPath());
  323. mFile->mNeedsResaving = false;
  324. }
  325. }
  326. if (terr->mFileVersion != TerrainFile::FILE_VERSION || terr->mNeedsResaving)
  327. {
  328. Con::errorf(" *********************************************************");
  329. Con::errorf(" *********************************************************");
  330. Con::errorf(" *********************************************************");
  331. Con::errorf(" PLEASE RESAVE THE TERRAIN FILE FOR THIS MISSION! THANKS!");
  332. Con::errorf(" *********************************************************");
  333. Con::errorf(" *********************************************************");
  334. Con::errorf(" *********************************************************");
  335. }
  336. _updateBounds();
  337. resetWorldBox();
  338. setRenderTransform(mObjToWorld);
  339. if (isClientObject())
  340. {
  341. if (mCRC != terr.getChecksum())
  342. {
  343. NetConnection::setLastError("Your terrain file doesn't match the version that is running on the server.");
  344. return;
  345. }
  346. clearLightMap();
  347. // Init the detail layer rendering helper.
  348. _updateMaterials();
  349. _updateLayerTexture();
  350. // If the cached base texture is older that the terrain file or
  351. // it doesn't exist then generate and cache it.
  352. String baseCachePath = _getBaseTexCacheFileName();
  353. if (Platform::compareModifiedTimes(baseCachePath, mTerrainAsset->getTerrainFilePath()) < 0 && mUpdateBasetex)
  354. _updateBaseTexture(true);
  355. // The base texture should have been cached by now... so load it.
  356. mBaseTex.set(baseCachePath, &GFXStaticTextureSRGBProfile, "TerrainBlock::mBaseTex");
  357. GFXTextureManager::addEventDelegate(this, &TerrainBlock::_onTextureEvent);
  358. MATMGR->getFlushSignal().notify(this, &TerrainBlock::_onFlushMaterials);
  359. // Build the terrain quadtree.
  360. _rebuildQuadtree();
  361. // Preload all the materials.
  362. mCell->preloadMaterials();
  363. mZoningDirty = true;
  364. SceneZoneSpaceManager::getZoningChangedSignal().notify(this, &TerrainBlock::_onZoningChanged);
  365. }
  366. else
  367. mCRC = terr.getChecksum();
  368. }
  369. bool TerrainBlock::setTerrainAsset(const StringTableEntry terrainAssetId)
  370. {
  371. if (TerrainAsset::getAssetById(terrainAssetId, &mTerrainAsset))
  372. {
  373. //Special exception case. If we've defaulted to the 'no shape' mesh, don't save it out, we'll retain the original ids/paths so it doesn't break
  374. //the TSStatic
  375. if (!mTerrainAsset.isNull())
  376. {
  377. mTerrFileName = StringTable->EmptyString();
  378. }
  379. setFile(mTerrainAsset->getTerrainResource());
  380. setMaskBits(-1);
  381. return true;
  382. }
  383. return false;
  384. }
  385. bool TerrainBlock::save(const char *filename)
  386. {
  387. return mFile->save(filename);
  388. }
  389. bool TerrainBlock::saveAsset()
  390. {
  391. if (!mTerrainAsset.isNull() && mTerrainAsset->isAssetValid())
  392. {
  393. mTerrainAsset->clearAssetDependencyFields("terrainMaterailAsset");
  394. AssetQuery* pAssetQuery = new AssetQuery();
  395. pAssetQuery->registerObject();
  396. AssetDatabase.findAssetType(pAssetQuery, "TerrainMaterialAsset");
  397. TerrainBlock* clientTerr = static_cast<TerrainBlock*>(getClientObject());
  398. for (U32 i = 0; i < pAssetQuery->mAssetList.size(); i++)
  399. {
  400. //Acquire it so we can check it for matches
  401. AssetPtr<TerrainMaterialAsset> terrMatAsset = pAssetQuery->mAssetList[i];
  402. for (U32 m = 0; m < clientTerr->mFile->mMaterials.size(); m++)
  403. {
  404. StringTableEntry intMatName = clientTerr->mFile->mMaterials[m]->getInternalName();
  405. StringTableEntry assetMatDefName = terrMatAsset->getMaterialDefinitionName();
  406. if (assetMatDefName == intMatName)
  407. {
  408. mTerrainAsset->addAssetDependencyField("terrainMaterailAsset", terrMatAsset.getAssetId());
  409. }
  410. }
  411. terrMatAsset.clear();
  412. }
  413. pAssetQuery->destroySelf();
  414. bool saveAssetSuccess = mTerrainAsset->saveAsset();
  415. if (!saveAssetSuccess)
  416. return false;
  417. return mFile->save(mTerrainAsset->getTerrainFilePath());
  418. }
  419. return false;
  420. }
  421. bool TerrainBlock::_setTerrainFile( void *obj, const char *index, const char *data )
  422. {
  423. //TerrainBlock* terrain = static_cast<TerrainBlock*>( obj )->setFile( FileName( data ) );
  424. TerrainBlock* terrain = static_cast<TerrainBlock*>(obj);
  425. StringTableEntry file = StringTable->insert(data);
  426. if (file != StringTable->EmptyString())
  427. {
  428. StringTableEntry assetId = TerrainAsset::getAssetIdByFilename(file);
  429. if (assetId != StringTable->EmptyString())
  430. {
  431. if (terrain->setTerrainAsset(assetId))
  432. {
  433. terrain->mTerrainAssetId = assetId;
  434. terrain->mTerrFileName = StringTable->EmptyString();
  435. return false;
  436. }
  437. }
  438. else
  439. {
  440. terrain->mTerrainAsset = StringTable->EmptyString();
  441. }
  442. }
  443. return true;
  444. }
  445. bool TerrainBlock::_setTerrainAsset(void* obj, const char* index, const char* data)
  446. {
  447. TerrainBlock* terr = static_cast<TerrainBlock*>(obj);// ->setFile(FileName(data));
  448. terr->mTerrainAssetId = StringTable->insert(data);
  449. return terr->setTerrainAsset(terr->mTerrainAssetId);
  450. }
  451. void TerrainBlock::_updateBounds()
  452. {
  453. if ( !mFile )
  454. return; // quick fix to stop crashing when deleting terrainblocks
  455. // Setup our object space bounds.
  456. mBounds.minExtents.set( 0.0f, 0.0f, 0.0f );
  457. mBounds.maxExtents.set( getWorldBlockSize(), getWorldBlockSize(), 0.0f );
  458. getMinMaxHeight( &mBounds.minExtents.z, &mBounds.maxExtents.z );
  459. // Set our mObjBox to be equal to mBounds
  460. if ( mObjBox.maxExtents != mBounds.maxExtents ||
  461. mObjBox.minExtents != mBounds.minExtents )
  462. {
  463. mObjBox = mBounds;
  464. resetWorldBox();
  465. }
  466. }
  467. void TerrainBlock::_onZoningChanged( SceneZoneSpaceManager *zoneManager )
  468. {
  469. const SceneManager* sm = getSceneManager();
  470. if (mCell == NULL || (sm != NULL && sm->getZoneManager() != NULL && zoneManager != sm->getZoneManager()))
  471. return;
  472. mZoningDirty = true;
  473. }
  474. void TerrainBlock::setHeight( const Point2I &pos, F32 height )
  475. {
  476. U16 ht = floatToFixed( height );
  477. mFile->setHeight( pos.x, pos.y, ht );
  478. // Note: We do not update the grid here as this could
  479. // be called several times in a loop. We depend on the
  480. // caller doing a grid update when he is done.
  481. }
  482. F32 TerrainBlock::getHeight( const Point2I &pos )
  483. {
  484. U16 ht = mFile->getHeight( pos.x, pos.y );
  485. return fixedToFloat( ht );
  486. }
  487. void TerrainBlock::updateGridMaterials( const Point2I &minPt, const Point2I &maxPt )
  488. {
  489. if ( mCell )
  490. {
  491. // Tell the terrain cell that something changed.
  492. const RectI gridRect( minPt, maxPt - minPt );
  493. mCell->updateGrid( gridRect, true );
  494. }
  495. // We mark us as dirty... it will be updated
  496. // before the next time we render the terrain.
  497. mLayerTexDirty = true;
  498. // Signal anyone that cares that the opacity was changed.
  499. smUpdateSignal.trigger( LayersUpdate, this, minPt, maxPt );
  500. }
  501. Point2I TerrainBlock::getGridPos( const Point3F &worldPos ) const
  502. {
  503. Point3F terrainPos = worldPos;
  504. getWorldTransform().mulP( terrainPos );
  505. F32 squareSize = ( F32 ) getSquareSize();
  506. F32 halfSquareSize = squareSize / 2.0;
  507. F32 x = ( terrainPos.x + halfSquareSize ) / squareSize;
  508. F32 y = ( terrainPos.y + halfSquareSize ) / squareSize;
  509. Point2I gridPos( ( S32 ) mFloor( x ), ( S32 ) mFloor( y ) );
  510. return gridPos;
  511. }
  512. void TerrainBlock::updateGrid( const Point2I &minPt, const Point2I &maxPt, bool updateClient )
  513. {
  514. // On the client we just signal everyone that the height
  515. // map has changed... the server does the actual changes.
  516. if ( isClientObject() )
  517. {
  518. PROFILE_SCOPE( TerrainBlock_updateGrid_Client );
  519. // This depends on the client getting this call 'after' the server.
  520. // Which is currently the case.
  521. _updateBounds();
  522. mZoningDirty = true;
  523. smUpdateSignal.trigger( HeightmapUpdate, this, minPt, maxPt );
  524. // Tell the terrain cell that the height changed.
  525. const RectI gridRect( minPt, maxPt - minPt );
  526. mCell->updateGrid( gridRect );
  527. // Rebuild the physics representation.
  528. if ( mPhysicsRep )
  529. {
  530. // Delay the update by a few milliseconds so
  531. // that we're not rebuilding during an active
  532. // editing operation.
  533. mPhysicsRep->queueCallback( 500, Delegate<void()>( this, &TerrainBlock::_updatePhysics ) );
  534. }
  535. return;
  536. }
  537. // Now on the server we rebuild the
  538. // affected area of the grid map.
  539. mFile->updateGrid( minPt, maxPt );
  540. // Fix up the bounds.
  541. _updateBounds();
  542. // Rebuild the physics representation.
  543. if ( mPhysicsRep )
  544. {
  545. // Delay the update by a few milliseconds so
  546. // that we're not rebuilding during an active
  547. // editing operation.
  548. mPhysicsRep->queueCallback( 500, Delegate<void()>( this, &TerrainBlock::_updatePhysics ) );
  549. }
  550. // Signal again here for any server side observers.
  551. smUpdateSignal.trigger( HeightmapUpdate, this, minPt, maxPt );
  552. // If this is a server object and the client update
  553. // was requested then try to use the local connection
  554. // pointer to do it.
  555. if ( updateClient && getClientObject() )
  556. ((TerrainBlock*)getClientObject())->updateGrid( minPt, maxPt, false );
  557. }
  558. bool TerrainBlock::getHeight( const Point2F &pos, F32 *height ) const
  559. {
  560. PROFILE_SCOPE( TerrainBlock_getHeight );
  561. F32 invSquareSize = 1.0f / mSquareSize;
  562. F32 xp = pos.x * invSquareSize;
  563. F32 yp = pos.y * invSquareSize;
  564. S32 x = S32(xp);
  565. S32 y = S32(yp);
  566. xp -= (F32)x;
  567. yp -= (F32)y;
  568. const U32 blockMask = mFile->mSize - 1;
  569. if ( x & ~blockMask || y & ~blockMask )
  570. return false;
  571. x &= blockMask;
  572. y &= blockMask;
  573. const TerrainSquare *sq = mFile->findSquare( 0, x, y );
  574. if ( sq->flags & TerrainSquare::Empty )
  575. return false;
  576. F32 zBottomLeft = fixedToFloat( mFile->getHeight( x, y ) );
  577. F32 zBottomRight = fixedToFloat( mFile->getHeight( x + 1, y ) );
  578. F32 zTopLeft = fixedToFloat( mFile->getHeight( x, y + 1 ) );
  579. F32 zTopRight = fixedToFloat( mFile->getHeight( x + 1, y + 1 ) );
  580. if ( sq->flags & TerrainSquare::Split45 )
  581. {
  582. if (xp>yp)
  583. // bottom half
  584. *height = zBottomLeft + xp * (zBottomRight-zBottomLeft) + yp * (zTopRight-zBottomRight);
  585. else
  586. // top half
  587. *height = zBottomLeft + xp * (zTopRight-zTopLeft) + yp * (zTopLeft-zBottomLeft);
  588. }
  589. else
  590. {
  591. if (1.0f-xp>yp)
  592. // bottom half
  593. *height = zBottomRight + (1.0f-xp) * (zBottomLeft-zBottomRight) + yp * (zTopLeft-zBottomLeft);
  594. else
  595. // top half
  596. *height = zBottomRight + (1.0f-xp) * (zTopLeft-zTopRight) + yp * (zTopRight-zBottomRight);
  597. }
  598. return true;
  599. }
  600. bool TerrainBlock::getNormal( const Point2F &pos, Point3F *normal, bool normalize, bool skipEmpty ) const
  601. {
  602. PROFILE_SCOPE( TerrainBlock_getNormal );
  603. F32 invSquareSize = 1.0f / mSquareSize;
  604. F32 xp = pos.x * invSquareSize;
  605. F32 yp = pos.y * invSquareSize;
  606. S32 x = S32(xp);
  607. S32 y = S32(yp);
  608. xp -= (F32)x;
  609. yp -= (F32)y;
  610. const U32 blockMask = mFile->mSize - 1;
  611. if ( x & ~blockMask || y & ~blockMask )
  612. return false;
  613. x &= blockMask;
  614. y &= blockMask;
  615. const TerrainSquare *sq = mFile->findSquare( 0, x, y );
  616. if ( skipEmpty && sq->flags & TerrainSquare::Empty )
  617. return false;
  618. F32 zBottomLeft = fixedToFloat( mFile->getHeight( x, y ) );
  619. F32 zBottomRight = fixedToFloat( mFile->getHeight( x + 1, y ) );
  620. F32 zTopLeft = fixedToFloat( mFile->getHeight( x, y + 1 ) );
  621. F32 zTopRight = fixedToFloat( mFile->getHeight( x + 1, y + 1 ) );
  622. if ( sq->flags & TerrainSquare::Split45 )
  623. {
  624. if (xp>yp)
  625. // bottom half
  626. normal->set(zBottomLeft-zBottomRight, zBottomRight-zTopRight, mSquareSize);
  627. else
  628. // top half
  629. normal->set(zTopLeft-zTopRight, zBottomLeft-zTopLeft, mSquareSize);
  630. }
  631. else
  632. {
  633. if (1.0f-xp>yp)
  634. // bottom half
  635. normal->set(zBottomLeft-zBottomRight, zBottomLeft-zTopLeft, mSquareSize);
  636. else
  637. // top half
  638. normal->set(zTopLeft-zTopRight, zBottomRight-zTopRight, mSquareSize);
  639. }
  640. if (normalize)
  641. normal->normalize();
  642. return true;
  643. }
  644. bool TerrainBlock::getSmoothNormal( const Point2F &pos,
  645. Point3F *normal,
  646. bool normalize,
  647. bool skipEmpty ) const
  648. {
  649. PROFILE_SCOPE( TerrainBlock_getSmoothNormal );
  650. F32 invSquareSize = 1.0f / mSquareSize;
  651. F32 xp = pos.x * invSquareSize;
  652. F32 yp = pos.y * invSquareSize;
  653. S32 x = S32(xp);
  654. S32 y = S32(yp);
  655. const U32 blockMask = mFile->mSize - 1;
  656. if ( x & ~blockMask || y & ~blockMask )
  657. return false;
  658. x &= blockMask;
  659. y &= blockMask;
  660. const TerrainSquare *sq = mFile->findSquare( 0, x, y );
  661. if ( skipEmpty && sq->flags & TerrainSquare::Empty )
  662. return false;
  663. F32 h1 = fixedToFloat( mFile->getHeight( x + 1, y ) );
  664. F32 h2 = fixedToFloat( mFile->getHeight( x, y + 1 ) );
  665. F32 h3 = fixedToFloat( mFile->getHeight( x - 1, y ) );
  666. F32 h4 = fixedToFloat( mFile->getHeight( x, y - 1 ) );
  667. normal->set( h3 - h1, h4 - h2, mSquareSize * 2.0f );
  668. if ( normalize )
  669. normal->normalize();
  670. return true;
  671. }
  672. bool TerrainBlock::getNormalAndHeight( const Point2F &pos, Point3F *normal, F32 *height, bool normalize ) const
  673. {
  674. PROFILE_SCOPE( TerrainBlock_getNormalAndHeight );
  675. F32 invSquareSize = 1.0f / mSquareSize;
  676. F32 xp = pos.x * invSquareSize;
  677. F32 yp = pos.y * invSquareSize;
  678. S32 x = S32(xp);
  679. S32 y = S32(yp);
  680. xp -= (F32)x;
  681. yp -= (F32)y;
  682. const U32 blockMask = mFile->mSize - 1;
  683. if ( x & ~blockMask || y & ~blockMask )
  684. return false;
  685. x &= blockMask;
  686. y &= blockMask;
  687. const TerrainSquare *sq = mFile->findSquare( 0, x, y );
  688. if ( sq->flags & TerrainSquare::Empty )
  689. return false;
  690. F32 zBottomLeft = fixedToFloat( mFile->getHeight(x, y) );
  691. F32 zBottomRight = fixedToFloat( mFile->getHeight(x + 1, y) );
  692. F32 zTopLeft = fixedToFloat( mFile->getHeight(x, y + 1) );
  693. F32 zTopRight = fixedToFloat( mFile->getHeight(x + 1, y + 1) );
  694. if ( sq->flags & TerrainSquare::Split45 )
  695. {
  696. if (xp>yp)
  697. {
  698. // bottom half
  699. normal->set(zBottomLeft-zBottomRight, zBottomRight-zTopRight, mSquareSize);
  700. *height = zBottomLeft + xp * (zBottomRight-zBottomLeft) + yp * (zTopRight-zBottomRight);
  701. }
  702. else
  703. {
  704. // top half
  705. normal->set(zTopLeft-zTopRight, zBottomLeft-zTopLeft, mSquareSize);
  706. *height = zBottomLeft + xp * (zTopRight-zTopLeft) + yp * (zTopLeft-zBottomLeft);
  707. }
  708. }
  709. else
  710. {
  711. if (1.0f-xp>yp)
  712. {
  713. // bottom half
  714. normal->set(zBottomLeft-zBottomRight, zBottomLeft-zTopLeft, mSquareSize);
  715. *height = zBottomRight + (1.0f-xp) * (zBottomLeft-zBottomRight) + yp * (zTopLeft-zBottomLeft);
  716. }
  717. else
  718. {
  719. // top half
  720. normal->set(zTopLeft-zTopRight, zBottomRight-zTopRight, mSquareSize);
  721. *height = zBottomRight + (1.0f-xp) * (zTopLeft-zTopRight) + yp * (zTopRight-zBottomRight);
  722. }
  723. }
  724. if (normalize)
  725. normal->normalize();
  726. return true;
  727. }
  728. bool TerrainBlock::getNormalHeightMaterial( const Point2F &pos,
  729. Point3F *normal,
  730. F32 *height,
  731. StringTableEntry &matName ) const
  732. {
  733. PROFILE_SCOPE( TerrainBlock_getNormalHeightMaterial );
  734. F32 invSquareSize = 1.0f / mSquareSize;
  735. F32 xp = pos.x * invSquareSize;
  736. F32 yp = pos.y * invSquareSize;
  737. S32 x = S32(xp);
  738. S32 y = S32(yp);
  739. S32 xm = S32(mFloor( xp + 0.5f ));
  740. S32 ym = S32(mFloor( yp + 0.5f ));
  741. xp -= (F32)x;
  742. yp -= (F32)y;
  743. const U32 blockMask = mFile->mSize - 1;
  744. if ( x & ~blockMask || y & ~blockMask )
  745. return false;
  746. x &= blockMask;
  747. y &= blockMask;
  748. const TerrainSquare *sq = mFile->findSquare( 0, x, y );
  749. if ( sq->flags & TerrainSquare::Empty )
  750. return false;
  751. F32 zBottomLeft = fixedToFloat( mFile->getHeight(x, y) );
  752. F32 zBottomRight = fixedToFloat( mFile->getHeight(x + 1, y) );
  753. F32 zTopLeft = fixedToFloat( mFile->getHeight(x, y + 1) );
  754. F32 zTopRight = fixedToFloat( mFile->getHeight(x + 1, y + 1) );
  755. matName = mFile->getMaterialName( xm, ym );
  756. if ( sq->flags & TerrainSquare::Split45 )
  757. {
  758. if (xp>yp)
  759. {
  760. // bottom half
  761. normal->set(zBottomLeft-zBottomRight, zBottomRight-zTopRight, mSquareSize);
  762. *height = zBottomLeft + xp * (zBottomRight-zBottomLeft) + yp * (zTopRight-zBottomRight);
  763. }
  764. else
  765. {
  766. // top half
  767. normal->set(zTopLeft-zTopRight, zBottomLeft-zTopLeft, mSquareSize);
  768. *height = zBottomLeft + xp * (zTopRight-zTopLeft) + yp * (zTopLeft-zBottomLeft);
  769. }
  770. }
  771. else
  772. {
  773. if (1.0f-xp>yp)
  774. {
  775. // bottom half
  776. normal->set(zBottomLeft-zBottomRight, zBottomLeft-zTopLeft, mSquareSize);
  777. *height = zBottomRight + (1.0f-xp) * (zBottomLeft-zBottomRight) + yp * (zTopLeft-zBottomLeft);
  778. }
  779. else
  780. {
  781. // top half
  782. normal->set(zTopLeft-zTopRight, zBottomRight-zTopRight, mSquareSize);
  783. *height = zBottomRight + (1.0f-xp) * (zTopLeft-zTopRight) + yp * (zTopRight-zBottomRight);
  784. }
  785. }
  786. normal->normalize();
  787. return true;
  788. }
  789. U32 TerrainBlock::getMaterialCount() const
  790. {
  791. return mFile->mMaterials.size();
  792. }
  793. void TerrainBlock::addMaterial( const String &name, U32 insertAt )
  794. {
  795. TerrainMaterial *mat = TerrainMaterial::findOrCreate( name );
  796. StringTableEntry newMatName = StringTable->insert(name.c_str());
  797. if ( insertAt == -1 )
  798. {
  799. //Check to ensure we're not trying to add one that already exists, as that'd be kinda dumb
  800. for (U32 i = 0; i < mFile->mMaterials.size(); i++)
  801. {
  802. if (mFile->mMaterials[i]->getInternalName() == newMatName)
  803. return;
  804. }
  805. mFile->mMaterials.push_back( mat );
  806. mFile->_initMaterialInstMapping();
  807. //now we update our asset
  808. if (mTerrainAsset)
  809. {
  810. StringTableEntry terrMatName = StringTable->insert(name.c_str());
  811. AssetQuery* aq = new AssetQuery();
  812. U32 foundCount = AssetDatabase.findAssetType(aq, "TerrainMaterialAsset");
  813. for (U32 i = 0; i < foundCount; i++)
  814. {
  815. TerrainMaterialAsset* terrMatAsset = AssetDatabase.acquireAsset<TerrainMaterialAsset>(aq->mAssetList[i]);
  816. if (terrMatAsset && terrMatAsset->getMaterialDefinitionName() == terrMatName)
  817. {
  818. //Do iterative logic to find the next available slot and write to it with our new mat field
  819. mTerrainAsset->setDataField(StringTable->insert("terrainMaterialAsset"), nullptr, aq->mAssetList[i]);
  820. }
  821. }
  822. }
  823. }
  824. else
  825. {
  826. // TODO: Insert and reindex!
  827. }
  828. mDetailsDirty = true;
  829. mLayerTexDirty = true;
  830. }
  831. void TerrainBlock::removeMaterial( U32 index )
  832. {
  833. // Cannot delete if only one layer.
  834. if ( mFile->mMaterials.size() == 1 )
  835. return;
  836. mFile->mMaterials.erase( index );
  837. mFile->_initMaterialInstMapping();
  838. for ( S32 i = 0; i < mFile->mLayerMap.size(); i++ )
  839. {
  840. if ( mFile->mLayerMap[i] >= index &&
  841. mFile->mLayerMap[i] != 0 )
  842. {
  843. mFile->mLayerMap[i]--;
  844. }
  845. }
  846. mDetailsDirty = true;
  847. mLayerTexDirty = true;
  848. }
  849. void TerrainBlock::updateMaterial( U32 index, const String &name )
  850. {
  851. if ( index >= mFile->mMaterials.size() )
  852. return;
  853. mFile->mMaterials[ index ] = TerrainMaterial::findOrCreate( name );
  854. mFile->_initMaterialInstMapping();
  855. mDetailsDirty = true;
  856. mLayerTexDirty = true;
  857. }
  858. TerrainMaterial* TerrainBlock::getMaterial( U32 index ) const
  859. {
  860. if ( index >= mFile->mMaterials.size() )
  861. return NULL;
  862. return mFile->mMaterials[ index ];
  863. }
  864. void TerrainBlock::deleteAllMaterials()
  865. {
  866. mFile->mMaterials.clear();
  867. mFile->mMaterialInstMapping.clearMatInstList();
  868. }
  869. const char* TerrainBlock::getMaterialName( U32 index ) const
  870. {
  871. if ( index < mFile->mMaterials.size() )
  872. return mFile->mMaterials[ index ]->getInternalName();
  873. return NULL;
  874. }
  875. void TerrainBlock::setLightMap( GBitmap *newLightMap )
  876. {
  877. SAFE_DELETE( mLightMap );
  878. mLightMap = newLightMap;
  879. mLightMapTex = NULL;
  880. }
  881. void TerrainBlock::clearLightMap()
  882. {
  883. if ( !mLightMap )
  884. mLightMap = new GBitmap( mLightMapSize, mLightMapSize, 0, GFXFormatR8G8B8 );
  885. mLightMap->fillWhite();
  886. mLightMapTex = NULL;
  887. }
  888. GFXTextureObject* TerrainBlock::getLightMapTex()
  889. {
  890. if ( mLightMapTex.isNull() && mLightMap )
  891. {
  892. mLightMapTex.set( mLightMap,
  893. &GFXStaticTextureProfile,
  894. false,
  895. "TerrainBlock::getLightMapTex()" );
  896. }
  897. return mLightMapTex;
  898. }
  899. void TerrainBlock::onEditorEnable()
  900. {
  901. }
  902. void TerrainBlock::onEditorDisable()
  903. {
  904. }
  905. bool TerrainBlock::onAdd()
  906. {
  907. if(!Parent::onAdd())
  908. return false;
  909. Resource<TerrainFile> terr;
  910. if (!mTerrainAsset.isNull())
  911. {
  912. terr = mTerrainAsset->getTerrainResource();
  913. if (terr == NULL)
  914. {
  915. if (isClientObject())
  916. NetConnection::setLastError("Unable to load terrain asset: %s", mTerrainAsset.getAssetId());
  917. return false;
  918. }
  919. setFile(terr);
  920. }
  921. addToScene();
  922. _updatePhysics();
  923. return true;
  924. }
  925. String TerrainBlock::_getBaseTexCacheFileName() const
  926. {
  927. Torque::Path basePath( mTerrainAsset->getTerrainFilePath() );
  928. basePath.setFileName( basePath.getFileName() + "_basetex" );
  929. basePath.setExtension( formatToExtension(mBaseTexFormat) );
  930. return basePath.getFullPath();
  931. }
  932. void TerrainBlock::_rebuildQuadtree()
  933. {
  934. SAFE_DELETE( mCell );
  935. // Recursively build the cells.
  936. mCell = TerrCell::init( this );
  937. // Build the shared PrimitiveBuffer.
  938. mCell->createPrimBuffer( &mPrimBuffer );
  939. deleteZodiacPrimitiveBuffer();
  940. }
  941. void TerrainBlock::_updatePhysics()
  942. {
  943. if ( !PHYSICSMGR )
  944. return;
  945. SAFE_DELETE( mPhysicsRep );
  946. PhysicsCollision *colShape;
  947. // If we can steal the collision shape from the local server
  948. // object then do so as it saves us alot of cpu time and memory.
  949. //
  950. // TODO: We should move this sharing down into TerrFile where
  951. // it probably belongs.
  952. //
  953. if ( getServerObject() )
  954. {
  955. TerrainBlock *serverTerrain = (TerrainBlock*)getServerObject();
  956. colShape = serverTerrain->mPhysicsRep->getColShape();
  957. }
  958. else
  959. {
  960. // Get empty state of each vert
  961. bool *holes = new bool[ getBlockSize() * getBlockSize() ];
  962. for ( U32 row = 0; row < getBlockSize(); row++ )
  963. for ( U32 column = 0; column < getBlockSize(); column++ )
  964. holes[ row + (column * getBlockSize()) ] = mFile->isEmptyAt( row, column );
  965. colShape = PHYSICSMGR->createCollision();
  966. colShape->addHeightfield( mFile->getHeightMap().address(), holes, getBlockSize(), mSquareSize, MatrixF::Identity );
  967. delete [] holes;
  968. }
  969. PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  970. mPhysicsRep = PHYSICSMGR->createBody();
  971. mPhysicsRep->init( colShape, 0, 0, this, world );
  972. mPhysicsRep->setTransform( getTransform() );
  973. }
  974. void TerrainBlock::onRemove()
  975. {
  976. removeFromScene();
  977. SceneZoneSpaceManager::getZoningChangedSignal().remove( this, &TerrainBlock::_onZoningChanged );
  978. SAFE_DELETE( mPhysicsRep );
  979. if ( isClientObject() )
  980. {
  981. mBaseTex = NULL;
  982. mLayerTex = NULL;
  983. SAFE_DELETE( mBaseMaterial );
  984. SAFE_DELETE( mDefaultMatInst );
  985. SAFE_DELETE( mCell );
  986. mPrimBuffer = NULL;
  987. mBaseShader = NULL;
  988. GFXTextureManager::removeEventDelegate( this, &TerrainBlock::_onTextureEvent );
  989. MATMGR->getFlushSignal().remove( this, &TerrainBlock::_onFlushMaterials );
  990. }
  991. Parent::onRemove();
  992. }
  993. void TerrainBlock::prepRenderImage( SceneRenderState* state )
  994. {
  995. PROFILE_SCOPE(TerrainBlock_prepRenderImage);
  996. // If we need to update our cached
  997. // zone state then do it now.
  998. if ( mZoningDirty )
  999. {
  1000. mZoningDirty = false;
  1001. mCell->updateZoning( getSceneManager()->getZoneManager() );
  1002. }
  1003. _renderBlock( state );
  1004. }
  1005. void TerrainBlock::setTransform(const MatrixF & mat)
  1006. {
  1007. Parent::setTransform( mat );
  1008. // Update world-space OBBs.
  1009. if( mCell )
  1010. {
  1011. mCell->updateOBBs();
  1012. mZoningDirty = true;
  1013. }
  1014. if ( mPhysicsRep )
  1015. mPhysicsRep->setTransform( mat );
  1016. setRenderTransform( mat );
  1017. setMaskBits( TransformMask );
  1018. if(isClientObject())
  1019. smUpdateSignal.trigger( HeightmapUpdate, this, Point2I::Zero, Point2I::Max );
  1020. }
  1021. void TerrainBlock::setScale( const VectorF &scale )
  1022. {
  1023. // We disable scaling... we never scale!
  1024. Parent::setScale( VectorF::One );
  1025. }
  1026. void TerrainBlock::initPersistFields()
  1027. {
  1028. addGroup( "Media" );
  1029. addProtectedField("terrainAsset", TypeTerrainAssetId, Offset(mTerrainAssetId, TerrainBlock),
  1030. &TerrainBlock::_setTerrainAsset, &defaultProtectedGetFn,
  1031. "The source terrain data asset.");
  1032. addProtectedField( "terrainFile", TypeStringFilename, Offset( mTerrFileName, TerrainBlock ),
  1033. &TerrainBlock::_setTerrainFile, &defaultProtectedGetFn,
  1034. "The source terrain data file." );
  1035. endGroup( "Media" );
  1036. addGroup( "Misc" );
  1037. addField( "castShadows", TypeBool, Offset( mCastShadows, TerrainBlock ),
  1038. "Allows the terrain to cast shadows onto itself and other objects.");
  1039. addProtectedField( "squareSize", TypeF32, Offset( mSquareSize, TerrainBlock ),
  1040. &TerrainBlock::_setSquareSize, &defaultProtectedGetFn,
  1041. "Indicates the spacing between points on the XY plane on the terrain." );
  1042. addProtectedField( "baseTexSize", TypeS32, Offset( mBaseTexSize, TerrainBlock ),
  1043. &TerrainBlock::_setBaseTexSize, &defaultProtectedGetFn,
  1044. "Size of base texture size per meter." );
  1045. addProtectedField("baseTexFormat", TYPEID<baseTexFormat>(), Offset(mBaseTexFormat, TerrainBlock),
  1046. &TerrainBlock::_setBaseTexFormat, &defaultProtectedGetFn,
  1047. "");
  1048. addProtectedField( "lightMapSize", TypeS32, Offset( mLightMapSize, TerrainBlock ),
  1049. &TerrainBlock::_setLightMapSize, &defaultProtectedGetFn,
  1050. "Light map dimensions in pixels." );
  1051. addField( "screenError", TypeS32, Offset( mScreenError, TerrainBlock ), "Not yet implemented." );
  1052. addField( "updateBasetex", TypeBool, Offset( mUpdateBasetex, TerrainBlock ), "Whether or not to update the Base Texture" );
  1053. endGroup( "Misc" );
  1054. addGroup("AFX");
  1055. addField("ignoreZodiacs", TypeBool, Offset(mIgnoreZodiacs, TerrainBlock));
  1056. endGroup("AFX");
  1057. Parent::initPersistFields();
  1058. removeField( "scale" );
  1059. Con::addVariable( "$TerrainBlock::debugRender", TypeBool, &smDebugRender, "Triggers debug rendering of terrain cells\n\n"
  1060. "@ingroup Terrain");
  1061. Con::addVariable( "$pref::Terrain::lodScale", TypeF32, &smLODScale, "A global LOD scale used to tweak the default terrain screen error value.\n\n"
  1062. "@ingroup Terrain");
  1063. Con::addVariable( "$pref::Terrain::detailScale", TypeF32, &smDetailScale, "A global detail scale used to tweak the material detail distances.\n\n"
  1064. "@ingroup Terrain");
  1065. }
  1066. void TerrainBlock::inspectPostApply()
  1067. {
  1068. Parent::inspectPostApply();
  1069. setMaskBits( MiscMask );
  1070. }
  1071. U32 TerrainBlock::packUpdate(NetConnection* con, U32 mask, BitStream *stream)
  1072. {
  1073. U32 retMask = Parent::packUpdate( con, mask, stream );
  1074. if ( stream->writeFlag( mask & TransformMask ) )
  1075. mathWrite( *stream, getTransform() );
  1076. if ( stream->writeFlag( mask & SizeMask ) )
  1077. stream->write( mSquareSize );
  1078. stream->writeFlag( mCastShadows );
  1079. if ( stream->writeFlag( mask & MaterialMask ) )
  1080. {
  1081. stream->write( mBaseTexSize );
  1082. stream->write( mLightMapSize );
  1083. }
  1084. if ( stream->writeFlag( mask & FileMask ) )
  1085. {
  1086. stream->write(mCRC);
  1087. stream->writeString( mTerrainAsset.getAssetId() );
  1088. }
  1089. stream->writeFlag( mask & HeightMapChangeMask );
  1090. if ( stream->writeFlag( mask & MiscMask ) )
  1091. stream->write( mScreenError );
  1092. stream->writeInt(mBaseTexFormat, 32);
  1093. stream->writeFlag(mUpdateBasetex);
  1094. stream->writeFlag(mIgnoreZodiacs);
  1095. return retMask;
  1096. }
  1097. void TerrainBlock::unpackUpdate(NetConnection* con, BitStream *stream)
  1098. {
  1099. Parent::unpackUpdate( con, stream );
  1100. if ( stream->readFlag() ) // TransformMask
  1101. {
  1102. MatrixF mat;
  1103. mathRead( *stream, &mat );
  1104. setTransform( mat );
  1105. }
  1106. if ( stream->readFlag() ) // SizeMask
  1107. stream->read( &mSquareSize );
  1108. mCastShadows = stream->readFlag();
  1109. bool baseTexSizeChanged = false;
  1110. if ( stream->readFlag() ) // MaterialMask
  1111. {
  1112. U32 baseTexSize;
  1113. stream->read( &baseTexSize );
  1114. if ( mBaseTexSize != baseTexSize )
  1115. {
  1116. mBaseTexSize = baseTexSize;
  1117. baseTexSizeChanged = true;
  1118. }
  1119. U32 lightMapSize;
  1120. stream->read( &lightMapSize );
  1121. if ( mLightMapSize != lightMapSize )
  1122. {
  1123. mLightMapSize = lightMapSize;
  1124. if ( isProperlyAdded() )
  1125. {
  1126. SAFE_DELETE( mLightMap );
  1127. clearLightMap();
  1128. }
  1129. }
  1130. }
  1131. if (stream->readFlag()) // FileMask
  1132. {
  1133. stream->read(&mCRC);
  1134. char buffer[256];
  1135. stream->readString(buffer);
  1136. }
  1137. if (baseTexSizeChanged && isProperlyAdded())
  1138. _updateBaseTexture(NONE);
  1139. if ( stream->readFlag() && isProperlyAdded() ) // HeightMapChangeMask
  1140. {
  1141. _updateBounds();
  1142. _rebuildQuadtree();
  1143. _updatePhysics();
  1144. mDetailsDirty = true;
  1145. mLayerTexDirty = true;
  1146. }
  1147. if ( stream->readFlag() ) // MiscMask
  1148. stream->read( &mScreenError );
  1149. mBaseTexFormat = (BaseTexFormat)stream->readInt(32);
  1150. mUpdateBasetex = stream->readFlag();
  1151. mIgnoreZodiacs = stream->readFlag();
  1152. }
  1153. void TerrainBlock::getMinMaxHeight( F32 *minHeight, F32 *maxHeight ) const
  1154. {
  1155. // We can get the bound height from the last grid level.
  1156. const TerrainSquare *sq = mFile->findSquare( mFile->mGridLevels, 0, 0 );
  1157. *minHeight = fixedToFloat( sq->minHeight );
  1158. *maxHeight = fixedToFloat( sq->maxHeight );
  1159. }
  1160. void TerrainBlock::getUtilizedAssets(Vector<StringTableEntry>* usedAssetsList)
  1161. {
  1162. if (!mTerrainAsset.isNull())
  1163. usedAssetsList->push_back_unique(mTerrainAsset->getAssetId());
  1164. }
  1165. //-----------------------------------------------------------------------------
  1166. // Console Methods
  1167. //-----------------------------------------------------------------------------
  1168. DefineEngineMethod( TerrainBlock, save, bool, ( const char* fileName),,
  1169. "@brief Saves the terrain block's terrain file to the specified file name.\n\n"
  1170. "@param fileName Name and path of file to save terrain data to.\n\n"
  1171. "@return True if file save was successful, false otherwise")
  1172. {
  1173. char filename[256];
  1174. dStrcpy(filename,fileName,256);
  1175. char *ext = dStrrchr(filename, '.');
  1176. if (!ext || dStricmp(ext, ".ter") != 0)
  1177. dStrcat(filename, ".ter", 256);
  1178. return static_cast<TerrainBlock*>(object)->save(filename);
  1179. }
  1180. DefineEngineMethod(TerrainBlock, saveAsset, bool, (), ,
  1181. "@brief Saves the terrain block's terrain file to the specified file name.\n\n"
  1182. "@param fileName Name and path of file to save terrain data to.\n\n"
  1183. "@return True if file save was successful, false otherwise")
  1184. {
  1185. return static_cast<TerrainBlock*>(object)->saveAsset();
  1186. }
  1187. DefineEngineMethod( TerrainBlock, setMaterialsDirty, void, (),, "")
  1188. {
  1189. static_cast<TerrainBlock*>(object)->setMaterialsDirty();
  1190. }
  1191. //ConsoleMethod(TerrainBlock, save, bool, 3, 3, "(string fileName) - saves the terrain block's terrain file to the specified file name.")
  1192. //{
  1193. // char filename[256];
  1194. // dStrcpy(filename,argv[2],256);
  1195. // char *ext = dStrrchr(filename, '.');
  1196. // if (!ext || dStricmp(ext, ".ter") != 0)
  1197. // dStrcat(filename, ".ter", 256);
  1198. // return static_cast<TerrainBlock*>(object)->save(filename);
  1199. //}
  1200. ConsoleDocFragment _getTerrainHeight1(
  1201. "@brief Gets the terrain height at the specified position\n\n"
  1202. "@param position The world space point, minus the z (height) value. Formatted as (\"x y\")\n\n"
  1203. "@return Returns the terrain height at the given point as an F32 value.\n\n"
  1204. "@ingroup Terrain",
  1205. NULL,
  1206. "bool getTerrainHeight( Point2I position );"
  1207. );
  1208. ConsoleDocFragment _getTerrainHeight2(
  1209. "@brief Gets the terrain height at the specified position\n\n"
  1210. "@param x The X coordinate in world space\n"
  1211. "@param y The Y coordinate in world space\n\n"
  1212. "@return Returns the terrain height at the given point as an F32 value.\n\n"
  1213. "@ingroup Terrain",
  1214. NULL,
  1215. "bool getTerrainHeight( F32 x, F32 y);"
  1216. );
  1217. DefineEngineFunction( getTerrainHeight, F32, (const char* ptOrX, const char* y), (""), "(Point2 pos) - gets the terrain height at the specified position."
  1218. "@param pos The world space point, minus the z (height) value\n Can be formatted as either (\"x y\") or (x,y)\n"
  1219. "@return Returns the terrain height at the given point as an F32 value.\n"
  1220. "@hide")
  1221. {
  1222. F32 height = 0.0f;
  1223. Point2F pos;
  1224. if(!String::isEmpty(ptOrX) && String::isEmpty(y))
  1225. dSscanf(ptOrX, "%f %f", &pos.x, &pos.y);
  1226. else if(!String::isEmpty(ptOrX) && !String::isEmpty(y))
  1227. {
  1228. pos.x = dAtof(ptOrX);
  1229. pos.y = dAtof(y);
  1230. }
  1231. TerrainBlock * terrain = getTerrainUnderWorldPoint(Point3F(pos.x, pos.y, 5000.0f));
  1232. if(terrain && terrain->isServerObject())
  1233. {
  1234. Point3F offset;
  1235. terrain->getTransform().getColumn(3, &offset);
  1236. pos -= Point2F(offset.x, offset.y);
  1237. terrain->getHeight(pos, &height);
  1238. }
  1239. return height;
  1240. }
  1241. ConsoleDocFragment _getTerrainHeightBelowPosition1(
  1242. "@brief Takes a world point and find the \"highest\" terrain underneath it\n\n"
  1243. "@param position The world space point, minus the z (height) value. Formatted as (\"x y\")\n\n"
  1244. "@return Returns the closest terrain height below the given point as an F32 value.\n\n"
  1245. "@ingroup Terrain",
  1246. NULL,
  1247. "bool getTerrainHeightBelowPosition( Point2I position );"
  1248. );
  1249. ConsoleDocFragment _getTerrainHeightBelowPosition2(
  1250. "@brief Takes a world point and find the \"highest\" terrain underneath it\n\n"
  1251. "@param x The X coordinate in world space\n"
  1252. "@param y The Y coordinate in world space\n\n"
  1253. "@return Returns the closest terrain height below the given point as an F32 value.\n\n"
  1254. "@ingroup Terrain",
  1255. NULL,
  1256. "bool getTerrainHeightBelowPosition( F32 x, F32 y);"
  1257. );
  1258. DefineEngineFunction( getTerrainHeightBelowPosition, F32, (const char* ptOrX, const char* y, const char* z), ("", ""),
  1259. "(Point3F pos) - gets the terrain height at the specified position."
  1260. "@param pos The world space point. Can be formatted as either (\"x y z\") or (x,y,z)\n"
  1261. "@note This function is useful if you simply want to grab the terrain height underneath an object.\n"
  1262. "@return Returns the terrain height at the given point as an F32 value.\n"
  1263. "@hide")
  1264. {
  1265. F32 height = 0.0f;
  1266. Point3F pos;
  1267. if(!String::isEmpty(ptOrX) && String::isEmpty(y) && String::isEmpty(z))
  1268. dSscanf(ptOrX, "%f %f %f", &pos.x, &pos.y, &pos.z);
  1269. else if(!String::isEmpty(ptOrX) && !String::isEmpty(y) && !String::isEmpty(z))
  1270. {
  1271. pos.x = dAtof(ptOrX);
  1272. pos.y = dAtof(y);
  1273. pos.z = dAtof(z);
  1274. }
  1275. TerrainBlock * terrain = getTerrainUnderWorldPoint(pos);
  1276. Point2F nohghtPos(pos.x, pos.y);
  1277. if(terrain)
  1278. {
  1279. if(terrain->isServerObject())
  1280. {
  1281. Point3F offset;
  1282. terrain->getTransform().getColumn(3, &offset);
  1283. nohghtPos -= Point2F(offset.x, offset.y);
  1284. terrain->getHeight(nohghtPos, &height);
  1285. }
  1286. }
  1287. return height;
  1288. }
  1289. const U16* TerrainBlock::getZodiacPrimitiveBuffer()
  1290. {
  1291. if (!zode_primBuffer && !mIgnoreZodiacs)
  1292. TerrCell::createZodiacPrimBuffer(&zode_primBuffer);
  1293. return zode_primBuffer;
  1294. }
  1295. void TerrainBlock::deleteZodiacPrimitiveBuffer()
  1296. {
  1297. if (zode_primBuffer != 0)
  1298. {
  1299. delete [] zode_primBuffer;
  1300. zode_primBuffer = 0;
  1301. }
  1302. }
  1303. DefineEngineMethod(TerrainBlock, getTerrain, String, (), , "Returns the terrain file used for this terrain block, either via the asset or the filename assigned, which ever is valid")
  1304. {
  1305. return object->getTerrain();
  1306. }
  1307. DefineEngineMethod(TerrainBlock, getTerrainAsset, String, (), , "Returns the assetId used for this terrain block")
  1308. {
  1309. return object->getTerrainAssetId();
  1310. }
  1311. DefineEngineMethod(TerrainBlock, setTerrain, bool, (const char* terrain), , "Terrain assignment.first tries asset then flat file.")
  1312. {
  1313. return object->_setTerrain(StringTable->insert(terrain));
  1314. }