terrData.cpp 47 KB

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