renderMeshExample.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. #include "platform/platform.h"
  23. #include "T3D/examples/renderMeshExample.h"
  24. #include "math/mathIO.h"
  25. #include "scene/sceneRenderState.h"
  26. #include "console/consoleTypes.h"
  27. #include "core/stream/bitStream.h"
  28. #include "materials/materialManager.h"
  29. #include "materials/baseMatInstance.h"
  30. #include "renderInstance/renderPassManager.h"
  31. #include "lighting/lightQuery.h"
  32. #include "console/engineAPI.h"
  33. IMPLEMENT_CO_NETOBJECT_V1(RenderMeshExample);
  34. ConsoleDocClass( RenderMeshExample,
  35. "@brief An example scene object which renders a mesh.\n\n"
  36. "This class implements a basic SceneObject that can exist in the world at a "
  37. "3D position and render itself. There are several valid ways to render an "
  38. "object in Torque. This class implements the preferred rendering method which "
  39. "is to submit a MeshRenderInst along with a Material, vertex buffer, "
  40. "primitive buffer, and transform and allow the RenderMeshMgr handle the "
  41. "actual setup and rendering for you.\n\n"
  42. "See the C++ code for implementation details.\n\n"
  43. "@ingroup Examples\n" );
  44. //-----------------------------------------------------------------------------
  45. // Object setup and teardown
  46. //-----------------------------------------------------------------------------
  47. RenderMeshExample::RenderMeshExample()
  48. {
  49. // Flag this object so that it will always
  50. // be sent across the network to clients
  51. mNetFlags.set( Ghostable | ScopeAlways );
  52. // Set it as a "static" object that casts shadows
  53. mTypeMask |= StaticObjectType | StaticShapeObjectType;
  54. INIT_ASSET(Material);
  55. mMaterialInst = NULL;
  56. }
  57. RenderMeshExample::~RenderMeshExample()
  58. {
  59. if ( mMaterialInst )
  60. SAFE_DELETE( mMaterialInst );
  61. }
  62. //-----------------------------------------------------------------------------
  63. // Object Editing
  64. //-----------------------------------------------------------------------------
  65. void RenderMeshExample::initPersistFields()
  66. {
  67. docsURL;
  68. addGroup( "Rendering" );
  69. INITPERSISTFIELD_MATERIALASSET(Material, RenderMeshExample, "The material used to render the mesh.");
  70. endGroup( "Rendering" );
  71. // SceneObject already handles exposing the transform
  72. Parent::initPersistFields();
  73. }
  74. void RenderMeshExample::inspectPostApply()
  75. {
  76. Parent::inspectPostApply();
  77. // Flag the network mask to send the updates
  78. // to the client object
  79. setMaskBits( UpdateMask );
  80. }
  81. bool RenderMeshExample::onAdd()
  82. {
  83. if ( !Parent::onAdd() )
  84. return false;
  85. // Set up a 1x1x1 bounding box
  86. mObjBox.set( Point3F( -0.5f, -0.5f, -0.5f ),
  87. Point3F( 0.5f, 0.5f, 0.5f ) );
  88. resetWorldBox();
  89. // Add this object to the scene
  90. addToScene();
  91. // Refresh this object's material (if any)
  92. updateMaterial();
  93. return true;
  94. }
  95. void RenderMeshExample::onRemove()
  96. {
  97. // Remove this object from the scene
  98. removeFromScene();
  99. Parent::onRemove();
  100. }
  101. void RenderMeshExample::setTransform(const MatrixF & mat)
  102. {
  103. // Let SceneObject handle all of the matrix manipulation
  104. Parent::setTransform( mat );
  105. // Dirty our network mask so that the new transform gets
  106. // transmitted to the client object
  107. setMaskBits( TransformMask );
  108. }
  109. U32 RenderMeshExample::packUpdate( NetConnection *conn, U32 mask, BitStream *stream )
  110. {
  111. // Allow the Parent to get a crack at writing its info
  112. U32 retMask = Parent::packUpdate( conn, mask, stream );
  113. // Write our transform information
  114. if ( stream->writeFlag( mask & TransformMask ) )
  115. {
  116. mathWrite(*stream, getTransform());
  117. mathWrite(*stream, getScale());
  118. }
  119. // Write out any of the updated editable properties
  120. if (stream->writeFlag(mask & UpdateMask))
  121. {
  122. PACK_ASSET(conn, Material);
  123. }
  124. return retMask;
  125. }
  126. void RenderMeshExample::unpackUpdate(NetConnection *conn, BitStream *stream)
  127. {
  128. // Let the Parent read any info it sent
  129. Parent::unpackUpdate(conn, stream);
  130. if ( stream->readFlag() ) // TransformMask
  131. {
  132. mathRead(*stream, &mObjToWorld);
  133. mathRead(*stream, &mObjScale);
  134. setTransform( mObjToWorld );
  135. }
  136. if ( stream->readFlag() ) // UpdateMask
  137. {
  138. UNPACK_ASSET(conn, Material);
  139. if ( isProperlyAdded() )
  140. updateMaterial();
  141. }
  142. }
  143. //-----------------------------------------------------------------------------
  144. // Object Rendering
  145. //-----------------------------------------------------------------------------
  146. void RenderMeshExample::createGeometry()
  147. {
  148. static const Point3F cubePoints[8] =
  149. {
  150. Point3F( 1, -1, -1), Point3F( 1, -1, 1), Point3F( 1, 1, -1), Point3F( 1, 1, 1),
  151. Point3F(-1, -1, -1), Point3F(-1, 1, -1), Point3F(-1, -1, 1), Point3F(-1, 1, 1)
  152. };
  153. static const Point3F cubeNormals[6] =
  154. {
  155. Point3F( 1, 0, 0), Point3F(-1, 0, 0), Point3F( 0, 1, 0),
  156. Point3F( 0, -1, 0), Point3F( 0, 0, 1), Point3F( 0, 0, -1)
  157. };
  158. static const Point2F cubeTexCoords[4] =
  159. {
  160. Point2F( 0, 0), Point2F( 0, -1),
  161. Point2F( 1, 0), Point2F( 1, -1)
  162. };
  163. static const U32 cubeFaces[36][3] =
  164. {
  165. { 3, 0, 3 }, { 0, 0, 0 }, { 1, 0, 1 },
  166. { 2, 0, 2 }, { 0, 0, 0 }, { 3, 0, 3 },
  167. { 7, 1, 1 }, { 4, 1, 2 }, { 5, 1, 0 },
  168. { 6, 1, 3 }, { 4, 1, 2 }, { 7, 1, 1 },
  169. { 3, 2, 1 }, { 5, 2, 2 }, { 2, 2, 0 },
  170. { 7, 2, 3 }, { 5, 2, 2 }, { 3, 2, 1 },
  171. { 1, 3, 3 }, { 4, 3, 0 }, { 6, 3, 1 },
  172. { 0, 3, 2 }, { 4, 3, 0 }, { 1, 3, 3 },
  173. { 3, 4, 3 }, { 6, 4, 0 }, { 7, 4, 1 },
  174. { 1, 4, 2 }, { 6, 4, 0 }, { 3, 4, 3 },
  175. { 2, 5, 1 }, { 4, 5, 2 }, { 0, 5, 0 },
  176. { 5, 5, 3 }, { 4, 5, 2 }, { 2, 5, 1 }
  177. };
  178. // Fill the vertex buffer
  179. VertexType *pVert = NULL;
  180. mVertexBuffer.set( GFX, 36, GFXBufferTypeStatic );
  181. pVert = mVertexBuffer.lock();
  182. Point3F halfSize = getObjBox().getExtents() * 0.5f;
  183. for (U32 i = 0; i < 36; i++)
  184. {
  185. const U32& vdx = cubeFaces[i][0];
  186. const U32& ndx = cubeFaces[i][1];
  187. const U32& tdx = cubeFaces[i][2];
  188. pVert[i].point = cubePoints[vdx] * halfSize;
  189. pVert[i].normal = cubeNormals[ndx];
  190. pVert[i].texCoord = cubeTexCoords[tdx];
  191. }
  192. mVertexBuffer.unlock();
  193. // Fill the primitive buffer
  194. U16 *pIdx = NULL;
  195. mPrimitiveBuffer.set( GFX, 36, 12, GFXBufferTypeStatic );
  196. mPrimitiveBuffer.lock(&pIdx);
  197. for (U16 i = 0; i < 36; i++)
  198. pIdx[i] = i;
  199. mPrimitiveBuffer.unlock();
  200. }
  201. void RenderMeshExample::updateMaterial()
  202. {
  203. if (mMaterialAsset.notNull())
  204. {
  205. if (mMaterialInst && String(mMaterialAsset->getMaterialDefinitionName()).equal(mMaterialInst->getMaterial()->getName(), String::NoCase))
  206. return;
  207. SAFE_DELETE(mMaterialInst);
  208. mMaterialInst = MATMGR->createMatInstance(mMaterialAsset->getMaterialDefinitionName(), getGFXVertexFormat< VertexType >());
  209. if (!mMaterialInst)
  210. Con::errorf("RenderMeshExample::updateMaterial - no Material called '%s'", mMaterialAsset->getMaterialDefinitionName());
  211. }
  212. }
  213. void RenderMeshExample::prepRenderImage( SceneRenderState *state )
  214. {
  215. // Do a little prep work if needed
  216. if ( mVertexBuffer.isNull() )
  217. createGeometry();
  218. // If we have no material then skip out.
  219. if ( !mMaterialInst || !state)
  220. return;
  221. // If we don't have a material instance after the override then
  222. // we can skip rendering all together.
  223. BaseMatInstance *matInst = state->getOverrideMaterial( mMaterialInst );
  224. if ( !matInst )
  225. return;
  226. // Get a handy pointer to our RenderPassmanager
  227. RenderPassManager *renderPass = state->getRenderPass();
  228. // Allocate an MeshRenderInst so that we can submit it to the RenderPassManager
  229. MeshRenderInst *ri = renderPass->allocInst<MeshRenderInst>();
  230. // Set our RenderInst as a standard mesh render
  231. ri->type = RenderPassManager::RIT_Mesh;
  232. //If our material has transparency set on this will redirect it to proper render bin
  233. if ( matInst->getMaterial()->isTranslucent() )
  234. {
  235. ri->type = RenderPassManager::RIT_Translucent;
  236. ri->translucentSort = true;
  237. }
  238. // Calculate our sorting point
  239. if ( state )
  240. {
  241. // Calculate our sort point manually.
  242. const Box3F& rBox = getRenderWorldBox();
  243. ri->sortDistSq = rBox.getSqDistanceToPoint( state->getCameraPosition() );
  244. }
  245. else
  246. ri->sortDistSq = 0.0f;
  247. // Set up our transforms
  248. MatrixF objectToWorld = getRenderTransform();
  249. objectToWorld.scale( getScale() );
  250. ri->objectToWorld = renderPass->allocUniqueXform( objectToWorld );
  251. ri->worldToCamera = renderPass->allocSharedXform(RenderPassManager::View);
  252. ri->projection = renderPass->allocSharedXform(RenderPassManager::Projection);
  253. // If our material needs lights then fill the RIs
  254. // light vector with the best lights.
  255. if ( matInst->isForwardLit() )
  256. {
  257. LightQuery query;
  258. query.init( getWorldSphere() );
  259. query.getLights( ri->lights, 8 );
  260. }
  261. // Make sure we have an up-to-date backbuffer in case
  262. // our Material would like to make use of it
  263. // NOTICE: SFXBB is removed and refraction is disabled!
  264. //ri->backBuffTex = GFX->getSfxBackBuffer();
  265. // Set our Material
  266. ri->matInst = matInst;
  267. // Set up our vertex buffer and primitive buffer
  268. ri->vertBuff = &mVertexBuffer;
  269. ri->primBuff = &mPrimitiveBuffer;
  270. ri->prim = renderPass->allocPrim();
  271. ri->prim->type = GFXTriangleList;
  272. ri->prim->minIndex = 0;
  273. ri->prim->startIndex = 0;
  274. ri->prim->numPrimitives = 12;
  275. ri->prim->startVertex = 0;
  276. ri->prim->numVertices = 36;
  277. // We sort by the material then vertex buffer
  278. ri->defaultKey = matInst->getStateHint();
  279. ri->defaultKey2 = (uintptr_t)ri->vertBuff; // Not 64bit safe!
  280. // Submit our RenderInst to the RenderPassManager
  281. state->getRenderPass()->addInst( ri );
  282. }
  283. DefineEngineMethod( RenderMeshExample, postApply, void, (),,
  284. "A utility method for forcing a network update.\n")
  285. {
  286. object->inspectPostApply();
  287. }