07_Billboards.as 11 KB

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