07_Billboards.as 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. // Billboard example.
  2. // This sample demonstrates:
  3. // - Populating a 3D scene with billboard sets and several shadow casting spotlights
  4. // - Parenting scene nodes to allow more intuitive creation of groups of objects
  5. // - Examining rendering performance with a somewhat large object and light count
  6. #include "Scripts/Utilities/Sample.as"
  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 viewport for displaying the scene
  16. SetupViewport();
  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 a Zone component for ambient lighting & fog control
  30. Node@ zoneNode = scene_.CreateChild("Zone");
  31. Zone@ zone = zoneNode.CreateComponent("Zone");
  32. zone.boundingBox = BoundingBox(-1000.0f, 1000.0f);
  33. zone.ambientColor = Color(0.1f, 0.1f, 0.1f);
  34. zone.fogStart = 100.0f;
  35. zone.fogEnd = 300.0f;
  36. // Create a directional light without shadows
  37. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  38. lightNode.direction = Vector3(0.5f, -1.0f, 0.5f);
  39. Light@ light = lightNode.CreateComponent("Light");
  40. light.lightType = LIGHT_DIRECTIONAL;
  41. light.color = Color(0.2f, 0.2f, 0.2f);
  42. light.specularIntensity = 1.0f;
  43. // Create a "floor" consisting of several tiles
  44. for (int y = -5; y <= 5; ++y)
  45. {
  46. for (int x = -5; x <= 5; ++x)
  47. {
  48. Node@ floorNode = scene_.CreateChild("FloorTile");
  49. floorNode.position = Vector3(x * 20.5f, -0.5f, y * 20.5f);
  50. floorNode.scale = Vector3(20.0f, 1.0f, 20.f);
  51. StaticModel@ floorObject = floorNode.CreateComponent("StaticModel");
  52. floorObject.model = cache.GetResource("Model", "Models/Box.mdl");
  53. floorObject.material = cache.GetResource("Material", "Materials/Stone.xml");
  54. }
  55. }
  56. // Create groups of mushrooms, which act as shadow casters
  57. const uint NUM_MUSHROOMGROUPS = 25;
  58. const uint NUM_MUSHROOMS = 25;
  59. for (uint i = 0; i < NUM_MUSHROOMGROUPS; ++i)
  60. {
  61. // First create a scene node for the group. The individual mushrooms nodes will be created as children
  62. Node@ groupNode = scene_.CreateChild("MushroomGroup");
  63. groupNode.position = Vector3(Random(190.0f) - 95.0f, 0.0f, Random(190.0f) - 95.0f);
  64. for (uint j = 0; j < NUM_MUSHROOMS; ++j)
  65. {
  66. Node@ mushroomNode = groupNode.CreateChild("Mushroom");
  67. mushroomNode.position = Vector3(Random(25.0f) - 12.5f, 0.0f, Random(25.0f) - 12.5f);
  68. mushroomNode.rotation = Quaternion(0.0f, Random() * 360.0f, 0.0f);
  69. mushroomNode.SetScale(1.0f + Random() * 4.0f);
  70. StaticModel@ mushroomObject = mushroomNode.CreateComponent("StaticModel");
  71. mushroomObject.model = cache.GetResource("Model", "Models/Mushroom.mdl");
  72. mushroomObject.material = cache.GetResource("Material", "Materials/Mushroom.xml");
  73. mushroomObject.castShadows = true;
  74. }
  75. }
  76. // Create billboard sets (floating smoke)
  77. const uint NUM_BILLBOARDNODES = 25;
  78. const uint NUM_BILLBOARDS = 10;
  79. for (uint i = 0; i < NUM_BILLBOARDNODES; ++i)
  80. {
  81. Node@ smokeNode = scene_.CreateChild("Smoke");
  82. smokeNode.position = Vector3(Random(200.0f) - 100.0f, Random(20.0f) + 10.0f, Random(200.0f) - 100.0f);
  83. BillboardSet@ billboardObject = smokeNode.CreateComponent("BillboardSet");
  84. billboardObject.numBillboards = NUM_BILLBOARDS;
  85. billboardObject.material = cache.GetResource("Material", "Materials/LitSmoke.xml");
  86. billboardObject.sorted = true;
  87. for (uint j = 0; j < NUM_BILLBOARDS; ++j)
  88. {
  89. Billboard@ bb = billboardObject.billboards[j];
  90. bb.position = Vector3(Random(12.0f) - 6.0f, Random(8.0f) - 4.0f, Random(12.0f) - 6.0f);
  91. bb.size = Vector2(Random(2.0f) + 3.0f, Random(2.0f) + 3.0f);
  92. bb.rotation = Random() * 360.0f;
  93. bb.enabled = true;
  94. }
  95. // After modifying the billboards, they need to be "committed" so that the BillboardSet updates its internals
  96. billboardObject.Commit();
  97. }
  98. // Create shadow casting spotlights
  99. const uint NUM_LIGHTS = 9;
  100. for (uint i = 0; i < NUM_LIGHTS; ++i)
  101. {
  102. Node@ lightNode = scene_.CreateChild("SpotLight");
  103. Light@ light = lightNode.CreateComponent("Light");
  104. float angle = 0.0f;
  105. Vector3 position((i % 3) * 60.0f - 60.0f, 45.0f, (i / 3) * 60.0f - 60.0f);
  106. Color color(((i + 1) & 1) * 0.5f + 0.5f, (((i + 1) >> 1) & 1) * 0.5f + 0.5f, (((i + 1) >> 2) & 1) * 0.5f + 0.5f);
  107. lightNode.position = position;
  108. lightNode.direction = Vector3(Sin(angle), -1.5f, Cos(angle));
  109. light.lightType = LIGHT_SPOT;
  110. light.range = 90.0f;
  111. light.rampTexture = cache.GetResource("Texture2D", "Textures/RampExtreme.png");
  112. light.fov = 45.0f;
  113. light.color = color;
  114. light.specularIntensity = 1.0f;
  115. light.castShadows = true;
  116. light.shadowBias = BiasParameters(0.00002f, 0.0f);
  117. // Configure shadow fading for the lights. When they are far away enough, the lights eventually become unshadowed for
  118. // better GPU performance. Note that we could also set the maximum distance for each object to cast shadows
  119. light.shadowFadeDistance = 100.0f; // Fade start distance
  120. light.shadowDistance = 125.0f; // Fade end distance, shadows are disabled
  121. // Set half resolution for the shadow maps for increased performance
  122. light.shadowResolution = 0.5f;
  123. // The spot lights will not have anything near them, so move the near plane of the shadow camera farther
  124. // for better shadow depth resolution
  125. light.shadowNearFarRatio = 0.01f;
  126. }
  127. // Create the camera. Limit far clip distance to match the fog
  128. cameraNode = scene_.CreateChild("Camera");
  129. Camera@ camera = cameraNode.CreateComponent("Camera");
  130. camera.farClip = 300.0f;
  131. // Set an initial position for the camera scene node above the plane
  132. cameraNode.position = Vector3(0.0f, 5.0f, 0.0f);
  133. }
  134. void CreateInstructions()
  135. {
  136. // Construct new Text object, set string to display and font to use
  137. Text@ instructionText = ui.root.CreateChild("Text");
  138. instructionText.text =
  139. "Use WASD keys and mouse to move\n"
  140. "Space to toggle debug geometry";
  141. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  142. // The text has multiple rows. Center them in relation to each other
  143. instructionText.textAlignment = HA_CENTER;
  144. // Position the text relative to the screen center
  145. instructionText.horizontalAlignment = HA_CENTER;
  146. instructionText.verticalAlignment = VA_CENTER;
  147. instructionText.SetPosition(0, ui.root.height / 4);
  148. }
  149. void SetupViewport()
  150. {
  151. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  152. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  153. renderer.viewports[0] = viewport;
  154. }
  155. void SubscribeToEvents()
  156. {
  157. // Subscribe HandleUpdate() function for processing update events
  158. SubscribeToEvent("Update", "HandleUpdate");
  159. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  160. // debug geometry
  161. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
  162. }
  163. void MoveCamera(float timeStep)
  164. {
  165. // Do not move if the UI has a focused element (the console)
  166. if (ui.focusElement !is null)
  167. return;
  168. // Movement speed as world units per second
  169. const float MOVE_SPEED = 20.0f;
  170. // Mouse sensitivity as degrees per pixel
  171. const float MOUSE_SENSITIVITY = 0.1f;
  172. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  173. IntVector2 mouseMove = input.mouseMove;
  174. yaw += MOUSE_SENSITIVITY * mouseMove.x;
  175. pitch += MOUSE_SENSITIVITY * mouseMove.y;
  176. pitch = Clamp(pitch, -90.0f, 90.0f);
  177. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  178. cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
  179. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  180. if (input.keyDown[KEY_W])
  181. cameraNode.Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  182. if (input.keyDown[KEY_S])
  183. cameraNode.Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  184. if (input.keyDown[KEY_A])
  185. cameraNode.Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  186. if (input.keyDown[KEY_D])
  187. cameraNode.Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  188. // Toggle debug geometry with space
  189. if (input.keyPress[KEY_SPACE])
  190. drawDebug = !drawDebug;
  191. }
  192. void AnimateScene(float timeStep)
  193. {
  194. // Get the light and billboard scene nodes
  195. Array<Node@> lightNodes = scene_.GetChildrenWithComponent("Light");
  196. Array<Node@> billboardNodes = scene_.GetChildrenWithComponent("BillboardSet");
  197. const float LIGHT_ROTATION_SPEED = 20.0f;
  198. const float BILLBOARD_ROTATION_SPEED = 50.0f;
  199. // Rotate the lights around the world Y-axis
  200. for (uint i = 0; i < lightNodes.length; ++i)
  201. lightNodes[i].Rotate(Quaternion(0.0f, LIGHT_ROTATION_SPEED * timeStep, 0.0f), TS_WORLD);
  202. // Rotate the individual billboards within the billboard sets, then recommit to make the changes visible
  203. for (uint i = 0; i < billboardNodes.length; ++i)
  204. {
  205. BillboardSet@ billboardObject = billboardNodes[i].GetComponent("BillboardSet");
  206. for (uint j = 0; j < billboardObject.numBillboards; ++j)
  207. {
  208. Billboard@ bb = billboardObject.billboards[j];
  209. bb.rotation += BILLBOARD_ROTATION_SPEED * timeStep;
  210. }
  211. billboardObject.Commit();
  212. }
  213. }
  214. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  215. {
  216. // Take the frame time step, which is stored as a float
  217. float timeStep = eventData["TimeStep"].GetFloat();
  218. // Move the camera and animate the scene, scale movement with time step
  219. MoveCamera(timeStep);
  220. AnimateScene(timeStep);
  221. }
  222. void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  223. {
  224. // If draw debug mode is enabled, draw viewport debug geometry. This time use depth test, as otherwise the result becomes
  225. // hard to interpret due to large object count
  226. if (drawDebug)
  227. renderer.DrawDebugGeometry(true);
  228. }
  229. // Create XML patch instructions for screen joystick layout specific to this sample app
  230. String patchInstructions =
  231. "<patch>" +
  232. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" +
  233. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" +
  234. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" +
  235. " <element type=\"Text\">" +
  236. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  237. " <attribute name=\"Text\" value=\"SPACE\" />" +
  238. " </element>" +
  239. " </add>" +
  240. "</patch>";