09_MultipleViewports.as 13 KB

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