SubScene.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. #include "SubScene.h"
  2. #include "gameMode.h"
  3. #include "console/persistenceManager.h"
  4. #include "console/script.h"
  5. #include "environment/meshRoad.h"
  6. #include "environment/river.h"
  7. #include "scene/sceneRenderState.h"
  8. #include "renderInstance/renderPassManager.h"
  9. #include "gfx/gfxDrawUtil.h"
  10. #include "gfx/gfxTransformSaver.h"
  11. #include "gui/editor/inspector/group.h"
  12. #include "T3D/gameBase/gameBase.h"
  13. bool SubScene::smTransformChildren = false;
  14. IMPLEMENT_CO_NETOBJECT_V1(SubScene);
  15. S32 SubScene::mUnloadTimeoutMs = 5000;
  16. IMPLEMENT_CALLBACK(SubScene, onLoaded, void, (), (),
  17. "@brief Called when a subScene has been loaded and has game mode implications.\n\n");
  18. IMPLEMENT_CALLBACK(SubScene, onUnloaded, void, (), (),
  19. "@brief Called when a subScene has been unloaded and has game mode implications.\n\n");
  20. SubScene::SubScene() :
  21. mSubSceneAssetId(StringTable->EmptyString()),
  22. mGameModesNames(StringTable->EmptyString()),
  23. mScopeDistance(-1),
  24. mLoaded(false),
  25. mFreezeLoading(false),
  26. mTickPeriodMS(1000),
  27. mCurrTick(0),
  28. mGlobalLayer(false),
  29. mSaving(false)
  30. {
  31. mNetFlags.set(Ghostable | ScopeAlways);
  32. mTypeMask |= StaticObjectType;
  33. }
  34. SubScene::~SubScene()
  35. {
  36. }
  37. bool SubScene::onAdd()
  38. {
  39. if (!Parent::onAdd())
  40. return false;
  41. setProcessTick(true);
  42. return true;
  43. }
  44. void SubScene::onRemove()
  45. {
  46. if (isClientObject())
  47. removeFromScene();
  48. unload();
  49. Parent::onRemove();
  50. }
  51. void SubScene::initPersistFields()
  52. {
  53. addGroup("SubScene");
  54. addField("isGlobalLayer", TypeBool, Offset(mGlobalLayer, SubScene), "");
  55. INITPERSISTFIELD_SUBSCENEASSET(SubScene, SubScene, "The subscene asset to load.");
  56. addField("tickPeriodMS", TypeS32, Offset(mTickPeriodMS, SubScene), "evaluation rate (ms)");
  57. addField("gameModes", TypeGameModeList, Offset(mGameModesNames, SubScene), "The game modes that this subscene is associated with.");
  58. endGroup("SubScene");
  59. addGroup("LoadingManagement");
  60. addField("freezeLoading", TypeBool, Offset(mFreezeLoading, SubScene), "If true, will prevent the zone from being changed from it's current loading state.");
  61. addField("loadIf", TypeCommand, Offset(mLoadIf, SubScene), "evaluation condition (true/false)");
  62. addField("tickPeriodMS", TypeS32, Offset(mTickPeriodMS, SubScene), "evaluation rate (ms)");
  63. addField("onLoadCommand", TypeCommand, Offset(mOnLoadCommand, SubScene), "The command to execute when the subscene is loaded. Maximum 1023 characters.");
  64. addField("onUnloadCommand", TypeCommand, Offset(mOnUnloadCommand, SubScene), "The command to execute when subscene is unloaded. Maximum 1023 characters.");
  65. endGroup("LoadingManagement");
  66. Parent::initPersistFields();
  67. }
  68. void SubScene::consoleInit()
  69. {
  70. Parent::consoleInit();
  71. Con::addVariable("$SubScene::UnloadTimeoutMS", TypeBool, &SubScene::mUnloadTimeoutMs, "The amount of time in milliseconds it takes for a SubScene to be unloaded if it's inactive.\n"
  72. "@ingroup Editors\n");
  73. Con::addVariable("$SubScene::transformChildren", TypeBool, &SubScene::smTransformChildren,
  74. "@brief If true, then transform manipulations modify child objects. If false, only triggering bounds is manipulated\n\n"
  75. "@ingroup Editors");
  76. }
  77. void SubScene::addObject(SimObject* object)
  78. {
  79. SceneObject::addObject(object);
  80. }
  81. void SubScene::removeObject(SimObject* object)
  82. {
  83. SceneObject::removeObject(object);
  84. }
  85. U32 SubScene::packUpdate(NetConnection* conn, U32 mask, BitStream* stream)
  86. {
  87. U32 retMask = Parent::packUpdate(conn, mask, stream);
  88. stream->writeFlag(mGlobalLayer);
  89. return retMask;
  90. }
  91. void SubScene::unpackUpdate(NetConnection* conn, BitStream* stream)
  92. {
  93. Parent::unpackUpdate(conn, stream);
  94. mGlobalLayer = stream->readFlag();
  95. }
  96. void SubScene::onInspect(GuiInspector* inspector)
  97. {
  98. Parent::onInspect(inspector);
  99. #ifdef TORQUE_TOOLS
  100. //Put the SubScene group before everything that'd be SubScene-effecting, for orginazational purposes
  101. GuiInspectorGroup* subsceneGrp = inspector->findExistentGroup(StringTable->insert("SubScene"));
  102. if (!subsceneGrp)
  103. return;
  104. GuiControl* stack = dynamic_cast<GuiControl*>(subsceneGrp->findObjectByInternalName(StringTable->insert("Stack")));
  105. //Save button
  106. GuiInspectorField* saveFieldGui = subsceneGrp->createInspectorField();
  107. saveFieldGui->init(inspector, subsceneGrp);
  108. saveFieldGui->setSpecialEditField(true);
  109. saveFieldGui->setTargetObject(this);
  110. StringTableEntry fldnm = StringTable->insert("SaveSubScene");
  111. saveFieldGui->setSpecialEditVariableName(fldnm);
  112. saveFieldGui->setInspectorField(NULL, fldnm);
  113. saveFieldGui->setDocs("");
  114. stack->addObject(saveFieldGui);
  115. GuiButtonCtrl* saveButton = new GuiButtonCtrl();
  116. saveButton->registerObject();
  117. saveButton->setDataField(StringTable->insert("profile"), NULL, "ToolsGuiButtonProfile");
  118. saveButton->setText("Save SubScene");
  119. saveButton->resize(Point2I::Zero, saveFieldGui->getExtent());
  120. saveButton->setHorizSizing(GuiControl::horizResizeWidth);
  121. saveButton->setVertSizing(GuiControl::vertResizeHeight);
  122. char szBuffer[512];
  123. dSprintf(szBuffer, 512, "%d.save();", this->getId());
  124. saveButton->setConsoleCommand(szBuffer);
  125. saveFieldGui->addObject(saveButton);
  126. #endif
  127. }
  128. void SubScene::inspectPostApply()
  129. {
  130. Parent::inspectPostApply();
  131. setMaskBits(-1);
  132. }
  133. void SubScene::setTransform(const MatrixF& mat)
  134. {
  135. if(SubScene::smTransformChildren)
  136. {
  137. Parent::setTransform(mat);
  138. }
  139. else
  140. {
  141. SceneObject::setTransform(mat);
  142. }
  143. }
  144. void SubScene::setRenderTransform(const MatrixF& mat)
  145. {
  146. if (SubScene::smTransformChildren)
  147. {
  148. Parent::setRenderTransform(mat);
  149. }
  150. else
  151. {
  152. SceneObject::setRenderTransform(mat);
  153. }
  154. }
  155. bool SubScene::evaluateCondition()
  156. {
  157. if (!mLoadIf.isEmpty())
  158. {
  159. //test the mapper plugged in condition line
  160. String resVar = getIdString() + String(".result");
  161. Con::setBoolVariable(resVar.c_str(), false);
  162. String command = resVar + "=" + mLoadIf + ";";
  163. Con::evaluatef(command.c_str());
  164. return Con::getBoolVariable(resVar.c_str());
  165. }
  166. return true;
  167. }
  168. bool SubScene::testBox(const Box3F& testBox)
  169. {
  170. bool passes = mGlobalLayer;
  171. if (!passes)
  172. passes = getWorldBox().isOverlapped(testBox);
  173. if (passes)
  174. passes = evaluateCondition();
  175. return passes;
  176. }
  177. void SubScene::write(Stream& stream, U32 tabStop, U32 flags)
  178. {
  179. MutexHandle handle;
  180. handle.lock(mMutex);
  181. // export selected only?
  182. if ((flags & SelectedOnly) && !isSelected())
  183. {
  184. for (U32 i = 0; i < size(); i++)
  185. (*this)[i]->write(stream, tabStop, flags);
  186. return;
  187. }
  188. stream.writeTabs(tabStop);
  189. char buffer[2048];
  190. const U32 bufferWriteLen = dSprintf(buffer, sizeof(buffer), "new %s(%s) {\r\n", getClassName(), getName() && !(flags & NoName) ? getName() : "");
  191. stream.write(bufferWriteLen, buffer);
  192. writeFields(stream, tabStop + 1);
  193. //The only meaningful difference between this and simSet for writing is we skip the children, since they're just the levelAsset contents
  194. stream.writeTabs(tabStop);
  195. stream.write(4, "};\r\n");
  196. }
  197. void SubScene::processTick(const Move* move)
  198. {
  199. mCurrTick += TickMs;
  200. if (mCurrTick > mTickPeriodMS)
  201. {
  202. mCurrTick = 0;
  203. //re-evaluate
  204. if (!evaluateCondition())
  205. unload();
  206. }
  207. }
  208. void SubScene::_onFileChanged(const Torque::Path& path)
  209. {
  210. if(mSubSceneAsset.isNull() || Torque::Path(mSubSceneAsset->getLevelPath()) != path)
  211. return;
  212. if (mSaving)
  213. return;
  214. AssertFatal(path == mSubSceneAsset->getLevelPath(), "SubScene::_onFileChanged - path does not match filename.");
  215. _closeFile(false);
  216. _loadFile(false);
  217. setMaskBits(U32_MAX);
  218. }
  219. void SubScene::_removeContents(SimGroupIterator set)
  220. {
  221. for (SimGroupIterator itr(set); *itr; ++itr)
  222. {
  223. SimGroup* child = dynamic_cast<SimGroup*>(*itr);
  224. if (child)
  225. {
  226. _removeContents(SimGroupIterator(child));
  227. GameBase* asGameBase = dynamic_cast<GameBase*>(child);
  228. if (asGameBase)
  229. {
  230. asGameBase->scriptOnRemove();
  231. }
  232. Sim::cancelPendingEvents(child);
  233. child->safeDeleteObject();
  234. }
  235. }
  236. }
  237. void SubScene::_closeFile(bool removeFileNotify)
  238. {
  239. AssertFatal(isServerObject(), "Trying to close out a subscene file on the client is bad!");
  240. _removeContents(SimGroupIterator(this));
  241. if (removeFileNotify && mSubSceneAsset.notNull() && mSubSceneAsset->getLevelPath() != StringTable->EmptyString())
  242. {
  243. Torque::FS::RemoveChangeNotification(mSubSceneAsset->getLevelPath(), this, &SubScene::_onFileChanged);
  244. }
  245. mGameModesList.clear();
  246. }
  247. void SubScene::_loadFile(bool addFileNotify)
  248. {
  249. AssertFatal(isServerObject(), "Trying to load a SubScene file on the client is bad!");
  250. if(mSubSceneAsset.isNull() || mSubSceneAsset->getLevelPath() == StringTable->EmptyString())
  251. return;
  252. String evalCmd = String::ToString("exec(\"%s\");", mSubSceneAsset->getLevelPath());
  253. String instantGroup = Con::getVariable("InstantGroup");
  254. Con::setIntVariable("InstantGroup", this->getId());
  255. Con::evaluate((const char*)evalCmd.c_str(), false, mSubSceneAsset->getLevelPath());
  256. Con::setVariable("InstantGroup", instantGroup.c_str());
  257. if (addFileNotify)
  258. Torque::FS::AddChangeNotification(mSubSceneAsset->getLevelPath(), this, &SubScene::_onFileChanged);
  259. }
  260. void SubScene::load()
  261. {
  262. mStartUnloadTimerMS = -1; //reset unload timers
  263. //no need to load multiple times
  264. if (mLoaded)
  265. return;
  266. if (mFreezeLoading)
  267. return;
  268. if (mSaving)
  269. return;
  270. GameMode::findGameModes(mGameModesNames, &mGameModesList);
  271. if (!isSelected() && (String(mGameModesNames).isNotEmpty() && mGameModesList.size() == 0) || !evaluateCondition())
  272. {
  273. mLoaded = false;
  274. return;
  275. }
  276. _loadFile(true);
  277. mLoaded = true;
  278. onLoaded_callback();
  279. for (U32 i = 0; i < mGameModesList.size(); i++)
  280. {
  281. mGameModesList[i]->onSubsceneLoaded_callback(this);
  282. }
  283. }
  284. void SubScene::unload()
  285. {
  286. if (!mLoaded)
  287. return;
  288. if (mFreezeLoading)
  289. return;
  290. if (mSaving)
  291. return;
  292. if (isSelected())
  293. {
  294. mStartUnloadTimerMS = Sim::getCurrentTime();
  295. return; //if a child is selected, then we don't want to unload
  296. }
  297. //scan down through our child objects, see if any are marked as selected,
  298. //if so, skip unloading and reset the timer
  299. for (SimGroupIterator itr(this); *itr; ++itr)
  300. {
  301. SimGroup* childGrp = dynamic_cast<SimGroup*>(*itr);
  302. if (childGrp)
  303. {
  304. if (childGrp->isSelected())
  305. {
  306. mStartUnloadTimerMS = Sim::getCurrentTime();
  307. return; //if a child is selected, then we don't want to unload
  308. }
  309. for (SimGroupIterator cldItr(childGrp); *cldItr; ++cldItr)
  310. {
  311. SimObject* chldChld = dynamic_cast<SimObject*>(*cldItr);
  312. if (chldChld && chldChld->isSelected())
  313. {
  314. mStartUnloadTimerMS = Sim::getCurrentTime();
  315. return; //if a child is selected, then we don't want to unload
  316. }
  317. }
  318. }
  319. }
  320. onUnloaded_callback();
  321. for (U32 i = 0; i < mGameModesList.size(); i++)
  322. {
  323. mGameModesList[i]->onSubsceneUnloaded_callback(this);
  324. }
  325. if (!mOnUnloadCommand.isEmpty())
  326. {
  327. String command = "%this = " + String(getIdString()) + "; " + mOnUnloadCommand + ";";
  328. Con::evaluatef(command.c_str());
  329. }
  330. _closeFile(true);
  331. mLoaded = false;
  332. }
  333. bool SubScene::save()
  334. {
  335. if (!isServerObject())
  336. return false;
  337. //if there's nothing TO save, don't bother
  338. if (size() == 0 || !isLoaded())
  339. return false;
  340. if (mSubSceneAsset.isNull())
  341. return false;
  342. if (mSaving)
  343. return false;
  344. //If we're flagged for unload, push back the unload timer so we can't accidentally trip be saving partway through an unload
  345. if (mStartUnloadTimerMS != -1)
  346. mStartUnloadTimerMS = Sim::getCurrentTime();
  347. mSaving = true;
  348. PersistenceManager prMger;
  349. StringTableEntry levelPath = mSubSceneAsset->getLevelPath();
  350. FileStream fs;
  351. fs.open(levelPath, Torque::FS::File::Write);
  352. fs.close();
  353. for (SimGroupIterator itr(this); *itr; ++itr)
  354. {
  355. SimObject* childObj = (*itr);
  356. if (!prMger.isDirty(childObj))
  357. {
  358. if ((*itr)->isMethod("onSaving"))
  359. {
  360. Con::executef((*itr), "onSaving", mSubSceneAssetId);
  361. }
  362. if (childObj->getGroup() == this)
  363. {
  364. prMger.setDirty((*itr), levelPath);
  365. }
  366. }
  367. if(dynamic_cast<MeshRoad*>(childObj) || dynamic_cast<River*>(childObj))
  368. {
  369. prMger.addRemoveField(childObj, "position");
  370. }
  371. }
  372. prMger.saveDirty();
  373. //process our gameModeList and write it out to the levelAsset for metadata stashing
  374. bool saveSuccess = false;
  375. //Get the level asset
  376. if (mSubSceneAsset.isNull())
  377. return saveSuccess;
  378. //update the gamemode list as well
  379. mSubSceneAsset->setDataField(StringTable->insert("gameModesNames"), NULL, StringTable->insert(mGameModesNames));
  380. //Finally, save
  381. saveSuccess = mSubSceneAsset->saveAsset();
  382. mSaving = false;
  383. return saveSuccess;
  384. }
  385. void SubScene::_onSelected()
  386. {
  387. if (!isLoaded() && isServerObject())
  388. load();
  389. }
  390. void SubScene::_onUnselected()
  391. {
  392. }
  393. void SubScene::prepRenderImage(SceneRenderState* state)
  394. {
  395. // only render if selected or render flag is set
  396. if (/*!smRenderTriggers && */!isSelected())
  397. return;
  398. ObjectRenderInst* ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  399. ri->renderDelegate.bind(this, &SubScene::renderObject);
  400. ri->type = RenderPassManager::RIT_Editor;
  401. ri->translucentSort = true;
  402. ri->defaultKey = 1;
  403. state->getRenderPass()->addInst(ri);
  404. }
  405. void SubScene::renderObject(ObjectRenderInst* ri,
  406. SceneRenderState* state,
  407. BaseMatInstance* overrideMat)
  408. {
  409. if (overrideMat)
  410. return;
  411. GFXStateBlockDesc desc;
  412. desc.setZReadWrite(true, false);
  413. desc.setBlend(true);
  414. // Trigger polyhedrons are set up with outward facing normals and CCW ordering
  415. // so can't enable backface culling.
  416. desc.setCullMode(GFXCullNone);
  417. GFXTransformSaver saver;
  418. MatrixF mat = getRenderTransform();
  419. GFX->multWorld(mat);
  420. GFXDrawUtil* drawer = GFX->getDrawUtil();
  421. //Box3F scale = getScale()
  422. //Box3F bounds = Box3F(-m)
  423. Point3F scale = getScale();
  424. Box3F bounds = Box3F(-scale/2, scale/2);
  425. ColorI boundsColor = ColorI(135, 206, 235, 50);
  426. if (mGlobalLayer)
  427. boundsColor = ColorI(200, 100, 100, 25);
  428. else if (mLoaded)
  429. boundsColor = ColorI(50, 200, 50, 50);
  430. drawer->drawCube(desc, bounds, boundsColor);
  431. // Render wireframe.
  432. desc.setFillModeWireframe();
  433. drawer->drawCube(desc, bounds, ColorI::BLACK);
  434. }
  435. DefineEngineMethod(SubScene, save, bool, (),,
  436. "Save out the subScene.\n")
  437. {
  438. return object->save();
  439. }
  440. DefineEngineMethod(SubScene, load, void, (), ,
  441. "Loads the SubScene's level file.\n")
  442. {
  443. object->load();
  444. }
  445. DefineEngineMethod(SubScene, unload, void, (), ,
  446. "Unloads the SubScene's level file.\n")
  447. {
  448. object->unload();
  449. }