08_Decals.as 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. // Decals example.
  2. // This sample demonstrates:
  3. // - Performing a raycast to the octree and adding a decal to the hit location
  4. // - Defining a Cursor UI element which stays inside the window and can be shown/hidden
  5. // - Marking suitable (large) objects as occluders for occlusion culling
  6. // - Displaying renderer debug geometry to see the effect of occlusion
  7. #include "Scripts/Utilities/Sample.as"
  8. void Start()
  9. {
  10. // Execute the common startup for samples
  11. SampleStart();
  12. // Create the scene content
  13. CreateScene();
  14. // Create the UI content
  15. CreateUI();
  16. // Setup the viewport for displaying the scene
  17. SetupViewport();
  18. // Set the mouse mode to use in the sample
  19. SampleInitMouseMode(MM_RELATIVE);
  20. // Hook up to the frame update and render post-update events
  21. SubscribeToEvents();
  22. }
  23. void CreateScene()
  24. {
  25. scene_ = Scene();
  26. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  27. // Also create a DebugRenderer component so that we can draw debug geometry
  28. scene_.CreateComponent("Octree");
  29. scene_.CreateComponent("DebugRenderer");
  30. // Create scene node & StaticModel component for showing a static plane
  31. Node@ planeNode = scene_.CreateChild("Plane");
  32. planeNode.scale = Vector3(100.0f, 1.0f, 100.0f);
  33. StaticModel@ planeObject = planeNode.CreateComponent("StaticModel");
  34. planeObject.model = cache.GetResource("Model", "Models/Plane.mdl");
  35. planeObject.material = cache.GetResource("Material", "Materials/StoneTiled.xml");
  36. // Create a Zone component for ambient lighting & fog control
  37. Node@ zoneNode = scene_.CreateChild("Zone");
  38. Zone@ zone = zoneNode.CreateComponent("Zone");
  39. zone.boundingBox = BoundingBox(-1000.0f, 1000.0f);
  40. zone.ambientColor = Color(0.15f, 0.15f, 0.15f);
  41. zone.fogColor = Color(0.5f, 0.5f, 0.7f);
  42. zone.fogStart = 100.0f;
  43. zone.fogEnd = 300.0f;
  44. // Create a directional light to the world. Enable cascaded shadows on it
  45. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  46. lightNode.direction = Vector3(0.6f, -1.0f, 0.8f);
  47. Light@ light = lightNode.CreateComponent("Light");
  48. light.lightType = LIGHT_DIRECTIONAL;
  49. light.castShadows = true;
  50. light.shadowBias = BiasParameters(0.00025f, 0.5f);
  51. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  52. light.shadowCascade = CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  53. // Create some mushrooms
  54. const uint NUM_MUSHROOMS = 240;
  55. for (uint i = 0; i < NUM_MUSHROOMS; ++i)
  56. {
  57. Node@ mushroomNode = scene_.CreateChild("Mushroom");
  58. mushroomNode.position = Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f);
  59. mushroomNode.rotation = Quaternion(0.0f, Random(360.0f), 0.0f);
  60. mushroomNode.SetScale(0.5f + Random(2.0f));
  61. StaticModel@ mushroomObject = mushroomNode.CreateComponent("StaticModel");
  62. mushroomObject.model = cache.GetResource("Model", "Models/Mushroom.mdl");
  63. mushroomObject.material = cache.GetResource("Material", "Materials/Mushroom.xml");
  64. mushroomObject.castShadows = true;
  65. }
  66. // Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
  67. // rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
  68. const uint NUM_BOXES = 20;
  69. for (uint i = 0; i < NUM_BOXES; ++i)
  70. {
  71. Node@ boxNode = scene_.CreateChild("Box");
  72. float size = 1.0f + Random(10.0f);
  73. boxNode.position = Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f);
  74. boxNode.SetScale(size);
  75. StaticModel@ boxObject = boxNode.CreateComponent("StaticModel");
  76. boxObject.model = cache.GetResource("Model", "Models/Box.mdl");
  77. boxObject.material = cache.GetResource("Material", "Materials/Stone.xml");
  78. boxObject.castShadows = true;
  79. if (size >= 3.0f)
  80. boxObject.occluder = true;
  81. }
  82. // Create the camera. Limit far clip distance to match the fog
  83. cameraNode = scene_.CreateChild("Camera");
  84. Camera@ camera = cameraNode.CreateComponent("Camera");
  85. camera.farClip = 300.0f;
  86. // Set an initial position for the camera scene node above the plane
  87. cameraNode.position = Vector3(0.0f, 5.0f, 0.0f);
  88. }
  89. void CreateUI()
  90. {
  91. // Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
  92. // control the camera, and when visible, it will point the raycast target
  93. XMLFile@ style = cache.GetResource("XMLFile", "UI/DefaultStyle.xml");
  94. Cursor@ cursor = Cursor();
  95. cursor.SetStyleAuto(style);
  96. ui.cursor = cursor;
  97. // Set starting position of the cursor at the rendering window center
  98. cursor.SetPosition(graphics.width / 2, graphics.height / 2);
  99. // Construct new Text object, set string to display and font to use
  100. Text@ instructionText = ui.root.CreateChild("Text");
  101. instructionText.text =
  102. "Use WASD keys to move\n"
  103. "LMB to paint decals, RMB to rotate view\n"
  104. "Space to toggle debug geometry\n"
  105. "7 to toggle occlusion culling";
  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 SetupViewport()
  115. {
  116. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  117. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  118. renderer.viewports[0] = viewport;
  119. }
  120. void SubscribeToEvents()
  121. {
  122. // Subscribe HandleUpdate() function for processing update events
  123. SubscribeToEvent("Update", "HandleUpdate");
  124. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  125. // debug geometry
  126. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
  127. }
  128. void MoveCamera(float timeStep)
  129. {
  130. input.mouseVisible = input.mouseMode != MM_RELATIVE;
  131. bool mouseDown = input.mouseButtonDown[MOUSEB_RIGHT];
  132. // Override the MM_RELATIVE mouse grabbed settings, to allow interaction with UI
  133. input.mouseGrabbed = mouseDown;
  134. // Right mouse button controls mouse cursor visibility: hide when pressed
  135. ui.cursor.visible = !mouseDown;
  136. // Do not move if the UI has a focused element (the console)
  137. if (ui.focusElement !is null)
  138. return;
  139. // Movement speed as world units per second
  140. const float MOVE_SPEED = 20.0f;
  141. // Mouse sensitivity as degrees per pixel
  142. const float MOUSE_SENSITIVITY = 0.1f;
  143. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  144. // Only move the camera when the cursor is hidden
  145. if (!ui.cursor.visible)
  146. {
  147. IntVector2 mouseMove = input.mouseMove;
  148. yaw += MOUSE_SENSITIVITY * mouseMove.x;
  149. pitch += MOUSE_SENSITIVITY * mouseMove.y;
  150. pitch = Clamp(pitch, -90.0f, 90.0f);
  151. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  152. cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
  153. }
  154. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  155. if (input.keyDown[KEY_W])
  156. cameraNode.Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  157. if (input.keyDown[KEY_S])
  158. cameraNode.Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  159. if (input.keyDown[KEY_A])
  160. cameraNode.Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  161. if (input.keyDown[KEY_D])
  162. cameraNode.Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  163. // Toggle debug geometry with space
  164. if (input.keyPress[KEY_SPACE])
  165. drawDebug = !drawDebug;
  166. // Paint decal with the left mousebutton; cursor must be visible
  167. if (ui.cursor.visible && input.mouseButtonPress[MOUSEB_LEFT])
  168. PaintDecal();
  169. }
  170. void PaintDecal()
  171. {
  172. Vector3 hitPos;
  173. Drawable@ hitDrawable;
  174. if (Raycast(250.0f, hitPos, hitDrawable))
  175. {
  176. // Check if target scene node already has a DecalSet component. If not, create now
  177. Node@ targetNode = hitDrawable.node;
  178. DecalSet@ decal = targetNode.GetComponent("DecalSet");
  179. if (decal is null)
  180. {
  181. decal = targetNode.CreateComponent("DecalSet");
  182. decal.material = cache.GetResource("Material", "Materials/UrhoDecal.xml");
  183. }
  184. // Add a square decal to the decal set using the geometry of the drawable that was hit, orient it to face the camera,
  185. // use full texture UV's (0,0) to (1,1). Note that if we create several decals to a large object (such as the ground
  186. // plane) over a large area using just one DecalSet component, the decals will all be culled as one unit. If that is
  187. // undesirable, it may be necessary to create more than one DecalSet based on the distance
  188. decal.AddDecal(hitDrawable, hitPos, cameraNode.rotation, 0.5f, 1.0f, 1.0f, Vector2::ZERO, Vector2::ONE);
  189. }
  190. }
  191. bool Raycast(float maxDistance, Vector3& hitPos, Drawable@& hitDrawable)
  192. {
  193. hitDrawable = null;
  194. IntVector2 pos = ui.cursorPosition;
  195. // Check the cursor is visible and there is no UI element in front of the cursor
  196. if (!ui.cursor.visible || ui.GetElementAt(pos, true) !is null)
  197. return false;
  198. Camera@ camera = cameraNode.GetComponent("Camera");
  199. Ray cameraRay = camera.GetScreenRay(float(pos.x) / graphics.width, float(pos.y) / graphics.height);
  200. // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  201. // Note the convenience accessor to scene's Octree component
  202. RayQueryResult result = scene_.octree.RaycastSingle(cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY);
  203. if (result.drawable !is null)
  204. {
  205. hitPos = result.position;
  206. hitDrawable = result.drawable;
  207. return true;
  208. }
  209. return false;
  210. }
  211. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  212. {
  213. // Take the frame time step, which is stored as a float
  214. float timeStep = eventData["TimeStep"].GetFloat();
  215. // Move the camera, scale movement with time step
  216. MoveCamera(timeStep);
  217. }
  218. void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  219. {
  220. // If draw debug mode is enabled, draw viewport debug geometry. Disable depth test so that we can see the effect of occlusion
  221. if (drawDebug)
  222. renderer.DrawDebugGeometry(false);
  223. }
  224. // Create XML patch instructions for screen joystick layout specific to this sample app
  225. String patchInstructions =
  226. "<patch>" +
  227. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" +
  228. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Paint</replace>" +
  229. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" +
  230. " <element type=\"Text\">" +
  231. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
  232. " <attribute name=\"Text\" value=\"LEFT\" />" +
  233. " </element>" +
  234. " </add>" +
  235. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" +
  236. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" +
  237. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" +
  238. " <element type=\"Text\">" +
  239. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  240. " <attribute name=\"Text\" value=\"SPACE\" />" +
  241. " </element>" +
  242. " </add>" +
  243. "</patch>";