08_Decals.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. // Copyright (c) 2015 Xamarin Inc
  4. // Copyright (c) 2016 THUNDERBEAST GAMES LLC
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. using System;
  25. using System.Linq;
  26. using AtomicEngine;
  27. namespace FeatureExamples
  28. {
  29. public class DecalSample : Sample
  30. {
  31. Scene scene;
  32. bool drawDebug;
  33. Camera camera;
  34. public DecalSample() : base() { }
  35. public override void Start()
  36. {
  37. base.Start();
  38. CreateScene();
  39. CreateUI();
  40. SetupViewport();
  41. SubscribeToEvents();
  42. }
  43. void CreateUI()
  44. {
  45. SimpleCreateInstructionsWithWasd(
  46. "\nLMB to paint decals, RMB to rotate view\n" +
  47. "Space to toggle debug geometry\n" +
  48. "7 to toggle occlusion culling");
  49. }
  50. void SubscribeToEvents()
  51. {
  52. // Subscribe HandlePostRenderUpdate() function for
  53. // processing the post-render update event, sent after
  54. // Renderer subsystem is done with defining the draw
  55. // calls for the viewports (but before actually
  56. // executing them.) We will request debug geometry
  57. // rendering during that event
  58. SubscribeToEvent<PostRenderUpdateEvent>(e =>
  59. {
  60. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  61. // bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
  62. // bones properly
  63. if (drawDebug)
  64. {
  65. GetSubsystem<Renderer>().DrawDebugGeometry(false);
  66. }
  67. });
  68. }
  69. protected override void Update(float timeStep)
  70. {
  71. UI ui = GetSubsystem<UI>();
  72. var input = GetSubsystem<Input>();
  73. const float mouseSensitivity = .1f;
  74. const float moveSpeed = 40f;
  75. if (input.GetMouseButtonDown(Constants.MOUSEB_RIGHT))
  76. {
  77. var mouseMove = input.MouseMove;
  78. Yaw += mouseSensitivity * mouseMove.X;
  79. Pitch += mouseSensitivity * mouseMove.Y;
  80. Pitch = MathHelper.Clamp(Pitch, -90, 90);
  81. }
  82. CameraNode.Rotation = new Quaternion(Pitch, Yaw, 0);
  83. if (input.GetKeyDown(Constants.KEY_W))
  84. CameraNode.Translate(Vector3.UnitZ * moveSpeed * timeStep);
  85. if (input.GetKeyDown(Constants.KEY_S))
  86. CameraNode.Translate(-Vector3.UnitZ * moveSpeed * timeStep);
  87. if (input.GetKeyDown(Constants.KEY_A))
  88. CameraNode.Translate(-Vector3.UnitX * moveSpeed * timeStep);
  89. if (input.GetKeyDown(Constants.KEY_D))
  90. CameraNode.Translate(Vector3.UnitX * moveSpeed * timeStep);
  91. if (input.GetKeyPress(Constants.KEY_SPACE))
  92. drawDebug = !drawDebug;
  93. if (input.GetMouseButtonPress(Constants.MOUSEB_LEFT))
  94. PaintDecal();
  95. base.Update(timeStep);
  96. }
  97. void SetupViewport()
  98. {
  99. var renderer = GetSubsystem<Renderer>();
  100. renderer.SetViewport(0, new Viewport(scene, CameraNode.GetComponent<Camera>()));
  101. }
  102. void CreateScene()
  103. {
  104. var cache = GetSubsystem<ResourceCache>();
  105. scene = new Scene();
  106. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  107. // Also create a DebugRenderer component so that we can draw debug geometry
  108. scene.CreateComponent<Octree>();
  109. scene.CreateComponent<DebugRenderer>();
  110. // Create scene node & StaticModel component for showing a static plane
  111. var planeNode = scene.CreateChild("Plane");
  112. planeNode.Scale = new Vector3(100.0f, 1.0f, 100.0f);
  113. var planeObject = planeNode.CreateComponent<StaticModel>();
  114. planeObject.Model = cache.Get<Model>("Models/Plane.mdl");
  115. planeObject.SetMaterial(cache.Get<Material>("Materials/StoneTiled.xml"));
  116. // Create a Zone component for ambient lighting & fog control
  117. var zoneNode = scene.CreateChild("Zone");
  118. var zone = zoneNode.CreateComponent<Zone>();
  119. zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f));
  120. zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
  121. zone.FogColor = new Color(0.5f, 0.5f, 0.7f);
  122. zone.FogStart = 100.0f;
  123. zone.FogEnd = 300.0f;
  124. // Create a directional light to the world. Enable cascaded shadows on it
  125. var lightNode = scene.CreateChild("DirectionalLight");
  126. lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f));
  127. var light = lightNode.CreateComponent<Light>();
  128. light.LightType = LightType.LIGHT_DIRECTIONAL;
  129. light.CastShadows = true;
  130. light.ShadowBias = new BiasParameters(0.00025f, 0.5f);
  131. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  132. light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  133. // Create some mushrooms
  134. const uint numMushrooms = 240;
  135. for (uint i = 0; i < numMushrooms; ++i)
  136. {
  137. var mushroomNode = scene.CreateChild("Mushroom");
  138. mushroomNode.Position = new Vector3(NextRandom(90.0f) - 45.0f, 0.0f, NextRandom(90.0f) - 45.0f);
  139. mushroomNode.Rotation = new Quaternion(0.0f, NextRandom(360.0f), 0.0f);
  140. mushroomNode.SetScale(0.5f + NextRandom(2.0f));
  141. var mushroomObject = mushroomNode.CreateComponent<StaticModel>();
  142. mushroomObject.Model = cache.Get<Model>("Models/Mushroom.mdl");
  143. mushroomObject.SetMaterial(cache.Get<Material>("Materials/Mushroom.xml"));
  144. mushroomObject.CastShadows = true;
  145. }
  146. // Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
  147. // rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
  148. const uint numBoxes = 20;
  149. for (uint i = 0; i < numBoxes; ++i)
  150. {
  151. var boxNode = scene.CreateChild("Box");
  152. float size = 1.0f + NextRandom(10.0f);
  153. boxNode.Position = new Vector3(NextRandom(80.0f) - 40.0f, size * 0.5f, NextRandom(80.0f) - 40.0f);
  154. boxNode.SetScale(size);
  155. var boxObject = boxNode.CreateComponent<StaticModel>();
  156. boxObject.Model = cache.Get<Model>("Models/Box.mdl");
  157. boxObject.SetMaterial(cache.Get<Material>("Materials/Stone.xml"));
  158. boxObject.CastShadows = true;
  159. if (size >= 3.0f)
  160. boxObject.Occluder = true;
  161. }
  162. // Create the camera. Limit far clip distance to match the fog
  163. CameraNode = scene.CreateChild("Camera");
  164. camera = CameraNode.CreateComponent<Camera>();
  165. camera.FarClip = 300.0f;
  166. // Set an initial position for the camera scene node above the plane
  167. CameraNode.Position = new Vector3(0.0f, 5.0f, 0.0f);
  168. }
  169. bool Raycast(float maxDistance, out Vector3 hitPos, out Drawable hitDrawable)
  170. {
  171. hitDrawable = null;
  172. hitPos = Vector3.Zero;
  173. var graphics = GetSubsystem<Graphics>();
  174. var input = GetSubsystem<Input>();
  175. IntVector2 pos = input.MousePosition;
  176. Ray cameraRay = camera.GetScreenRay((float)pos.X / graphics.Width, (float)pos.Y / graphics.Height);
  177. RayOctreeQuery query = new RayOctreeQuery(cameraRay, RayQueryLevel.RAY_TRIANGLE, maxDistance, Constants.DRAWABLE_GEOMETRY);
  178. scene.GetComponent<Octree>().RaycastSingle(query);
  179. if (query.Results.Count > 0)
  180. {
  181. var first = query.Results.First();
  182. hitPos = first.Position;
  183. hitDrawable = first.Drawable;
  184. return true;
  185. }
  186. return false;
  187. }
  188. void PaintDecal()
  189. {
  190. Vector3 hitPos;
  191. Drawable hitDrawable;
  192. if (Raycast(250.0f, out hitPos, out hitDrawable))
  193. {
  194. var targetNode = hitDrawable.Node;
  195. var decal = targetNode.GetComponent<DecalSet>();
  196. if (decal == null)
  197. {
  198. var cache = GetSubsystem<ResourceCache>();
  199. decal = targetNode.CreateComponent<DecalSet>();
  200. decal.Material = cache.Get<Material>("Materials/UrhoDecal.xml");
  201. }
  202. // Add a square decal to the decal set using the geometry of the drawable that was hit, orient it to face the camera,
  203. // 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
  204. // plane) over a large area using just one DecalSet component, the decals will all be culled as one unit. If that is
  205. // undesirable, it may be necessary to create more than one DecalSet based on the distance
  206. decal.AddDecal(hitDrawable, hitPos, CameraNode.Rotation, 0.5f, 1.0f, 1.0f, Vector2.Zero,
  207. Vector2.One, 0.0f, 0.1f, uint.MaxValue);
  208. }
  209. }
  210. }
  211. }