tsStatic.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  26. #include "platform/platform.h"
  27. #include "T3D/tsStatic.h"
  28. #include "core/resourceManager.h"
  29. #include "core/stream/bitStream.h"
  30. #include "scene/sceneRenderState.h"
  31. #include "scene/sceneManager.h"
  32. #include "scene/sceneObjectLightingPlugin.h"
  33. #include "lighting/lightManager.h"
  34. #include "math/mathIO.h"
  35. #include "ts/tsShapeInstance.h"
  36. #include "ts/tsMaterialList.h"
  37. #include "console/consoleTypes.h"
  38. #include "T3D/shapeBase.h"
  39. #include "sim/netConnection.h"
  40. #include "gfx/gfxDevice.h"
  41. #include "gfx/gfxTransformSaver.h"
  42. #include "ts/tsRenderState.h"
  43. #include "collision/boxConvex.h"
  44. #include "T3D/physics/physicsPlugin.h"
  45. #include "T3D/physics/physicsBody.h"
  46. #include "T3D/physics/physicsCollision.h"
  47. #include "materials/materialDefinition.h"
  48. #include "materials/materialManager.h"
  49. #include "materials/matInstance.h"
  50. #include "materials/materialFeatureData.h"
  51. #include "materials/materialFeatureTypes.h"
  52. #include "console/engineAPI.h"
  53. #include "T3D/accumulationVolume.h"
  54. using namespace Torque;
  55. extern bool gEditingMission;
  56. #ifdef TORQUE_AFX_ENABLED
  57. #include "afx/ce/afxZodiacMgr.h"
  58. #endif
  59. IMPLEMENT_CO_NETOBJECT_V1(TSStatic);
  60. ConsoleDocClass( TSStatic,
  61. "@brief A static object derived from a 3D model file and placed within the game world.\n\n"
  62. "TSStatic is the most basic 3D shape in Torque. Unlike StaticShape it doesn't make use of "
  63. "a datablock. It derrives directly from SceneObject. This makes TSStatic extremely light "
  64. "weight, which is why the Tools use this class when you want to drop in a DTS or DAE object.\n\n"
  65. "While a TSStatic doesn't provide any motion -- it stays were you initally put it -- it does allow for "
  66. "a single ambient animation sequence to play when the object is first added to the scene.\n\n"
  67. "@tsexample\n"
  68. "new TSStatic(Team1Base) {\n"
  69. " shapeName = \"art/shapes/desertStructures/station01.dts\";\n"
  70. " playAmbient = \"1\";\n"
  71. " receiveSunLight = \"1\";\n"
  72. " receiveLMLighting = \"1\";\n"
  73. " useCustomAmbientLighting = \"0\";\n"
  74. " customAmbientLighting = \"0 0 0 1\";\n"
  75. " collisionType = \"Visible Mesh\";\n"
  76. " decalType = \"Collision Mesh\";\n"
  77. " allowPlayerStep = \"1\";\n"
  78. " renderNormals = \"0\";\n"
  79. " forceDetail = \"-1\";\n"
  80. " position = \"315.18 -180.418 244.313\";\n"
  81. " rotation = \"0 0 1 195.952\";\n"
  82. " scale = \"1 1 1\";\n"
  83. " isRenderEnabled = \"true\";\n"
  84. " canSaveDynamicFields = \"1\";\n"
  85. "};\n"
  86. "@endtsexample\n"
  87. "@ingroup gameObjects\n"
  88. );
  89. TSStatic::TSStatic()
  90. :
  91. cubeDescId( 0 ),
  92. reflectorDesc( NULL )
  93. {
  94. mNetFlags.set(Ghostable | ScopeAlways);
  95. mTypeMask |= StaticObjectType | StaticShapeObjectType;
  96. mShapeName = "";
  97. mShapeInstance = NULL;
  98. mPlayAmbient = true;
  99. mAmbientThread = NULL;
  100. mAllowPlayerStep = false;
  101. mConvexList = new Convex;
  102. mRenderNormalScalar = 0;
  103. mForceDetail = -1;
  104. mMeshCulling = false;
  105. mUseOriginSort = false;
  106. mUseAlphaFade = false;
  107. mAlphaFadeStart = 100.0f;
  108. mAlphaFadeEnd = 150.0f;
  109. mInvertAlphaFade = false;
  110. mAlphaFade = 1.0f;
  111. mPhysicsRep = NULL;
  112. mCollisionType = CollisionMesh;
  113. mDecalType = CollisionMesh;
  114. mIgnoreZodiacs = false;
  115. mHasGradients = false;
  116. mInvertGradientRange = false;
  117. mGradientRangeUser.set(0.0f, 180.0f);
  118. #ifdef TORQUE_AFX_ENABLED
  119. afxZodiacData::convertGradientRangeFromDegrees(mGradientRange, mGradientRangeUser);
  120. #endif
  121. }
  122. TSStatic::~TSStatic()
  123. {
  124. delete mConvexList;
  125. mConvexList = NULL;
  126. }
  127. ImplementEnumType( TSMeshType,
  128. "Type of mesh data available in a shape.\n"
  129. "@ingroup gameObjects" )
  130. { TSStatic::None, "None", "No mesh data." },
  131. { TSStatic::Bounds, "Bounds", "Bounding box of the shape." },
  132. { TSStatic::CollisionMesh, "Collision Mesh", "Specifically desingated \"collision\" meshes." },
  133. { TSStatic::VisibleMesh, "Visible Mesh", "Rendered mesh polygons." },
  134. EndImplementEnumType;
  135. void TSStatic::initPersistFields()
  136. {
  137. addGroup("Media");
  138. addField("shapeName", TypeShapeFilename, Offset( mShapeName, TSStatic ),
  139. "%Path and filename of the model file (.DTS, .DAE) to use for this TSStatic." );
  140. addProtectedField( "skin", TypeRealString, Offset( mAppliedSkinName, TSStatic ), &_setFieldSkin, &_getFieldSkin,
  141. "@brief The skin applied to the shape.\n\n"
  142. "'Skinning' the shape effectively renames the material targets, allowing "
  143. "different materials to be used on different instances of the same model.\n\n"
  144. "Any material targets that start with the old skin name have that part "
  145. "of the name replaced with the new skin name. The initial old skin name is "
  146. "\"base\". For example, if a new skin of \"blue\" was applied to a model "
  147. "that had material targets <i>base_body</i> and <i>face</i>, the new targets "
  148. "would be <i>blue_body</i> and <i>face</i>. Note that <i>face</i> was not "
  149. "renamed since it did not start with the old skin name of \"base\".\n\n"
  150. "To support models that do not use the default \"base\" naming convention, "
  151. "you can also specify the part of the name to replace in the skin field "
  152. "itself. For example, if a model had a material target called <i>shapemat</i>, "
  153. "we could apply a new skin \"shape=blue\", and the material target would be "
  154. "renamed to <i>bluemat</i> (note \"shape\" has been replaced with \"blue\").\n\n"
  155. "Multiple skin updates can also be applied at the same time by separating "
  156. "them with a semicolon. For example: \"base=blue;face=happy_face\".\n\n"
  157. "Material targets are only renamed if an existing Material maps to that "
  158. "name, or if there is a diffuse texture in the model folder with the same "
  159. "name as the new target.\n\n" );
  160. endGroup("Media");
  161. addGroup("Rendering");
  162. addField( "playAmbient", TypeBool, Offset( mPlayAmbient, TSStatic ),
  163. "Enables automatic playing of the animation sequence named \"ambient\" (if it exists) when the TSStatic is loaded.");
  164. addField( "meshCulling", TypeBool, Offset( mMeshCulling, TSStatic ),
  165. "Enables detailed culling of meshes within the TSStatic. Should only be used "
  166. "with large complex shapes like buildings which contain many submeshes." );
  167. addField( "originSort", TypeBool, Offset( mUseOriginSort, TSStatic ),
  168. "Enables translucent sorting of the TSStatic by its origin instead of the bounds." );
  169. endGroup("Rendering");
  170. addGroup( "Reflection" );
  171. addField( "cubeReflectorDesc", TypeRealString, Offset( cubeDescName, TSStatic ),
  172. "References a ReflectorDesc datablock that defines performance and quality properties for dynamic reflections.\n");
  173. endGroup( "Reflection" );
  174. addGroup("Collision");
  175. addField( "collisionType", TypeTSMeshType, Offset( mCollisionType, TSStatic ),
  176. "The type of mesh data to use for collision queries." );
  177. addField( "decalType", TypeTSMeshType, Offset( mDecalType, TSStatic ),
  178. "The type of mesh data used to clip decal polygons against." );
  179. addField( "allowPlayerStep", TypeBool, Offset( mAllowPlayerStep, TSStatic ),
  180. "@brief Allow a Player to walk up sloping polygons in the TSStatic (based on the collisionType).\n\n"
  181. "When set to false, the slightest bump will stop the player from walking on top of the object.\n");
  182. endGroup("Collision");
  183. addGroup( "AlphaFade" );
  184. addField( "alphaFadeEnable", TypeBool, Offset(mUseAlphaFade, TSStatic), "Turn on/off Alpha Fade" );
  185. addField( "alphaFadeStart", TypeF32, Offset(mAlphaFadeStart, TSStatic), "Distance of start Alpha Fade" );
  186. addField( "alphaFadeEnd", TypeF32, Offset(mAlphaFadeEnd, TSStatic), "Distance of end Alpha Fade" );
  187. addField( "alphaFadeInverse", TypeBool, Offset(mInvertAlphaFade, TSStatic), "Invert Alpha Fade's Start & End Distance" );
  188. endGroup( "AlphaFade" );
  189. addGroup("Debug");
  190. addField( "renderNormals", TypeF32, Offset( mRenderNormalScalar, TSStatic ),
  191. "Debug rendering mode shows the normals for each point in the TSStatic's mesh." );
  192. addField( "forceDetail", TypeS32, Offset( mForceDetail, TSStatic ),
  193. "Forces rendering to a particular detail level." );
  194. endGroup("Debug");
  195. addGroup("AFX");
  196. addField("ignoreZodiacs", TypeBool, Offset(mIgnoreZodiacs, TSStatic));
  197. addField("useGradientRange", TypeBool, Offset(mHasGradients, TSStatic));
  198. addField("gradientRange", TypePoint2F, Offset(mGradientRangeUser, TSStatic));
  199. addField("invertGradientRange", TypeBool, Offset(mInvertGradientRange, TSStatic));
  200. endGroup("AFX");
  201. Parent::initPersistFields();
  202. }
  203. bool TSStatic::_setFieldSkin( void *object, const char *index, const char *data )
  204. {
  205. TSStatic *ts = static_cast<TSStatic*>( object );
  206. if ( ts )
  207. ts->setSkinName( data );
  208. return false;
  209. }
  210. const char *TSStatic::_getFieldSkin( void *object, const char *data )
  211. {
  212. TSStatic *ts = static_cast<TSStatic*>( object );
  213. return ts ? ts->mSkinNameHandle.getString() : "";
  214. }
  215. void TSStatic::inspectPostApply()
  216. {
  217. // Apply any transformations set in the editor
  218. Parent::inspectPostApply();
  219. if(isServerObject())
  220. {
  221. setMaskBits(AdvancedStaticOptionsMask);
  222. prepCollision();
  223. }
  224. _updateShouldTick();
  225. }
  226. bool TSStatic::onAdd()
  227. {
  228. PROFILE_SCOPE(TSStatic_onAdd);
  229. if ( isServerObject() )
  230. {
  231. // Handle the old "usePolysoup" field
  232. SimFieldDictionary* fieldDict = getFieldDictionary();
  233. if ( fieldDict )
  234. {
  235. StringTableEntry slotName = StringTable->insert( "usePolysoup" );
  236. SimFieldDictionary::Entry * entry = fieldDict->findDynamicField( slotName );
  237. if ( entry )
  238. {
  239. // Was "usePolysoup" set?
  240. bool usePolysoup = dAtob( entry->value );
  241. // "usePolysoup" maps to the new VisibleMesh type
  242. if ( usePolysoup )
  243. mCollisionType = VisibleMesh;
  244. // Remove the field in favor on the new "collisionType" field
  245. fieldDict->setFieldValue( slotName, "" );
  246. }
  247. }
  248. }
  249. if ( !Parent::onAdd() )
  250. return false;
  251. // Setup the shape.
  252. if ( !_createShape() )
  253. {
  254. Con::errorf( "TSStatic::onAdd() - Shape creation failed!" );
  255. return false;
  256. }
  257. setRenderTransform(mObjToWorld);
  258. // Register for the resource change signal.
  259. ResourceManager::get().getChangedSignal().notify( this, &TSStatic::_onResourceChanged );
  260. addToScene();
  261. if ( isClientObject() )
  262. {
  263. mCubeReflector.unregisterReflector();
  264. if ( reflectorDesc )
  265. mCubeReflector.registerReflector( this, reflectorDesc );
  266. }
  267. _updateShouldTick();
  268. // Accumulation and environment mapping
  269. if (isClientObject() && mShapeInstance)
  270. {
  271. AccumulationVolume::addObject(this);
  272. }
  273. return true;
  274. }
  275. bool TSStatic::_createShape()
  276. {
  277. // Cleanup before we create.
  278. mCollisionDetails.clear();
  279. mDecalDetails.clear();
  280. mDecalDetailsPtr = 0;
  281. mLOSDetails.clear();
  282. SAFE_DELETE( mPhysicsRep );
  283. SAFE_DELETE( mShapeInstance );
  284. mAmbientThread = NULL;
  285. mShape = NULL;
  286. if (!mShapeName || mShapeName[0] == '\0')
  287. {
  288. Con::errorf( "TSStatic::_createShape() - No shape name!" );
  289. return false;
  290. }
  291. mShapeHash = _StringTable::hashString(mShapeName);
  292. mShape = ResourceManager::get().load(mShapeName);
  293. if ( bool(mShape) == false )
  294. {
  295. Con::errorf( "TSStatic::_createShape() - Unable to load shape: %s", mShapeName );
  296. return false;
  297. }
  298. if ( isClientObject() &&
  299. !mShape->preloadMaterialList(mShape.getPath()) &&
  300. NetConnection::filesWereDownloaded() )
  301. return false;
  302. mObjBox = mShape->mBounds;
  303. resetWorldBox();
  304. mShapeInstance = new TSShapeInstance( mShape, isClientObject() );
  305. if (isClientObject())
  306. {
  307. mShapeInstance->cloneMaterialList();
  308. }
  309. if (isClientObject())
  310. mShapeInstance->cloneMaterialList();
  311. if( isGhost() )
  312. {
  313. // Reapply the current skin
  314. mAppliedSkinName = "";
  315. reSkin();
  316. }
  317. prepCollision();
  318. // Find the "ambient" animation if it exists
  319. S32 ambientSeq = mShape->findSequence("ambient");
  320. if ( ambientSeq > -1 && !mAmbientThread )
  321. mAmbientThread = mShapeInstance->addThread();
  322. if ( mAmbientThread )
  323. mShapeInstance->setSequence( mAmbientThread, ambientSeq, 0);
  324. // Resolve CubeReflectorDesc.
  325. if ( cubeDescName.isNotEmpty() )
  326. {
  327. Sim::findObject( cubeDescName, reflectorDesc );
  328. }
  329. else if( cubeDescId > 0 )
  330. {
  331. Sim::findObject( cubeDescId, reflectorDesc );
  332. }
  333. return true;
  334. }
  335. void TSStatic::prepCollision()
  336. {
  337. // Let the client know that the collision was updated
  338. setMaskBits( UpdateCollisionMask );
  339. // Allow the ShapeInstance to prep its collision if it hasn't already
  340. if ( mShapeInstance )
  341. mShapeInstance->prepCollision();
  342. // Cleanup any old collision data
  343. mCollisionDetails.clear();
  344. mDecalDetails.clear();
  345. mDecalDetailsPtr = 0;
  346. mLOSDetails.clear();
  347. mConvexList->nukeList();
  348. if ( mCollisionType == CollisionMesh || mCollisionType == VisibleMesh )
  349. {
  350. mShape->findColDetails( mCollisionType == VisibleMesh, &mCollisionDetails, &mLOSDetails );
  351. if ( mDecalType == mCollisionType )
  352. {
  353. mDecalDetailsPtr = &mCollisionDetails;
  354. }
  355. else if ( mDecalType == CollisionMesh || mDecalType == VisibleMesh )
  356. {
  357. mShape->findColDetails( mDecalType == VisibleMesh, &mDecalDetails, 0 );
  358. mDecalDetailsPtr = &mDecalDetails;
  359. }
  360. }
  361. else if ( mDecalType == CollisionMesh || mDecalType == VisibleMesh )
  362. {
  363. mShape->findColDetails( mDecalType == VisibleMesh, &mDecalDetails, 0 );
  364. mDecalDetailsPtr = &mDecalDetails;
  365. }
  366. _updatePhysics();
  367. }
  368. void TSStatic::_updatePhysics()
  369. {
  370. SAFE_DELETE( mPhysicsRep );
  371. if ( !PHYSICSMGR || mCollisionType == None )
  372. return;
  373. PhysicsCollision *colShape = NULL;
  374. if ( mCollisionType == Bounds )
  375. {
  376. MatrixF offset( true );
  377. offset.setPosition( mShape->center );
  378. colShape = PHYSICSMGR->createCollision();
  379. colShape->addBox( getObjBox().getExtents() * 0.5f * mObjScale, offset );
  380. }
  381. else
  382. colShape = mShape->buildColShape( mCollisionType == VisibleMesh, getScale() );
  383. if ( colShape )
  384. {
  385. PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  386. mPhysicsRep = PHYSICSMGR->createBody();
  387. mPhysicsRep->init( colShape, 0, 0, this, world );
  388. mPhysicsRep->setTransform( getTransform() );
  389. }
  390. }
  391. void TSStatic::onRemove()
  392. {
  393. SAFE_DELETE( mPhysicsRep );
  394. // Accumulation
  395. if ( isClientObject() && mShapeInstance )
  396. {
  397. if ( mShapeInstance->hasAccumulation() )
  398. AccumulationVolume::removeObject(this);
  399. }
  400. mConvexList->nukeList();
  401. removeFromScene();
  402. // Remove the resource change signal.
  403. ResourceManager::get().getChangedSignal().remove( this, &TSStatic::_onResourceChanged );
  404. delete mShapeInstance;
  405. mShapeInstance = NULL;
  406. mAmbientThread = NULL;
  407. if ( isClientObject() )
  408. mCubeReflector.unregisterReflector();
  409. Parent::onRemove();
  410. }
  411. void TSStatic::_onResourceChanged( const Torque::Path &path )
  412. {
  413. if ( path != Path( mShapeName ) )
  414. return;
  415. _createShape();
  416. _updateShouldTick();
  417. }
  418. void TSStatic::setSkinName( const char *name )
  419. {
  420. if ( !isGhost() )
  421. {
  422. if ( name[0] != '\0' )
  423. {
  424. // Use tags for better network performance
  425. // Should be a tag, but we'll convert to one if it isn't.
  426. if ( name[0] == StringTagPrefixByte )
  427. mSkinNameHandle = NetStringHandle( U32(dAtoi(name + 1)) );
  428. else
  429. mSkinNameHandle = NetStringHandle( name );
  430. }
  431. else
  432. mSkinNameHandle = NetStringHandle();
  433. setMaskBits( SkinMask );
  434. }
  435. }
  436. void TSStatic::reSkin()
  437. {
  438. if ( isGhost() && mShapeInstance && mSkinNameHandle.isValidString() )
  439. {
  440. mShapeInstance->resetMaterialList();
  441. Vector<String> skins;
  442. String(mSkinNameHandle.getString()).split( ";", skins );
  443. for (S32 i = 0; i < skins.size(); i++)
  444. {
  445. String oldSkin( mAppliedSkinName.c_str() );
  446. String newSkin( skins[i] );
  447. // Check if the skin handle contains an explicit "old" base string. This
  448. // allows all models to support skinning, even if they don't follow the
  449. // "base_xxx" material naming convention.
  450. S32 split = newSkin.find( '=' ); // "old=new" format skin?
  451. if ( split != String::NPos )
  452. {
  453. oldSkin = newSkin.substr( 0, split );
  454. newSkin = newSkin.erase( 0, split+1 );
  455. }
  456. mShapeInstance->reSkin( newSkin, oldSkin );
  457. mAppliedSkinName = newSkin;
  458. }
  459. }
  460. }
  461. void TSStatic::processTick( const Move *move )
  462. {
  463. if ( isServerObject() && mPlayAmbient && mAmbientThread )
  464. mShapeInstance->advanceTime( TickSec, mAmbientThread );
  465. if ( isMounted() )
  466. {
  467. MatrixF mat( true );
  468. mMount.object->getMountTransform(mMount.node, mMount.xfm, &mat );
  469. setTransform( mat );
  470. }
  471. }
  472. void TSStatic::interpolateTick( F32 delta )
  473. {
  474. }
  475. void TSStatic::advanceTime( F32 dt )
  476. {
  477. if ( mPlayAmbient && mAmbientThread )
  478. mShapeInstance->advanceTime( dt, mAmbientThread );
  479. if ( isMounted() )
  480. {
  481. MatrixF mat( true );
  482. mMount.object->getRenderMountTransform( dt, mMount.node, mMount.xfm, &mat );
  483. setRenderTransform( mat );
  484. }
  485. }
  486. void TSStatic::_updateShouldTick()
  487. {
  488. bool shouldTick = (mPlayAmbient && mAmbientThread) || isMounted();
  489. if ( isTicking() != shouldTick )
  490. setProcessTick( shouldTick );
  491. }
  492. void TSStatic::prepRenderImage( SceneRenderState* state )
  493. {
  494. if( !mShapeInstance )
  495. return;
  496. Point3F cameraOffset;
  497. getRenderTransform().getColumn(3,&cameraOffset);
  498. cameraOffset -= state->getDiffuseCameraPosition();
  499. F32 dist = cameraOffset.len();
  500. if (dist < 0.01f)
  501. dist = 0.01f;
  502. if (mUseAlphaFade)
  503. {
  504. mAlphaFade = 1.0f;
  505. if ((mAlphaFadeStart < mAlphaFadeEnd) && mAlphaFadeStart > 0.1f)
  506. {
  507. if (mInvertAlphaFade)
  508. {
  509. if (dist <= mAlphaFadeStart)
  510. {
  511. return;
  512. }
  513. if (dist < mAlphaFadeEnd)
  514. {
  515. mAlphaFade = ((dist - mAlphaFadeStart) / (mAlphaFadeEnd - mAlphaFadeStart));
  516. }
  517. }
  518. else
  519. {
  520. if (dist >= mAlphaFadeEnd)
  521. {
  522. return;
  523. }
  524. if (dist > mAlphaFadeStart)
  525. {
  526. mAlphaFade -= ((dist - mAlphaFadeStart) / (mAlphaFadeEnd - mAlphaFadeStart));
  527. }
  528. }
  529. }
  530. }
  531. F32 invScale = (1.0f/getMax(getMax(mObjScale.x,mObjScale.y),mObjScale.z));
  532. // If we're currently rendering our own reflection we
  533. // don't want to render ourselves into it.
  534. if ( mCubeReflector.isRendering() )
  535. return;
  536. if ( mForceDetail == -1 )
  537. mShapeInstance->setDetailFromDistance( state, dist * invScale );
  538. else
  539. mShapeInstance->setCurrentDetail( mForceDetail );
  540. if ( mShapeInstance->getCurrentDetail() < 0 )
  541. return;
  542. GFXTransformSaver saver;
  543. // Set up our TS render state.
  544. TSRenderState rdata;
  545. rdata.setSceneState( state );
  546. rdata.setFadeOverride( 1.0f );
  547. rdata.setOriginSort( mUseOriginSort );
  548. if ( mCubeReflector.isEnabled() )
  549. rdata.setCubemap( mCubeReflector.getCubemap() );
  550. // Acculumation
  551. rdata.setAccuTex(mAccuTex);
  552. // If we have submesh culling enabled then prepare
  553. // the object space frustum to pass to the shape.
  554. Frustum culler;
  555. if ( mMeshCulling )
  556. {
  557. culler = state->getCullingFrustum();
  558. MatrixF xfm( true );
  559. xfm.scale( Point3F::One / getScale() );
  560. xfm.mul( getRenderWorldTransform() );
  561. xfm.mul( culler.getTransform() );
  562. culler.setTransform( xfm );
  563. rdata.setCuller( &culler );
  564. }
  565. // We might have some forward lit materials
  566. // so pass down a query to gather lights.
  567. LightQuery query;
  568. query.init( getWorldSphere() );
  569. rdata.setLightQuery( &query );
  570. MatrixF mat = getRenderTransform();
  571. mat.scale( mObjScale );
  572. GFX->setWorldMatrix( mat );
  573. if ( state->isDiffusePass() && mCubeReflector.isEnabled() && mCubeReflector.getOcclusionQuery() )
  574. {
  575. RenderPassManager *pass = state->getRenderPass();
  576. OccluderRenderInst *ri = pass->allocInst<OccluderRenderInst>();
  577. ri->type = RenderPassManager::RIT_Occluder;
  578. ri->query = mCubeReflector.getOcclusionQuery();
  579. mObjToWorld.mulP( mObjBox.getCenter(), &ri->position );
  580. ri->scale.set( mObjBox.getExtents() );
  581. ri->orientation = pass->allocUniqueXform( mObjToWorld );
  582. ri->isSphere = false;
  583. state->getRenderPass()->addInst( ri );
  584. }
  585. mShapeInstance->animate();
  586. if(mShapeInstance)
  587. {
  588. if (mUseAlphaFade)
  589. {
  590. mShapeInstance->setAlphaAlways(mAlphaFade);
  591. S32 s = mShapeInstance->mMeshObjects.size();
  592. for(S32 x = 0; x < s; x++)
  593. {
  594. mShapeInstance->mMeshObjects[x].visible = mAlphaFade;
  595. }
  596. }
  597. }
  598. mShapeInstance->render( rdata );
  599. #ifdef TORQUE_AFX_ENABLED
  600. if (!mIgnoreZodiacs && mDecalDetailsPtr != 0)
  601. afxZodiacMgr::renderPolysoupZodiacs(state, this);
  602. #endif
  603. if ( mRenderNormalScalar > 0 )
  604. {
  605. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  606. ri->renderDelegate.bind( this, &TSStatic::_renderNormals );
  607. ri->type = RenderPassManager::RIT_Editor;
  608. state->getRenderPass()->addInst( ri );
  609. }
  610. }
  611. void TSStatic::_renderNormals( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  612. {
  613. PROFILE_SCOPE( TSStatic_RenderNormals );
  614. GFXTransformSaver saver;
  615. MatrixF mat = getRenderTransform();
  616. mat.scale( mObjScale );
  617. GFX->multWorld( mat );
  618. S32 dl = mShapeInstance->getCurrentDetail();
  619. mShapeInstance->renderDebugNormals( mRenderNormalScalar, dl );
  620. }
  621. void TSStatic::onScaleChanged()
  622. {
  623. Parent::onScaleChanged();
  624. if ( mPhysicsRep )
  625. {
  626. // If the editor is enabled delay the scale operation
  627. // by a few milliseconds so that we're not rebuilding
  628. // during an active scale drag operation.
  629. if ( gEditingMission )
  630. mPhysicsRep->queueCallback( 500, Delegate<void()>( this, &TSStatic::_updatePhysics ) );
  631. else
  632. _updatePhysics();
  633. }
  634. setMaskBits( ScaleMask );
  635. }
  636. void TSStatic::setTransform(const MatrixF & mat)
  637. {
  638. Parent::setTransform(mat);
  639. if ( !isMounted() )
  640. setMaskBits( TransformMask );
  641. if ( mPhysicsRep )
  642. mPhysicsRep->setTransform( mat );
  643. // Accumulation
  644. if ( isClientObject() && mShapeInstance )
  645. {
  646. if ( mShapeInstance->hasAccumulation() )
  647. AccumulationVolume::updateObject(this);
  648. }
  649. // Since this is a static it's render transform changes 1
  650. // to 1 with it's collision transform... no interpolation.
  651. setRenderTransform(mat);
  652. }
  653. U32 TSStatic::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  654. {
  655. U32 retMask = Parent::packUpdate(con, mask, stream);
  656. if ( stream->writeFlag( mask & TransformMask ) )
  657. mathWrite( *stream, getTransform() );
  658. if ( stream->writeFlag( mask & ScaleMask ) )
  659. {
  660. // Only write one bit if the scale is one.
  661. if ( stream->writeFlag( mObjScale != Point3F::One ) )
  662. mathWrite( *stream, mObjScale );
  663. }
  664. if ( stream->writeFlag( mask & UpdateCollisionMask ) )
  665. stream->write( (U32)mCollisionType );
  666. if ( stream->writeFlag( mask & SkinMask ) )
  667. con->packNetStringHandleU( stream, mSkinNameHandle );
  668. if (stream->writeFlag(mask & AdvancedStaticOptionsMask))
  669. {
  670. stream->writeString(mShapeName);
  671. stream->write((U32)mDecalType);
  672. stream->writeFlag(mAllowPlayerStep);
  673. stream->writeFlag(mMeshCulling);
  674. stream->writeFlag(mUseOriginSort);
  675. stream->write(mRenderNormalScalar);
  676. stream->write(mForceDetail);
  677. stream->writeFlag(mPlayAmbient);
  678. }
  679. if ( stream->writeFlag(mUseAlphaFade) )
  680. {
  681. stream->write(mAlphaFadeStart);
  682. stream->write(mAlphaFadeEnd);
  683. stream->write(mInvertAlphaFade);
  684. }
  685. stream->writeFlag(mIgnoreZodiacs);
  686. if (stream->writeFlag(mHasGradients))
  687. {
  688. stream->writeFlag(mInvertGradientRange);
  689. stream->write(mGradientRange.x);
  690. stream->write(mGradientRange.y);
  691. }
  692. if ( mLightPlugin )
  693. retMask |= mLightPlugin->packUpdate(this, AdvancedStaticOptionsMask, con, mask, stream);
  694. if( stream->writeFlag( reflectorDesc != NULL ) )
  695. {
  696. stream->writeRangedU32( reflectorDesc->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  697. }
  698. return retMask;
  699. }
  700. void TSStatic::unpackUpdate(NetConnection *con, BitStream *stream)
  701. {
  702. Parent::unpackUpdate(con, stream);
  703. if ( stream->readFlag() ) // TransformMask
  704. {
  705. MatrixF mat;
  706. mathRead( *stream, &mat );
  707. setTransform(mat);
  708. setRenderTransform(mat);
  709. }
  710. if ( stream->readFlag() ) // ScaleMask
  711. {
  712. if ( stream->readFlag() )
  713. {
  714. VectorF scale;
  715. mathRead( *stream, &scale );
  716. setScale( scale );
  717. }
  718. else
  719. setScale( Point3F::One );
  720. }
  721. if ( stream->readFlag() ) // UpdateCollisionMask
  722. {
  723. U32 collisionType = CollisionMesh;
  724. stream->read( &collisionType );
  725. // Handle it if we have changed CollisionType's
  726. if ( (MeshType)collisionType != mCollisionType )
  727. {
  728. mCollisionType = (MeshType)collisionType;
  729. if ( isProperlyAdded() && mShapeInstance )
  730. prepCollision();
  731. }
  732. }
  733. if (stream->readFlag()) // SkinMask
  734. {
  735. NetStringHandle skinDesiredNameHandle = con->unpackNetStringHandleU(stream);;
  736. if (mSkinNameHandle != skinDesiredNameHandle)
  737. {
  738. mSkinNameHandle = skinDesiredNameHandle;
  739. reSkin();
  740. }
  741. }
  742. if (stream->readFlag()) // AdvancedStaticOptionsMask
  743. {
  744. mShapeName = stream->readSTString();
  745. stream->read((U32*)&mDecalType);
  746. mAllowPlayerStep = stream->readFlag();
  747. mMeshCulling = stream->readFlag();
  748. mUseOriginSort = stream->readFlag();
  749. stream->read(&mRenderNormalScalar);
  750. stream->read(&mForceDetail);
  751. mPlayAmbient = stream->readFlag();
  752. }
  753. mUseAlphaFade = stream->readFlag();
  754. if (mUseAlphaFade)
  755. {
  756. stream->read(&mAlphaFadeStart);
  757. stream->read(&mAlphaFadeEnd);
  758. stream->read(&mInvertAlphaFade);
  759. }
  760. mIgnoreZodiacs = stream->readFlag();
  761. mHasGradients = stream->readFlag();
  762. if (mHasGradients)
  763. {
  764. mInvertGradientRange = stream->readFlag();
  765. stream->read(&mGradientRange.x);
  766. stream->read(&mGradientRange.y);
  767. }
  768. if ( mLightPlugin )
  769. {
  770. mLightPlugin->unpackUpdate(this, con, stream);
  771. }
  772. if( stream->readFlag() )
  773. {
  774. cubeDescId = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  775. }
  776. if ( isProperlyAdded() )
  777. _updateShouldTick();
  778. set_special_typing();
  779. }
  780. //----------------------------------------------------------------------------
  781. bool TSStatic::castRay(const Point3F &start, const Point3F &end, RayInfo* info)
  782. {
  783. if ( mCollisionType == None )
  784. return false;
  785. if ( !mShapeInstance )
  786. return false;
  787. if ( mCollisionType == Bounds )
  788. {
  789. F32 fst;
  790. if (!mObjBox.collideLine(start, end, &fst, &info->normal))
  791. return false;
  792. info->t = fst;
  793. info->object = this;
  794. info->point.interpolate( start, end, fst );
  795. info->material = NULL;
  796. return true;
  797. }
  798. else
  799. {
  800. RayInfo shortest = *info;
  801. RayInfo localInfo;
  802. shortest.t = 1e8f;
  803. localInfo.generateTexCoord = info->generateTexCoord;
  804. for ( U32 i = 0; i < mLOSDetails.size(); i++ )
  805. {
  806. mShapeInstance->animate( mLOSDetails[i] );
  807. if ( mShapeInstance->castRayOpcode( mLOSDetails[i], start, end, &localInfo ) )
  808. {
  809. localInfo.object = this;
  810. if (localInfo.t < shortest.t)
  811. shortest = localInfo;
  812. }
  813. }
  814. if (shortest.object == this)
  815. {
  816. // Copy out the shortest time...
  817. *info = shortest;
  818. return true;
  819. }
  820. }
  821. return false;
  822. }
  823. bool TSStatic::castRayRendered(const Point3F &start, const Point3F &end, RayInfo *info)
  824. {
  825. if ( !mShapeInstance )
  826. return false;
  827. // Cast the ray against the currently visible detail
  828. RayInfo localInfo;
  829. if (info && info->generateTexCoord)
  830. localInfo.generateTexCoord = true;
  831. bool res = mShapeInstance->castRayOpcode( mShapeInstance->getCurrentDetail(), start, end, &localInfo );
  832. if ( res )
  833. {
  834. *info = localInfo;
  835. info->object = this;
  836. return true;
  837. }
  838. return false;
  839. }
  840. bool TSStatic::buildPolyList(PolyListContext context, AbstractPolyList* polyList, const Box3F &box, const SphereF &)
  841. {
  842. if ( !mShapeInstance )
  843. return false;
  844. // This is safe to set even if we're not outputing
  845. polyList->setTransform( &mObjToWorld, mObjScale );
  846. polyList->setObject( this );
  847. if ( context == PLC_Export )
  848. {
  849. // Use highest detail level
  850. S32 dl = 0;
  851. // Try to call on the client so we can export materials
  852. if ( isServerObject() && getClientObject() )
  853. dynamic_cast<TSStatic*>(getClientObject())->mShapeInstance->buildPolyList( polyList, dl );
  854. else
  855. mShapeInstance->buildPolyList( polyList, dl );
  856. }
  857. else if ( context == PLC_Selection )
  858. {
  859. // Use the last rendered detail level
  860. S32 dl = mShapeInstance->getCurrentDetail();
  861. mShapeInstance->buildPolyListOpcode( dl, polyList, box );
  862. }
  863. else
  864. {
  865. // Figure out the mesh type we're looking for.
  866. MeshType meshType = ( context == PLC_Decal ) ? mDecalType : mCollisionType;
  867. if ( meshType == None )
  868. return false;
  869. else if ( meshType == Bounds )
  870. polyList->addBox( mObjBox );
  871. else if ( meshType == VisibleMesh )
  872. mShapeInstance->buildPolyList( polyList, 0 );
  873. else if (context == PLC_Decal && mDecalDetailsPtr != 0)
  874. {
  875. for ( U32 i = 0; i < mDecalDetailsPtr->size(); i++ )
  876. mShapeInstance->buildPolyListOpcode( (*mDecalDetailsPtr)[i], polyList, box );
  877. }
  878. else
  879. {
  880. // Everything else is done from the collision meshes
  881. // which may be built from either the visual mesh or
  882. // special collision geometry.
  883. for ( U32 i = 0; i < mCollisionDetails.size(); i++ )
  884. mShapeInstance->buildPolyListOpcode( mCollisionDetails[i], polyList, box );
  885. }
  886. }
  887. return true;
  888. }
  889. bool TSStatic::buildExportPolyList(ColladaUtils::ExportData* exportData, const Box3F &box, const SphereF &)
  890. {
  891. if (!mShapeInstance)
  892. return false;
  893. if (mCollisionType == Bounds)
  894. {
  895. ColladaUtils::ExportData::colMesh* colMesh;
  896. exportData->colMeshes.increment();
  897. colMesh = &exportData->colMeshes.last();
  898. colMesh->mesh.setTransform(&mObjToWorld, mObjScale);
  899. colMesh->mesh.setObject(this);
  900. colMesh->mesh.addBox(mObjBox);
  901. colMesh->colMeshName = String::ToString("ColBox%d-1", exportData->colMeshes.size());
  902. }
  903. else if (mCollisionType == VisibleMesh)
  904. {
  905. ColladaUtils::ExportData::colMesh* colMesh;
  906. exportData->colMeshes.increment();
  907. colMesh = &exportData->colMeshes.last();
  908. colMesh->mesh.setTransform(&mObjToWorld, mObjScale);
  909. colMesh->mesh.setObject(this);
  910. mShapeInstance->buildPolyList(&colMesh->mesh, 0);
  911. colMesh->colMeshName = String::ToString("ColMesh%d-1", exportData->colMeshes.size());
  912. }
  913. else if (mCollisionType == CollisionMesh)
  914. {
  915. // Everything else is done from the collision meshes
  916. // which may be built from either the visual mesh or
  917. // special collision geometry.
  918. for (U32 i = 0; i < mCollisionDetails.size(); i++)
  919. {
  920. ColladaUtils::ExportData::colMesh* colMesh;
  921. exportData->colMeshes.increment();
  922. colMesh = &exportData->colMeshes.last();
  923. colMesh->mesh.setTransform(&mObjToWorld, mObjScale);
  924. colMesh->mesh.setObject(this);
  925. mShapeInstance->buildPolyListOpcode(mCollisionDetails[i], &colMesh->mesh, box);
  926. colMesh->colMeshName = String::ToString("ColMesh%d-1", exportData->colMeshes.size());
  927. }
  928. }
  929. //Next, process the LOD levels and materials.
  930. if (isServerObject() && getClientObject())
  931. {
  932. TSStatic* clientShape = dynamic_cast<TSStatic*>(getClientObject());
  933. U32 numDetails = clientShape->mShapeInstance->getNumDetails() - 1;
  934. exportData->meshData.increment();
  935. //Prep a meshData for this shape in particular
  936. ColladaUtils::ExportData::meshLODData* meshData = &exportData->meshData.last();
  937. //Fill out the info we'll need later to actually append our mesh data for the detail levels during the processing phase
  938. meshData->shapeInst = clientShape->mShapeInstance;
  939. meshData->originatingObject = this;
  940. meshData->meshTransform = mObjToWorld;
  941. meshData->scale = mObjScale;
  942. //Iterate over all our detail levels
  943. for (U32 i = 0; i < clientShape->mShapeInstance->getNumDetails(); i++)
  944. {
  945. TSShape::Detail detail = clientShape->mShapeInstance->getShape()->details[i];
  946. String detailName = String::ToLower(clientShape->mShapeInstance->getShape()->getName(detail.nameIndex));
  947. //Skip it if it's a collision or line of sight element
  948. if (detailName.startsWith("col") || detailName.startsWith("los"))
  949. continue;
  950. meshData->meshDetailLevels.increment();
  951. ColladaUtils::ExportData::detailLevel* curDetail = &meshData->meshDetailLevels.last();
  952. //Make sure we denote the size this detail level has
  953. curDetail->size = detail.size;
  954. }
  955. }
  956. return true;
  957. }
  958. void TSStatic::buildConvex(const Box3F& box, Convex* convex)
  959. {
  960. if ( mCollisionType == None )
  961. return;
  962. if ( mShapeInstance == NULL )
  963. return;
  964. // These should really come out of a pool
  965. mConvexList->collectGarbage();
  966. if ( mCollisionType == Bounds )
  967. {
  968. // Just return a box convex for the entire shape...
  969. Convex* cc = 0;
  970. CollisionWorkingList& wl = convex->getWorkingList();
  971. for (CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext)
  972. {
  973. if (itr->mConvex->getType() == BoxConvexType &&
  974. itr->mConvex->getObject() == this)
  975. {
  976. cc = itr->mConvex;
  977. break;
  978. }
  979. }
  980. if (cc)
  981. return;
  982. // Create a new convex.
  983. BoxConvex* cp = new BoxConvex;
  984. mConvexList->registerObject(cp);
  985. convex->addToWorkingList(cp);
  986. cp->init(this);
  987. mObjBox.getCenter(&cp->mCenter);
  988. cp->mSize.x = mObjBox.len_x() / 2.0f;
  989. cp->mSize.y = mObjBox.len_y() / 2.0f;
  990. cp->mSize.z = mObjBox.len_z() / 2.0f;
  991. }
  992. else // CollisionMesh || VisibleMesh
  993. {
  994. TSStaticPolysoupConvex::smCurObject = this;
  995. for (U32 i = 0; i < mCollisionDetails.size(); i++)
  996. mShapeInstance->buildConvexOpcode( mObjToWorld, mObjScale, mCollisionDetails[i], box, convex, mConvexList );
  997. TSStaticPolysoupConvex::smCurObject = NULL;
  998. }
  999. }
  1000. SceneObject* TSStaticPolysoupConvex::smCurObject = NULL;
  1001. TSStaticPolysoupConvex::TSStaticPolysoupConvex()
  1002. : box( 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f ),
  1003. normal( 0.0f, 0.0f, 0.0f, 0.0f ),
  1004. idx( 0 ),
  1005. mesh( NULL )
  1006. {
  1007. mType = TSPolysoupConvexType;
  1008. for ( U32 i = 0; i < 4; ++i )
  1009. {
  1010. verts[i].set( 0.0f, 0.0f, 0.0f );
  1011. }
  1012. }
  1013. Point3F TSStaticPolysoupConvex::support(const VectorF& vec) const
  1014. {
  1015. F32 bestDot = mDot( verts[0], vec );
  1016. const Point3F *bestP = &verts[0];
  1017. for(S32 i=1; i<4; i++)
  1018. {
  1019. F32 newD = mDot(verts[i], vec);
  1020. if(newD > bestDot)
  1021. {
  1022. bestDot = newD;
  1023. bestP = &verts[i];
  1024. }
  1025. }
  1026. return *bestP;
  1027. }
  1028. Box3F TSStaticPolysoupConvex::getBoundingBox() const
  1029. {
  1030. Box3F wbox = box;
  1031. wbox.minExtents.convolve( mObject->getScale() );
  1032. wbox.maxExtents.convolve( mObject->getScale() );
  1033. mObject->getTransform().mul(wbox);
  1034. return wbox;
  1035. }
  1036. Box3F TSStaticPolysoupConvex::getBoundingBox(const MatrixF& mat, const Point3F& scale) const
  1037. {
  1038. AssertISV(false, "TSStaticPolysoupConvex::getBoundingBox(m,p) - Not implemented. -- XEA");
  1039. return box;
  1040. }
  1041. void TSStaticPolysoupConvex::getPolyList(AbstractPolyList *list)
  1042. {
  1043. // Transform the list into object space and set the pointer to the object
  1044. MatrixF i( mObject->getTransform() );
  1045. Point3F iS( mObject->getScale() );
  1046. list->setTransform(&i, iS);
  1047. list->setObject(mObject);
  1048. // Add only the original collision triangle
  1049. S32 base = list->addPoint(verts[0]);
  1050. list->addPoint(verts[2]);
  1051. list->addPoint(verts[1]);
  1052. list->begin(0, (U32)idx ^ (uintptr_t)mesh);
  1053. list->vertex(base + 2);
  1054. list->vertex(base + 1);
  1055. list->vertex(base + 0);
  1056. list->plane(base + 0, base + 1, base + 2);
  1057. list->end();
  1058. }
  1059. void TSStaticPolysoupConvex::getFeatures(const MatrixF& mat,const VectorF& n, ConvexFeature* cf)
  1060. {
  1061. cf->material = 0;
  1062. cf->object = mObject;
  1063. // For a tetrahedron this is pretty easy... first
  1064. // convert everything into world space.
  1065. Point3F tverts[4];
  1066. mat.mulP(verts[0], &tverts[0]);
  1067. mat.mulP(verts[1], &tverts[1]);
  1068. mat.mulP(verts[2], &tverts[2]);
  1069. mat.mulP(verts[3], &tverts[3]);
  1070. // points...
  1071. S32 firstVert = cf->mVertexList.size();
  1072. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[0];
  1073. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[1];
  1074. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[2];
  1075. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[3];
  1076. // edges...
  1077. cf->mEdgeList.increment();
  1078. cf->mEdgeList.last().vertex[0] = firstVert+0;
  1079. cf->mEdgeList.last().vertex[1] = firstVert+1;
  1080. cf->mEdgeList.increment();
  1081. cf->mEdgeList.last().vertex[0] = firstVert+1;
  1082. cf->mEdgeList.last().vertex[1] = firstVert+2;
  1083. cf->mEdgeList.increment();
  1084. cf->mEdgeList.last().vertex[0] = firstVert+2;
  1085. cf->mEdgeList.last().vertex[1] = firstVert+0;
  1086. cf->mEdgeList.increment();
  1087. cf->mEdgeList.last().vertex[0] = firstVert+3;
  1088. cf->mEdgeList.last().vertex[1] = firstVert+0;
  1089. cf->mEdgeList.increment();
  1090. cf->mEdgeList.last().vertex[0] = firstVert+3;
  1091. cf->mEdgeList.last().vertex[1] = firstVert+1;
  1092. cf->mEdgeList.increment();
  1093. cf->mEdgeList.last().vertex[0] = firstVert+3;
  1094. cf->mEdgeList.last().vertex[1] = firstVert+2;
  1095. // triangles...
  1096. cf->mFaceList.increment();
  1097. cf->mFaceList.last().normal = PlaneF(tverts[2], tverts[1], tverts[0]);
  1098. cf->mFaceList.last().vertex[0] = firstVert+2;
  1099. cf->mFaceList.last().vertex[1] = firstVert+1;
  1100. cf->mFaceList.last().vertex[2] = firstVert+0;
  1101. cf->mFaceList.increment();
  1102. cf->mFaceList.last().normal = PlaneF(tverts[1], tverts[0], tverts[3]);
  1103. cf->mFaceList.last().vertex[0] = firstVert+1;
  1104. cf->mFaceList.last().vertex[1] = firstVert+0;
  1105. cf->mFaceList.last().vertex[2] = firstVert+3;
  1106. cf->mFaceList.increment();
  1107. cf->mFaceList.last().normal = PlaneF(tverts[2], tverts[1], tverts[3]);
  1108. cf->mFaceList.last().vertex[0] = firstVert+2;
  1109. cf->mFaceList.last().vertex[1] = firstVert+1;
  1110. cf->mFaceList.last().vertex[2] = firstVert+3;
  1111. cf->mFaceList.increment();
  1112. cf->mFaceList.last().normal = PlaneF(tverts[0], tverts[2], tverts[3]);
  1113. cf->mFaceList.last().vertex[0] = firstVert+0;
  1114. cf->mFaceList.last().vertex[1] = firstVert+2;
  1115. cf->mFaceList.last().vertex[2] = firstVert+3;
  1116. // All done!
  1117. }
  1118. void TSStatic::onMount( SceneObject *obj, S32 node )
  1119. {
  1120. Parent::onMount(obj, node);
  1121. _updateShouldTick();
  1122. }
  1123. void TSStatic::onUnmount( SceneObject *obj, S32 node )
  1124. {
  1125. Parent::onUnmount( obj, node );
  1126. setMaskBits( TransformMask );
  1127. _updateShouldTick();
  1128. }
  1129. U32 TSStatic::getNumDetails()
  1130. {
  1131. if (isServerObject() && getClientObject())
  1132. {
  1133. TSStatic* clientShape = dynamic_cast<TSStatic*>(getClientObject());
  1134. return clientShape->mShapeInstance->getNumDetails();
  1135. }
  1136. return 0;
  1137. };
  1138. //------------------------------------------------------------------------
  1139. //These functions are duplicated in tsStatic and shapeBase.
  1140. //They each function a little differently; but achieve the same purpose of gathering
  1141. //target names/counts without polluting simObject.
  1142. DefineEngineMethod( TSStatic, getTargetName, const char*, ( S32 index ),(0),
  1143. "Get the name of the indexed shape material.\n"
  1144. "@param index index of the material to get (valid range is 0 - getTargetCount()-1).\n"
  1145. "@return the name of the indexed material.\n"
  1146. "@see getTargetCount()\n")
  1147. {
  1148. TSStatic *obj = dynamic_cast< TSStatic* > ( object );
  1149. if(obj)
  1150. {
  1151. // Try to use the client object (so we get the reskinned targets in the Material Editor)
  1152. if ((TSStatic*)obj->getClientObject())
  1153. obj = (TSStatic*)obj->getClientObject();
  1154. return obj->getShapeInstance()->getTargetName(index);
  1155. }
  1156. return "";
  1157. }
  1158. DefineEngineMethod( TSStatic, getTargetCount, S32,(),,
  1159. "Get the number of materials in the shape.\n"
  1160. "@return the number of materials in the shape.\n"
  1161. "@see getTargetName()\n")
  1162. {
  1163. TSStatic *obj = dynamic_cast< TSStatic* > ( object );
  1164. if(obj)
  1165. {
  1166. // Try to use the client object (so we get the reskinned targets in the Material Editor)
  1167. if ((TSStatic*)obj->getClientObject())
  1168. obj = (TSStatic*)obj->getClientObject();
  1169. return obj->getShapeInstance()->getTargetCount();
  1170. }
  1171. return -1;
  1172. }
  1173. // This method is able to change materials per map to with others. The material that is being replaced is being mapped to
  1174. // unmapped_mat as a part of this transition
  1175. DefineEngineMethod( TSStatic, changeMaterial, void, ( const char* mapTo, Material* oldMat, Material* newMat ),("",nullAsType<Material*>(),nullAsType<Material*>()),
  1176. "@brief Change one of the materials on the shape.\n\n"
  1177. "This method changes materials per mapTo with others. The material that "
  1178. "is being replaced is mapped to unmapped_mat as a part of this transition.\n"
  1179. "@note Warning, right now this only sort of works. It doesn't do a live "
  1180. "update like it should.\n"
  1181. "@param mapTo the name of the material target to remap (from getTargetName)\n"
  1182. "@param oldMat the old Material that was mapped \n"
  1183. "@param newMat the new Material to map\n\n"
  1184. "@tsexample\n"
  1185. "// remap the first material in the shape\n"
  1186. "%mapTo = %obj.getTargetName( 0 );\n"
  1187. "%obj.changeMaterial( %mapTo, 0, MyMaterial );\n"
  1188. "@endtsexample\n" )
  1189. {
  1190. // if no valid new material, theres no reason for doing this
  1191. if( !newMat )
  1192. {
  1193. Con::errorf("TSShape::changeMaterial failed: New material does not exist!");
  1194. return;
  1195. }
  1196. TSMaterialList* shapeMaterialList = object->getShape()->materialList;
  1197. // Check the mapTo name exists for this shape
  1198. S32 matIndex = shapeMaterialList->getMaterialNameList().find_next(String(mapTo));
  1199. if (matIndex < 0)
  1200. {
  1201. Con::errorf("TSShape::changeMaterial failed: Invalid mapTo name '%s'", mapTo);
  1202. return;
  1203. }
  1204. // Lets remap the old material off, so as to let room for our current material room to claim its spot
  1205. if( oldMat )
  1206. oldMat->mMapTo = String("unmapped_mat");
  1207. newMat->mMapTo = mapTo;
  1208. // Map the material by name in the matmgr
  1209. MATMGR->mapMaterial( mapTo, newMat->getName() );
  1210. // Replace instances with the new material being traded in. Lets make sure that we only
  1211. // target the specific targets per inst, this is actually doing more than we thought
  1212. delete shapeMaterialList->mMatInstList[matIndex];
  1213. shapeMaterialList->mMatInstList[matIndex] = newMat->createMatInstance();
  1214. // Finish up preparing the material instances for rendering
  1215. const GFXVertexFormat *flags = getGFXVertexFormat<GFXVertexPNTTB>();
  1216. FeatureSet features = MATMGR->getDefaultFeatures();
  1217. shapeMaterialList->getMaterialInst(matIndex)->init(features, flags);
  1218. }
  1219. DefineEngineMethod( TSStatic, getModelFile, const char *, (),,
  1220. "@brief Get the model filename used by this shape.\n\n"
  1221. "@return the shape filename\n\n"
  1222. "@tsexample\n"
  1223. "// Acquire the model filename used on this shape.\n"
  1224. "%modelFilename = %obj.getModelFile();\n"
  1225. "@endtsexample\n"
  1226. )
  1227. {
  1228. return object->getShapeFileName();
  1229. }
  1230. void TSStatic::set_special_typing()
  1231. {
  1232. if (mCollisionType == VisibleMesh || mCollisionType == CollisionMesh)
  1233. mTypeMask |= InteriorLikeObjectType;
  1234. else
  1235. mTypeMask &= ~InteriorLikeObjectType;
  1236. }
  1237. void TSStatic::onStaticModified(const char* slotName, const char*newValue)
  1238. {
  1239. #ifdef TORQUE_AFX_ENABLED
  1240. if (slotName == afxZodiacData::GradientRangeSlot)
  1241. {
  1242. afxZodiacData::convertGradientRangeFromDegrees(mGradientRange, mGradientRangeUser);
  1243. return;
  1244. }
  1245. #endif
  1246. set_special_typing();
  1247. }
  1248. void TSStatic::setSelectionFlags(U8 flags)
  1249. {
  1250. Parent::setSelectionFlags(flags);
  1251. if (!mShapeInstance || !isClientObject())
  1252. return;
  1253. if (!mShapeInstance->ownMaterialList())
  1254. return;
  1255. TSMaterialList* pMatList = mShapeInstance->getMaterialList();
  1256. for (S32 j = 0; j < pMatList->size(); j++)
  1257. {
  1258. BaseMatInstance * bmi = pMatList->getMaterialInst(j);
  1259. bmi->setSelectionHighlighting(needsSelectionHighlighting());
  1260. }
  1261. }