prefab.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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/prefab.h"
  24. #include "math/mathIO.h"
  25. #include "core/stream/bitStream.h"
  26. #include "scene/sceneRenderState.h"
  27. #include "gfx/gfxTransformSaver.h"
  28. #include "renderInstance/renderPassManager.h"
  29. #include "console/consoleTypes.h"
  30. #include "core/volume.h"
  31. #include "console/engineAPI.h"
  32. #include "T3D/physics/physicsShape.h"
  33. #include "core/util/path.h"
  34. #include "T3D/Scene.h"
  35. // We use this locally ( within this file ) to prevent infinite recursion
  36. // while loading prefab files that contain other prefabs.
  37. static Vector<String> sPrefabFileStack;
  38. Map<SimObjectId,SimObjectId> Prefab::smChildToPrefabMap;
  39. IMPLEMENT_CO_NETOBJECT_V1(Prefab);
  40. ConsoleDocClass( Prefab,
  41. "@brief A collection of arbitrary objects which can be allocated and manipulated as a group.\n\n"
  42. "%Prefab always points to a (.prefab) file which defines its objects. In "
  43. "fact more than one %Prefab can reference this file and both will update "
  44. "if the file is modified.\n\n"
  45. "%Prefab is a very simple object and only exists on the server. When it is "
  46. "created it allocates children objects by reading the (.prefab) file like "
  47. "a list of instructions. It then sets their transform relative to the %Prefab "
  48. "and Torque networking handles the rest by ghosting the new objects to clients. "
  49. "%Prefab itself is not ghosted.\n\n"
  50. "@ingroup enviroMisc"
  51. );
  52. IMPLEMENT_CALLBACK( Prefab, onLoad, void, ( SimGroup *children ), ( children ),
  53. "Called when the prefab file is loaded and children objects are created.\n"
  54. "@param children SimGroup containing all children objects.\n"
  55. );
  56. Prefab::Prefab()
  57. {
  58. // Not ghosted unless we're editing
  59. mNetFlags.clear(Ghostable);
  60. mTypeMask |= StaticObjectType;
  61. mFilename = StringTable->EmptyString();
  62. }
  63. Prefab::~Prefab()
  64. {
  65. }
  66. void Prefab::initPersistFields()
  67. {
  68. addGroup( "Prefab" );
  69. addProtectedField( "filename", TypePrefabFilename, Offset( mFilename, Prefab ),
  70. &protectedSetFile, &defaultProtectedGetFn,
  71. "(.prefab) File describing objects within this prefab." );
  72. endGroup( "Prefab" );
  73. Parent::initPersistFields();
  74. }
  75. extern bool gEditingMission;
  76. bool Prefab::onAdd()
  77. {
  78. if ( !Parent::onAdd() )
  79. return false;
  80. mObjBox.set( Point3F( -0.5f, -0.5f, -0.5f ),
  81. Point3F( 0.5f, 0.5f, 0.5f ) );
  82. resetWorldBox();
  83. // Not added to the scene unless we are editing.
  84. if ( gEditingMission )
  85. onEditorEnable();
  86. // Only the server-side prefab needs to create/update child objects.
  87. // We rely on regular Torque ghosting of the individual child objects
  88. // to take care of the rest.
  89. if ( isServerObject() )
  90. {
  91. _loadFile( true );
  92. _updateChildren();
  93. }
  94. return true;
  95. }
  96. void Prefab::onRemove()
  97. {
  98. if ( isServerObject() )
  99. _closeFile( true );
  100. removeFromScene();
  101. Parent::onRemove();
  102. }
  103. void Prefab::onEditorEnable()
  104. {
  105. if ( isClientObject() )
  106. return;
  107. // Just in case we are already in the scene, lets not cause an assert.
  108. if ( mContainer != NULL )
  109. return;
  110. // Enable ghosting so we can see this on the client.
  111. mNetFlags.set(Ghostable);
  112. setScopeAlways();
  113. addToScene();
  114. Parent::onEditorEnable();
  115. }
  116. void Prefab::onEditorDisable()
  117. {
  118. if ( isClientObject() )
  119. return;
  120. // Just in case we are not in the scene, lets not cause an assert.
  121. if ( mContainer == NULL )
  122. return;
  123. // Do not need this on the client if we are not editing.
  124. removeFromScene();
  125. mNetFlags.clear(Ghostable);
  126. clearScopeAlways();
  127. Parent::onEditorDisable();
  128. }
  129. void Prefab::inspectPostApply()
  130. {
  131. Parent::inspectPostApply();
  132. }
  133. void Prefab::setTransform(const MatrixF & mat)
  134. {
  135. Parent::setTransform( mat );
  136. if ( isServerObject() )
  137. {
  138. setMaskBits( TransformMask );
  139. _updateChildren();
  140. }
  141. }
  142. void Prefab::setScale(const VectorF & scale)
  143. {
  144. Parent::setScale( scale );
  145. if ( isServerObject() )
  146. {
  147. setMaskBits( TransformMask );
  148. _updateChildren();
  149. }
  150. }
  151. U32 Prefab::packUpdate( NetConnection *conn, U32 mask, BitStream *stream )
  152. {
  153. U32 retMask = Parent::packUpdate( conn, mask, stream );
  154. mathWrite(*stream,mObjBox);
  155. if ( stream->writeFlag( mask & FileMask ) )
  156. {
  157. stream->writeString( mFilename );
  158. }
  159. if ( stream->writeFlag( mask & TransformMask ) )
  160. {
  161. mathWrite(*stream, getTransform());
  162. mathWrite(*stream, getScale());
  163. }
  164. return retMask;
  165. }
  166. void Prefab::unpackUpdate(NetConnection *conn, BitStream *stream)
  167. {
  168. Parent::unpackUpdate(conn, stream);
  169. mathRead(*stream, &mObjBox);
  170. resetWorldBox();
  171. // FileMask
  172. if ( stream->readFlag() )
  173. {
  174. mFilename = stream->readSTString();
  175. }
  176. // TransformMask
  177. if ( stream->readFlag() )
  178. {
  179. mathRead(*stream, &mObjToWorld);
  180. mathRead(*stream, &mObjScale);
  181. setTransform( mObjToWorld );
  182. }
  183. }
  184. bool Prefab::protectedSetFile( void *object, const char *index, const char *data )
  185. {
  186. Prefab *prefab = static_cast<Prefab*>(object);
  187. prefab->setFile( StringTable->insert(Platform::makeRelativePathName(data, Platform::getMainDotCsDir())));
  188. return false;
  189. }
  190. void Prefab::setFile( StringTableEntry file )
  191. {
  192. AssertFatal( isServerObject(), "Prefab-bad" );
  193. if ( !isProperlyAdded() )
  194. {
  195. mFilename = file;
  196. return;
  197. }
  198. // Client-side Prefab(s) do not create/update/reference children, everything
  199. // is handled on the server-side. In normal usage this will never actually
  200. // be called for the client-side prefab but maybe the user did so accidentally.
  201. if ( isClientObject() )
  202. {
  203. Con::errorf( "Prefab::setFile( %s ) - Should not be called on a client-side Prefab.", file );
  204. return;
  205. }
  206. _closeFile( true );
  207. mFilename = file;
  208. if ( isProperlyAdded() )
  209. _loadFile( true );
  210. }
  211. SimGroup* Prefab::explode()
  212. {
  213. Scene* scene = Scene::getRootScene();
  214. if ( !scene)
  215. {
  216. Con::errorf( "Prefab::explode, Scene was not found." );
  217. return NULL;
  218. }
  219. if ( !mChildGroup )
  220. return NULL;
  221. SimGroup *group = mChildGroup;
  222. Vector<SceneObject*> foundObjects;
  223. group->findObjectByType( foundObjects );
  224. if ( foundObjects.empty() )
  225. return NULL;
  226. for ( S32 i = 0; i < foundObjects.size(); i++ )
  227. {
  228. SceneObject *child = foundObjects[i];
  229. _updateChildTransform( child );
  230. smChildToPrefabMap.erase( child->getId() );
  231. }
  232. scene->addObject(group);
  233. mChildGroup = NULL;
  234. mChildMap.clear();
  235. return group;
  236. }
  237. void Prefab::_closeFile( bool removeFileNotify )
  238. {
  239. AssertFatal( isServerObject(), "Prefab-bad" );
  240. mChildMap.clear();
  241. if ( mChildGroup )
  242. {
  243. // Get a flat vector of all our children.
  244. Vector<SceneObject*> foundObjects;
  245. mChildGroup->findObjectByType( foundObjects );
  246. // Remove them all from the ChildToPrefabMap.
  247. for ( S32 i = 0; i < foundObjects.size(); i++ )
  248. smChildToPrefabMap.erase( foundObjects[i]->getId() );
  249. mChildGroup->deleteObject();
  250. mChildGroup = NULL;
  251. }
  252. if ( removeFileNotify )
  253. Torque::FS::RemoveChangeNotification( mFilename, this, &Prefab::_onFileChanged );
  254. // Back to a default bounding box size.
  255. mObjBox.set( Point3F( -0.5f, -0.5f, -0.5f ), Point3F( 0.5f, 0.5f, 0.5f ) );
  256. resetWorldBox();
  257. }
  258. void Prefab::_loadFile( bool addFileNotify )
  259. {
  260. AssertFatal( isServerObject(), "Prefab-bad" );
  261. if ( mFilename == StringTable->EmptyString())
  262. return;
  263. if ( !Torque::FS::IsScriptFile( mFilename ) )
  264. {
  265. Con::errorf( "Prefab::_loadFile() - file %s was not found.", mFilename );
  266. return;
  267. }
  268. if ( sPrefabFileStack.contains(mFilename) )
  269. {
  270. Con::errorf(
  271. "Prefab::_loadFile - failed loading prefab file (%s). \n"
  272. "File was referenced recursively by both a Parent and Child prefab.", mFilename );
  273. return;
  274. }
  275. sPrefabFileStack.push_back(mFilename);
  276. String command = String::ToString( "exec( \"%s\" );", mFilename );
  277. Con::evaluate( command );
  278. SimGroup *group;
  279. if ( !Sim::findObject( Con::getVariable( "$ThisPrefab" ), group ) )
  280. {
  281. Con::errorf( "Prefab::_loadFile() - file %s did not create $ThisPrefab.", mFilename );
  282. return;
  283. }
  284. if ( addFileNotify )
  285. Torque::FS::AddChangeNotification( mFilename, this, &Prefab::_onFileChanged );
  286. mChildGroup = group;
  287. Vector<SceneObject*> foundObjects;
  288. mChildGroup->findObjectByType( foundObjects );
  289. if ( !foundObjects.empty() )
  290. {
  291. mWorldBox = Box3F::Invalid;
  292. for ( S32 i = 0; i < foundObjects.size(); i++ )
  293. {
  294. SceneObject *child = foundObjects[i];
  295. mChildMap.insert( child->getId(), Transform( child->getTransform(), child->getScale() ) );
  296. smChildToPrefabMap.insert( child->getId(), getId() );
  297. _updateChildTransform( child );
  298. mWorldBox.intersect( child->getWorldBox() );
  299. }
  300. resetObjectBox();
  301. }
  302. sPrefabFileStack.pop_back();
  303. onLoad_callback( mChildGroup );
  304. }
  305. void Prefab::_updateChildTransform( SceneObject* child )
  306. {
  307. ChildToMatMap::Iterator itr = mChildMap.find(child->getId());
  308. AssertFatal( itr != mChildMap.end(), "Prefab, mChildMap out of synch with mChildGroup." );
  309. MatrixF mat( itr->value.mat );
  310. Point3F pos = mat.getPosition();
  311. pos.convolve( mObjScale );
  312. mat.setPosition( pos );
  313. mat.mulL( mObjToWorld );
  314. child->setTransform( mat );
  315. child->setScale( itr->value.scale * mObjScale );
  316. // Hack for PhysicsShape... need to store the "editor" position to return to
  317. // when a physics reset event occurs. Normally this would be where it is
  318. // during onAdd, but in this case it is not because the prefab stores its
  319. // child objects in object space...
  320. PhysicsShape *childPS = dynamic_cast<PhysicsShape*>( child );
  321. if ( childPS )
  322. childPS->storeRestorePos();
  323. }
  324. void Prefab::_updateChildren()
  325. {
  326. if ( !mChildGroup )
  327. return;
  328. Vector<SceneObject*> foundObjects;
  329. mChildGroup->findObjectByType( foundObjects );
  330. for ( S32 i = 0; i < foundObjects.size(); i++ )
  331. {
  332. SceneObject *child = foundObjects[i];
  333. _updateChildTransform( child );
  334. if ( child->getClientObject() )
  335. {
  336. ((SceneObject*)child->getClientObject())->setTransform( child->getTransform() );
  337. ((SceneObject*)child->getClientObject())->setScale( child->getScale() );
  338. }
  339. }
  340. }
  341. void Prefab::_onFileChanged( const Torque::Path &path )
  342. {
  343. AssertFatal( path == mFilename, "Prefab::_onFileChanged - path does not match filename." );
  344. _closeFile(false);
  345. _loadFile(false);
  346. setMaskBits(U32_MAX);
  347. }
  348. Prefab* Prefab::getPrefabByChild( SimObject *child )
  349. {
  350. ChildToPrefabMap::Iterator itr = smChildToPrefabMap.find( child->getId() );
  351. if ( itr == smChildToPrefabMap.end() )
  352. return NULL;
  353. Prefab *prefab;
  354. if ( !Sim::findObject( itr->value, prefab ) )
  355. {
  356. Con::errorf( "Prefab::getPrefabByChild - child object mapped to a prefab that no longer exists." );
  357. return NULL;
  358. }
  359. return prefab;
  360. }
  361. bool Prefab::isValidChild( SimObject *simobj, bool logWarnings )
  362. {
  363. if ( simobj->getName() && simobj == Scene::getRootScene() )
  364. {
  365. if ( logWarnings )
  366. Con::warnf( "root Scene is not valid within a Prefab." );
  367. return false;
  368. }
  369. if ( simobj->getClassRep()->isClass( AbstractClassRep::findClassRep("LevelInfo") ) )
  370. {
  371. if ( logWarnings )
  372. Con::warnf( "LevelInfo objects are not valid within a Prefab" );
  373. return false;
  374. }
  375. if ( simobj->getClassRep()->isClass( AbstractClassRep::findClassRep("TimeOfDay") ) )
  376. {
  377. if ( logWarnings )
  378. Con::warnf( "TimeOfDay objects are not valid within a Prefab" );
  379. return false;
  380. }
  381. SceneObject *sceneobj = dynamic_cast<SceneObject*>(simobj);
  382. if ( !sceneobj )
  383. return false;
  384. if ( sceneobj->isGlobalBounds() )
  385. {
  386. if ( logWarnings )
  387. Con::warnf( "SceneObject's with global bounds are not valid within a Prefab." );
  388. return false;
  389. }
  390. if ( sceneobj->getClassRep()->isClass( AbstractClassRep::findClassRep("TerrainBlock") ) )
  391. {
  392. if ( logWarnings )
  393. Con::warnf( "TerrainBlock objects are not valid within a Prefab" );
  394. return false;
  395. }
  396. if ( sceneobj->getClassRep()->isClass( AbstractClassRep::findClassRep("Player") ) )
  397. {
  398. if ( logWarnings )
  399. Con::warnf( "Player objects are not valid within a Prefab" );
  400. return false;
  401. }
  402. if ( sceneobj->getClassRep()->isClass( AbstractClassRep::findClassRep("DecalRoad") ) )
  403. {
  404. if ( logWarnings )
  405. Con::warnf( "DecalRoad objects are not valid within a Prefab" );
  406. return false;
  407. }
  408. return true;
  409. }
  410. bool Prefab::buildPolyList(PolyListContext context, AbstractPolyList* polyList, const Box3F &box, const SphereF& sphere)
  411. {
  412. Vector<SceneObject*> foundObjects;
  413. if (mChildGroup.isNull() || mChildGroup->empty())
  414. {
  415. Con::warnf("Bad Prefab Config! %s has no valid entries!", getName());
  416. return false;
  417. }
  418. mChildGroup->findObjectByType(foundObjects);
  419. for (S32 i = 0; i < foundObjects.size(); i++)
  420. {
  421. foundObjects[i]->buildPolyList(context, polyList, box, sphere);
  422. }
  423. return true;
  424. }
  425. bool Prefab::buildExportPolyList(ColladaUtils::ExportData* exportData, const Box3F &box, const SphereF &sphere)
  426. {
  427. Vector<SceneObject*> foundObjects;
  428. mChildGroup->findObjectByType(foundObjects);
  429. for (S32 i = 0; i < foundObjects.size(); i++)
  430. {
  431. foundObjects[i]->buildExportPolyList(exportData, box, sphere);
  432. }
  433. return true;
  434. }
  435. void Prefab::getUtilizedAssets(Vector<StringTableEntry>* usedAssetsList)
  436. {
  437. if (!mChildGroup) return;
  438. Vector<SceneObject*> foundObjects;
  439. mChildGroup->findObjectByType(foundObjects);
  440. for (S32 i = 0; i < foundObjects.size(); i++)
  441. {
  442. SceneObject* child = foundObjects[i];
  443. child->getUtilizedAssets(usedAssetsList);
  444. }
  445. }
  446. ExplodePrefabUndoAction::ExplodePrefabUndoAction( Prefab *prefab )
  447. : UndoAction( "Explode Prefab" )
  448. {
  449. mPrefabId = prefab->getId();
  450. mGroup = NULL;
  451. // Do the action.
  452. redo();
  453. }
  454. void ExplodePrefabUndoAction::undo()
  455. {
  456. if ( !mGroup )
  457. {
  458. Con::errorf( "ExplodePrefabUndoAction::undo - NULL Group" );
  459. return;
  460. }
  461. mGroup->deleteObject();
  462. mGroup = NULL;
  463. }
  464. void ExplodePrefabUndoAction::redo()
  465. {
  466. Prefab *prefab;
  467. if ( !Sim::findObject( mPrefabId, prefab ) )
  468. {
  469. Con::errorf( "ExplodePrefabUndoAction::redo - Prefab (%i) not found.", mPrefabId );
  470. return;
  471. }
  472. mGroup = prefab->explode();
  473. String name;
  474. if ( prefab->getName() && prefab->getName()[0] != '\0' )
  475. name = prefab->getName();
  476. else
  477. name = "prefab";
  478. name += "_exploded";
  479. name = Sim::getUniqueName( name );
  480. mGroup->assignName( name );
  481. }
  482. DefineEngineMethod(Prefab, getChildGroup, S32, (),,
  483. "")
  484. {
  485. return object->getChildGroup();
  486. }