prefab.cpp 16 KB

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