SubScene.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. #include "SubScene.h"
  2. #include "gameMode.h"
  3. #include "console/script.h"
  4. #include "scene/sceneRenderState.h"
  5. #include "renderInstance/renderPassManager.h"
  6. #include "gfx/gfxDrawUtil.h"
  7. #include "gfx/gfxTransformSaver.h"
  8. #include "gui/editor/inspector/group.h"
  9. IMPLEMENT_CO_NETOBJECT_V1(SubScene);
  10. S32 SubScene::mUnloadTimeoutMs = 5000;
  11. SubScene::SubScene() :
  12. mLevelAssetId(StringTable->EmptyString()),
  13. mGameModesNames(StringTable->EmptyString()),
  14. mScopeDistance(-1),
  15. mLoaded(false),
  16. mGlobalLayer(false)
  17. {
  18. mNetFlags.set(Ghostable | ScopeAlways);
  19. mTypeMask |= StaticObjectType;
  20. }
  21. SubScene::~SubScene()
  22. {
  23. }
  24. bool SubScene::onAdd()
  25. {
  26. if (!Parent::onAdd())
  27. return false;
  28. return true;
  29. }
  30. void SubScene::onRemove()
  31. {
  32. if (isClientObject())
  33. removeFromScene();
  34. Parent::onRemove();
  35. }
  36. void SubScene::initPersistFields()
  37. {
  38. addGroup("SubScene");
  39. addField("isGlobalLayer", TypeBool, Offset(mGlobalLayer, SubScene), "");
  40. INITPERSISTFIELD_LEVELASSET(Level, SubScene, "The level asset to load.");
  41. addField("gameModes", TypeGameModeList, Offset(mGameModesNames, SubScene), "The game modes that this subscene is associated with.");
  42. endGroup("SubScene");
  43. Parent::initPersistFields();
  44. }
  45. void SubScene::consoleInit()
  46. {
  47. Parent::consoleInit();
  48. 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"
  49. "@ingroup Editors\n");
  50. }
  51. void SubScene::addObject(SimObject* object)
  52. {
  53. SceneObject::addObject(object);
  54. }
  55. void SubScene::removeObject(SimObject* object)
  56. {
  57. SceneObject::removeObject(object);
  58. }
  59. U32 SubScene::packUpdate(NetConnection* conn, U32 mask, BitStream* stream)
  60. {
  61. U32 retMask = Parent::packUpdate(conn, mask, stream);
  62. stream->writeFlag(mGlobalLayer);
  63. return retMask;
  64. }
  65. void SubScene::unpackUpdate(NetConnection* conn, BitStream* stream)
  66. {
  67. Parent::unpackUpdate(conn, stream);
  68. mGlobalLayer = stream->readFlag();
  69. }
  70. void SubScene::onInspect(GuiInspector* inspector)
  71. {
  72. Parent::onInspect(inspector);
  73. //Put the SubScene group before everything that'd be SubScene-effecting, for orginazational purposes
  74. GuiInspectorGroup* subsceneGrp = inspector->findExistentGroup(StringTable->insert("SubScene"));
  75. if (!subsceneGrp)
  76. return;
  77. GuiControl* stack = dynamic_cast<GuiControl*>(subsceneGrp->findObjectByInternalName(StringTable->insert("Stack")));
  78. //Save button
  79. GuiInspectorField* saveFieldGui = subsceneGrp->createInspectorField();
  80. saveFieldGui->init(inspector, subsceneGrp);
  81. saveFieldGui->setSpecialEditField(true);
  82. saveFieldGui->setTargetObject(this);
  83. StringTableEntry fldnm = StringTable->insert("SaveSubScene");
  84. saveFieldGui->setSpecialEditVariableName(fldnm);
  85. saveFieldGui->setInspectorField(NULL, fldnm);
  86. saveFieldGui->setDocs("");
  87. stack->addObject(saveFieldGui);
  88. GuiButtonCtrl* saveButton = new GuiButtonCtrl();
  89. saveButton->registerObject();
  90. saveButton->setDataField(StringTable->insert("profile"), NULL, "ToolsGuiButtonProfile");
  91. saveButton->setText("Save SubScene");
  92. saveButton->resize(Point2I::Zero, saveFieldGui->getExtent());
  93. saveButton->setHorizSizing(GuiControl::horizResizeWidth);
  94. saveButton->setVertSizing(GuiControl::vertResizeHeight);
  95. char szBuffer[512];
  96. dSprintf(szBuffer, 512, "%d.save();", this->getId());
  97. saveButton->setConsoleCommand(szBuffer);
  98. saveFieldGui->addObject(saveButton);
  99. }
  100. void SubScene::inspectPostApply()
  101. {
  102. Parent::inspectPostApply();
  103. setMaskBits(-1);
  104. }
  105. bool SubScene::testBox(const Box3F& testBox)
  106. {
  107. if (mGlobalLayer)
  108. return true;
  109. bool isOverlapped = getWorldBox().isOverlapped(testBox);
  110. return getWorldBox().isOverlapped(testBox);
  111. }
  112. void SubScene::write(Stream& stream, U32 tabStop, U32 flags)
  113. {
  114. MutexHandle handle;
  115. handle.lock(mMutex);
  116. // export selected only?
  117. if ((flags & SelectedOnly) && !isSelected())
  118. {
  119. for (U32 i = 0; i < size(); i++)
  120. (*this)[i]->write(stream, tabStop, flags);
  121. return;
  122. }
  123. stream.writeTabs(tabStop);
  124. char buffer[2048];
  125. const U32 bufferWriteLen = dSprintf(buffer, sizeof(buffer), "new %s(%s) {\r\n", getClassName(), getName() && !(flags & NoName) ? getName() : "");
  126. stream.write(bufferWriteLen, buffer);
  127. writeFields(stream, tabStop + 1);
  128. //The only meaningful difference between this and simSet for writing is we skip the children, since they're just the levelAsset contents
  129. stream.writeTabs(tabStop);
  130. stream.write(4, "};\r\n");
  131. }
  132. void SubScene::processTick(const Move* move)
  133. {
  134. }
  135. void SubScene::_onFileChanged(const Torque::Path& path)
  136. {
  137. if(mLevelAsset.isNull() || Torque::Path(mLevelAsset->getLevelPath()) != path)
  138. return;
  139. AssertFatal(path == mLevelAsset->getLevelPath(), "Prefab::_onFileChanged - path does not match filename.");
  140. _closeFile(false);
  141. _loadFile(false);
  142. setMaskBits(U32_MAX);
  143. }
  144. void SubScene::_closeFile(bool removeFileNotify)
  145. {
  146. AssertFatal(isServerObject(), "Trying to close out a subscene file on the client is bad!");
  147. U32 count = size();
  148. for (SimSetIterator itr(this); *itr; ++itr)
  149. {
  150. SimObject* child = dynamic_cast<SimObject*>(*itr);
  151. if (child)
  152. child->safeDeleteObject();
  153. }
  154. if (removeFileNotify && mLevelAsset.notNull() && mLevelAsset->getLevelPath() != StringTable->EmptyString())
  155. {
  156. Torque::FS::RemoveChangeNotification(mLevelAsset->getLevelPath(), this, &SubScene::_onFileChanged);
  157. }
  158. mGameModesList.clear();
  159. }
  160. void SubScene::_loadFile(bool addFileNotify)
  161. {
  162. AssertFatal(isServerObject(), "Trying to load a SubScene file on the client is bad!");
  163. if(mLevelAsset.isNull() || mLevelAsset->getLevelPath() == StringTable->EmptyString())
  164. return;
  165. String evalCmd = String::ToString("exec(\"%s\");", mLevelAsset->getLevelPath());
  166. String instantGroup = Con::getVariable("InstantGroup");
  167. Con::setIntVariable("InstantGroup", this->getId());
  168. Con::evaluate((const char*)evalCmd.c_str(), false, mLevelAsset->getLevelPath());
  169. Con::setVariable("InstantGroup", instantGroup.c_str());
  170. if (addFileNotify)
  171. Torque::FS::AddChangeNotification(mLevelAsset->getLevelPath(), this, &SubScene::_onFileChanged);
  172. }
  173. void SubScene::load()
  174. {
  175. mStartUnloadTimerMS = -1; //reset unload timers
  176. //no need to load multiple times
  177. if (mLoaded)
  178. return;
  179. _loadFile(true);
  180. mLoaded = true;
  181. GameMode::findGameModes(mGameModesNames, &mGameModesList);
  182. for (U32 i = 0; i < mGameModesList.size(); i++)
  183. {
  184. mGameModesList[i]->onSubsceneLoaded_callback();
  185. }
  186. }
  187. void SubScene::unload()
  188. {
  189. if (!mLoaded)
  190. return;
  191. if (isSelected())
  192. {
  193. mStartUnloadTimerMS = Sim::getCurrentTime();
  194. return; //if a child is selected, then we don't want to unload
  195. }
  196. //scan down through our child objects, see if any are marked as selected,
  197. //if so, skip unloading and reset the timer
  198. for (SimSetIterator itr(this); *itr; ++itr)
  199. {
  200. SimGroup* childGrp = dynamic_cast<SimGroup*>(*itr);
  201. if (childGrp && childGrp->isSelected())
  202. {
  203. mStartUnloadTimerMS = Sim::getCurrentTime();
  204. return; //if a child is selected, then we don't want to unload
  205. }
  206. for (SimSetIterator cldItr(childGrp); *cldItr; ++cldItr)
  207. {
  208. SimObject* chldChld = dynamic_cast<SimObject*>(*cldItr);
  209. if (chldChld && chldChld->isSelected())
  210. {
  211. mStartUnloadTimerMS = Sim::getCurrentTime();
  212. return; //if a child is selected, then we don't want to unload
  213. }
  214. }
  215. }
  216. _closeFile(true);
  217. mLoaded = false;
  218. for (U32 i = 0; i < mGameModesList.size(); i++)
  219. {
  220. mGameModesList[i]->onSubsceneUnloaded_callback();
  221. }
  222. }
  223. bool SubScene::save()
  224. {
  225. //if there's nothing TO save, don't bother
  226. if (size() == 0 || !isLoaded())
  227. return false;
  228. if (mLevelAsset.isNull())
  229. return false;
  230. //If we're flagged for unload, push back the unload timer so we can't accidentally trip be saving partway through an unload
  231. if (mStartUnloadTimerMS != -1)
  232. mStartUnloadTimerMS = Sim::getCurrentTime();
  233. StringTableEntry levelPath = mLevelAsset->getLevelPath();
  234. for (SimGroup::iterator itr = begin(); itr != end(); itr++)
  235. {
  236. //Just in case there's a valid callback the scene object would like to invoke for saving
  237. SceneObject* gc = dynamic_cast<SceneObject*>(*itr);
  238. if (gc)
  239. {
  240. gc->onSaving_callback(mLevelAssetId);
  241. }
  242. SimObject* sO = static_cast<SimObject*>(*itr);
  243. if (!sO->save(levelPath))
  244. {
  245. Con::errorf("SubScene::save() - error, failed to write object %s to file: %s", sO->getIdString(), levelPath);
  246. return false;
  247. }
  248. }
  249. //process our gameModeList and write it out to the levelAsset for metadata stashing
  250. bool saveSuccess = false;
  251. //Get the level asset
  252. if (mLevelAsset.isNull())
  253. return saveSuccess;
  254. //update the gamemode list as well
  255. mLevelAsset->setDataField(StringTable->insert("gameModesNames"), NULL, StringTable->insert(mGameModesNames));
  256. //Finally, save
  257. saveSuccess = mLevelAsset->saveAsset();
  258. }
  259. void SubScene::_onSelected()
  260. {
  261. if (!isLoaded() && isServerObject())
  262. load();
  263. }
  264. void SubScene::_onUnselected()
  265. {
  266. }
  267. void SubScene::prepRenderImage(SceneRenderState* state)
  268. {
  269. // only render if selected or render flag is set
  270. if (/*!smRenderTriggers && */!isSelected())
  271. return;
  272. ObjectRenderInst* ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  273. ri->renderDelegate.bind(this, &SubScene::renderObject);
  274. ri->type = RenderPassManager::RIT_Editor;
  275. ri->translucentSort = true;
  276. ri->defaultKey = 1;
  277. state->getRenderPass()->addInst(ri);
  278. }
  279. void SubScene::renderObject(ObjectRenderInst* ri,
  280. SceneRenderState* state,
  281. BaseMatInstance* overrideMat)
  282. {
  283. if (overrideMat)
  284. return;
  285. GFXStateBlockDesc desc;
  286. desc.setZReadWrite(true, false);
  287. desc.setBlend(true);
  288. // Trigger polyhedrons are set up with outward facing normals and CCW ordering
  289. // so can't enable backface culling.
  290. desc.setCullMode(GFXCullNone);
  291. GFXTransformSaver saver;
  292. MatrixF mat = getRenderTransform();
  293. GFX->multWorld(mat);
  294. GFXDrawUtil* drawer = GFX->getDrawUtil();
  295. //Box3F scale = getScale()
  296. //Box3F bounds = Box3F(-m)
  297. Point3F scale = getScale();
  298. Box3F bounds = Box3F(-scale/2, scale/2);
  299. ColorI boundsColor = ColorI(135, 206, 235, 50);
  300. if (mGlobalLayer)
  301. boundsColor = ColorI(200, 100, 100, 25);
  302. else if (mLoaded)
  303. boundsColor = ColorI(50, 200, 50, 50);
  304. drawer->drawCube(desc, bounds, boundsColor);
  305. // Render wireframe.
  306. desc.setFillModeWireframe();
  307. drawer->drawCube(desc, bounds, ColorI::BLACK);
  308. }
  309. DefineEngineMethod(SubScene, save, bool, (),,
  310. "Save out the subScene.\n")
  311. {
  312. return object->save();
  313. }
  314. DefineEngineMethod(SubScene, load, void, (), ,
  315. "Loads the SubScene's level file.\n")
  316. {
  317. object->load();
  318. }
  319. DefineEngineMethod(SubScene, unload, void, (), ,
  320. "Unloads the SubScene's level file.\n")
  321. {
  322. object->unload();
  323. }