09_MultipleViewports.as 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. // Multiple viewports example.
  2. // This sample demonstrates:
  3. // - Setting up two viewports with two separate cameras
  4. // - Adding post processing effects to a viewport's render path and toggling them
  5. #include "Scripts/Utilities/Sample.as"
  6. Node@ rearCameraNode;
  7. void Start()
  8. {
  9. // Execute the common startup for samples
  10. SampleStart();
  11. // Create the scene content
  12. CreateScene();
  13. // Create the UI content
  14. CreateInstructions();
  15. // Setup the viewports for displaying the scene
  16. SetupViewports();
  17. // Set the mouse mode to use in the sample
  18. SampleInitMouseMode(MM_RELATIVE);
  19. // Hook up to the frame update and render post-update events
  20. SubscribeToEvents();
  21. }
  22. void CreateScene()
  23. {
  24. scene_ = Scene();
  25. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  26. // Also create a DebugRenderer component so that we can draw debug geometry
  27. scene_.CreateComponent("Octree");
  28. scene_.CreateComponent("DebugRenderer");
  29. // Create scene node & StaticModel component for showing a static plane
  30. Node@ planeNode = scene_.CreateChild("Plane");
  31. planeNode.scale = Vector3(100.0f, 1.0f, 100.0f);
  32. StaticModel@ planeObject = planeNode.CreateComponent("StaticModel");
  33. planeObject.model = cache.GetResource("Model", "Models/Plane.mdl");
  34. planeObject.material = cache.GetResource("Material", "Materials/StoneTiled.xml");
  35. // Create a Zone component for ambient lighting & fog control
  36. Node@ zoneNode = scene_.CreateChild("Zone");
  37. Zone@ zone = zoneNode.CreateComponent("Zone");
  38. zone.boundingBox = BoundingBox(-1000.0f, 1000.0f);
  39. zone.ambientColor = Color(0.15f, 0.15f, 0.15f);
  40. zone.fogColor = Color(0.5f, 0.5f, 0.7f);
  41. zone.fogStart = 100.0f;
  42. zone.fogEnd = 300.0f;
  43. // Create a directional light to the world. Enable cascaded shadows on it
  44. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  45. lightNode.direction = Vector3(0.6f, -1.0f, 0.8f);
  46. Light@ light = lightNode.CreateComponent("Light");
  47. light.lightType = LIGHT_DIRECTIONAL;
  48. light.castShadows = true;
  49. light.shadowBias = BiasParameters(0.00025f, 0.5f);
  50. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  51. light.shadowCascade = CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  52. // Create some mushrooms
  53. const uint NUM_MUSHROOMS = 240;
  54. for (uint i = 0; i < NUM_MUSHROOMS; ++i)
  55. {
  56. Node@ mushroomNode = scene_.CreateChild("Mushroom");
  57. mushroomNode.position = Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f);
  58. mushroomNode.rotation = Quaternion(0.0f, Random(360.0f), 0.0f);
  59. mushroomNode.SetScale(0.5f + Random(2.0f));
  60. StaticModel@ mushroomObject = mushroomNode.CreateComponent("StaticModel");
  61. mushroomObject.model = cache.GetResource("Model", "Models/Mushroom.mdl");
  62. mushroomObject.material = cache.GetResource("Material", "Materials/Mushroom.xml");
  63. mushroomObject.castShadows = true;
  64. }
  65. // Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
  66. // rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
  67. const uint NUM_BOXES = 20;
  68. for (uint i = 0; i < NUM_BOXES; ++i)
  69. {
  70. Node@ boxNode = scene_.CreateChild("Box");
  71. float size = 1.0f + Random(10.0f);
  72. boxNode.position = Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f);
  73. boxNode.SetScale(size);
  74. StaticModel@ boxObject = boxNode.CreateComponent("StaticModel");
  75. boxObject.model = cache.GetResource("Model", "Models/Box.mdl");
  76. boxObject.material = cache.GetResource("Material", "Materials/Stone.xml");
  77. boxObject.castShadows = true;
  78. if (size >= 3.0f)
  79. boxObject.occluder = true;
  80. }
  81. // Create the cameras. Limit far clip distance to match the fog
  82. cameraNode = scene_.CreateChild("Camera");
  83. Camera@ camera = cameraNode.CreateComponent("Camera");
  84. camera.farClip = 300.0f;
  85. // Parent the rear camera node to the front camera node and turn it 180 degrees to face backward
  86. // Here, we use the angle-axis constructor for Quaternion instead of the usual Euler angles
  87. rearCameraNode = cameraNode.CreateChild("RearCamera");
  88. rearCameraNode.Rotate(Quaternion(180.0f, Vector3::UP));
  89. Camera@ rearCamera = rearCameraNode.CreateComponent("Camera");
  90. rearCamera.farClip = 300.0f;
  91. // Because the rear viewport is rather small, disable occlusion culling from it. Use the camera's
  92. // "view override flags" for this. We could also disable eg. shadows or force low material quality
  93. // if we wanted
  94. rearCamera.viewOverrideFlags = VO_DISABLE_OCCLUSION;
  95. // Set an initial position for the front camera scene node above the plane
  96. cameraNode.position = Vector3(0.0f, 5.0f, 0.0f);
  97. }
  98. void CreateInstructions()
  99. {
  100. // Construct new Text object, set string to display and font to use
  101. Text@ instructionText = ui.root.CreateChild("Text");
  102. instructionText.text =
  103. "Use WASD keys and mouse to move\n"
  104. "B to toggle bloom, F to toggle FXAA\n"
  105. "Space to toggle debug geometry\n";
  106. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  107. // The text has multiple rows. Center them in relation to each other
  108. instructionText.textAlignment = HA_CENTER;
  109. // Position the text relative to the screen center
  110. instructionText.horizontalAlignment = HA_CENTER;
  111. instructionText.verticalAlignment = VA_CENTER;
  112. instructionText.SetPosition(0, ui.root.height / 4);
  113. }
  114. void SetupViewports()
  115. {
  116. renderer.numViewports = 2;
  117. // Set up the front camera viewport
  118. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  119. renderer.viewports[0] = viewport;
  120. // Clone the default render path so that we do not interfere with the other viewport, then add
  121. // bloom and FXAA post process effects to the front viewport. Render path commands can be tagged
  122. // for example with the effect name to allow easy toggling on and off. We start with the effects
  123. // disabled.
  124. RenderPath@ effectRenderPath = viewport.renderPath.Clone();
  125. effectRenderPath.Append(cache.GetResource("XMLFile", "PostProcess/Bloom.xml"));
  126. effectRenderPath.Append(cache.GetResource("XMLFile", "PostProcess/FXAA2.xml"));
  127. // Make the bloom mixing parameter more pronounced
  128. effectRenderPath.shaderParameters["BloomMix"] = Variant(Vector2(0.9f, 0.6f));
  129. effectRenderPath.SetEnabled("Bloom", false);
  130. effectRenderPath.SetEnabled("FXAA2", false);
  131. viewport.renderPath = effectRenderPath;
  132. // Set up the rear camera viewport on top of the front view ("rear view mirror")
  133. // The viewport index must be greater in that case, otherwise the view would be left behind
  134. Viewport@ rearViewport = Viewport(scene_, rearCameraNode.GetComponent("Camera"),
  135. IntRect(graphics.width * 2 / 3, 32, graphics.width - 32, graphics.height / 3));
  136. renderer.viewports[1] = rearViewport;
  137. }
  138. void SubscribeToEvents()
  139. {
  140. // Subscribe HandleUpdate() function for processing update events
  141. SubscribeToEvent("Update", "HandleUpdate");
  142. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  143. // debug geometry
  144. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
  145. }
  146. void MoveCamera(float timeStep)
  147. {
  148. // Do not move if the UI has a focused element (the console)
  149. if (ui.focusElement !is null)
  150. return;
  151. // Movement speed as world units per second
  152. const float MOVE_SPEED = 20.0f;
  153. // Mouse sensitivity as degrees per pixel
  154. const float MOUSE_SENSITIVITY = 0.1f;
  155. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  156. IntVector2 mouseMove = input.mouseMove;
  157. yaw += MOUSE_SENSITIVITY * mouseMove.x;
  158. pitch += MOUSE_SENSITIVITY * mouseMove.y;
  159. pitch = Clamp(pitch, -90.0f, 90.0f);
  160. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  161. cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
  162. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  163. if (input.keyDown[KEY_W])
  164. cameraNode.Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  165. if (input.keyDown[KEY_S])
  166. cameraNode.Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  167. if (input.keyDown[KEY_A])
  168. cameraNode.Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  169. if (input.keyDown[KEY_D])
  170. cameraNode.Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  171. // Toggle post processing effects on the front viewport. Note that the rear viewport is unaffected
  172. RenderPath@ effectRenderPath = renderer.viewports[0].renderPath;
  173. if (input.keyPress[KEY_B])
  174. effectRenderPath.ToggleEnabled("Bloom");
  175. if (input.keyPress[KEY_F])
  176. effectRenderPath.ToggleEnabled("FXAA2");
  177. // Toggle debug geometry with space
  178. if (input.keyPress[KEY_SPACE])
  179. drawDebug = !drawDebug;
  180. }
  181. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  182. {
  183. // Take the frame time step, which is stored as a float
  184. float timeStep = eventData["TimeStep"].GetFloat();
  185. // Move the camera, scale movement with time step
  186. MoveCamera(timeStep);
  187. }
  188. void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  189. {
  190. // If draw debug mode is enabled, draw viewport debug geometry. Disable depth test so that we can see the effect of occlusion
  191. if (drawDebug)
  192. renderer.DrawDebugGeometry(false);
  193. }
  194. // Create XML patch instructions for screen joystick layout specific to this sample app
  195. String patchInstructions =
  196. "<patch>" +
  197. " <add sel=\"/element\">" +
  198. " <element type=\"Button\">" +
  199. " <attribute name=\"Name\" value=\"Button3\" />" +
  200. " <attribute name=\"Position\" value=\"-120 -120\" />" +
  201. " <attribute name=\"Size\" value=\"96 96\" />" +
  202. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" +
  203. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" +
  204. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" +
  205. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" +
  206. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" +
  207. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" +
  208. " <element type=\"Text\">" +
  209. " <attribute name=\"Name\" value=\"Label\" />" +
  210. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" +
  211. " <attribute name=\"Vert Alignment\" value=\"Center\" />" +
  212. " <attribute name=\"Color\" value=\"0 0 0 1\" />" +
  213. " <attribute name=\"Text\" value=\"FXAA\" />" +
  214. " </element>" +
  215. " <element type=\"Text\">" +
  216. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  217. " <attribute name=\"Text\" value=\"F\" />" +
  218. " </element>" +
  219. " </element>" +
  220. " </add>" +
  221. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" +
  222. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Bloom</replace>" +
  223. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" +
  224. " <element type=\"Text\">" +
  225. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  226. " <attribute name=\"Text\" value=\"B\" />" +
  227. " </element>" +
  228. " </add>" +
  229. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" +
  230. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" +
  231. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" +
  232. " <element type=\"Text\">" +
  233. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  234. " <attribute name=\"Text\" value=\"SPACE\" />" +
  235. " </element>" +
  236. " </add>" +
  237. "</patch>";