terrData.cpp 50 KB

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