meshComponent.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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 "console/consoleTypes.h"
  24. #include "T3D/components/render/meshComponent.h"
  25. #include "core/util/safeDelete.h"
  26. #include "core/resourceManager.h"
  27. #include "core/stream/fileStream.h"
  28. #include "console/consoleTypes.h"
  29. #include "console/consoleObject.h"
  30. #include "core/stream/bitStream.h"
  31. #include "sim/netConnection.h"
  32. #include "gfx/gfxTransformSaver.h"
  33. #include "console/engineAPI.h"
  34. #include "lighting/lightQuery.h"
  35. #include "scene/sceneManager.h"
  36. #include "gfx/bitmap/ddsFile.h"
  37. #include "gfx/bitmap/ddsUtils.h"
  38. #include "gfx/gfxTextureManager.h"
  39. #include "materials/materialFeatureTypes.h"
  40. #include "renderInstance/renderImposterMgr.h"
  41. #include "util/imposterCapture.h"
  42. #include "gfx/sim/debugDraw.h"
  43. #include "gfx/gfxDrawUtil.h"
  44. #include "materials/materialManager.h"
  45. #include "materials/matInstance.h"
  46. #include "core/strings/findMatch.h"
  47. #include "T3D/components/render/meshComponent_ScriptBinding.h"
  48. //////////////////////////////////////////////////////////////////////////
  49. // Constructor/Destructor
  50. //////////////////////////////////////////////////////////////////////////
  51. MeshComponent::MeshComponent() : Component()
  52. {
  53. mShapeName = StringTable->insert("");
  54. mShapeAsset = StringTable->insert("");
  55. mShapeInstance = NULL;
  56. mChangingMaterials.clear();
  57. mMaterials.clear();
  58. mFriendlyName = "Mesh Component";
  59. mComponentType = "Render";
  60. mDescription = getDescriptionText("Causes the object to render a non-animating 3d shape using the file provided.");
  61. mNetworked = true;
  62. mNetFlags.set(Ghostable | ScopeAlways);
  63. }
  64. MeshComponent::~MeshComponent(){}
  65. IMPLEMENT_CO_NETOBJECT_V1(MeshComponent);
  66. //==========================================================================================
  67. void MeshComponent::boneObject::addObject(SimObject* object)
  68. {
  69. SceneObject* sc = dynamic_cast<SceneObject*>(object);
  70. if(sc && mOwner)
  71. {
  72. if(TSShape* shape = mOwner->getShape())
  73. {
  74. S32 nodeID = shape->findNode(mBoneName);
  75. //we may have a offset on the shape's center
  76. //so make sure we accomodate for that when setting up the mount offsets
  77. MatrixF mat = mOwner->getNodeTransform(nodeID);
  78. mOwner->getOwner()->mountObject(sc, nodeID, mat);
  79. }
  80. }
  81. }
  82. bool MeshComponent::onAdd()
  83. {
  84. if(! Parent::onAdd())
  85. return false;
  86. // Register for the resource change signal.
  87. ResourceManager::get().getChangedSignal().notify( this, &MeshComponent::_onResourceChanged );
  88. return true;
  89. }
  90. void MeshComponent::onComponentAdd()
  91. {
  92. Parent::onComponentAdd();
  93. //get the default shape, if any
  94. updateShape();
  95. }
  96. void MeshComponent::onRemove()
  97. {
  98. Parent::onRemove();
  99. mMeshAsset.clear();
  100. SAFE_DELETE(mShapeInstance);
  101. }
  102. void MeshComponent::onComponentRemove()
  103. {
  104. if(mOwner)
  105. {
  106. Point3F pos = mOwner->getPosition(); //store our center pos
  107. mOwner->setObjectBox(Box3F(Point3F(-1,-1,-1), Point3F(1,1,1)));
  108. mOwner->setPosition(pos);
  109. }
  110. Parent::onComponentRemove();
  111. }
  112. void MeshComponent::initPersistFields()
  113. {
  114. Parent::initPersistFields();
  115. //create a hook to our internal variables
  116. addGroup("Model");
  117. addProtectedField("MeshAsset", TypeAssetId, Offset(mShapeAsset, MeshComponent), &_setMesh, &defaultProtectedGetFn,
  118. "The asset Id used for the mesh.", AbstractClassRep::FieldFlags::FIELD_ComponentInspectors);
  119. endGroup("Model");
  120. }
  121. bool MeshComponent::_setMesh(void *object, const char *index, const char *data)
  122. {
  123. MeshComponent *rbI = static_cast<MeshComponent*>(object);
  124. // Sanity!
  125. AssertFatal(data != NULL, "Cannot use a NULL asset Id.");
  126. return rbI->setMeshAsset(data);
  127. }
  128. bool MeshComponent::_setShape( void *object, const char *index, const char *data )
  129. {
  130. MeshComponent *rbI = static_cast<MeshComponent*>(object);
  131. rbI->mShapeName = StringTable->insert(data);
  132. rbI->updateShape(); //make sure we force the update to resize the owner bounds
  133. rbI->setMaskBits(ShapeMask);
  134. return true;
  135. }
  136. bool MeshComponent::setMeshAsset(const char* assetName)
  137. {
  138. // Fetch the asset Id.
  139. mMeshAssetId = StringTable->insert(assetName);
  140. mMeshAsset = mMeshAssetId;
  141. if (mMeshAsset.isNull())
  142. {
  143. Con::errorf("[MeshComponent] Failed to load mesh asset.");
  144. return false;
  145. }
  146. mShapeName = mMeshAssetId;
  147. mShapeAsset = mShapeName;
  148. updateShape(); //make sure we force the update to resize the owner bounds
  149. setMaskBits(ShapeMask);
  150. return true;
  151. }
  152. void MeshComponent::_onResourceChanged( const Torque::Path &path )
  153. {
  154. if ( path != Torque::Path( mShapeName ) )
  155. return;
  156. updateShape();
  157. setMaskBits(ShapeMask);
  158. }
  159. void MeshComponent::inspectPostApply()
  160. {
  161. Parent::inspectPostApply();
  162. }
  163. U32 MeshComponent::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  164. {
  165. U32 retMask = Parent::packUpdate(con, mask, stream);
  166. if (!mOwner || con->getGhostIndex(mOwner) == -1)
  167. {
  168. stream->writeFlag(false);
  169. stream->writeFlag(false);
  170. if (mask & ShapeMask)
  171. retMask |= ShapeMask;
  172. if (mask & MaterialMask)
  173. retMask |= MaterialMask;
  174. return retMask;
  175. }
  176. if (stream->writeFlag(mask & ShapeMask))
  177. {
  178. stream->writeString(mShapeName);
  179. }
  180. if (stream->writeFlag( mask & MaterialMask ))
  181. {
  182. stream->writeInt(mChangingMaterials.size(), 16);
  183. for(U32 i=0; i < mChangingMaterials.size(); i++)
  184. {
  185. stream->writeInt(mChangingMaterials[i].slot, 16);
  186. NetStringHandle matNameStr = mChangingMaterials[i].matName.c_str();
  187. con->packNetStringHandleU(stream, matNameStr);
  188. }
  189. mChangingMaterials.clear();
  190. }
  191. return retMask;
  192. }
  193. void MeshComponent::unpackUpdate(NetConnection *con, BitStream *stream)
  194. {
  195. Parent::unpackUpdate(con, stream);
  196. if(stream->readFlag())
  197. {
  198. mShapeName = stream->readSTString();
  199. setMeshAsset(mShapeName);
  200. updateShape();
  201. }
  202. if(stream->readFlag())
  203. {
  204. mChangingMaterials.clear();
  205. U32 materialCount = stream->readInt(16);
  206. for(U32 i=0; i < materialCount; i++)
  207. {
  208. matMap newMatMap;
  209. newMatMap.slot = stream->readInt(16);
  210. newMatMap.matName = String(con->unpackNetStringHandleU(stream).getString());
  211. mChangingMaterials.push_back(newMatMap);
  212. }
  213. updateMaterials();
  214. }
  215. }
  216. void MeshComponent::prepRenderImage( SceneRenderState *state )
  217. {
  218. if (!mEnabled || !mOwner || !mShapeInstance)
  219. return;
  220. Point3F cameraOffset;
  221. mOwner->getRenderTransform().getColumn(3, &cameraOffset);
  222. cameraOffset -= state->getDiffuseCameraPosition();
  223. F32 dist = cameraOffset.len();
  224. if (dist < 0.01f)
  225. dist = 0.01f;
  226. Point3F objScale = getOwner()->getScale();
  227. F32 invScale = (1.0f / getMax(getMax(objScale.x, objScale.y), objScale.z));
  228. mShapeInstance->setDetailFromDistance(state, dist * invScale);
  229. if (mShapeInstance->getCurrentDetail() < 0)
  230. return;
  231. GFXTransformSaver saver;
  232. // Set up our TS render state.
  233. TSRenderState rdata;
  234. rdata.setSceneState(state);
  235. rdata.setFadeOverride(1.0f);
  236. rdata.setOriginSort(false);
  237. // We might have some forward lit materials
  238. // so pass down a query to gather lights.
  239. LightQuery query;
  240. query.init(mOwner->getWorldSphere());
  241. rdata.setLightQuery(&query);
  242. MatrixF mat = mOwner->getRenderTransform();
  243. Point3F renderPos = mat.getPosition();
  244. EulerF renderRot = mat.toEuler();
  245. mat.scale(objScale);
  246. GFX->setWorldMatrix(mat);
  247. mShapeInstance->render(rdata);
  248. }
  249. void MeshComponent::updateShape()
  250. {
  251. bool isServer = isServerObject();
  252. if ((mShapeName && mShapeName[0] != '\0') || (mShapeAsset && mShapeAsset[0] != '\0'))
  253. {
  254. if (mMeshAsset == NULL)
  255. return;
  256. mShape = mMeshAsset->getShape();
  257. if (!mShape)
  258. return;
  259. setupShape();
  260. //Do this on both the server and client
  261. S32 materialCount = mShape->materialList->getMaterialNameList().size();
  262. if(isServerObject())
  263. {
  264. //we need to update the editor
  265. for (U32 i = 0; i < mFields.size(); i++)
  266. {
  267. //find any with the materialslot title and clear them out
  268. if (FindMatch::isMatch("MaterialSlot*", mFields[i].mFieldName, false))
  269. {
  270. setDataField(mFields[i].mFieldName, NULL, "");
  271. mFields.erase(i);
  272. continue;
  273. }
  274. }
  275. //next, get a listing of our materials in the shape, and build our field list for them
  276. char matFieldName[128];
  277. if(materialCount > 0)
  278. mComponentGroup = StringTable->insert("Materials");
  279. for(U32 i=0; i < materialCount; i++)
  280. {
  281. String materialname = mShape->materialList->getMaterialName(i);
  282. if(materialname == String("ShapeBounds"))
  283. continue;
  284. dSprintf(matFieldName, 128, "MaterialSlot%d", i);
  285. addComponentField(matFieldName, "A material used in the shape file", "TypeAssetId", materialname, "");
  286. }
  287. if(materialCount > 0)
  288. mComponentGroup = "";
  289. }
  290. if(mOwner != NULL)
  291. {
  292. Point3F min, max, pos;
  293. pos = mOwner->getPosition();
  294. mOwner->getWorldToObj().mulP(pos);
  295. min = mShape->bounds.minExtents;
  296. max = mShape->bounds.maxExtents;
  297. mShapeBounds.set(min, max);
  298. mOwner->setObjectBox(Box3F(min, max));
  299. if( mOwner->getSceneManager() != NULL )
  300. mOwner->getSceneManager()->notifyObjectDirty( mOwner );
  301. }
  302. //finally, notify that our shape was changed
  303. onShapeInstanceChanged.trigger(this);
  304. }
  305. }
  306. void MeshComponent::setupShape()
  307. {
  308. mShapeInstance = new TSShapeInstance(mShape, true);
  309. }
  310. void MeshComponent::updateMaterials()
  311. {
  312. if (mChangingMaterials.empty() || !mShape)
  313. return;
  314. TSMaterialList* pMatList = mShapeInstance->getMaterialList();
  315. pMatList->setTextureLookupPath(getShapeResource().getPath().getPath());
  316. const Vector<String> &materialNames = pMatList->getMaterialNameList();
  317. for ( S32 i = 0; i < materialNames.size(); i++ )
  318. {
  319. const String &pName = materialNames[i];
  320. for(U32 m=0; m < mChangingMaterials.size(); m++)
  321. {
  322. if(mChangingMaterials[m].slot == i)
  323. {
  324. pMatList->renameMaterial( i, mChangingMaterials[m].matName );
  325. }
  326. }
  327. mChangingMaterials.clear();
  328. }
  329. // Initialize the material instances
  330. mShapeInstance->initMaterialList();
  331. }
  332. MatrixF MeshComponent::getNodeTransform(S32 nodeIdx)
  333. {
  334. if (mShape)
  335. {
  336. S32 nodeCount = getShape()->nodes.size();
  337. if(nodeIdx >= 0 && nodeIdx < nodeCount)
  338. {
  339. //animate();
  340. MatrixF mountTransform = mShapeInstance->mNodeTransforms[nodeIdx];
  341. mountTransform.mul(mOwner->getRenderTransform());
  342. return mountTransform;
  343. }
  344. }
  345. return MatrixF::Identity;
  346. }
  347. S32 MeshComponent::getNodeByName(String nodeName)
  348. {
  349. if (mShape)
  350. {
  351. S32 nodeIdx = getShape()->findNode(nodeName);
  352. return nodeIdx;
  353. }
  354. return -1;
  355. }
  356. bool MeshComponent::castRayRendered(const Point3F &start, const Point3F &end, RayInfo *info)
  357. {
  358. return false;
  359. }
  360. void MeshComponent::mountObjectToNode(SceneObject* objB, String node, MatrixF txfm)
  361. {
  362. const char* test;
  363. test = node.c_str();
  364. if(dIsdigit(test[0]))
  365. {
  366. getOwner()->mountObject(objB, dAtoi(node), txfm);
  367. }
  368. else
  369. {
  370. if(TSShape* shape = getShape())
  371. {
  372. S32 idx = shape->findNode(node);
  373. getOwner()->mountObject(objB, idx, txfm);
  374. }
  375. }
  376. }
  377. void MeshComponent::onDynamicModified(const char* slotName, const char* newValue)
  378. {
  379. if(FindMatch::isMatch( "materialslot*", slotName, false ))
  380. {
  381. if(!getShape())
  382. return;
  383. S32 slot = -1;
  384. String outStr( String::GetTrailingNumber( slotName, slot ) );
  385. if(slot == -1)
  386. return;
  387. bool found = false;
  388. for(U32 i=0; i < mChangingMaterials.size(); i++)
  389. {
  390. if(mChangingMaterials[i].slot == slot)
  391. {
  392. mChangingMaterials[i].matName = String(newValue);
  393. found = true;
  394. }
  395. }
  396. if(!found)
  397. {
  398. matMap newMatMap;
  399. newMatMap.slot = slot;
  400. newMatMap.matName = String(newValue);
  401. mChangingMaterials.push_back(newMatMap);
  402. }
  403. setMaskBits(MaterialMask);
  404. }
  405. Parent::onDynamicModified(slotName, newValue);
  406. }
  407. void MeshComponent::changeMaterial(U32 slot, const char* newMat)
  408. {
  409. char fieldName[512];
  410. //update our respective field
  411. dSprintf(fieldName, 512, "materialSlot%d", slot);
  412. setDataField(fieldName, NULL, newMat);
  413. }
  414. void MeshComponent::onInspect()
  415. {
  416. }
  417. void MeshComponent::onEndInspect()
  418. {
  419. }