34_DynamicGeometry.as 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. // Dynamic geometry example.
  2. // This sample demonstrates:
  3. // - Cloning a Model resource
  4. // - Modifying the vertex buffer data of the cloned models at runtime to efficiently animate them
  5. // - Creating a Model resource and its buffer data from scratch
  6. #include "Scripts/Utilities/Sample.as"
  7. bool animate = true;
  8. float animTime = 0.0;
  9. VectorBuffer originalVertexData;
  10. Array<VertexBuffer@> animatingBuffers;
  11. Array<Vector3> originalVertices;
  12. Array<uint> vertexDuplicates;
  13. void Start()
  14. {
  15. // Execute the common startup for samples
  16. SampleStart();
  17. // Create the scene content
  18. CreateScene();
  19. // Create the UI content
  20. CreateInstructions();
  21. // Setup the viewport for displaying the scene
  22. SetupViewport();
  23. // Set the mouse mode to use in the sample
  24. SampleInitMouseMode(MM_RELATIVE);
  25. // Hook up to the frame update events
  26. SubscribeToEvents();
  27. }
  28. void CreateScene()
  29. {
  30. scene_ = Scene();
  31. // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume
  32. // (-1000, -1000, -1000) to (1000, 1000, 1000)
  33. scene_.CreateComponent("Octree");
  34. // Create a Zone for ambient light & fog control
  35. Node@ zoneNode = scene_.CreateChild("Zone");
  36. Zone@ zone = zoneNode.CreateComponent("Zone");
  37. zone.boundingBox = BoundingBox(-1000.0, 1000.0);
  38. zone.fogColor = Color(0.2, 0.2, 0.2);
  39. zone.fogStart = 200.0;
  40. zone.fogEnd = 300.0;
  41. // Create a directional light
  42. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  43. lightNode.direction = Vector3(-0.6, -1.0, -0.8); // The direction vector does not need to be normalized
  44. Light@ light = lightNode.CreateComponent("Light");
  45. light.lightType = LIGHT_DIRECTIONAL;
  46. light.color = Color(0.4, 1.0, 0.4);
  47. light.specularIntensity = 1.5;
  48. // Get the original model and its unmodified vertices, which are used as source data for the animation
  49. Model@ originalModel = cache.GetResource("Model", "Models/Box.mdl");
  50. if (originalModel is null)
  51. {
  52. Print("Model not found, cannot initialize example scene");
  53. return;
  54. }
  55. // Get the vertex buffer from the first geometry's first LOD level
  56. VertexBuffer@ buffer = originalModel.GetGeometry(0, 0).vertexBuffers[0];
  57. originalVertexData = buffer.GetData();
  58. uint numVertices = buffer.vertexCount;
  59. uint vertexSize = buffer.vertexSize;
  60. // Copy the original vertex positions
  61. for (uint i = 0; i < numVertices; ++i)
  62. {
  63. originalVertexData.Seek(i * vertexSize);
  64. originalVertices.Push(originalVertexData.ReadVector3());
  65. }
  66. // Detect duplicate vertices to allow seamless animation
  67. vertexDuplicates.Resize(originalVertices.length);
  68. for (uint i = 0; i < originalVertices.length; ++i)
  69. {
  70. vertexDuplicates[i] = i; // Assume not a duplicate
  71. for (uint j = 0; j < i; ++j)
  72. {
  73. if (originalVertices[i].Equals(originalVertices[j]))
  74. {
  75. vertexDuplicates[i] = j;
  76. break;
  77. }
  78. }
  79. }
  80. // Create StaticModels in the scene. Clone the model for each so that we can modify the vertex data individually
  81. for (int y = -1; y <= 1; ++y)
  82. {
  83. for (int x = -1; x <= 1; ++x)
  84. {
  85. Node@ node = scene_.CreateChild("Object");
  86. node.position = Vector3(x * 2.0, 0.0, y * 2.0);
  87. StaticModel@ object = node.CreateComponent("StaticModel");
  88. Model@ cloneModel = originalModel.Clone();
  89. object.model = cloneModel;
  90. // Store the cloned vertex buffer that we will modify when animating
  91. animatingBuffers.Push(cloneModel.GetGeometry(0, 0).vertexBuffers[0]);
  92. }
  93. }
  94. // Finally create one model (pyramid shape) and a StaticModel to display it from scratch
  95. // Note: there are duplicated vertices to enable face normals. We will calculate normals programmatically
  96. {
  97. const uint numVertices = 18;
  98. float[] vertexData = {
  99. // Position Normal
  100. 0.0, 0.5, 0.0, 0.0, 0.0, 0.0,
  101. 0.5, -0.5, 0.5, 0.0, 0.0, 0.0,
  102. 0.5, -0.5, -0.5, 0.0, 0.0, 0.0,
  103. 0.0, 0.5, 0.0, 0.0, 0.0, 0.0,
  104. -0.5, -0.5, 0.5, 0.0, 0.0, 0.0,
  105. 0.5, -0.5, 0.5, 0.0, 0.0, 0.0,
  106. 0.0, 0.5, 0.0, 0.0, 0.0, 0.0,
  107. -0.5, -0.5, -0.5, 0.0, 0.0, 0.0,
  108. -0.5, -0.5, 0.5, 0.0, 0.0, 0.0,
  109. 0.0, 0.5, 0.0, 0.0, 0.0, 0.0,
  110. 0.5, -0.5, -0.5, 0.0, 0.0, 0.0,
  111. -0.5, -0.5, -0.5, 0.0, 0.0, 0.0,
  112. 0.5, -0.5, -0.5, 0.0, 0.0, 0.0,
  113. 0.5, -0.5, 0.5, 0.0, 0.0, 0.0,
  114. -0.5, -0.5, 0.5, 0.0, 0.0, 0.0,
  115. 0.5, -0.5, -0.5, 0.0, 0.0, 0.0,
  116. -0.5, -0.5, 0.5, 0.0, 0.0, 0.0,
  117. -0.5, -0.5, -0.5, 0.0, 0.0, 0.0
  118. };
  119. const uint16[] indexData = {
  120. 0, 1, 2,
  121. 3, 4, 5,
  122. 6, 7, 8,
  123. 9, 10, 11,
  124. 12, 13, 14,
  125. 15, 16, 17
  126. };
  127. // Calculate face normals now
  128. for (uint i = 0; i < numVertices; i += 3)
  129. {
  130. Vector3 v1(vertexData[6 * i], vertexData[6 * i + 1], vertexData[6 * i + 2]);
  131. Vector3 v2(vertexData[6 * i + 6], vertexData[6 * i + 7], vertexData[6 * i + 8]);
  132. Vector3 v3(vertexData[6 * i + 12], vertexData[6 * i + 13], vertexData[6 * i + 14]);
  133. Vector3 edge1 = v1 - v2;
  134. Vector3 edge2 = v1 - v3;
  135. Vector3 normal = edge1.CrossProduct(edge2).Normalized();
  136. vertexData[6 * i + 3] = vertexData[6 * i + 9] = vertexData[6 * i + 15] = normal.x;
  137. vertexData[6 * i + 4] = vertexData[6 * i + 10] = vertexData[6 * i + 16] = normal.y;
  138. vertexData[6 * i + 5] = vertexData[6 * i + 11] = vertexData[6 * i + 17] = normal.z;
  139. }
  140. Model@ fromScratchModel = Model();
  141. VertexBuffer@ vb = VertexBuffer();
  142. IndexBuffer@ ib = IndexBuffer();
  143. Geometry@ geom = Geometry();
  144. // Shadowed buffer needed for raycasts to work, and so that data can be automatically restored on device loss
  145. vb.shadowed = true;
  146. // We could use the "legacy" element bitmask to define elements for more compact code, but let's demonstrate
  147. // defining the vertex elements explicitly to allow any element types and order
  148. Array<VertexElement> elements;
  149. elements.Push(VertexElement(TYPE_VECTOR3, SEM_POSITION));
  150. elements.Push(VertexElement(TYPE_VECTOR3, SEM_NORMAL));
  151. vb.SetSize(numVertices, elements);
  152. VectorBuffer temp;
  153. for (uint i = 0; i < numVertices * 6; ++i)
  154. temp.WriteFloat(vertexData[i]);
  155. vb.SetData(temp);
  156. ib.shadowed = true;
  157. ib.SetSize(numVertices, false);
  158. temp.Clear();
  159. for (uint i = 0; i < numVertices; ++i)
  160. temp.WriteUShort(indexData[i]);
  161. ib.SetData(temp);
  162. geom.SetVertexBuffer(0, vb);
  163. geom.SetIndexBuffer(ib);
  164. geom.SetDrawRange(TRIANGLE_LIST, 0, numVertices);
  165. fromScratchModel.numGeometries = 1;
  166. fromScratchModel.SetGeometry(0, 0, geom);
  167. fromScratchModel.boundingBox = BoundingBox(Vector3(-0.5, -0.5, -0.5), Vector3(0.5, 0.5, 0.5));
  168. // Though not necessary to render, the vertex & index buffers must be listed in the model so that it can be saved properly
  169. Array<VertexBuffer@> vertexBuffers;
  170. Array<IndexBuffer@> indexBuffers;
  171. vertexBuffers.Push(vb);
  172. indexBuffers.Push(ib);
  173. // Morph ranges could also be not defined. Here we simply define a zero range (no morphing) for the vertex buffer
  174. Array<uint> morphRangeStarts;
  175. Array<uint> morphRangeCounts;
  176. morphRangeStarts.Push(0);
  177. morphRangeCounts.Push(0);
  178. fromScratchModel.SetVertexBuffers(vertexBuffers, morphRangeStarts, morphRangeCounts);
  179. fromScratchModel.SetIndexBuffers(indexBuffers);
  180. Node@ node = scene_.CreateChild("FromScratchObject");
  181. node.position = Vector3(0.0, 3.0, 0.0);
  182. StaticModel@ object = node.CreateComponent("StaticModel");
  183. object.model = fromScratchModel;
  184. }
  185. // Create the camera
  186. cameraNode = Node("Camera");
  187. cameraNode.position = Vector3(0.0, 2.0, -20.0);
  188. Camera@ camera = cameraNode.CreateComponent("Camera");
  189. camera.farClip = 300.0f;
  190. }
  191. void CreateInstructions()
  192. {
  193. // Construct new Text object, set string to display and font to use
  194. Text@ instructionText = ui.root.CreateChild("Text");
  195. instructionText.text =
  196. "Use WASD keys and mouse/touch to move\n"
  197. "Space to toggle animation";
  198. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  199. // The text has multiple rows. Center them in relation to each other
  200. instructionText.textAlignment = HA_CENTER;
  201. // Position the text relative to the screen center
  202. instructionText.horizontalAlignment = HA_CENTER;
  203. instructionText.verticalAlignment = VA_CENTER;
  204. instructionText.SetPosition(0, ui.root.height / 4);
  205. }
  206. void SetupViewport()
  207. {
  208. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  209. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  210. renderer.viewports[0] = viewport;
  211. }
  212. void SubscribeToEvents()
  213. {
  214. // Subscribe HandleUpdate() function for processing update events
  215. SubscribeToEvent("Update", "HandleUpdate");
  216. }
  217. void MoveCamera(float timeStep)
  218. {
  219. // Do not move if the UI has a focused element (the console)
  220. if (ui.focusElement !is null)
  221. return;
  222. // Movement speed as world units per second
  223. const float MOVE_SPEED = 20.0f;
  224. // Mouse sensitivity as degrees per pixel
  225. const float MOUSE_SENSITIVITY = 0.1f;
  226. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  227. IntVector2 mouseMove = input.mouseMove;
  228. yaw += MOUSE_SENSITIVITY * mouseMove.x;
  229. pitch += MOUSE_SENSITIVITY * mouseMove.y;
  230. pitch = Clamp(pitch, -90.0, 90.0f);
  231. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  232. cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
  233. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  234. if (input.keyDown[KEY_W])
  235. cameraNode.Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  236. if (input.keyDown[KEY_S])
  237. cameraNode.Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  238. if (input.keyDown[KEY_A])
  239. cameraNode.Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  240. if (input.keyDown[KEY_D])
  241. cameraNode.Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  242. }
  243. void AnimateObjects(float timeStep)
  244. {
  245. animTime += timeStep * 100.0;
  246. // Repeat for each of the cloned vertex buffers
  247. for (uint i = 0; i < animatingBuffers.length; ++i)
  248. {
  249. float startPhase = animTime + i * 30.0;
  250. VertexBuffer@ buffer = animatingBuffers[i];
  251. // Need to prepare a VectorBuffer with all data (positions, normals, uvs...)
  252. VectorBuffer newData;
  253. uint numVertices = buffer.vertexCount;
  254. uint vertexSize = buffer.vertexSize;
  255. for (uint j = 0; j < numVertices; ++j)
  256. {
  257. // If there are duplicate vertices, animate them in phase of the original
  258. float phase = startPhase + vertexDuplicates[j] * 10.0f;
  259. Vector3 src = originalVertices[j];
  260. Vector3 dest;
  261. dest.x = src.x * (1.0 + 0.1 * Sin(phase));
  262. dest.y = src.y * (1.0 + 0.1 * Sin(phase + 60.0));
  263. dest.z = src.z * (1.0 + 0.1 * Sin(phase + 120.0));
  264. // Write position
  265. newData.WriteVector3(dest);
  266. // Copy other vertex elements
  267. originalVertexData.Seek(j * vertexSize + 12); // Seek past the vertex position
  268. for (uint k = 12; k < vertexSize; k += 4)
  269. newData.WriteFloat(originalVertexData.ReadFloat());
  270. }
  271. buffer.SetData(newData);
  272. }
  273. }
  274. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  275. {
  276. // Take the frame time step, which is stored as a float
  277. float timeStep = eventData["TimeStep"].GetFloat();
  278. // Toggle animation with space
  279. if (input.keyPress[KEY_SPACE])
  280. animate = !animate;
  281. // Move the camera, scale movement with time step
  282. MoveCamera(timeStep);
  283. // Animate objects' vertex data if enabled
  284. if (animate)
  285. AnimateObjects(timeStep);
  286. }
  287. // Create XML patch instructions for screen joystick layout specific to this sample app
  288. String patchInstructions =
  289. "<patch>"
  290. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />"
  291. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Animation</replace>"
  292. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">"
  293. " <element type=\"Text\">"
  294. " <attribute name=\"Name\" value=\"KeyBinding\" />"
  295. " <attribute name=\"Text\" value=\"SPACE\" />"
  296. " </element>"
  297. " </add>"
  298. "</patch>";