Main.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. #include <windows.h>
  2. #include "BsApplication.h"
  3. #include "BsImporter.h"
  4. #include "BsGpuProgramImportOptions.h"
  5. #include "BsTextureImportOptions.h"
  6. #include "BsMaterial.h"
  7. #include "BsShader.h"
  8. #include "BsTechnique.h"
  9. #include "BsPass.h"
  10. #include "BsCoreThreadAccessor.h"
  11. #include "BsApplication.h"
  12. #include "BsVirtualInput.h"
  13. #include "BsCamera.h"
  14. #include "BsRenderable.h"
  15. #include "BsGUIWidget.h"
  16. #include "BsGUIArea.h"
  17. #include "BsGUILayoutX.h"
  18. #include "BsGUILayoutY.h"
  19. #include "BsGUISpace.h"
  20. #include "BsGUILabel.h"
  21. #include "BsGUIButton.h"
  22. #include "BsGUIListBox.h"
  23. #include "BsBuiltinResources.h"
  24. #include "BsRTTIType.h"
  25. #include "BsHString.h"
  26. #include "BsRenderWindow.h"
  27. #include "BsSceneObject.h"
  28. #include "BsCoreThread.h"
  29. #include "BsProfilerOverlay.h"
  30. #include "BsRenderer.h"
  31. #include "BsResources.h"
  32. #include "CameraFlyer.h"
  33. namespace BansheeEngine
  34. {
  35. UINT32 windowResWidth = 1280;
  36. UINT32 windowResHeight = 720;
  37. /**
  38. * Imports all of our assets and prepares GameObject that handle the example logic.
  39. */
  40. void setUpExample();
  41. /**
  42. * Toggles the primary window between full-screen and windowed mode.
  43. */
  44. void toggleFullscreen();
  45. /**
  46. * Called whenever the main render window is resized.
  47. */
  48. void renderWindowResized();
  49. /**
  50. * Called when the selected video mode changes in the video mode list box.
  51. */
  52. void videoModeChanged(UINT32 idx);
  53. /**
  54. * Triggered whenever a virtual button is released.
  55. */
  56. void buttonUp(const VirtualButton& button, UINT32 deviceIdx);
  57. }
  58. using namespace BansheeEngine;
  59. /**
  60. * Main entry point into the application.
  61. */
  62. int CALLBACK WinMain(
  63. _In_ HINSTANCE hInstance,
  64. _In_ HINSTANCE hPrevInstance,
  65. _In_ LPSTR lpCmdLine,
  66. _In_ int nCmdShow
  67. )
  68. {
  69. // Descriptor used for initializing the primary application window.
  70. RENDER_WINDOW_DESC renderWindowDesc;
  71. renderWindowDesc.videoMode = VideoMode(windowResWidth, windowResHeight);
  72. renderWindowDesc.title = "Banshee Example App";
  73. renderWindowDesc.fullscreen = false;
  74. // Initializes the application with primary window defined as above and DirectX 11 render system.
  75. // You may use other render systems than DirectX 11, however this example for simplicity only uses DirectX 11.
  76. // If you wanted other render systems you would need to create separate shaders for them and import them
  77. // along with (or replace) the DX11 ones.
  78. Application::startUp(renderWindowDesc, RenderSystemPlugin::DX11);
  79. // Imports all of ours assets and prepares GameObject that handle the example logic.
  80. setUpExample();
  81. // Runs the main loop that does most of the work. This method will exit when user closes the main
  82. // window or exits in some other way.
  83. Application::instance().runMainLoop();
  84. Application::shutDown();
  85. return 0;
  86. }
  87. namespace BansheeEngine
  88. {
  89. Path exampleModelPath = "..\\..\\..\\..\\Data\\Examples\\Pyromancer.fbx";
  90. Path exampleTexturePath = "..\\..\\..\\..\\Data\\Examples\\Pyromancer.psd";
  91. Path exampleFragmentShaderPath = "..\\..\\..\\..\\Data\\Examples\\example_fs.gpuprog";
  92. Path exampleVertexShaderPath = "..\\..\\..\\..\\Data\\Examples\\example_vs.gpuprog";
  93. GUIButton* toggleFullscreenButton = nullptr;
  94. bool fullscreen = false;
  95. const VideoMode* selectedVideoMode = nullptr;
  96. Vector<const VideoMode*> videoModes;
  97. HMesh exampleModel;
  98. HTexture exampleTexture;
  99. HGpuProgram exampleFragmentGPUProg;
  100. HGpuProgram exampleVertexGPUProg;
  101. HCamera sceneCamera;
  102. HProfilerOverlay profilerOverlay;
  103. VirtualButton toggleCPUProfilerBtn;
  104. VirtualButton toggleGPUProfilerBtn;
  105. bool cpuProfilerActive = false;
  106. bool gpuProfilerActive = false;
  107. void setUpExample()
  108. {
  109. /************************************************************************/
  110. /* IMPORT ASSETS */
  111. /************************************************************************/
  112. // Import mesh, texture and shader from the disk. In a normal application you would want to save the imported assets
  113. // so next time the application is ran you can just load them directly. This can be done with Resources::save/load.
  114. // Import an FBX mesh.
  115. exampleModel = Importer::instance().import<Mesh>(exampleModelPath);
  116. // When importing you may specify optional import options that control how is the asset imported.
  117. ImportOptionsPtr textureImportOptions = Importer::instance().createImportOptions(exampleTexturePath);
  118. // 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.
  119. // This is similar to dynamic_cast but uses Banshee internal RTTI system for type checking.
  120. if (rtti_is_of_type<TextureImportOptions>(textureImportOptions))
  121. {
  122. TextureImportOptions* importOptions = static_cast<TextureImportOptions*>(textureImportOptions.get());
  123. // We want maximum number of mipmaps to be generated
  124. importOptions->setGenerateMipmaps(true);
  125. }
  126. // Import texture with specified import options
  127. exampleTexture = Importer::instance().import<Texture>(exampleTexturePath, textureImportOptions);
  128. // Create import options for fragment GPU program
  129. ImportOptionsPtr gpuProgImportOptions = Importer::instance().createImportOptions(exampleFragmentShaderPath);
  130. if (rtti_is_of_type<GpuProgramImportOptions>(gpuProgImportOptions))
  131. {
  132. GpuProgramImportOptions* importOptions = static_cast<GpuProgramImportOptions*>(gpuProgImportOptions.get());
  133. // Name of the entry function in the GPU program
  134. importOptions->setEntryPoint("ps_main");
  135. // Language the GPU program is written in. Can only be hlsl for DX11
  136. importOptions->setLanguage("hlsl");
  137. // GPU program profile specifying what feature-set the shader code uses.
  138. importOptions->setProfile(GPP_PS_4_0);
  139. // Type of the shader.
  140. importOptions->setType(GPT_FRAGMENT_PROGRAM);
  141. }
  142. // Import fragment GPU program
  143. exampleFragmentGPUProg = Importer::instance().import<GpuProgram>(exampleFragmentShaderPath, gpuProgImportOptions);
  144. // Create import options for vertex GPU program. Similar as above.
  145. gpuProgImportOptions = Importer::instance().createImportOptions(exampleVertexShaderPath);
  146. if (rtti_is_of_type<GpuProgramImportOptions>(gpuProgImportOptions))
  147. {
  148. GpuProgramImportOptions* importOptions = static_cast<GpuProgramImportOptions*>(gpuProgImportOptions.get());
  149. importOptions->setEntryPoint("vs_main");
  150. importOptions->setLanguage("hlsl");
  151. importOptions->setProfile(GPP_VS_4_0);
  152. importOptions->setType(GPT_VERTEX_PROGRAM);
  153. }
  154. // Import vertex GPU program
  155. exampleVertexGPUProg = Importer::instance().import<GpuProgram>(exampleVertexShaderPath, gpuProgImportOptions);
  156. /************************************************************************/
  157. /* CREATE SHADER */
  158. /************************************************************************/
  159. // Create a shader that references our vertex and fragment GPU programs, and set
  160. // up shader input parameters.
  161. ShaderPtr exampleShader = Shader::create("ExampleShader");
  162. // Set up shader parameters and renderer semantics.
  163. // Renderer semantics allow our renderer to automatically populate certain shader parameters (e.g. a world view projection matrix).
  164. // These semantics are purely optional and depend on the renderer used. Certain renderers expect certain semantics to be set up
  165. // otherwise they will not render the objects. You always have the option to populate all the parameters manually, but in this example
  166. // we go with the semantics route as it allows for a "set up and forget" approach.
  167. // Add a world view projection matrix parameter, which will be populated by the renderer.
  168. // We map our shader parameter name to the actual GPU program variable, both being "matWorldViewProj" in this case.
  169. exampleShader->addParameter("matWorldViewProj", "matWorldViewProj", GPDT_MATRIX_4X4, RPS_WorldViewProjTfrm);
  170. // Add a sampler and a texture semantic that we will populate manually.
  171. exampleShader->addParameter("samp", "samp", GPOT_SAMPLER2D);
  172. exampleShader->addParameter("tex", "tex", GPOT_TEXTURE2D);
  173. // Our GPU programs use parameter blocks (constant buffers in DX11 lingo). Here we notify the renderer
  174. // that this particular parameter block contains object-specific data (like the world view projection parameter
  175. // we defined above).
  176. exampleShader->setParamBlockAttribs("PerObject", true, GPBU_DYNAMIC, RBS_PerObject);
  177. /************************************************************************/
  178. /* CREATE MATERIAL */
  179. /************************************************************************/
  180. // Create a shader technique. Shader can have many different techniques and the renderer will automatically
  181. // use the most appropriate technique depending on the active renderer and render system. e.g. you can have different
  182. // techniques using HLSL9, HLSL11 and GLSL GPU programs for DirectX 9, DirectX 11 and OpenGL render systems respectively.
  183. TechniquePtr technique = exampleShader->addTechnique(RenderSystemDX11, RendererDefault);
  184. // Add a new pass to the technique. Each technique can have multiple passes that allow you to render the same
  185. // object multiple times using different GPU programs.
  186. PassPtr pass = technique->addPass();
  187. pass->setVertexProgram(exampleVertexGPUProg);
  188. pass->setFragmentProgram(exampleFragmentGPUProg);
  189. // And finally create a material with the newly created shader
  190. HMaterial exampleMaterial = Material::create(exampleShader);
  191. // And set the texture to be used by the "tex" shader parameter. We leave the "samp"
  192. // parameter at its defaults.
  193. exampleMaterial->setTexture("tex", exampleTexture);
  194. /************************************************************************/
  195. /* SCENE OBJECT */
  196. /************************************************************************/
  197. // Now we create a scene object that has a position, orientation, scale and optionally
  198. // components to govern its logic. In this particular case we are creating a SceneObject
  199. // with a Renderable component which will render a mesh at the position of the scene object
  200. // with the provided material.
  201. // Create new scene object at (0, 0, 0)
  202. HSceneObject pyromancerSO = SceneObject::create("Pyromancer");
  203. // Attach the Renderable component and hook up the mesh we imported earlier,
  204. // and the material we created in the previous section.
  205. HRenderable renderable = pyromancerSO->addComponent<Renderable>();
  206. renderable->setMesh(exampleModel);
  207. renderable->setMaterial(exampleMaterial);
  208. /************************************************************************/
  209. /* CAMERA */
  210. /************************************************************************/
  211. // In order something to render on screen we need at least one camera.
  212. // Like before, we create a new scene object at (0, 0, 0).
  213. HSceneObject sceneCameraSO = SceneObject::create("SceneCamera");
  214. // Get the primary render window we need for creating the camera. Additionally
  215. // hook up a callback so we are notified when user resizes the window.
  216. RenderWindowPtr window = gApplication().getPrimaryWindow();
  217. window->onResized.connect(&renderWindowResized);
  218. // Add a Camera component that will output whatever it sees into that window
  219. // (You could also use a render texture or another window you created).
  220. sceneCamera = sceneCameraSO->addComponent<Camera>(window);
  221. // Set up camera component properties
  222. // Priority determines in what order are cameras rendered in case multiple cameras render to the same render target.
  223. // We raise the priority slightly because later in code we have defined a GUI camera that we want to render second.
  224. sceneCamera->setPriority(1);
  225. // Set closest distance that is visible. Anything below that is clipped.
  226. sceneCamera->setNearClipDistance(5);
  227. // Set aspect ratio depending on the current resolution
  228. sceneCamera->setAspectRatio(windowResWidth / (float)windowResHeight);
  229. // Add a CameraFlyer component that allows us to move the camera. See CameraFlyer for more information.
  230. sceneCameraSO->addComponent<CameraFlyer>();
  231. // Position and orient the camera scene object
  232. sceneCameraSO->setPosition(Vector3(40.0f, 30.0f, 230.0f));
  233. sceneCameraSO->lookAt(Vector3(0, 0, 0));
  234. /************************************************************************/
  235. /* INPUT */
  236. /************************************************************************/
  237. // Register input configuration
  238. // Banshee allows you to use VirtualInput system which will map input device buttons
  239. // and axes to arbitrary names, which allows you to change input buttons without affecting
  240. // the code that uses it, since the code is only aware of the virtual names.
  241. // If you want more direct input, see Input class.
  242. auto inputConfig = VirtualInput::instance().getConfiguration();
  243. // Camera controls for buttons (digital 0-1 input, e.g. keyboard or gamepad button)
  244. inputConfig->registerButton("Forward", BC_W);
  245. inputConfig->registerButton("Back", BC_S);
  246. inputConfig->registerButton("Left", BC_A);
  247. inputConfig->registerButton("Right", BC_D);
  248. inputConfig->registerButton("Forward", BC_UP);
  249. inputConfig->registerButton("Back", BC_BACK);
  250. inputConfig->registerButton("Left", BC_LEFT);
  251. inputConfig->registerButton("Right", BC_RIGHT);
  252. inputConfig->registerButton("FastMove", BC_LSHIFT);
  253. inputConfig->registerButton("RotateCam", BC_MOUSE_RIGHT);
  254. // Camera controls for axes (analog input, e.g. mouse or gamepad thumbstick)
  255. // These return values in [-1.0, 1.0] range.
  256. inputConfig->registerAxis("Horizontal", VIRTUAL_AXIS_DESC((UINT32)InputAxis::MouseX));
  257. inputConfig->registerAxis("Vertical", VIRTUAL_AXIS_DESC((UINT32)InputAxis::MouseY));
  258. // Controls that toggle the profiler overlays
  259. inputConfig->registerButton("CPUProfilerOverlay", BC_F1);
  260. inputConfig->registerButton("GPUProfilerOverlay", BC_F2);
  261. // Cache the profiler overlay buttons so when a button is pressed we can quickly
  262. // use these to determine its the one we want
  263. toggleCPUProfilerBtn = VirtualButton("CPUProfilerOverlay");
  264. toggleGPUProfilerBtn = VirtualButton("GPUProfilerOverlay");
  265. // Hook up a callback that gets triggered whenever a virtual button is released
  266. VirtualInput::instance().onButtonUp.connect(&buttonUp);
  267. /************************************************************************/
  268. /* GUI */
  269. /************************************************************************/
  270. // Create a scene object that will contain GUI components
  271. HSceneObject guiSO = SceneObject::create("Example");
  272. // First we want another camera that is responsible for rendering GUI
  273. HCamera guiCamera = guiSO->addComponent<Camera>(window);
  274. // Set up GUI camera properties.
  275. // We don't care about aspect ratio for GUI camera.
  276. guiCamera->setAspectRatio(1.0f);
  277. // This camera should ignore any Renderable objects in the scene
  278. guiCamera->setIgnoreSceneRenderables(true);
  279. // Don't clear this camera as that would clear anything the main camera has rendered.
  280. guiCamera->getViewport()->setRequiresClear(false, false, false);
  281. // Add a GUIWidget, the top-level GUI component, parent to all GUI elements. GUI widgets
  282. // require you to specify a viewport that they will output rendered GUI elements to.
  283. HGUIWidget gui = guiSO->addComponent<GUIWidget>(guiCamera->getViewport().get());
  284. // Depth allows you to control how is a GUI widget rendered in relation to other widgets
  285. // Lower depth means the widget will be rendered in front of those with higher. In this case we just
  286. // make the depth mid-range as there are no other widgets.
  287. gui->setDepth(128);
  288. // GUI skin defines how are all child elements of the GUI widget renderered. It contains all their styles
  289. // and default layout properties. We use the default skin that comes built into Banshee.
  290. gui->setSkin(BuiltinResources::instance().getGUISkin());
  291. // Create a GUI area that is used for displaying messages about toggling profiler overlays.
  292. // This area will stretch the entire surface of its parent widget, even if the widget is resized.
  293. GUIArea* topArea = GUIArea::createStretchedXY(*gui, 0, 0, 0, 0);
  294. // Add a vertical layout that will automatically position any child elements top to bottom.
  295. GUILayout& topLayout = topArea->getLayout().addLayoutY();
  296. // Add a couple of labels to the layout with the needed messages. Labels expect a HString object that
  297. // maps into a string table and allows for easily localization.
  298. topLayout.addElement(GUILabel::create(HString(L"Press F1 to toggle CPU profiler overlay")));
  299. topLayout.addElement(GUILabel::create(HString(L"Press F2 to toggle GPU profiler overlay")));
  300. // Add a flexible space that fills up any remaining area in the layout, making the two labels above be aligned
  301. // to the top of the GUI widget (and the screen).
  302. topLayout.addFlexibleSpace();
  303. // Create a GUI area that is used for displaying resolution and fullscreen options.
  304. GUIArea* rightArea = GUIArea::createStretchedXY(*gui, 0, 0, 0, 0);
  305. // We want all the GUI elements be right aligned, so we add a flexible space first.
  306. rightArea->getLayout().addFlexibleSpace();
  307. // And we want the elements to be vertically placed, top to bottom
  308. GUILayout& rightLayout = rightArea->getLayout().addLayoutY();
  309. // Add an empty space of 50 pixels
  310. rightLayout.addSpace(50);
  311. // Add a button that will trigger a callback when clicked
  312. toggleFullscreenButton = GUIButton::create(HString(L"Toggle fullscreen"));
  313. toggleFullscreenButton->onClick.connect(&toggleFullscreen);
  314. rightLayout.addElement(toggleFullscreenButton);
  315. // Add a profiler overlay object that is resposible for displaying CPU and GPU profiling GUI
  316. profilerOverlay = guiSO->addComponent<ProfilerOverlay>(guiCamera->getViewport());
  317. // Set up video mode list box
  318. // First get a list of output devices
  319. const VideoModeInfo& videoModeInfo = RenderSystem::instance().getVideoModeInfo();
  320. // Get video mode info for the primary monitor
  321. const VideoOutputInfo& primaryMonitorInfo = videoModeInfo.getOutputInfo(0);
  322. // Make the current desktop mode the default video mode
  323. selectedVideoMode = &primaryMonitorInfo.getDesktopVideoMode();
  324. // Create list box elements for each available video mode
  325. UINT32 numVideoModes = primaryMonitorInfo.getNumVideoModes();
  326. Vector<HString> videoModeLabels(numVideoModes);
  327. UINT32 selectedVideoModeIdx = 0;
  328. for (UINT32 i = 0; i < numVideoModes; i++)
  329. {
  330. const VideoMode& curVideoMode = primaryMonitorInfo.getVideoMode(i);
  331. HString videoModeLabel(L"{0} x {1} at {2}Hz");
  332. videoModeLabel.setParameter(0, toWString(curVideoMode.getWidth()));
  333. videoModeLabel.setParameter(1, toWString(curVideoMode.getHeight()));
  334. videoModeLabel.setParameter(2, toWString(Math::roundToInt(curVideoMode.getRefreshRate())));
  335. videoModeLabels[i] = videoModeLabel;
  336. videoModes.push_back(&curVideoMode);
  337. if (curVideoMode == *selectedVideoMode)
  338. selectedVideoModeIdx = i;
  339. }
  340. // Create the list box
  341. GUIListBox* videoModeListBox = GUIListBox::create(videoModeLabels);
  342. rightLayout.addElement(videoModeListBox);
  343. // Select the default (desktop) video mode
  344. videoModeListBox->selectElement(selectedVideoModeIdx);
  345. // Set up a callback to be notified when video mode changes
  346. videoModeListBox->onSelectionChanged.connect(&videoModeChanged);
  347. }
  348. void toggleFullscreen()
  349. {
  350. RenderWindowPtr window = gApplication().getPrimaryWindow();
  351. // In order to toggle between full-screen and windowed mode we need to use a CoreAccessor.
  352. // Banshee is a multi-threaded engine and when you need to communicate between simulation and
  353. // core thread you will use a CoreAccessor. Calling a core accessor method will essentially
  354. // queue the method to be executed later. Since RenderWindow is a core object you need to use
  355. // CoreAccessor to modify and access it from simulation thread, except where noted otherwise.
  356. // Classes where it is not clear if they are to be used on the core or simulation thread have
  357. // it noted in their documentation. e.g. RenderWindow::setWindowed method is marked as "Core only".
  358. // Additional asserts are normally in place for debug builds which make it harder for you to accidentally
  359. // call something from the wrong thread.
  360. if (fullscreen)
  361. {
  362. gCoreAccessor().setWindowed(window, windowResWidth, windowResHeight);
  363. }
  364. else
  365. {
  366. gCoreAccessor().setFullscreen(window, *selectedVideoMode);
  367. }
  368. fullscreen = !fullscreen;
  369. }
  370. void renderWindowResized()
  371. {
  372. RenderWindowPtr window = gApplication().getPrimaryWindow();
  373. if (!fullscreen)
  374. {
  375. windowResWidth = window->getWidth();
  376. windowResHeight = window->getHeight();
  377. }
  378. sceneCamera->setAspectRatio(window->getWidth() / (float)window->getHeight());
  379. }
  380. void videoModeChanged(UINT32 idx)
  381. {
  382. selectedVideoMode = videoModes[idx];
  383. if (fullscreen)
  384. {
  385. RenderWindowPtr window = gApplication().getPrimaryWindow();
  386. gCoreAccessor().setFullscreen(window, *selectedVideoMode);
  387. }
  388. }
  389. void buttonUp(const VirtualButton& button, UINT32 deviceIdx)
  390. {
  391. // Check if the pressed button is one of the either buttons we defined
  392. // in "setUpExample", and toggle profiler overlays accordingly.
  393. // Device index is ignored for now, as it is assumed the user is using a single keyboard,
  394. // but if you wanted support for multiple gamepads you would check deviceIdx.
  395. if (button == toggleCPUProfilerBtn)
  396. {
  397. if (cpuProfilerActive)
  398. {
  399. profilerOverlay->hide();
  400. cpuProfilerActive = false;
  401. }
  402. else
  403. {
  404. profilerOverlay->show(ProfilerOverlayType::CPUSamples);
  405. cpuProfilerActive = true;
  406. gpuProfilerActive = false;
  407. }
  408. }
  409. else if (button == toggleGPUProfilerBtn)
  410. {
  411. if (gpuProfilerActive)
  412. {
  413. profilerOverlay->hide();
  414. gpuProfilerActive = false;
  415. }
  416. else
  417. {
  418. profilerOverlay->show(ProfilerOverlayType::GPUSamples);
  419. gpuProfilerActive = true;
  420. cpuProfilerActive = false;
  421. }
  422. }
  423. }
  424. }