07_Billboards.as 12 KB

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