Main.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include <windows.h>
  4. #include "BsApplication.h"
  5. #include "BsImporter.h"
  6. #include "BsTextureImportOptions.h"
  7. #include "BsMaterial.h"
  8. #include "BsShader.h"
  9. #include "BsVirtualInput.h"
  10. #include "BsCCamera.h"
  11. #include "BsCRenderable.h"
  12. #include "BsCGUIWidget.h"
  13. #include "BsGUILayoutX.h"
  14. #include "BsGUILayoutY.h"
  15. #include "BsGUISpace.h"
  16. #include "BsGUILabel.h"
  17. #include "BsGUIButton.h"
  18. #include "BsGUIPanel.h"
  19. #include "BsRenderAPI.h"
  20. #include "BsGUIListBox.h"
  21. #include "BsBuiltinResources.h"
  22. #include "BsRTTIType.h"
  23. #include "BsHString.h"
  24. #include "BsRenderWindow.h"
  25. #include "BsSceneObject.h"
  26. #include "BsCoreThread.h"
  27. #include "BsProfilerOverlay.h"
  28. #include "CameraFlyer.h"
  29. namespace BansheeEngine
  30. {
  31. UINT32 windowResWidth = 1280;
  32. UINT32 windowResHeight = 720;
  33. /**
  34. * Imports all of our assets and prepares GameObject that handle the example logic.
  35. */
  36. void setUpExample();
  37. /**
  38. * Import mesh/texture/GPU programs used by the example.
  39. */
  40. void importAssets(HMesh& model, HTexture& texture, HShader& shader);
  41. /**
  42. * Create a material used by our example model.
  43. */
  44. HMaterial createMaterial(const HTexture& texture, const HShader& shader);
  45. /**
  46. * Set up example scene objects.
  47. */
  48. void setUp3DScene(const HMesh& mesh, const HMaterial& material);
  49. /**
  50. * Set up example GUI.
  51. */
  52. void setUpGUI();
  53. /**
  54. * Set up input configuration and callbacks.
  55. */
  56. void setUpInput();
  57. /**
  58. * Toggles the primary window between full-screen and windowed mode.
  59. */
  60. void toggleFullscreen();
  61. /**
  62. * Called whenever the main render window is resized.
  63. */
  64. void renderWindowResized();
  65. /**
  66. * Called when the selected video mode changes in the video mode list box.
  67. */
  68. void videoModeChanged(UINT32 idx, bool enabled);
  69. /**
  70. * Triggered whenever a virtual button is released.
  71. */
  72. void buttonUp(const VirtualButton& button, UINT32 deviceIdx);
  73. }
  74. using namespace BansheeEngine;
  75. /**
  76. * Main entry point into the application.
  77. */
  78. int CALLBACK WinMain(
  79. _In_ HINSTANCE hInstance,
  80. _In_ HINSTANCE hPrevInstance,
  81. _In_ LPSTR lpCmdLine,
  82. _In_ int nCmdShow
  83. )
  84. {
  85. // Descriptor used for initializing the primary application window.
  86. RENDER_WINDOW_DESC renderWindowDesc;
  87. renderWindowDesc.videoMode = VideoMode(windowResWidth, windowResHeight);
  88. renderWindowDesc.title = "Banshee Example App";
  89. renderWindowDesc.fullscreen = false;
  90. // List of importer plugins we plan on using for importing various resources
  91. Vector<String> importers;
  92. importers.push_back("BansheeFreeImgImporter"); // For importing textures
  93. importers.push_back("BansheeFBXImporter"); // For importing meshes
  94. importers.push_back("BansheeFontImporter"); // For importing fonts
  95. importers.push_back("BansheeSL"); // For importing shaders
  96. // Initializes the application with primary window defined as above and DirectX 11 render system.
  97. // You may use other render systems than DirectX 11, however this example for simplicity only uses DirectX 11.
  98. // If you wanted other render systems you would need to create separate shaders for them and import them
  99. // along with (or replace) the DX11 ones.
  100. Application::startUp(renderWindowDesc, RenderAPIPlugin::DX11, RendererPlugin::Default, importers);
  101. // Imports all of ours assets and prepares GameObject that handle the example logic.
  102. setUpExample();
  103. // Runs the main loop that does most of the work. This method will exit when user closes the main
  104. // window or exits in some other way.
  105. Application::instance().runMainLoop();
  106. Application::shutDown();
  107. return 0;
  108. }
  109. namespace BansheeEngine
  110. {
  111. Path dataPath = Paths::getRuntimeDataPath();
  112. Path exampleModelPath = dataPath + "Examples\\Dragon.fbx";
  113. Path exampleTexturePath = dataPath + "Examples\\Dragon.tga";
  114. Path exampleShaderPath = dataPath + "Examples\\Example.bsl";
  115. GUIButton* toggleFullscreenButton = nullptr;
  116. bool fullscreen = false;
  117. const VideoMode* selectedVideoMode = nullptr;
  118. Vector<const VideoMode*> videoModes;
  119. HCamera sceneCamera;
  120. HProfilerOverlay profilerOverlay;
  121. VirtualButton toggleCPUProfilerBtn;
  122. VirtualButton toggleGPUProfilerBtn;
  123. bool cpuProfilerActive = false;
  124. bool gpuProfilerActive = false;
  125. void setUpExample()
  126. {
  127. HMesh exampleModel;
  128. HTexture exampleTexture;
  129. HShader exampleShader;
  130. importAssets(exampleModel, exampleTexture, exampleShader);
  131. HMaterial exampleMaterial = createMaterial(exampleTexture, exampleShader);
  132. setUp3DScene(exampleModel, exampleMaterial);
  133. setUpGUI();
  134. setUpInput();
  135. }
  136. void importAssets(HMesh& model, HTexture& texture, HShader& shader)
  137. {
  138. // Import mesh, texture and shader from the disk. In a normal application you would want to save the imported assets
  139. // so next time the application is ran you can just load them directly. This can be done with Resources::save/load.
  140. // Import an FBX mesh.
  141. model = Importer::instance().import<Mesh>(exampleModelPath);
  142. // When importing you may specify optional import options that control how is the asset imported.
  143. ImportOptionsPtr textureImportOptions = Importer::instance().createImportOptions(exampleTexturePath);
  144. // rtti_is_of_type checks if the import options are of valid type, in case the provided path is pointing to a non-texture resource.
  145. // This is similar to dynamic_cast but uses Banshee internal RTTI system for type checking.
  146. if (rtti_is_of_type<TextureImportOptions>(textureImportOptions))
  147. {
  148. TextureImportOptions* importOptions = static_cast<TextureImportOptions*>(textureImportOptions.get());
  149. // We want maximum number of mipmaps to be generated
  150. importOptions->setGenerateMipmaps(true);
  151. }
  152. // Import texture with specified import options
  153. texture = Importer::instance().import<Texture>(exampleTexturePath, textureImportOptions);
  154. // Import shader
  155. shader = Importer::instance().import<Shader>(exampleShaderPath);
  156. }
  157. HMaterial createMaterial(const HTexture& texture, const HShader& shader)
  158. {
  159. // And finally create a material with the newly created shader
  160. HMaterial exampleMaterial = Material::create(shader);
  161. // And set the texture to be used by the "tex" shader parameter. We leave the "samp"
  162. // parameter at its defaults.
  163. exampleMaterial->setTexture("tex", texture);
  164. return exampleMaterial;
  165. }
  166. void setUp3DScene(const HMesh& mesh, const HMaterial& material)
  167. {
  168. /************************************************************************/
  169. /* SCENE OBJECT */
  170. /************************************************************************/
  171. // Now we create a scene object that has a position, orientation, scale and optionally
  172. // components to govern its logic. In this particular case we are creating a SceneObject
  173. // with a Renderable component which will render a mesh at the position of the scene object
  174. // with the provided material.
  175. // Create new scene object at (0, 0, 0)
  176. HSceneObject dragonSO = SceneObject::create("Dragon");
  177. // Attach the Renderable component and hook up the mesh we imported earlier,
  178. // and the material we created in the previous section.
  179. HRenderable renderable = dragonSO->addComponent<CRenderable>();
  180. renderable->setMesh(mesh);
  181. renderable->setMaterial(material);
  182. /************************************************************************/
  183. /* CAMERA */
  184. /************************************************************************/
  185. // In order something to render on screen we need at least one camera.
  186. // Like before, we create a new scene object at (0, 0, 0).
  187. HSceneObject sceneCameraSO = SceneObject::create("SceneCamera");
  188. // Get the primary render window we need for creating the camera. Additionally
  189. // hook up a callback so we are notified when user resizes the window.
  190. RenderWindowPtr window = gApplication().getPrimaryWindow();
  191. window->onResized.connect(&renderWindowResized);
  192. // Add a Camera component that will output whatever it sees into that window
  193. // (You could also use a render texture or another window you created).
  194. sceneCamera = sceneCameraSO->addComponent<CCamera>(window);
  195. // Set up camera component properties
  196. // Priority determines in what order are cameras rendered in case multiple cameras render to the same render target.
  197. // We raise the priority slightly because later in code we have defined a GUI camera that we want to render second.
  198. sceneCamera->setPriority(1);
  199. // Set closest distance that is visible. Anything below that is clipped.
  200. sceneCamera->setNearClipDistance(5);
  201. // Set aspect ratio depending on the current resolution
  202. sceneCamera->setAspectRatio(windowResWidth / (float)windowResHeight);
  203. // Add a CameraFlyer component that allows us to move the camera. See CameraFlyer for more information.
  204. sceneCameraSO->addComponent<CameraFlyer>();
  205. // Position and orient the camera scene object
  206. sceneCameraSO->setPosition(Vector3(-130.0f, 140.0f, 650.0f));
  207. sceneCameraSO->lookAt(Vector3(0, 0, 0));
  208. }
  209. void setUpInput()
  210. {
  211. // Register input configuration
  212. // Banshee allows you to use VirtualInput system which will map input device buttons
  213. // and axes to arbitrary names, which allows you to change input buttons without affecting
  214. // the code that uses it, since the code is only aware of the virtual names.
  215. // If you want more direct input, see Input class.
  216. auto inputConfig = VirtualInput::instance().getConfiguration();
  217. // Camera controls for buttons (digital 0-1 input, e.g. keyboard or gamepad button)
  218. inputConfig->registerButton("Forward", BC_W);
  219. inputConfig->registerButton("Back", BC_S);
  220. inputConfig->registerButton("Left", BC_A);
  221. inputConfig->registerButton("Right", BC_D);
  222. inputConfig->registerButton("Forward", BC_UP);
  223. inputConfig->registerButton("Back", BC_BACK);
  224. inputConfig->registerButton("Left", BC_LEFT);
  225. inputConfig->registerButton("Right", BC_RIGHT);
  226. inputConfig->registerButton("FastMove", BC_LSHIFT);
  227. inputConfig->registerButton("RotateCam", BC_MOUSE_RIGHT);
  228. // Camera controls for axes (analog input, e.g. mouse or gamepad thumbstick)
  229. // These return values in [-1.0, 1.0] range.
  230. inputConfig->registerAxis("Horizontal", VIRTUAL_AXIS_DESC((UINT32)InputAxis::MouseX));
  231. inputConfig->registerAxis("Vertical", VIRTUAL_AXIS_DESC((UINT32)InputAxis::MouseY));
  232. // Controls that toggle the profiler overlays
  233. inputConfig->registerButton("CPUProfilerOverlay", BC_F1);
  234. inputConfig->registerButton("GPUProfilerOverlay", BC_F2);
  235. // Cache the profiler overlay buttons so when a button is pressed we can quickly
  236. // use these to determine its the one we want
  237. toggleCPUProfilerBtn = VirtualButton("CPUProfilerOverlay");
  238. toggleGPUProfilerBtn = VirtualButton("GPUProfilerOverlay");
  239. // Hook up a callback that gets triggered whenever a virtual button is released
  240. VirtualInput::instance().onButtonUp.connect(&buttonUp);
  241. }
  242. void setUpGUI()
  243. {
  244. // Create a scene object that will contain GUI components
  245. HSceneObject guiSO = SceneObject::create("Example");
  246. // Get the primary render window we need for creating the camera.
  247. RenderWindowPtr window = gApplication().getPrimaryWindow();
  248. // First we want another camera that is responsible for rendering GUI
  249. HCamera guiCamera = guiSO->addComponent<CCamera>(window);
  250. // Notify the renderer that the camera will only be used for overlays (e.g. GUI) so it can optimize its usage
  251. guiCamera->setFlags(CameraFlags::Overlay);
  252. // Set up GUI camera properties.
  253. // We don't care about aspect ratio for GUI camera.
  254. guiCamera->setAspectRatio(1.0f);
  255. // This camera should ignore any Renderable objects in the scene
  256. guiCamera->setLayers(0);
  257. // Don't clear this camera as that would clear anything the main camera has rendered.
  258. guiCamera->getViewport()->setRequiresClear(false, false, false);
  259. // Add a GUIWidget, the top-level GUI component, parent to all GUI elements. GUI widgets
  260. // require you to specify a viewport that they will output rendered GUI elements to.
  261. HGUIWidget gui = guiSO->addComponent<CGUIWidget>(guiCamera);
  262. // Depth allows you to control how is a GUI widget rendered in relation to other widgets
  263. // Lower depth means the widget will be rendered in front of those with higher. In this case we just
  264. // make the depth mid-range as there are no other widgets.
  265. gui->setDepth(128);
  266. // GUI skin defines how are all child elements of the GUI widget renderered. It contains all their styles
  267. // and default layout properties. We use the default skin that comes built into Banshee.
  268. gui->setSkin(BuiltinResources::instance().getGUISkin());
  269. // Get the primary GUI panel that stretches over the entire window and add to it a vertical layout
  270. // that will be using for vertically positioning messages about toggling profiler overlay.
  271. GUILayout* bottomLayout = gui->getPanel()->addNewElement<GUILayoutY>();
  272. // Add a flexible space that fills up any remaining area in the layout, making the two labels above be aligned
  273. // to the bottom of the GUI widget (and the screen).
  274. bottomLayout->addNewElement<GUIFlexibleSpace>();
  275. // Add a couple of labels to the layout with the needed messages. Labels expect a HString object that
  276. // maps into a string table and allows for easily localization.
  277. bottomLayout->addElement(GUILabel::create(HString(L"Press F1 to toggle CPU profiler overlay")));
  278. bottomLayout->addElement(GUILabel::create(HString(L"Press F2 to toggle GPU profiler overlay")));
  279. // Create a GUI panel that is used for displaying resolution and fullscreen options.
  280. GUILayout* rightLayout = gui->getPanel()->addNewElement<GUILayoutX>();
  281. rightLayout->setPosition(30, 30);
  282. // We want all the GUI elements be right aligned, so we add a flexible space first.
  283. rightLayout->addNewElement<GUIFlexibleSpace>();
  284. // And we want the elements to be vertically placed, top to bottom
  285. GUILayout* elemLayout = rightLayout->addNewElement<GUILayoutY>();
  286. // Add a button that will trigger a callback when clicked
  287. toggleFullscreenButton = GUIButton::create(HString(L"Toggle fullscreen"));
  288. toggleFullscreenButton->onClick.connect(&toggleFullscreen);
  289. elemLayout->addElement(toggleFullscreenButton);
  290. // Leave 30 pixels to the right free
  291. rightLayout->addNewElement<GUIFixedSpace>(30);
  292. // Add a profiler overlay object that is responsible for displaying CPU and GPU profiling GUI
  293. profilerOverlay = guiSO->addComponent<ProfilerOverlay>(guiCamera->_getCamera());
  294. // Set up video mode list box
  295. // First get a list of output devices
  296. const VideoModeInfo& videoModeInfo = RenderAPI::getVideoModeInfo();
  297. // Get video mode info for the primary monitor
  298. const VideoOutputInfo& primaryMonitorInfo = videoModeInfo.getOutputInfo(0);
  299. // Make the current desktop mode the default video mode
  300. selectedVideoMode = &primaryMonitorInfo.getDesktopVideoMode();
  301. // Create list box elements for each available video mode
  302. UINT32 numVideoModes = primaryMonitorInfo.getNumVideoModes();
  303. Vector<HString> videoModeLabels(numVideoModes);
  304. UINT32 selectedVideoModeIdx = 0;
  305. for (UINT32 i = 0; i < numVideoModes; i++)
  306. {
  307. const VideoMode& curVideoMode = primaryMonitorInfo.getVideoMode(i);
  308. HString videoModeLabel(L"{0} x {1} at {2}Hz");
  309. videoModeLabel.setParameter(0, toWString(curVideoMode.getWidth()));
  310. videoModeLabel.setParameter(1, toWString(curVideoMode.getHeight()));
  311. videoModeLabel.setParameter(2, toWString(Math::roundToInt(curVideoMode.getRefreshRate())));
  312. videoModeLabels[i] = videoModeLabel;
  313. videoModes.push_back(&curVideoMode);
  314. if (curVideoMode == *selectedVideoMode)
  315. selectedVideoModeIdx = i;
  316. }
  317. // Create the list box
  318. GUIListBox* videoModeListBox = GUIListBox::create(videoModeLabels);
  319. rightLayout->addElement(videoModeListBox);
  320. // Select the default (desktop) video mode
  321. videoModeListBox->selectElement(selectedVideoModeIdx);
  322. // Set up a callback to be notified when video mode changes
  323. videoModeListBox->onSelectionToggled.connect(&videoModeChanged);
  324. }
  325. void toggleFullscreen()
  326. {
  327. RenderWindowPtr window = gApplication().getPrimaryWindow();
  328. // In order to toggle between full-screen and windowed mode we need to use a CoreAccessor.
  329. // Banshee is a multi-threaded engine and when you need to communicate between simulation and
  330. // core thread you will use a CoreAccessor. Calling a core accessor method will essentially
  331. // queue the method to be executed later. Since RenderWindow is a core object you need to use
  332. // CoreAccessor to modify and access it from simulation thread, except where noted otherwise.
  333. // Classes where it is not clear if they are to be used on the core or simulation thread have
  334. // it noted in their documentation. e.g. RenderWindow::setWindowed method is marked as "Core only".
  335. // Additional asserts are normally in place for debug builds which make it harder for you to accidentally
  336. // call something from the wrong thread.
  337. if (fullscreen)
  338. {
  339. window->setWindowed(gCoreAccessor(), windowResWidth, windowResHeight);
  340. }
  341. else
  342. {
  343. window->setFullscreen(gCoreAccessor(), *selectedVideoMode);
  344. }
  345. fullscreen = !fullscreen;
  346. }
  347. void renderWindowResized()
  348. {
  349. RenderWindowPtr window = gApplication().getPrimaryWindow();
  350. const RenderWindowProperties& rwProps = window->getProperties();
  351. if (!fullscreen)
  352. {
  353. windowResWidth = rwProps.getWidth();
  354. windowResHeight = rwProps.getHeight();
  355. }
  356. sceneCamera->setAspectRatio(rwProps.getWidth() / (float)rwProps.getHeight());
  357. }
  358. void videoModeChanged(UINT32 idx, bool enabled)
  359. {
  360. if (!enabled)
  361. return;
  362. selectedVideoMode = videoModes[idx];
  363. if (fullscreen)
  364. {
  365. RenderWindowPtr window = gApplication().getPrimaryWindow();
  366. window->setFullscreen(gCoreAccessor(), *selectedVideoMode);
  367. }
  368. }
  369. void buttonUp(const VirtualButton& button, UINT32 deviceIdx)
  370. {
  371. // Check if the pressed button is one of the either buttons we defined
  372. // in "setUpExample", and toggle profiler overlays accordingly.
  373. // Device index is ignored for now, as it is assumed the user is using a single keyboard,
  374. // but if you wanted support for multiple gamepads you would check deviceIdx.
  375. if (button == toggleCPUProfilerBtn)
  376. {
  377. if (cpuProfilerActive)
  378. {
  379. profilerOverlay->hide();
  380. cpuProfilerActive = false;
  381. }
  382. else
  383. {
  384. profilerOverlay->show(ProfilerOverlayType::CPUSamples);
  385. cpuProfilerActive = true;
  386. gpuProfilerActive = false;
  387. }
  388. }
  389. else if (button == toggleGPUProfilerBtn)
  390. {
  391. if (gpuProfilerActive)
  392. {
  393. profilerOverlay->hide();
  394. gpuProfilerActive = false;
  395. }
  396. else
  397. {
  398. profilerOverlay->show(ProfilerOverlayType::GPUSamples);
  399. gpuProfilerActive = true;
  400. cpuProfilerActive = false;
  401. }
  402. }
  403. }
  404. }