fxFoliageReplicator.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812
  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. // Written by Melvyn May, Started on 4th August 2002.
  23. //
  24. // "My code is written for the Torque community, so do your worst with it,
  25. // just don't rip-it-off and call it your own without even thanking me".
  26. //
  27. // - Melv.
  28. //
  29. //
  30. // Conversion to TSE By Brian "bzztbomb" Richardson 9/2005
  31. // This was a neat piece of code! Thanks Melv!
  32. // I've switched this to use one large indexed primitive buffer. All animation
  33. // is then done in the vertex shader. This means we have a static vertex/primitive
  34. // buffer that never changes! How spiff! Because of this, the culling code was
  35. // changed to render out full quadtree nodes, we don't try to cull each individual
  36. // node ourselves anymore. This means to get good performance, you probably need to do the
  37. // following:
  38. // 1. If it's a small area to cover, turn off culling completely.
  39. // 2. You want to tune the parameters to make sure there are a lot of billboards within
  40. // each quadrant.
  41. //
  42. // POTENTIAL TODO LIST:
  43. // TODO: Clamp item alpha to fog alpha
  44. #include "platform/platform.h"
  45. #include "T3D/fx/fxFoliageReplicator.h"
  46. #include "gfx/gfxDevice.h"
  47. #include "gfx/primBuilder.h" // Used for debug / mission edit rendering
  48. #include "console/consoleTypes.h"
  49. #include "core/stream/bitStream.h"
  50. #include "math/mRandom.h"
  51. #include "math/mathIO.h"
  52. #include "console/simBase.h"
  53. #include "scene/sceneManager.h"
  54. #include "renderInstance/renderPassManager.h"
  55. #include "scene/sceneRenderState.h"
  56. #include "sim/netConnection.h"
  57. #include "materials/shaderData.h"
  58. #include "console/engineAPI.h"
  59. const U32 AlphaTexLen = 1024;
  60. GFXImplementVertexFormat( GFXVertexFoliage )
  61. {
  62. addElement( "POSITION", GFXDeclType_Float3 );
  63. addElement( "NORMAL", GFXDeclType_Float3 );
  64. addElement( "TEXCOORD", GFXDeclType_Float2, 0 );
  65. addElement( "TEXCOORD", GFXDeclType_Float2, 1 );
  66. }
  67. //------------------------------------------------------------------------------
  68. //
  69. // Put the function in /example/common/editor/ObjectBuilderGui.gui [around line 458] ...
  70. //
  71. // function ObjectBuilderGui::buildfxFoliageReplicator(%this)
  72. // {
  73. // %this.className = "fxFoliageReplicator";
  74. // %this.process();
  75. // }
  76. //
  77. //------------------------------------------------------------------------------
  78. //
  79. // Put this in /example/common/editor/EditorGui.cs in [function Creator::init( %this )]
  80. //
  81. // %Environment_Item[8] = "fxFoliageReplicator"; <-- ADD THIS.
  82. //
  83. //------------------------------------------------------------------------------
  84. //
  85. // Put this in /example/common/client/missionDownload.cs in [function clientCmdMissionStartPhase3(%seq,%missionName)] (line 65)
  86. // after codeline 'onPhase2Complete();'.
  87. //
  88. // StartFoliageReplication();
  89. //
  90. //------------------------------------------------------------------------------
  91. //
  92. // Put this in /engine/console/simBase.h (around line 509) in
  93. //
  94. // namespace Sim
  95. // {
  96. // DeclareNamedSet(fxFoliageSet) <-- ADD THIS (Note no semi-colon).
  97. //
  98. //------------------------------------------------------------------------------
  99. //
  100. // Put this in /engine/console/simBase.cc (around line 19) in
  101. //
  102. // ImplementNamedSet(fxFoliageSet) <-- ADD THIS (Note no semi-colon).
  103. //
  104. //------------------------------------------------------------------------------
  105. //
  106. // Put this in /engine/console/simManager.cc [function void init()] (around line 269).
  107. //
  108. // namespace Sim
  109. // {
  110. // InstantiateNamedSet(fxFoliageSet); <-- ADD THIS (Including Semi-colon).
  111. //
  112. //------------------------------------------------------------------------------
  113. extern bool gEditingMission;
  114. //------------------------------------------------------------------------------
  115. IMPLEMENT_CO_NETOBJECT_V1(fxFoliageReplicator);
  116. ConsoleDocClass( fxFoliageReplicator,
  117. "@brief An emitter to replicate fxFoliageItem objects across an area.\n"
  118. "@ingroup Foliage\n"
  119. );
  120. //------------------------------------------------------------------------------
  121. //
  122. // Trig Table Lookups.
  123. //
  124. //------------------------------------------------------------------------------
  125. const F32 PeriodLenMinus = (F32) (2.0f * M_PI) - 0.01f;
  126. //------------------------------------------------------------------------------
  127. //
  128. // Class: fxFoliageRenderList
  129. //
  130. //------------------------------------------------------------------------------
  131. void fxFoliageRenderList::SetupClipPlanes( SceneRenderState* state, const F32 farClipPlane )
  132. {
  133. const F32 nearPlane = state->getNearPlane();
  134. const F32 farPlane = farClipPlane;
  135. const Frustum& frustum = state->getCullingFrustum();
  136. // [rene, 23-Feb-11] Why isn't this preserving the ortho state of the original frustum?
  137. mFrustum.set( false,//zoneState.frustum.isOrtho(),
  138. frustum.getNearLeft(),
  139. frustum.getNearRight(),
  140. frustum.getNearTop(),
  141. frustum.getNearBottom(),
  142. nearPlane,
  143. farPlane,
  144. frustum.getTransform()
  145. );
  146. mBox = mFrustum.getBounds();
  147. }
  148. //------------------------------------------------------------------------------
  149. inline void fxFoliageRenderList::DrawQuadBox(const Box3F& QuadBox, const ColorF Colour)
  150. {
  151. // Define our debug box.
  152. static Point3F BoxPnts[] = {
  153. Point3F(0,0,0),
  154. Point3F(0,0,1),
  155. Point3F(0,1,0),
  156. Point3F(0,1,1),
  157. Point3F(1,0,0),
  158. Point3F(1,0,1),
  159. Point3F(1,1,0),
  160. Point3F(1,1,1)
  161. };
  162. static U32 BoxVerts[][4] = {
  163. {0,2,3,1}, // -x
  164. {7,6,4,5}, // +x
  165. {0,1,5,4}, // -y
  166. {3,2,6,7}, // +y
  167. {0,4,6,2}, // -z
  168. {3,7,5,1} // +z
  169. };
  170. // Project our Box Points.
  171. Point3F ProjectionPoints[8];
  172. for( U32 i=0; i<8; i++ )
  173. {
  174. ProjectionPoints[i].set(BoxPnts[i].x ? QuadBox.maxExtents.x : QuadBox.minExtents.x,
  175. BoxPnts[i].y ? QuadBox.maxExtents.y : QuadBox.minExtents.y,
  176. BoxPnts[i].z ? (mHeightLerp * QuadBox.maxExtents.z) + (1-mHeightLerp) * QuadBox.minExtents.z : QuadBox.minExtents.z);
  177. }
  178. PrimBuild::color(Colour);
  179. // Draw the Box.
  180. for(U32 x = 0; x < 6; x++)
  181. {
  182. // Draw a line-loop.
  183. PrimBuild::begin(GFXLineStrip, 5);
  184. for(U32 y = 0; y < 4; y++)
  185. {
  186. PrimBuild::vertex3f(ProjectionPoints[BoxVerts[x][y]].x,
  187. ProjectionPoints[BoxVerts[x][y]].y,
  188. ProjectionPoints[BoxVerts[x][y]].z);
  189. }
  190. PrimBuild::vertex3f(ProjectionPoints[BoxVerts[x][0]].x,
  191. ProjectionPoints[BoxVerts[x][0]].y,
  192. ProjectionPoints[BoxVerts[x][0]].z);
  193. PrimBuild::end();
  194. }
  195. }
  196. //------------------------------------------------------------------------------
  197. bool fxFoliageRenderList::IsQuadrantVisible(const Box3F VisBox, const MatrixF& RenderTransform)
  198. {
  199. // Can we trivially accept the visible box?
  200. if ( !mFrustum.isCulled( VisBox ) )
  201. return true;
  202. // Not visible.
  203. return false;
  204. }
  205. //------------------------------------------------------------------------------
  206. //
  207. // Class: fxFoliageCulledList
  208. //
  209. //------------------------------------------------------------------------------
  210. fxFoliageCulledList::fxFoliageCulledList(Box3F SearchBox, fxFoliageCulledList* InVec)
  211. {
  212. // Find the Candidates.
  213. FindCandidates(SearchBox, InVec);
  214. }
  215. //------------------------------------------------------------------------------
  216. void fxFoliageCulledList::FindCandidates(const Box3F& SearchBox, fxFoliageCulledList* InVec)
  217. {
  218. // Search the Culled List.
  219. for (U32 i = 0; i < InVec->GetListCount(); i++)
  220. {
  221. // Is this Box overlapping our search box?
  222. if (SearchBox.isOverlapped(InVec->GetElement(i)->FoliageBox))
  223. {
  224. // Yes, so add it to our culled list.
  225. mCulledObjectSet.push_back(InVec->GetElement(i));
  226. }
  227. }
  228. }
  229. //------------------------------------------------------------------------------
  230. //
  231. // Class: fxFoliageReplicator
  232. //
  233. //------------------------------------------------------------------------------
  234. fxFoliageReplicator::fxFoliageReplicator()
  235. {
  236. // Setup NetObject.
  237. mTypeMask |= StaticObjectType;
  238. mNetFlags.set(Ghostable | ScopeAlways);
  239. // Reset Client Replication Started.
  240. mClientReplicationStarted = false;
  241. // Reset Foliage Count.
  242. mCurrentFoliageCount = 0;
  243. // Reset Creation Area Angle Animation.
  244. mCreationAreaAngle = 0;
  245. // Reset Last Render Time.
  246. mLastRenderTime = 0;
  247. // Reset Foliage Nodes.
  248. mPotentialFoliageNodes = 0;
  249. // Reset Billboards Acquired.
  250. mBillboardsAcquired = 0;
  251. // Reset Frame Serial ID.
  252. mFrameSerialID = 0;
  253. mAlphaLookup = NULL;
  254. mDirty = true;
  255. mFoliageShaderProjectionSC = NULL;
  256. mFoliageShaderWorldSC = NULL;
  257. mFoliageShaderGlobalSwayPhaseSC = NULL;
  258. mFoliageShaderSwayMagnitudeSideSC = NULL;
  259. mFoliageShaderSwayMagnitudeFrontSC = NULL;
  260. mFoliageShaderGlobalLightPhaseSC = NULL;
  261. mFoliageShaderLuminanceMagnitudeSC = NULL;
  262. mFoliageShaderLuminanceMidpointSC = NULL;
  263. mFoliageShaderDistanceRangeSC = NULL;
  264. mFoliageShaderCameraPosSC = NULL;
  265. mFoliageShaderTrueBillboardSC = NULL;
  266. mFoliageShaderGroundAlphaSC = NULL;
  267. mFoliageShaderAmbientColorSC = NULL;
  268. mShaderData = NULL;
  269. }
  270. //------------------------------------------------------------------------------
  271. fxFoliageReplicator::~fxFoliageReplicator()
  272. {
  273. if (mAlphaLookup)
  274. delete mAlphaLookup;
  275. mPlacementSB = NULL;
  276. }
  277. //------------------------------------------------------------------------------
  278. void fxFoliageReplicator::initPersistFields()
  279. {
  280. // Add out own persistent fields.
  281. addGroup( "Debugging" ); // MM: Added Group Header.
  282. addField( "UseDebugInfo", TypeBool, Offset( mFieldData.mUseDebugInfo, fxFoliageReplicator ), "Culling bins are drawn when set to true." );
  283. addField( "DebugBoxHeight", TypeF32, Offset( mFieldData.mDebugBoxHeight, fxFoliageReplicator ), "Height multiplier for drawn culling bins.");
  284. addField( "HideFoliage", TypeBool, Offset( mFieldData.mHideFoliage, fxFoliageReplicator ), "Foliage is hidden when set to true." );
  285. addField( "ShowPlacementArea", TypeBool, Offset( mFieldData.mShowPlacementArea, fxFoliageReplicator ), "Draw placement rings when set to true." );
  286. addField( "PlacementAreaHeight", TypeS32, Offset( mFieldData.mPlacementBandHeight, fxFoliageReplicator ), "Height of the placement ring in world units." );
  287. addField( "PlacementColour", TypeColorF, Offset( mFieldData.mPlaceAreaColour, fxFoliageReplicator ), "Color of the placement ring." );
  288. endGroup( "Debugging" ); // MM: Added Group Footer.
  289. addGroup( "Media" ); // MM: Added Group Header.
  290. addField( "Seed", TypeS32, Offset( mFieldData.mSeed, fxFoliageReplicator ), "Random seed for foliage placement." );
  291. addField( "FoliageFile", TypeFilename, Offset( mFieldData.mFoliageFile, fxFoliageReplicator ), "Image file for the foliage texture." );
  292. addField( "FoliageCount", TypeS32, Offset( mFieldData.mFoliageCount, fxFoliageReplicator ), "Maximum foliage instance count." );
  293. addField( "FoliageRetries", TypeS32, Offset( mFieldData.mFoliageRetries, fxFoliageReplicator ), "Number of times to try placing a foliage instance before giving up." );
  294. endGroup( "Media" ); // MM: Added Group Footer.
  295. addGroup( "Area" ); // MM: Added Group Header.
  296. addField( "InnerRadiusX", TypeS32, Offset( mFieldData.mInnerRadiusX, fxFoliageReplicator ), "Placement area inner radius on the X axis" );
  297. addField( "InnerRadiusY", TypeS32, Offset( mFieldData.mInnerRadiusY, fxFoliageReplicator ), "Placement area inner radius on the Y axis" );
  298. addField( "OuterRadiusX", TypeS32, Offset( mFieldData.mOuterRadiusX, fxFoliageReplicator ), "Placement area outer radius on the X axis" );
  299. addField( "OuterRadiusY", TypeS32, Offset( mFieldData.mOuterRadiusY, fxFoliageReplicator ), "Placement area outer radius on the Y axis" );
  300. endGroup( "Area" ); // MM: Added Group Footer.
  301. addGroup( "Dimensions" ); // MM: Added Group Header.
  302. addField( "MinWidth", TypeF32, Offset( mFieldData.mMinWidth, fxFoliageReplicator ), "Minimum width of foliage billboards" );
  303. addField( "MaxWidth", TypeF32, Offset( mFieldData.mMaxWidth, fxFoliageReplicator ), "Maximum width of foliage billboards" );
  304. addField( "MinHeight", TypeF32, Offset( mFieldData.mMinHeight, fxFoliageReplicator ), "Minimum height of foliage billboards" );
  305. addField( "MaxHeight", TypeF32, Offset( mFieldData.mMaxHeight, fxFoliageReplicator ), "Maximum height of foliage billboards" );
  306. addField( "FixAspectRatio", TypeBool, Offset( mFieldData.mFixAspectRatio, fxFoliageReplicator ), "Maintain aspect ratio of image if true. This option ignores MaxWidth." );
  307. addField( "FixSizeToMax", TypeBool, Offset( mFieldData.mFixSizeToMax, fxFoliageReplicator ), "Use only MaxWidth and MaxHeight for billboard size. Ignores MinWidth and MinHeight." );
  308. addField( "OffsetZ", TypeF32, Offset( mFieldData.mOffsetZ, fxFoliageReplicator ), "Offset billboards by this amount vertically." );
  309. addField( "RandomFlip", TypeBool, Offset( mFieldData.mRandomFlip, fxFoliageReplicator ), "Randomly flip billboards left-to-right." );
  310. addField( "UseTrueBillboards", TypeBool, Offset( mFieldData.mUseTrueBillboards, fxFoliageReplicator ), "Use camera facing billboards ( including the z axis )." );
  311. endGroup( "Dimensions" ); // MM: Added Group Footer.
  312. addGroup( "Culling" ); // MM: Added Group Header.
  313. addField( "UseCulling", TypeBool, Offset( mFieldData.mUseCulling, fxFoliageReplicator ), "Use culling bins when enabled." );
  314. addField( "CullResolution", TypeS32, Offset( mFieldData.mCullResolution, fxFoliageReplicator ), "Minimum size of culling bins. Must be >= 8 and <= OuterRadius." );
  315. addField( "ViewDistance", TypeF32, Offset( mFieldData.mViewDistance, fxFoliageReplicator ), "Maximum distance from camera where foliage appears." );
  316. addField( "ViewClosest", TypeF32, Offset( mFieldData.mViewClosest, fxFoliageReplicator ), "Minimum distance from camera where foliage appears." );
  317. addField( "FadeInRegion", TypeF32, Offset( mFieldData.mFadeInRegion, fxFoliageReplicator ), "Region beyond ViewDistance where foliage fades in/out." );
  318. addField( "FadeOutRegion", TypeF32, Offset( mFieldData.mFadeOutRegion, fxFoliageReplicator ), "Region before ViewClosest where foliage fades in/out." );
  319. addField( "AlphaCutoff", TypeF32, Offset( mFieldData.mAlphaCutoff, fxFoliageReplicator ), "Minimum alpha value allowed on foliage instances." );
  320. addField( "GroundAlpha", TypeF32, Offset( mFieldData.mGroundAlpha, fxFoliageReplicator ), "Alpha of the foliage at ground level. 0 = transparent, 1 = opaque." );
  321. endGroup( "Culling" ); // MM: Added Group Footer.
  322. addGroup( "Animation" ); // MM: Added Group Header.
  323. addField( "SwayOn", TypeBool, Offset( mFieldData.mSwayOn, fxFoliageReplicator ), "Foliage should sway randomly when true." );
  324. addField( "SwaySync", TypeBool, Offset( mFieldData.mSwaySync, fxFoliageReplicator ), "Foliage instances should sway together when true and SwayOn is enabled." );
  325. addField( "SwayMagSide", TypeF32, Offset( mFieldData.mSwayMagnitudeSide, fxFoliageReplicator ), "Left-to-right sway magnitude." );
  326. addField( "SwayMagFront", TypeF32, Offset( mFieldData.mSwayMagnitudeFront, fxFoliageReplicator ), "Front-to-back sway magnitude." );
  327. addField( "MinSwayTime", TypeF32, Offset( mFieldData.mMinSwayTime, fxFoliageReplicator ), "Minumum sway cycle time in seconds." );
  328. addField( "MaxSwayTime", TypeF32, Offset( mFieldData.mMaxSwayTime, fxFoliageReplicator ), "Maximum sway cycle time in seconds." );
  329. endGroup( "Animation" ); // MM: Added Group Footer.
  330. addGroup( "Lighting" ); // MM: Added Group Header.
  331. addField( "LightOn", TypeBool, Offset( mFieldData.mLightOn, fxFoliageReplicator ), "Foliage should be illuminated with changing lights when true." );
  332. addField( "LightSync", TypeBool, Offset( mFieldData.mLightSync, fxFoliageReplicator ), "Foliage instances have the same lighting when set and LightOn is set." );
  333. addField( "MinLuminance", TypeF32, Offset( mFieldData.mMinLuminance, fxFoliageReplicator ), "Minimum luminance for foliage instances." );
  334. addField( "MaxLuminance", TypeF32, Offset( mFieldData.mMaxLuminance, fxFoliageReplicator ), "Maximum luminance for foliage instances." );
  335. addField( "LightTime", TypeF32, Offset( mFieldData.mLightTime, fxFoliageReplicator ), "Time before foliage illumination cycle repeats." );
  336. endGroup( "Lighting" ); // MM: Added Group Footer.
  337. addGroup( "Restrictions" ); // MM: Added Group Header.
  338. addField( "AllowOnTerrain", TypeBool, Offset( mFieldData.mAllowOnTerrain, fxFoliageReplicator ), "Foliage will be placed on terrain when set." );
  339. addField( "AllowOnStatics", TypeBool, Offset( mFieldData.mAllowStatics, fxFoliageReplicator ), "Foliage will be placed on Static shapes when set." );
  340. addField( "AllowOnWater", TypeBool, Offset( mFieldData.mAllowOnWater, fxFoliageReplicator ), "Foliage will be placed on/under water when set." );
  341. addField( "AllowWaterSurface", TypeBool, Offset( mFieldData.mAllowWaterSurface, fxFoliageReplicator ), "Foliage will be placed on water when set. Requires AllowOnWater." );
  342. addField( "AllowedTerrainSlope", TypeS32, Offset( mFieldData.mAllowedTerrainSlope, fxFoliageReplicator ), "Maximum surface angle allowed for foliage instances." );
  343. endGroup( "Restrictions" ); // MM: Added Group Footer.
  344. // Initialise parents' persistent fields.
  345. Parent::initPersistFields();
  346. }
  347. //------------------------------------------------------------------------------
  348. void fxFoliageReplicator::CreateFoliage(void)
  349. {
  350. F32 HypX, HypY;
  351. F32 Angle;
  352. U32 RelocationRetry;
  353. Point3F FoliagePosition;
  354. Point3F FoliageStart;
  355. Point3F FoliageEnd;
  356. Point3F FoliageScale;
  357. bool CollisionResult;
  358. RayInfo RayEvent;
  359. // Let's get a minimum bounding volume.
  360. Point3F MinPoint( -0.5, -0.5, -0.5 );
  361. Point3F MaxPoint( 0.5, 0.5, 0.5 );
  362. // Check Host.
  363. AssertFatal(isClientObject(), "Trying to create Foliage on Server, this is bad!");
  364. // Cannot continue without Foliage Texture!
  365. if (dStrlen(mFieldData.mFoliageFile) == 0)
  366. return;
  367. // Check that we can position somewhere!
  368. if (!( mFieldData.mAllowOnTerrain ||
  369. mFieldData.mAllowStatics ||
  370. mFieldData.mAllowOnWater))
  371. {
  372. // Problem ...
  373. Con::warnf(ConsoleLogEntry::General, "fxFoliageReplicator - Could not place Foliage, All alloweds are off!");
  374. // Return here.
  375. return;
  376. }
  377. // Destroy Foliage if we've already got some.
  378. if (mCurrentFoliageCount != 0) DestroyFoliage();
  379. // Inform the user if culling has been disabled!
  380. if (!mFieldData.mUseCulling)
  381. {
  382. // Console Output.
  383. Con::printf("fxFoliageReplicator - Culling has been disabled!");
  384. }
  385. // ----------------------------------------------------------------------------------------------------------------------
  386. // > Calculate the Potential Foliage Nodes Required to achieve the selected culling resolution.
  387. // > Populate Quad-tree structure to depth determined by culling resolution.
  388. //
  389. // A little explanation is called for here ...
  390. //
  391. // The approach to this problem has been choosen to make it *much* easier for
  392. // the user to control the quad-tree culling resolution. The user enters a single
  393. // world-space value 'mCullResolution' which controls the highest resolution at
  394. // which the replicator will check visibility culling.
  395. //
  396. // example: If 'mCullResolution' is 32 and the size of the replicated area is 128 radius
  397. // (256 diameter) then this results in the replicator creating a quad-tree where
  398. // there are 256/32 = 8x8 blocks. Each of these can be checked to see if they
  399. // reside within the viewing frustum and if not then they get culled therefore
  400. // removing the need to parse all the billboards that occcupy that region.
  401. // Most of the time you will get better than this as the culling algorithm will
  402. // check the culling pyramid from the top to bottom e.g. the follow 'blocks'
  403. // will be checked:-
  404. //
  405. // 1 x 256 x 256 (All of replicated area)
  406. // 4 x 128 x 128 (4 corners of above)
  407. // 16 x 64 x 64 (16 x 4 corners of above)
  408. // etc.
  409. //
  410. //
  411. // 1. First-up, the replicator needs to create a fixed-list of quad-tree nodes to work with.
  412. //
  413. // To calculate this we take the largest outer-radius value set in the replicator and
  414. // calculate how many quad-tree levels are required to achieve the selected 'mCullResolution'.
  415. // One of the initial problems is that the replicator has seperate radii values for X & Y.
  416. // This can lead to a culling resolution smaller in one axis than the other if there is a
  417. // difference between the Outer-Radii. Unfortunately, we just live with this as there is
  418. // not much we can do here if we still want to allow the user to have this kind of
  419. // elliptical placement control.
  420. //
  421. // To calculate the number of nodes needed we using the following equation:-
  422. //
  423. // Note:- We are changing the Logarithmic bases from 10 -> 2 ... grrrr!
  424. //
  425. // Cr = mCullResolution
  426. // Rs = Maximum Radii Diameter
  427. //
  428. //
  429. // ( Log10( Rs / Cr ) )
  430. // int ( ---------------- + 0.5 )
  431. // ( Log10( 2 ) )
  432. //
  433. // ---------|
  434. // |
  435. // | n
  436. // / 4
  437. // /
  438. // ---------|
  439. // n = 0
  440. //
  441. //
  442. // So basically we calculate the number of blocks in 1D at the highest resolution, then
  443. // calculate the inverse exponential (base 2 - 1D) to achieve that quantity of blocks.
  444. // We round that upto the next highest integer = e. We then sum 4 to the power 0->e
  445. // which gives us the correct number of nodes required. e is also stored as the starting
  446. // level value for populating the quad-tree (see 3. below).
  447. //
  448. // 2. We then proceed to calculate the billboard positions as normal and calculate and assign
  449. // each billboard a basic volume (rather than treat each as a point). We need to take into
  450. // account possible front/back swaying as well as the basic plane dimensions here.
  451. // When all the billboards have been choosen we then proceed to populate the quad-tree.
  452. //
  453. // 3. To populate the quad-tree we start with a box which completely encapsulates the volume
  454. // occupied by all the billboards and enter into a recursive procedure to process that node.
  455. // Processing this node involves splitting it into quadrants in X/Y untouched (for now).
  456. // We then find candidate billboards with each of these quadrants searching using the
  457. // current subset of shapes from the parent (this reduces the searching to a minimum and
  458. // is very efficient).
  459. //
  460. // If a quadrant does not enclose any billboards then the node is dropped otherwise it
  461. // is processed again using the same procedure.
  462. //
  463. // This happens until we have recursed through the maximum number of levels as calculated
  464. // using the summation max (see equation above). When level 0 is reached, the current list
  465. // of enclosed objects is stored within the node (for the rendering algorithm).
  466. //
  467. // 4. When this is complete we have finished here. The next stage is when rendering takes place.
  468. // An algorithm steps through the quad-tree from the top and does visibility culling on
  469. // each box (with respect to the viewing frustum) and culls as appropriate. If the box is
  470. // visible then the next level is checked until we reach level 0 where the node contains
  471. // a complete subset of billboards enclosed by the visible box.
  472. //
  473. //
  474. // Using the above algorithm we can now generate *massive* quantities of billboards and (using the
  475. // appropriate 'mCullResolution') only visible blocks of billboards will be processed.
  476. //
  477. // - Melv.
  478. //
  479. // ----------------------------------------------------------------------------------------------------------------------
  480. // ----------------------------------------------------------------------------------------------------------------------
  481. // Step 1.
  482. // ----------------------------------------------------------------------------------------------------------------------
  483. // Calculate the maximum dimension.
  484. F32 MaxDimension = 2.0f * ( (mFieldData.mOuterRadiusX > mFieldData.mOuterRadiusY) ? mFieldData.mOuterRadiusX : mFieldData.mOuterRadiusY );
  485. // Let's check that our cull resolution is not greater than half our maximum dimension (and less than 1).
  486. if (mFieldData.mCullResolution > (MaxDimension/2) || mFieldData.mCullResolution < 8)
  487. {
  488. // Problem ...
  489. Con::warnf(ConsoleLogEntry::General, "fxFoliageReplicator - Could create Foliage, invalid Culling Resolution!");
  490. Con::warnf(ConsoleLogEntry::General, "fxFoliageReplicator - Culling Resolution *must* be >=8 or <= %0.2f!", (MaxDimension/2));
  491. // Return here.
  492. return;
  493. }
  494. // Take first Timestamp.
  495. F32 mStartCreationTime = (F32) Platform::getRealMilliseconds();
  496. // Calculate the quad-tree levels needed for selected 'mCullResolution'.
  497. mQuadTreeLevels = (U32)(mCeil(mLog( MaxDimension / mFieldData.mCullResolution ) / mLog( 2.0f )));
  498. // Calculate the number of potential nodes required.
  499. mPotentialFoliageNodes = 0;
  500. for (U32 n = 0; n <= mQuadTreeLevels; n++)
  501. mPotentialFoliageNodes += (U32)(mCeil(mPow(4.0f, (F32) n))); // Ceil to be safe!
  502. // ----------------------------------------------------------------------------------------------------------------------
  503. // Step 2.
  504. // ----------------------------------------------------------------------------------------------------------------------
  505. // Set Seed.
  506. RandomGen.setSeed(mFieldData.mSeed);
  507. // Add Foliage.
  508. for (U32 idx = 0; idx < mFieldData.mFoliageCount; idx++)
  509. {
  510. fxFoliageItem* pFoliageItem;
  511. Point3F FoliageOffsetPos;
  512. // Reset Relocation Retry.
  513. RelocationRetry = mFieldData.mFoliageRetries;
  514. // Find it a home ...
  515. do
  516. {
  517. // Get the fxFoliageReplicator Position.
  518. FoliagePosition = getPosition();
  519. // Calculate a random offset
  520. HypX = RandomGen.randF((F32) mFieldData.mInnerRadiusX < mFieldData.mOuterRadiusX ? mFieldData.mInnerRadiusX : mFieldData.mOuterRadiusX, (F32) mFieldData.mOuterRadiusX);
  521. HypY = RandomGen.randF((F32) mFieldData.mInnerRadiusY < mFieldData.mOuterRadiusY ? mFieldData.mInnerRadiusY : mFieldData.mOuterRadiusY, (F32) mFieldData.mOuterRadiusY);
  522. Angle = RandomGen.randF(0, (F32) M_2PI);
  523. // Calcualte the new position.
  524. FoliagePosition.x += HypX * mCos(Angle);
  525. FoliagePosition.y += HypY * mSin(Angle);
  526. // Initialise RayCast Search Start/End Positions.
  527. FoliageStart = FoliageEnd = FoliagePosition;
  528. FoliageStart.z = 2000.f;
  529. FoliageEnd.z= -2000.f;
  530. // Perform Ray Cast Collision on Client.
  531. CollisionResult = gClientContainer.castRay( FoliageStart, FoliageEnd, FXFOLIAGEREPLICATOR_COLLISION_MASK, &RayEvent);
  532. // Did we hit anything?
  533. if (CollisionResult)
  534. {
  535. // For now, let's pretend we didn't get a collision.
  536. CollisionResult = false;
  537. // Yes, so get it's type.
  538. U32 CollisionType = RayEvent.object->getTypeMask();
  539. // Check Illegal Placements, fail if we hit a disallowed type.
  540. if (((CollisionType & TerrainObjectType) && !mFieldData.mAllowOnTerrain) ||
  541. ((CollisionType & StaticShapeObjectType ) && !mFieldData.mAllowStatics) ||
  542. ((CollisionType & WaterObjectType) && !mFieldData.mAllowOnWater) ) continue;
  543. // If we collided with water and are not allowing on the water surface then let's find the
  544. // terrain underneath and pass this on as the original collision else fail.
  545. if ((CollisionType & WaterObjectType) && !mFieldData.mAllowWaterSurface &&
  546. !gClientContainer.castRay( FoliageStart, FoliageEnd, FXFOLIAGEREPLICATOR_NOWATER_COLLISION_MASK, &RayEvent)) continue;
  547. // We passed with flying colour so carry on.
  548. CollisionResult = true;
  549. }
  550. // Invalidate if we are below Allowed Terrain Angle.
  551. if (RayEvent.normal.z < mSin(mDegToRad(90.0f-mFieldData.mAllowedTerrainSlope))) CollisionResult = false;
  552. // Wait until we get a collision.
  553. } while(!CollisionResult && --RelocationRetry);
  554. // Check for Relocation Problem.
  555. if (RelocationRetry > 0)
  556. {
  557. // Adjust Impact point.
  558. RayEvent.point.z += mFieldData.mOffsetZ;
  559. // Set New Position.
  560. FoliagePosition = RayEvent.point;
  561. }
  562. else
  563. {
  564. // Warning.
  565. Con::warnf(ConsoleLogEntry::General, "fxFoliageReplicator - Could not find satisfactory position for Foliage!");
  566. // Skip to next.
  567. continue;
  568. }
  569. // Monitor the total volume.
  570. FoliageOffsetPos = FoliagePosition - getPosition();
  571. MinPoint.setMin(FoliageOffsetPos);
  572. MaxPoint.setMax(FoliageOffsetPos);
  573. // Create our Foliage Item.
  574. pFoliageItem = new fxFoliageItem;
  575. // Reset Frame Serial.
  576. pFoliageItem->LastFrameSerialID = 0;
  577. // Reset Transform.
  578. pFoliageItem->Transform.identity();
  579. // Set Position.
  580. pFoliageItem->Transform.setColumn(3, FoliagePosition);
  581. // Are we fixing size @ max?
  582. if (mFieldData.mFixSizeToMax)
  583. {
  584. // Yes, so set height maximum height.
  585. pFoliageItem->Height = mFieldData.mMaxHeight;
  586. // Is the Aspect Ratio Fixed?
  587. if (mFieldData.mFixAspectRatio)
  588. // Yes, so lock to height.
  589. pFoliageItem->Width = pFoliageItem->Height;
  590. else
  591. // No, so set width to maximum width.
  592. pFoliageItem->Width = mFieldData.mMaxWidth;
  593. }
  594. else
  595. {
  596. // No, so choose a new Scale.
  597. pFoliageItem->Height = RandomGen.randF(mFieldData.mMinHeight, mFieldData.mMaxHeight);
  598. // Is the Aspect Ratio Fixed?
  599. if (mFieldData.mFixAspectRatio)
  600. // Yes, so lock to height.
  601. pFoliageItem->Width = pFoliageItem->Height;
  602. else
  603. // No, so choose a random width.
  604. pFoliageItem->Width = RandomGen.randF(mFieldData.mMinWidth, mFieldData.mMaxWidth);
  605. }
  606. // Are we randomly flipping horizontally?
  607. if (mFieldData.mRandomFlip)
  608. // Yes, so choose a random flip for this object.
  609. pFoliageItem->Flipped = (RandomGen.randF(0, 1000) < 500.0f) ? false : true;
  610. else
  611. // No, so turn-off flipping.
  612. pFoliageItem->Flipped = false;
  613. // Calculate Foliage Item World Box.
  614. // NOTE:- We generate a psuedo-volume here. It's basically the volume to which the
  615. // plane can move and this includes swaying!
  616. //
  617. // Is Sway On?
  618. if (mFieldData.mSwayOn)
  619. {
  620. // Yes, so take swaying into account...
  621. pFoliageItem->FoliageBox.minExtents = FoliagePosition +
  622. Point3F(-pFoliageItem->Width / 2.0f - mFieldData.mSwayMagnitudeSide,
  623. -0.5f - mFieldData.mSwayMagnitudeFront,
  624. pFoliageItem->Height );
  625. pFoliageItem->FoliageBox.maxExtents = FoliagePosition +
  626. Point3F(+pFoliageItem->Width / 2.0f + mFieldData.mSwayMagnitudeSide,
  627. +0.5f + mFieldData.mSwayMagnitudeFront,
  628. pFoliageItem->Height );
  629. }
  630. else
  631. {
  632. // No, so give it a minimum volume...
  633. pFoliageItem->FoliageBox.minExtents = FoliagePosition +
  634. Point3F(-pFoliageItem->Width / 2.0f,
  635. -0.5f,
  636. pFoliageItem->Height );
  637. pFoliageItem->FoliageBox.maxExtents = FoliagePosition +
  638. Point3F(+pFoliageItem->Width / 2.0f,
  639. +0.5f,
  640. pFoliageItem->Height );
  641. }
  642. // Store Shape in Replicated Shapes Vector.
  643. mReplicatedFoliage.push_back(pFoliageItem);
  644. // Increase Foliage Count.
  645. mCurrentFoliageCount++;
  646. }
  647. // Is Lighting On?
  648. if (mFieldData.mLightOn)
  649. {
  650. // Yes, so reset Global Light phase.
  651. mGlobalLightPhase = 0.0f;
  652. // Set Global Light Time Ratio.
  653. mGlobalLightTimeRatio = PeriodLenMinus / mFieldData.mLightTime;
  654. // Yes, so step through Foliage.
  655. for (U32 idx = 0; idx < mCurrentFoliageCount; idx++)
  656. {
  657. fxFoliageItem* pFoliageItem;
  658. // Fetch the Foliage Item.
  659. pFoliageItem = mReplicatedFoliage[idx];
  660. // Do we have an item?
  661. if (pFoliageItem)
  662. {
  663. // Yes, so are lights syncronised?
  664. if (mFieldData.mLightSync)
  665. {
  666. pFoliageItem->LightTimeRatio = 1.0f;
  667. pFoliageItem->LightPhase = 0.0f;
  668. }
  669. else
  670. {
  671. // No, so choose a random Light phase.
  672. pFoliageItem->LightPhase = RandomGen.randF(0, PeriodLenMinus);
  673. // Set Light Time Ratio.
  674. pFoliageItem->LightTimeRatio = PeriodLenMinus / mFieldData.mLightTime;
  675. }
  676. }
  677. }
  678. }
  679. // Is Swaying Enabled?
  680. if (mFieldData.mSwayOn)
  681. {
  682. // Yes, so reset Global Sway phase.
  683. mGlobalSwayPhase = 0.0f;
  684. // Always set Global Sway Time Ratio.
  685. mGlobalSwayTimeRatio = PeriodLenMinus / RandomGen.randF(mFieldData.mMinSwayTime, mFieldData.mMaxSwayTime);
  686. // Yes, so step through Foliage.
  687. for (U32 idx = 0; idx < mCurrentFoliageCount; idx++)
  688. {
  689. fxFoliageItem* pFoliageItem;
  690. // Fetch the Foliage Item.
  691. pFoliageItem = mReplicatedFoliage[idx];
  692. // Do we have an item?
  693. if (pFoliageItem)
  694. {
  695. // Are we using Sway Sync?
  696. if (mFieldData.mSwaySync)
  697. {
  698. pFoliageItem->SwayPhase = 0;
  699. pFoliageItem->SwayTimeRatio = mGlobalSwayTimeRatio;
  700. }
  701. else
  702. {
  703. // No, so choose a random Sway phase.
  704. pFoliageItem->SwayPhase = RandomGen.randF(0, PeriodLenMinus);
  705. // Set to random Sway Time.
  706. pFoliageItem->SwayTimeRatio = PeriodLenMinus / RandomGen.randF(mFieldData.mMinSwayTime, mFieldData.mMaxSwayTime);
  707. }
  708. }
  709. }
  710. }
  711. // Update our Object Volume.
  712. mObjBox.minExtents.set(MinPoint);
  713. mObjBox.maxExtents.set(MaxPoint);
  714. setTransform(mObjToWorld);
  715. // ----------------------------------------------------------------------------------------------------------------------
  716. // Step 3.
  717. // ----------------------------------------------------------------------------------------------------------------------
  718. // Reset Next Allocated Node to Stack base.
  719. mNextAllocatedNodeIdx = 0;
  720. // Allocate a new Node.
  721. fxFoliageQuadrantNode* pNewNode = new fxFoliageQuadrantNode;
  722. // Store it in the Quad-tree.
  723. mFoliageQuadTree.push_back(pNewNode);
  724. // Populate Initial Node.
  725. //
  726. // Set Start Level.
  727. pNewNode->Level = mQuadTreeLevels;
  728. // Calculate Total Foliage Area.
  729. pNewNode->QuadrantBox = getWorldBox();
  730. // Reset Quadrant child nodes.
  731. pNewNode->QuadrantChildNode[0] =
  732. pNewNode->QuadrantChildNode[1] =
  733. pNewNode->QuadrantChildNode[2] =
  734. pNewNode->QuadrantChildNode[3] = NULL;
  735. // Create our initial cull list with *all* billboards into.
  736. fxFoliageCulledList CullList;
  737. CullList.mCulledObjectSet = mReplicatedFoliage;
  738. // Move to next node Index.
  739. mNextAllocatedNodeIdx++;
  740. // Let's start this thing going by recursing it's children.
  741. ProcessNodeChildren(pNewNode, &CullList);
  742. // Calculate Elapsed Time and take new Timestamp.
  743. F32 ElapsedTime = (Platform::getRealMilliseconds() - mStartCreationTime) * 0.001f;
  744. // Console Output.
  745. Con::printf("fxFoliageReplicator - Lev: %d PotNodes: %d Used: %d Objs: %d Time: %0.4fs.",
  746. mQuadTreeLevels,
  747. mPotentialFoliageNodes,
  748. mNextAllocatedNodeIdx-1,
  749. mBillboardsAcquired,
  750. ElapsedTime);
  751. // Dump (*very*) approximate allocated memory.
  752. F32 MemoryAllocated = (F32) ((mNextAllocatedNodeIdx-1) * sizeof(fxFoliageQuadrantNode));
  753. MemoryAllocated += mCurrentFoliageCount * sizeof(fxFoliageItem);
  754. MemoryAllocated += mCurrentFoliageCount * sizeof(fxFoliageItem*);
  755. Con::printf("fxFoliageReplicator - Approx. %0.2fMb allocated.", MemoryAllocated / 1048576.0f);
  756. // ----------------------------------------------------------------------------------------------------------------------
  757. SetupBuffers();
  758. // Take first Timestamp.
  759. mLastRenderTime = Platform::getVirtualMilliseconds();
  760. }
  761. void fxFoliageReplicator::SetupShader()
  762. {
  763. if ( !mShaderData )
  764. {
  765. if ( !Sim::findObject( "fxFoliageReplicatorShader", mShaderData ) )
  766. {
  767. Con::errorf( "fxFoliageReplicator::SetupShader - could not find ShaderData named fxFoliageReplicatorShader" );
  768. return;
  769. }
  770. }
  771. Vector<GFXShaderMacro> macros;
  772. if ( mFieldData.mUseTrueBillboards )
  773. macros.push_back( GFXShaderMacro( "TRUE_BILLBOARD" ) );
  774. mShader = mShaderData->getShader( macros );
  775. if ( !mShader )
  776. return;
  777. mFoliageShaderConsts = mShader->allocConstBuffer();
  778. mFoliageShaderProjectionSC = mShader->getShaderConstHandle( "$projection" );
  779. mFoliageShaderWorldSC = mShader->getShaderConstHandle( "$world" );
  780. mFoliageShaderGlobalSwayPhaseSC = mShader->getShaderConstHandle( "$GlobalSwayPhase" );
  781. mFoliageShaderSwayMagnitudeSideSC = mShader->getShaderConstHandle( "$SwayMagnitudeSide" );
  782. mFoliageShaderSwayMagnitudeFrontSC = mShader->getShaderConstHandle( "$SwayMagnitudeFront" );
  783. mFoliageShaderGlobalLightPhaseSC = mShader->getShaderConstHandle( "$GlobalLightPhase" );
  784. mFoliageShaderLuminanceMagnitudeSC = mShader->getShaderConstHandle( "$LuminanceMagnitude" );
  785. mFoliageShaderLuminanceMidpointSC = mShader->getShaderConstHandle( "$LuminanceMidpoint" );
  786. mFoliageShaderDistanceRangeSC = mShader->getShaderConstHandle( "$DistanceRange" );
  787. mFoliageShaderCameraPosSC = mShader->getShaderConstHandle( "$CameraPos" );
  788. mFoliageShaderTrueBillboardSC = mShader->getShaderConstHandle( "$TrueBillboard" );
  789. mFoliageShaderGroundAlphaSC = mShader->getShaderConstHandle( "$groundAlpha" );
  790. mFoliageShaderAmbientColorSC = mShader->getShaderConstHandle( "$ambient" );
  791. mDiffuseTextureSC = mShader->getShaderConstHandle( "$diffuseMap" );
  792. mAlphaMapTextureSC = mShader->getShaderConstHandle( "$alphaMap" );
  793. }
  794. // Ok, what we do is let the older code setup the FoliageItem list and the QuadTree.
  795. // Then we build the Vertex and Primitive buffers here. It would probably be
  796. // slightly more memory efficient to build the buffers directly, but we
  797. // want to sort the items within the buffer by the quadtreenodes
  798. void fxFoliageReplicator::SetupBuffers()
  799. {
  800. // Following two arrays are used to build the vertex and primitive buffers.
  801. Point3F basePoints[8];
  802. basePoints[0] = Point3F(-0.5f, 0.0f, 1.0f);
  803. basePoints[1] = Point3F(-0.5f, 0.0f, 0.0f);
  804. basePoints[2] = Point3F(0.5f, 0.0f, 0.0f);
  805. basePoints[3] = Point3F(0.5f, 0.0f, 1.0f);
  806. Point2F texCoords[4];
  807. texCoords[0] = Point2F(0.0, 0.0);
  808. texCoords[1] = Point2F(0.0, 1.0);
  809. texCoords[2] = Point2F(1.0, 1.0);
  810. texCoords[3] = Point2F(1.0, 0.0);
  811. // Init our Primitive Buffer
  812. U32 indexSize = mFieldData.mFoliageCount * 6;
  813. U16* indices = new U16[indexSize];
  814. // Two triangles per particle
  815. for (U16 i = 0; i < mFieldData.mFoliageCount; i++) {
  816. U16* idx = &indices[i*6]; // hey, no offset math below, neat
  817. U16 vertOffset = i*4;
  818. idx[0] = vertOffset + 0;
  819. idx[1] = vertOffset + 1;
  820. idx[2] = vertOffset + 2;
  821. idx[3] = vertOffset + 2;
  822. idx[4] = vertOffset + 3;
  823. idx[5] = vertOffset + 0;
  824. }
  825. // Init the prim buffer and copy our indexes over
  826. U16 *ibIndices;
  827. mPrimBuffer.set(GFX, indexSize, 0, GFXBufferTypeStatic);
  828. mPrimBuffer.lock(&ibIndices);
  829. dMemcpy(ibIndices, indices, indexSize * sizeof(U16));
  830. mPrimBuffer.unlock();
  831. delete[] indices;
  832. // Now, let's init the vertex buffer
  833. U32 currPrimitiveStartIndex = 0;
  834. mVertexBuffer.set(GFX, mFieldData.mFoliageCount * 4, GFXBufferTypeStatic);
  835. mVertexBuffer.lock();
  836. U32 idx = 0;
  837. for (S32 qtIdx = 0; qtIdx < mFoliageQuadTree.size(); qtIdx++) {
  838. fxFoliageQuadrantNode* quadNode = mFoliageQuadTree[qtIdx];
  839. if (quadNode->Level == 0) {
  840. quadNode->startIndex = currPrimitiveStartIndex;
  841. quadNode->primitiveCount = 0;
  842. // Ok, there should be data in here!
  843. for (S32 i = 0; i < quadNode->RenderList.size(); i++) {
  844. fxFoliageItem* pFoliageItem = quadNode->RenderList[i];
  845. if (pFoliageItem->LastFrameSerialID == 0) {
  846. pFoliageItem->LastFrameSerialID++;
  847. // Dump it into the vertex buffer
  848. for (U32 vertIndex = 0; vertIndex < 4; vertIndex++) {
  849. GFXVertexFoliage *vert = &mVertexBuffer[(idx*4) + vertIndex];
  850. // This is the position of the billboard.
  851. vert->point = pFoliageItem->Transform.getPosition();
  852. // Normal contains the point of the billboard (except for the y component, see below)
  853. vert->normal = basePoints[vertIndex];
  854. vert->normal.x *= pFoliageItem->Width;
  855. vert->normal.z *= pFoliageItem->Height;
  856. // Handle texture coordinates
  857. vert->texCoord = texCoords[vertIndex];
  858. if (pFoliageItem->Flipped)
  859. vert->texCoord.x = 1.0f - vert->texCoord.x;
  860. // Handle sway. Sway is stored in a texture coord. The x coordinate is the sway phase multiplier,
  861. // the y coordinate determines if this vertex actually sways or not.
  862. if ((vertIndex == 0) || (vertIndex == 3)) {
  863. vert->texCoord2.set(pFoliageItem->SwayTimeRatio / mGlobalSwayTimeRatio, 1.0f);
  864. } else {
  865. vert->texCoord2.set(0.0f, 0.0f);
  866. }
  867. // Handle lighting, lighting happens at the same time as global so this is just an offset.
  868. vert->normal.y = pFoliageItem->LightPhase;
  869. }
  870. idx++;
  871. quadNode->primitiveCount += 2;
  872. currPrimitiveStartIndex += 6;
  873. }
  874. }
  875. }
  876. }
  877. mVertexBuffer.unlock();
  878. DestroyFoliageItems();
  879. }
  880. //------------------------------------------------------------------------------
  881. Box3F fxFoliageReplicator::FetchQuadrant(const Box3F& Box, U32 Quadrant)
  882. {
  883. Box3F QuadrantBox;
  884. // Select Quadrant.
  885. switch(Quadrant)
  886. {
  887. // UL.
  888. case 0:
  889. QuadrantBox.minExtents = Box.minExtents + Point3F(0, Box.len_y()/2, 0);
  890. QuadrantBox.maxExtents = QuadrantBox.minExtents + Point3F(Box.len_x()/2, Box.len_y()/2, Box.len_z());
  891. break;
  892. // UR.
  893. case 1:
  894. QuadrantBox.minExtents = Box.minExtents + Point3F(Box.len_x()/2, Box.len_y()/2, 0);
  895. QuadrantBox.maxExtents = QuadrantBox.minExtents + Point3F(Box.len_x()/2, Box.len_y()/2, Box.len_z());
  896. break;
  897. // LL.
  898. case 2:
  899. QuadrantBox.minExtents = Box.minExtents;
  900. QuadrantBox.maxExtents = QuadrantBox.minExtents + Point3F(Box.len_x()/2, Box.len_y()/2, Box.len_z());
  901. break;
  902. // LR.
  903. case 3:
  904. QuadrantBox.minExtents = Box.minExtents + Point3F(Box.len_x()/2, 0, 0);
  905. QuadrantBox.maxExtents = QuadrantBox.minExtents + Point3F(Box.len_x()/2, Box.len_y()/2, Box.len_z());
  906. break;
  907. default:
  908. return Box;
  909. }
  910. return QuadrantBox;
  911. }
  912. //------------------------------------------------------------------------------
  913. void fxFoliageReplicator::ProcessNodeChildren(fxFoliageQuadrantNode* pParentNode, fxFoliageCulledList* pCullList)
  914. {
  915. // ---------------------------------------------------------------
  916. // Split Node into Quadrants and Process each.
  917. // ---------------------------------------------------------------
  918. // Process All Quadrants (UL/UR/LL/LR).
  919. for (U32 q = 0; q < 4; q++)
  920. ProcessQuadrant(pParentNode, pCullList, q);
  921. }
  922. //------------------------------------------------------------------------------
  923. void fxFoliageReplicator::ProcessQuadrant(fxFoliageQuadrantNode* pParentNode, fxFoliageCulledList* pCullList, U32 Quadrant)
  924. {
  925. // Fetch Quadrant Box.
  926. const Box3F QuadrantBox = FetchQuadrant(pParentNode->QuadrantBox, Quadrant);
  927. // Create our new Cull List.
  928. fxFoliageCulledList CullList(QuadrantBox, pCullList);
  929. // Did we get any objects?
  930. if (CullList.GetListCount() > 0)
  931. {
  932. // Yes, so allocate a new Node.
  933. fxFoliageQuadrantNode* pNewNode = new fxFoliageQuadrantNode;
  934. // Store it in the Quad-tree.
  935. mFoliageQuadTree.push_back(pNewNode);
  936. // Move to next node Index.
  937. mNextAllocatedNodeIdx++;
  938. // Populate Quadrant Node.
  939. //
  940. // Next Sub-level.
  941. pNewNode->Level = pParentNode->Level - 1;
  942. // Calculate Quadrant Box.
  943. pNewNode->QuadrantBox = QuadrantBox;
  944. // Reset Child Nodes.
  945. pNewNode->QuadrantChildNode[0] =
  946. pNewNode->QuadrantChildNode[1] =
  947. pNewNode->QuadrantChildNode[2] =
  948. pNewNode->QuadrantChildNode[3] = NULL;
  949. // Put a reference in parent.
  950. pParentNode->QuadrantChildNode[Quadrant] = pNewNode;
  951. // If we're not at sub-level 0 then process this nodes children.
  952. if (pNewNode->Level != 0) ProcessNodeChildren(pNewNode, &CullList);
  953. // If we've reached sub-level 0 then store Cull List (for rendering).
  954. if (pNewNode->Level == 0)
  955. {
  956. // Store the render list from our culled object set.
  957. pNewNode->RenderList = CullList.mCulledObjectSet;
  958. // Keep track of the total billboard acquired.
  959. mBillboardsAcquired += CullList.GetListCount();
  960. }
  961. }
  962. }
  963. //------------------------------------------------------------------------------
  964. void fxFoliageReplicator::SyncFoliageReplicators(void)
  965. {
  966. // Check Host.
  967. AssertFatal(isServerObject(), "We *MUST* be on server when Synchronising Foliage!");
  968. // Find the Replicator Set.
  969. SimSet *fxFoliageSet = dynamic_cast<SimSet*>(Sim::findObject("fxFoliageSet"));
  970. // Return if Error.
  971. if (!fxFoliageSet)
  972. {
  973. // Console Warning.
  974. Con::warnf("fxFoliageReplicator - Cannot locate the 'fxFoliageSet', this is bad!");
  975. // Return here.
  976. return;
  977. }
  978. // Parse Replication Object(s).
  979. for (SimSetIterator itr(fxFoliageSet); *itr; ++itr)
  980. {
  981. // Fetch the Replicator Object.
  982. fxFoliageReplicator* Replicator = static_cast<fxFoliageReplicator*>(*itr);
  983. // Set Foliage Replication Mask.
  984. if (Replicator->isServerObject())
  985. {
  986. Con::printf("fxFoliageReplicator - Restarting fxFoliageReplicator Object...");
  987. Replicator->setMaskBits(FoliageReplicationMask);
  988. }
  989. }
  990. // Info ...
  991. Con::printf("fxFoliageReplicator - Client Foliage Sync has completed.");
  992. }
  993. //------------------------------------------------------------------------------
  994. // Lets chill our memory requirements out a little
  995. void fxFoliageReplicator::DestroyFoliageItems()
  996. {
  997. // Remove shapes.
  998. for (S32 idx = 0; idx < mReplicatedFoliage.size(); idx++)
  999. {
  1000. fxFoliageItem* pFoliageItem;
  1001. // Fetch the Foliage Item.
  1002. pFoliageItem = mReplicatedFoliage[idx];
  1003. // Delete Shape.
  1004. if (pFoliageItem) delete pFoliageItem;
  1005. }
  1006. // Clear the Replicated Foliage Vector.
  1007. mReplicatedFoliage.clear();
  1008. // Clear out old references also
  1009. for (S32 qtIdx = 0; qtIdx < mFoliageQuadTree.size(); qtIdx++) {
  1010. fxFoliageQuadrantNode* quadNode = mFoliageQuadTree[qtIdx];
  1011. if (quadNode->Level == 0) {
  1012. quadNode->RenderList.clear();
  1013. }
  1014. }
  1015. }
  1016. void fxFoliageReplicator::DestroyFoliage(void)
  1017. {
  1018. // Check Host.
  1019. AssertFatal(isClientObject(), "Trying to destroy Foliage on Server, this is bad!");
  1020. // Destroy Quad-tree.
  1021. mPotentialFoliageNodes = 0;
  1022. // Reset Billboards Acquired.
  1023. mBillboardsAcquired = 0;
  1024. // Finish if we didn't create any shapes.
  1025. if (mCurrentFoliageCount == 0) return;
  1026. DestroyFoliageItems();
  1027. // Let's remove the Quad-Tree allocations.
  1028. for ( Vector<fxFoliageQuadrantNode*>::iterator QuadNodeItr = mFoliageQuadTree.begin();
  1029. QuadNodeItr != mFoliageQuadTree.end();
  1030. QuadNodeItr++ )
  1031. {
  1032. // Remove the node.
  1033. delete *QuadNodeItr;
  1034. }
  1035. // Clear the Foliage Quad-Tree Vector.
  1036. mFoliageQuadTree.clear();
  1037. // Clear the Frustum Render Set Vector.
  1038. mFrustumRenderSet.mVisObjectSet.clear();
  1039. // Reset Foliage Count.
  1040. mCurrentFoliageCount = 0;
  1041. }
  1042. //------------------------------------------------------------------------------
  1043. void fxFoliageReplicator::StartUp(void)
  1044. {
  1045. // Flag, Client Replication Started.
  1046. mClientReplicationStarted = true;
  1047. // Create foliage on Client.
  1048. if (isClientObject()) CreateFoliage();
  1049. }
  1050. //------------------------------------------------------------------------------
  1051. bool fxFoliageReplicator::onAdd()
  1052. {
  1053. if(!Parent::onAdd()) return(false);
  1054. // Add the Replicator to the Replicator Set.
  1055. dynamic_cast<SimSet*>(Sim::findObject("fxFoliageSet"))->addObject(this);
  1056. // Set Default Object Box.
  1057. mObjBox.minExtents.set( -0.5, -0.5, -0.5 );
  1058. mObjBox.maxExtents.set( 0.5, 0.5, 0.5 );
  1059. resetWorldBox();
  1060. setRenderTransform(mObjToWorld);
  1061. // Add to Scene.
  1062. addToScene();
  1063. // Are we on the client?
  1064. if ( isClientObject() )
  1065. {
  1066. // Yes, so load foliage texture.
  1067. if( mFieldData.mFoliageFile != NULL && dStrlen(mFieldData.mFoliageFile) > 0 )
  1068. mFieldData.mFoliageTexture = GFXTexHandle( mFieldData.mFoliageFile, &GFXDefaultStaticDiffuseProfile, avar("%s() - mFieldData.mFoliageTexture (line %d)", __FUNCTION__, __LINE__) );
  1069. if ((GFXTextureObject*) mFieldData.mFoliageTexture == NULL)
  1070. Con::printf("fxFoliageReplicator: %s is an invalid or missing foliage texture file.", mFieldData.mFoliageFile);
  1071. mAlphaLookup = new GBitmap(AlphaTexLen, 1);
  1072. computeAlphaTex();
  1073. // Register for notification when GhostAlways objects are done loading
  1074. NetConnection::smGhostAlwaysDone.notify( this, &fxFoliageReplicator::onGhostAlwaysDone );
  1075. SetupShader();
  1076. }
  1077. // Return OK.
  1078. return(true);
  1079. }
  1080. //------------------------------------------------------------------------------
  1081. void fxFoliageReplicator::onRemove()
  1082. {
  1083. // Remove the Replicator from the Replicator Set.
  1084. dynamic_cast<SimSet*>(Sim::findObject("fxFoliageSet"))->removeObject(this);
  1085. NetConnection::smGhostAlwaysDone.remove( this, &fxFoliageReplicator::onGhostAlwaysDone );
  1086. // Remove from Scene.
  1087. removeFromScene();
  1088. // Are we on the Client?
  1089. if (isClientObject())
  1090. {
  1091. // Yes, so destroy Foliage.
  1092. DestroyFoliage();
  1093. // Remove Texture.
  1094. mFieldData.mFoliageTexture = NULL;
  1095. mShader = NULL;
  1096. }
  1097. // Do Parent.
  1098. Parent::onRemove();
  1099. }
  1100. //------------------------------------------------------------------------------
  1101. void fxFoliageReplicator::onGhostAlwaysDone()
  1102. {
  1103. if ( isClientObject() )
  1104. CreateFoliage();
  1105. }
  1106. //------------------------------------------------------------------------------
  1107. void fxFoliageReplicator::inspectPostApply()
  1108. {
  1109. // Set Parent.
  1110. Parent::inspectPostApply();
  1111. // Set Foliage Replication Mask (this object only).
  1112. setMaskBits(FoliageReplicationMask);
  1113. mDirty = true;
  1114. }
  1115. //------------------------------------------------------------------------------
  1116. DefineEngineFunction(StartFoliageReplication, void,(),, "Activates the foliage replicator.\n"
  1117. "@tsexample\n"
  1118. "// Call the function\n"
  1119. "StartFoliageReplication();\n"
  1120. "@endtsexample\n"
  1121. "@ingroup Foliage")
  1122. {
  1123. // Find the Replicator Set.
  1124. SimSet *fxFoliageSet = dynamic_cast<SimSet*>(Sim::findObject("fxFoliageSet"));
  1125. // Return if Error.
  1126. if (!fxFoliageSet)
  1127. {
  1128. // Console Warning.
  1129. Con::warnf("fxFoliageReplicator - Cannot locate the 'fxFoliageSet', this is bad!");
  1130. // Return here.
  1131. return;
  1132. }
  1133. // Parse Replication Object(s).
  1134. U32 startupCount = 0;
  1135. for (SimSetIterator itr(fxFoliageSet); *itr; ++itr)
  1136. {
  1137. // Fetch the Replicator Object.
  1138. fxFoliageReplicator* Replicator = static_cast<fxFoliageReplicator*>(*itr);
  1139. // Start Client Objects Only.
  1140. if (Replicator->isClientObject())
  1141. {
  1142. Replicator->StartUp();
  1143. startupCount++;
  1144. }
  1145. }
  1146. // Info ...
  1147. Con::printf("fxFoliageReplicator - replicated client foliage for %d objects", startupCount);
  1148. }
  1149. //------------------------------------------------------------------------------
  1150. void fxFoliageReplicator::prepRenderImage( SceneRenderState* state )
  1151. {
  1152. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  1153. ri->renderDelegate.bind(this, &fxFoliageReplicator::renderObject);
  1154. ri->type = RenderPassManager::RIT_Foliage;
  1155. state->getRenderPass()->addInst( ri );
  1156. }
  1157. //
  1158. // RENDERING
  1159. //
  1160. void fxFoliageReplicator::computeAlphaTex()
  1161. {
  1162. // Distances used in alpha
  1163. const F32 ClippedViewDistance = mFieldData.mViewDistance;
  1164. const F32 MaximumViewDistance = ClippedViewDistance + mFieldData.mFadeInRegion;
  1165. // This is used for the alpha computation in the shader.
  1166. for (U32 i = 0; i < AlphaTexLen; i++) {
  1167. F32 Distance = ((float) i / (float) AlphaTexLen) * MaximumViewDistance;
  1168. F32 ItemAlpha = 1.0f;
  1169. // Are we fading out?
  1170. if (Distance < mFieldData.mViewClosest)
  1171. {
  1172. // Yes, so set fade-out.
  1173. ItemAlpha = 1.0f - ((mFieldData.mViewClosest - Distance) * mFadeOutGradient);
  1174. }
  1175. // No, so are we fading in?
  1176. else if (Distance > ClippedViewDistance)
  1177. {
  1178. // Yes, so set fade-in
  1179. ItemAlpha = 1.0f - ((Distance - ClippedViewDistance) * mFadeInGradient);
  1180. }
  1181. // Set texture info
  1182. ColorI c((U8) (255.0f * ItemAlpha), 0, 0);
  1183. mAlphaLookup->setColor(i, 0, c);
  1184. }
  1185. mAlphaTexture.set(mAlphaLookup, &GFXDefaultStaticDiffuseProfile, false, String("fxFoliage Replicator Alpha Texture") );
  1186. }
  1187. // Renders a triangle stripped oval
  1188. void fxFoliageReplicator::renderArc(const F32 fRadiusX, const F32 fRadiusY)
  1189. {
  1190. PrimBuild::begin(GFXTriangleStrip, 720);
  1191. for (U32 Angle = mCreationAreaAngle; Angle < (mCreationAreaAngle+360); Angle++)
  1192. {
  1193. F32 XPos, YPos;
  1194. // Calculate Position.
  1195. XPos = fRadiusX * mCos(mDegToRad(-(F32)Angle));
  1196. YPos = fRadiusY * mSin(mDegToRad(-(F32)Angle));
  1197. // Set Colour.
  1198. PrimBuild::color4f(mFieldData.mPlaceAreaColour.red,
  1199. mFieldData.mPlaceAreaColour.green,
  1200. mFieldData.mPlaceAreaColour.blue,
  1201. AREA_ANIMATION_ARC * (Angle-mCreationAreaAngle));
  1202. PrimBuild::vertex3f(XPos, YPos, -(F32)mFieldData.mPlacementBandHeight/2.0f);
  1203. PrimBuild::vertex3f(XPos, YPos, +(F32)mFieldData.mPlacementBandHeight/2.0f);
  1204. }
  1205. PrimBuild::end();
  1206. }
  1207. // This currently uses the primbuilder, could convert out, but why allocate the buffer if we
  1208. // never edit the misison?
  1209. void fxFoliageReplicator::renderPlacementArea(const F32 ElapsedTime)
  1210. {
  1211. if (gEditingMission && mFieldData.mShowPlacementArea)
  1212. {
  1213. GFX->pushWorldMatrix();
  1214. GFX->multWorld(getTransform());
  1215. if (!mPlacementSB)
  1216. {
  1217. GFXStateBlockDesc transparent;
  1218. transparent.setCullMode(GFXCullNone);
  1219. transparent.alphaTestEnable = true;
  1220. transparent.setZReadWrite(true);
  1221. transparent.zWriteEnable = false;
  1222. transparent.setBlend(true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha);
  1223. mPlacementSB = GFX->createStateBlock( transparent );
  1224. }
  1225. GFX->setStateBlock(mPlacementSB);
  1226. // Do we need to draw the Outer Radius?
  1227. if (mFieldData.mOuterRadiusX || mFieldData.mOuterRadiusY)
  1228. renderArc((F32) mFieldData.mOuterRadiusX, (F32) mFieldData.mOuterRadiusY);
  1229. // Inner radius?
  1230. if (mFieldData.mInnerRadiusX || mFieldData.mInnerRadiusY)
  1231. renderArc((F32) mFieldData.mInnerRadiusX, (F32) mFieldData.mInnerRadiusY);
  1232. GFX->popWorldMatrix();
  1233. mCreationAreaAngle = (U32)(mCreationAreaAngle + (1000 * ElapsedTime));
  1234. mCreationAreaAngle = mCreationAreaAngle % 360;
  1235. }
  1236. }
  1237. void fxFoliageReplicator::renderObject(ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance* overrideMat)
  1238. {
  1239. if (overrideMat)
  1240. return;
  1241. if ( !mShader )
  1242. return;
  1243. // If we're rendering and we haven't placed any foliage yet - do it.
  1244. if(!mClientReplicationStarted)
  1245. {
  1246. Con::warnf("fxFoliageReplicator::renderObject - tried to render a non replicated fxFoliageReplicator; replicating it now...");
  1247. StartUp();
  1248. }
  1249. // Calculate Elapsed Time and take new Timestamp.
  1250. S32 Time = Platform::getVirtualMilliseconds();
  1251. F32 ElapsedTime = (Time - mLastRenderTime) * 0.001f;
  1252. mLastRenderTime = Time;
  1253. renderPlacementArea(ElapsedTime);
  1254. if (mCurrentFoliageCount > 0) {
  1255. if ( mRenderSB.isNull() || mDirty)
  1256. {
  1257. mDirty = false;
  1258. GFXStateBlockDesc desc;
  1259. // Debug SB
  1260. desc.samplersDefined = true;
  1261. desc.samplers[0].textureColorOp = GFXTOPDisable;
  1262. desc.samplers[1].textureColorOp = GFXTOPDisable;
  1263. mDebugSB = GFX->createStateBlock(desc);
  1264. // Render SB
  1265. desc.samplers[0].textureColorOp = GFXTOPModulate;
  1266. desc.samplers[1].textureColorOp = GFXTOPModulate;
  1267. desc.samplers[1].addressModeU = GFXAddressClamp;
  1268. desc.samplers[1].addressModeV = GFXAddressClamp;
  1269. desc.setBlend(true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha);
  1270. desc.setAlphaTest(true, GFXCmpGreater, (U8) (255.0f * mFieldData.mAlphaCutoff));
  1271. desc.setCullMode(GFXCullNone);
  1272. mRenderSB = GFX->createStateBlock(desc);
  1273. }
  1274. if (!mFieldData.mHideFoliage) {
  1275. // Animate Global Sway Phase (Modulus).
  1276. mGlobalSwayPhase = mGlobalSwayPhase + (mGlobalSwayTimeRatio * ElapsedTime);
  1277. // Animate Global Light Phase (Modulus).
  1278. mGlobalLightPhase = mGlobalLightPhase + (mGlobalLightTimeRatio * ElapsedTime);
  1279. // Compute other light parameters
  1280. const F32 LuminanceMidPoint = (mFieldData.mMinLuminance + mFieldData.mMaxLuminance) / 2.0f;
  1281. const F32 LuminanceMagnitude = mFieldData.mMaxLuminance - LuminanceMidPoint;
  1282. // Distances used in alpha
  1283. const F32 ClippedViewDistance = mFieldData.mViewDistance;
  1284. const F32 MaximumViewDistance = ClippedViewDistance + mFieldData.mFadeInRegion;
  1285. if (mFoliageShaderConsts.isValid())
  1286. {
  1287. mFoliageShaderConsts->setSafe(mFoliageShaderGlobalSwayPhaseSC, mGlobalSwayPhase);
  1288. mFoliageShaderConsts->setSafe(mFoliageShaderSwayMagnitudeSideSC, mFieldData.mSwayMagnitudeSide);
  1289. mFoliageShaderConsts->setSafe(mFoliageShaderSwayMagnitudeFrontSC, mFieldData.mSwayMagnitudeFront);
  1290. mFoliageShaderConsts->setSafe(mFoliageShaderGlobalLightPhaseSC, mGlobalLightPhase);
  1291. mFoliageShaderConsts->setSafe(mFoliageShaderLuminanceMagnitudeSC, LuminanceMagnitude);
  1292. mFoliageShaderConsts->setSafe(mFoliageShaderLuminanceMidpointSC, LuminanceMidPoint);
  1293. // Set up our shader constants
  1294. // Projection matrix
  1295. MatrixF proj = GFX->getProjectionMatrix();
  1296. //proj.transpose();
  1297. mFoliageShaderConsts->setSafe(mFoliageShaderProjectionSC, proj);
  1298. // World transform matrix
  1299. MatrixF world = GFX->getWorldMatrix();
  1300. //world.transpose();
  1301. mFoliageShaderConsts->setSafe(mFoliageShaderWorldSC, world);
  1302. Point3F camPos = state->getCameraPosition();
  1303. mFoliageShaderConsts->setSafe(mFoliageShaderDistanceRangeSC, MaximumViewDistance);
  1304. mFoliageShaderConsts->setSafe(mFoliageShaderCameraPosSC, camPos);
  1305. mFoliageShaderConsts->setSafe(mFoliageShaderTrueBillboardSC, mFieldData.mUseTrueBillboards ? 1.0f : 0.0f );
  1306. mFoliageShaderConsts->setSafe(mFoliageShaderGroundAlphaSC, Point4F(mFieldData.mGroundAlpha, mFieldData.mGroundAlpha, mFieldData.mGroundAlpha, mFieldData.mGroundAlpha));
  1307. if (mFoliageShaderAmbientColorSC->isValid())
  1308. mFoliageShaderConsts->set(mFoliageShaderAmbientColorSC, state->getAmbientLightColor());
  1309. GFX->setShaderConstBuffer(mFoliageShaderConsts);
  1310. }
  1311. // Blend ops
  1312. // Set up our texture and color ops.
  1313. GFX->setStateBlock(mRenderSB);
  1314. GFX->setShader( mShader );
  1315. GFX->setTexture(mDiffuseTextureSC->getSamplerRegister(), mFieldData.mFoliageTexture);
  1316. // computeAlphaTex(); // Uncomment if we figure out how to clamp to fogAndHaze
  1317. GFX->setTexture(mAlphaMapTextureSC->getSamplerRegister(), mAlphaTexture);
  1318. // Setup our buffers
  1319. GFX->setVertexBuffer(mVertexBuffer);
  1320. GFX->setPrimitiveBuffer(mPrimBuffer);
  1321. // If we use culling, we're going to send chunks of our buffers to the card
  1322. if (mFieldData.mUseCulling)
  1323. {
  1324. // Setup the Clip-Planes.
  1325. F32 FarClipPlane = getMin((F32)state->getFarPlane(),
  1326. mFieldData.mViewDistance + mFieldData.mFadeInRegion);
  1327. mFrustumRenderSet.SetupClipPlanes(state, FarClipPlane);
  1328. renderQuad(mFoliageQuadTree[0], getRenderTransform(), false);
  1329. // Multipass, don't want to interrupt the vb state
  1330. if (mFieldData.mUseDebugInfo)
  1331. {
  1332. // hey man, we're done, so it doesn't matter if we kill it to render the next part
  1333. GFX->setStateBlock(mDebugSB);
  1334. renderQuad(mFoliageQuadTree[0], getRenderTransform(), true);
  1335. }
  1336. }
  1337. else
  1338. {
  1339. // Draw the whole shebang!
  1340. GFX->drawIndexedPrimitive(GFXTriangleList, 0, 0, mVertexBuffer->mNumVerts,
  1341. 0, mPrimBuffer->mIndexCount / 3);
  1342. }
  1343. }
  1344. }
  1345. }
  1346. void fxFoliageReplicator::renderQuad(fxFoliageQuadrantNode* quadNode, const MatrixF& RenderTransform, const bool UseDebug)
  1347. {
  1348. if (quadNode != NULL) {
  1349. if (mFrustumRenderSet.IsQuadrantVisible(quadNode->QuadrantBox, RenderTransform))
  1350. {
  1351. // Draw the Quad Box (Debug Only).
  1352. if (UseDebug)
  1353. mFrustumRenderSet.DrawQuadBox(quadNode->QuadrantBox, ColorF(0.0f, 1.0f, 0.1f, 1.0f));
  1354. if (quadNode->Level != 0) {
  1355. for (U32 i = 0; i < 4; i++)
  1356. renderQuad(quadNode->QuadrantChildNode[i], RenderTransform, UseDebug);
  1357. } else {
  1358. if (!UseDebug)
  1359. if(quadNode->primitiveCount)
  1360. GFX->drawIndexedPrimitive(GFXTriangleList, 0, 0, mVertexBuffer->mNumVerts,
  1361. quadNode->startIndex, quadNode->primitiveCount);
  1362. }
  1363. } else {
  1364. // Use a different color to say "I think I'm not visible!"
  1365. if (UseDebug)
  1366. mFrustumRenderSet.DrawQuadBox(quadNode->QuadrantBox, ColorF(1.0f, 0.8f, 0.1f, 1.0f));
  1367. }
  1368. }
  1369. }
  1370. //------------------------------------------------------------------------------
  1371. // NETWORK
  1372. //------------------------------------------------------------------------------
  1373. U32 fxFoliageReplicator::packUpdate(NetConnection * con, U32 mask, BitStream * stream)
  1374. {
  1375. // Pack Parent.
  1376. U32 retMask = Parent::packUpdate(con, mask, stream);
  1377. // Write Foliage Replication Flag.
  1378. if (stream->writeFlag(mask & FoliageReplicationMask))
  1379. {
  1380. stream->writeAffineTransform(mObjToWorld); // Foliage Master-Object Position.
  1381. stream->writeFlag(mFieldData.mUseDebugInfo); // Foliage Debug Information Flag.
  1382. stream->write(mFieldData.mDebugBoxHeight); // Foliage Debug Height.
  1383. stream->write(mFieldData.mSeed); // Foliage Seed.
  1384. stream->write(mFieldData.mFoliageCount); // Foliage Count.
  1385. stream->write(mFieldData.mFoliageRetries); // Foliage Retries.
  1386. stream->writeString(mFieldData.mFoliageFile); // Foliage File.
  1387. stream->write(mFieldData.mInnerRadiusX); // Foliage Inner Radius X.
  1388. stream->write(mFieldData.mInnerRadiusY); // Foliage Inner Radius Y.
  1389. stream->write(mFieldData.mOuterRadiusX); // Foliage Outer Radius X.
  1390. stream->write(mFieldData.mOuterRadiusY); // Foliage Outer Radius Y.
  1391. stream->write(mFieldData.mMinWidth); // Foliage Minimum Width.
  1392. stream->write(mFieldData.mMaxWidth); // Foliage Maximum Width.
  1393. stream->write(mFieldData.mMinHeight); // Foliage Minimum Height.
  1394. stream->write(mFieldData.mMaxHeight); // Foliage Maximum Height.
  1395. stream->write(mFieldData.mFixAspectRatio); // Foliage Fix Aspect Ratio.
  1396. stream->write(mFieldData.mFixSizeToMax); // Foliage Fix Size to Max.
  1397. stream->write(mFieldData.mOffsetZ); // Foliage Offset Z.
  1398. stream->writeFlag(mFieldData.mRandomFlip); // Foliage Random Flip.
  1399. stream->writeFlag(mFieldData.mUseTrueBillboards); // Foliage faces the camera (including z axis)
  1400. stream->write(mFieldData.mUseCulling); // Foliage Use Culling.
  1401. stream->write(mFieldData.mCullResolution); // Foliage Cull Resolution.
  1402. stream->write(mFieldData.mViewDistance); // Foliage View Distance.
  1403. stream->write(mFieldData.mViewClosest); // Foliage View Closest.
  1404. stream->write(mFieldData.mFadeInRegion); // Foliage Fade-In Region.
  1405. stream->write(mFieldData.mFadeOutRegion); // Foliage Fade-Out Region.
  1406. stream->write(mFieldData.mAlphaCutoff); // Foliage Alpha Cutoff.
  1407. stream->write(mFieldData.mGroundAlpha); // Foliage Ground Alpha.
  1408. stream->writeFlag(mFieldData.mSwayOn); // Foliage Sway On Flag.
  1409. stream->writeFlag(mFieldData.mSwaySync); // Foliage Sway Sync Flag.
  1410. stream->write(mFieldData.mSwayMagnitudeSide); // Foliage Sway Magnitude Side2Side.
  1411. stream->write(mFieldData.mSwayMagnitudeFront); // Foliage Sway Magnitude Front2Back.
  1412. stream->write(mFieldData.mMinSwayTime); // Foliage Minimum Sway Time.
  1413. stream->write(mFieldData.mMaxSwayTime); // Foliage Maximum way Time.
  1414. stream->writeFlag(mFieldData.mLightOn); // Foliage Light On Flag.
  1415. stream->writeFlag(mFieldData.mLightSync); // Foliage Light Sync
  1416. stream->write(mFieldData.mMinLuminance); // Foliage Minimum Luminance.
  1417. stream->write(mFieldData.mMaxLuminance); // Foliage Maximum Luminance.
  1418. stream->write(mFieldData.mLightTime); // Foliage Light Time.
  1419. stream->writeFlag(mFieldData.mAllowOnTerrain); // Allow on Terrain.
  1420. stream->writeFlag(mFieldData.mAllowStatics); // Allow on Statics.
  1421. stream->writeFlag(mFieldData.mAllowOnWater); // Allow on Water.
  1422. stream->writeFlag(mFieldData.mAllowWaterSurface); // Allow on Water Surface.
  1423. stream->write(mFieldData.mAllowedTerrainSlope); // Foliage Offset Z.
  1424. stream->writeFlag(mFieldData.mHideFoliage); // Hide Foliage.
  1425. stream->writeFlag(mFieldData.mShowPlacementArea); // Show Placement Area Flag.
  1426. stream->write(mFieldData.mPlacementBandHeight); // Placement Area Height.
  1427. stream->write(mFieldData.mPlaceAreaColour); // Placement Area Colour.
  1428. }
  1429. // Were done ...
  1430. return(retMask);
  1431. }
  1432. //------------------------------------------------------------------------------
  1433. void fxFoliageReplicator::unpackUpdate(NetConnection * con, BitStream * stream)
  1434. {
  1435. // Unpack Parent.
  1436. Parent::unpackUpdate(con, stream);
  1437. // Read Replication Details.
  1438. if(stream->readFlag())
  1439. {
  1440. MatrixF ReplicatorObjectMatrix;
  1441. stream->readAffineTransform(&ReplicatorObjectMatrix); // Foliage Master Object Position.
  1442. mFieldData.mUseDebugInfo = stream->readFlag(); // Foliage Debug Information Flag.
  1443. stream->read(&mFieldData.mDebugBoxHeight); // Foliage Debug Height.
  1444. stream->read(&mFieldData.mSeed); // Foliage Seed.
  1445. stream->read(&mFieldData.mFoliageCount); // Foliage Count.
  1446. stream->read(&mFieldData.mFoliageRetries); // Foliage Retries.
  1447. mFieldData.mFoliageFile = stream->readSTString(); // Foliage File.
  1448. stream->read(&mFieldData.mInnerRadiusX); // Foliage Inner Radius X.
  1449. stream->read(&mFieldData.mInnerRadiusY); // Foliage Inner Radius Y.
  1450. stream->read(&mFieldData.mOuterRadiusX); // Foliage Outer Radius X.
  1451. stream->read(&mFieldData.mOuterRadiusY); // Foliage Outer Radius Y.
  1452. stream->read(&mFieldData.mMinWidth); // Foliage Minimum Width.
  1453. stream->read(&mFieldData.mMaxWidth); // Foliage Maximum Width.
  1454. stream->read(&mFieldData.mMinHeight); // Foliage Minimum Height.
  1455. stream->read(&mFieldData.mMaxHeight); // Foliage Maximum Height.
  1456. stream->read(&mFieldData.mFixAspectRatio); // Foliage Fix Aspect Ratio.
  1457. stream->read(&mFieldData.mFixSizeToMax); // Foliage Fix Size to Max.
  1458. stream->read(&mFieldData.mOffsetZ); // Foliage Offset Z.
  1459. mFieldData.mRandomFlip = stream->readFlag(); // Foliage Random Flip.
  1460. bool wasTrueBB = mFieldData.mUseTrueBillboards;
  1461. mFieldData.mUseTrueBillboards = stream->readFlag(); // Foliage is camera facing (including z axis).
  1462. stream->read(&mFieldData.mUseCulling); // Foliage Use Culling.
  1463. stream->read(&mFieldData.mCullResolution); // Foliage Cull Resolution.
  1464. stream->read(&mFieldData.mViewDistance); // Foliage View Distance.
  1465. stream->read(&mFieldData.mViewClosest); // Foliage View Closest.
  1466. stream->read(&mFieldData.mFadeInRegion); // Foliage Fade-In Region.
  1467. stream->read(&mFieldData.mFadeOutRegion); // Foliage Fade-Out Region.
  1468. stream->read(&mFieldData.mAlphaCutoff); // Foliage Alpha Cutoff.
  1469. stream->read(&mFieldData.mGroundAlpha); // Foliage Ground Alpha.
  1470. mFieldData.mSwayOn = stream->readFlag(); // Foliage Sway On Flag.
  1471. mFieldData.mSwaySync = stream->readFlag(); // Foliage Sway Sync Flag.
  1472. stream->read(&mFieldData.mSwayMagnitudeSide); // Foliage Sway Magnitude Side2Side.
  1473. stream->read(&mFieldData.mSwayMagnitudeFront); // Foliage Sway Magnitude Front2Back.
  1474. stream->read(&mFieldData.mMinSwayTime); // Foliage Minimum Sway Time.
  1475. stream->read(&mFieldData.mMaxSwayTime); // Foliage Maximum way Time.
  1476. mFieldData.mLightOn = stream->readFlag(); // Foliage Light On Flag.
  1477. mFieldData.mLightSync = stream->readFlag(); // Foliage Light Sync
  1478. stream->read(&mFieldData.mMinLuminance); // Foliage Minimum Luminance.
  1479. stream->read(&mFieldData.mMaxLuminance); // Foliage Maximum Luminance.
  1480. stream->read(&mFieldData.mLightTime); // Foliage Light Time.
  1481. mFieldData.mAllowOnTerrain = stream->readFlag(); // Allow on Terrain.
  1482. mFieldData.mAllowStatics = stream->readFlag(); // Allow on Statics.
  1483. mFieldData.mAllowOnWater = stream->readFlag(); // Allow on Water.
  1484. mFieldData.mAllowWaterSurface = stream->readFlag(); // Allow on Water Surface.
  1485. stream->read(&mFieldData.mAllowedTerrainSlope); // Allowed Terrain Slope.
  1486. mFieldData.mHideFoliage = stream->readFlag(); // Hide Foliage.
  1487. mFieldData.mShowPlacementArea = stream->readFlag(); // Show Placement Area Flag.
  1488. stream->read(&mFieldData.mPlacementBandHeight); // Placement Area Height.
  1489. stream->read(&mFieldData.mPlaceAreaColour);
  1490. // Calculate Fade-In/Out Gradients.
  1491. mFadeInGradient = 1.0f / mFieldData.mFadeInRegion;
  1492. mFadeOutGradient = 1.0f / mFieldData.mFadeOutRegion;
  1493. // Set Transform.
  1494. setTransform(ReplicatorObjectMatrix);
  1495. // Load Foliage Texture on the client.
  1496. if( mFieldData.mFoliageFile != NULL && dStrlen(mFieldData.mFoliageFile) > 0 )
  1497. mFieldData.mFoliageTexture = GFXTexHandle( mFieldData.mFoliageFile, &GFXDefaultStaticDiffuseProfile, avar("%s() - mFieldData.mFoliageTexture (line %d)", __FUNCTION__, __LINE__) );
  1498. if ((GFXTextureObject*) mFieldData.mFoliageTexture == NULL)
  1499. Con::printf("fxFoliageReplicator: %s is an invalid or missing foliage texture file.", mFieldData.mFoliageFile);
  1500. // Set Quad-Tree Box Height Lerp.
  1501. mFrustumRenderSet.mHeightLerp = mFieldData.mDebugBoxHeight;
  1502. // Create Foliage (if Replication has begun).
  1503. if (mClientReplicationStarted)
  1504. {
  1505. CreateFoliage();
  1506. mDirty = true;
  1507. }
  1508. if ( isProperlyAdded() && mFieldData.mUseTrueBillboards != wasTrueBB )
  1509. SetupShader();
  1510. }
  1511. }