meshComponent.cpp 14 KB

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