LightweightRVO.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using Pathfinding.RVO;
  4. namespace Pathfinding.Examples {
  5. [RequireComponent(typeof(MeshFilter))]
  6. /// <summary>
  7. /// Lightweight RVO Circle Example.
  8. /// Lightweight script for simulating agents in a circle trying to reach their antipodal positions.
  9. /// This script, compared to using lots of RVOAgents shows the real power of the RVO simulator when
  10. /// little other overhead (e.g GameObjects) is present.
  11. ///
  12. /// For example with this script, I can simulate 5000 agents at around 50 fps on my laptop (with desired simulation fps = 10 and interpolation, 2 threads)
  13. /// however when using prefabs, only instantiating the 5000 agents takes 10 seconds and it runs at around 5 fps.
  14. ///
  15. /// This script will render the agents by generating a square for each agent combined into a single mesh with appropriate UV.
  16. ///
  17. /// A few GUI buttons will be drawn by this script with which the user can change the number of agents.
  18. /// </summary>
  19. [HelpURL("http://arongranberg.com/astar/documentation/stable/class_pathfinding_1_1_examples_1_1_lightweight_r_v_o.php")]
  20. public class LightweightRVO : MonoBehaviour {
  21. /// <summary>Number of agents created at start</summary>
  22. public int agentCount = 100;
  23. /// <summary>
  24. /// How large is the area where agents are placed.
  25. /// For e.g the circle example, it corresponds
  26. /// </summary>
  27. public float exampleScale = 100;
  28. public enum RVOExampleType {
  29. Circle,
  30. Line,
  31. Point,
  32. RandomStreams,
  33. Crossing
  34. }
  35. public RVOExampleType type = RVOExampleType.Circle;
  36. /// <summary>Agent radius</summary>
  37. public float radius = 3;
  38. /// <summary>Max speed for an agent</summary>
  39. public float maxSpeed = 2;
  40. /// <summary>How far in the future too look for agents</summary>
  41. public float agentTimeHorizon = 10;
  42. [HideInInspector]
  43. /// <summary>How far in the future too look for obstacles</summary>
  44. public float obstacleTimeHorizon = 10;
  45. /// <summary>Max number of neighbour agents to take into account</summary>
  46. public int maxNeighbours = 10;
  47. /// <summary>
  48. /// Offset from the agent position the actual drawn postition.
  49. /// Used to get rid of z-buffer issues
  50. /// </summary>
  51. public Vector3 renderingOffset = Vector3.up*0.1f;
  52. /// <summary>Enable the debug flag for all agents</summary>
  53. public bool debug = false;
  54. /// <summary>Mesh for rendering</summary>
  55. Mesh mesh;
  56. /// <summary>Reference to the simulator in the scene</summary>
  57. Pathfinding.RVO.Simulator sim;
  58. /// <summary>All agents handled by this script</summary>
  59. List<IAgent> agents;
  60. /// <summary>Goals for each agent</summary>
  61. List<Vector3> goals;
  62. /// <summary>Color for each agent</summary>
  63. List<Color> colors;
  64. Vector3[] verts;
  65. Vector2[] uv;
  66. int[] tris;
  67. Color[] meshColors;
  68. Vector2[] interpolatedVelocities;
  69. Vector2[] interpolatedRotations;
  70. public void Start () {
  71. mesh = new Mesh();
  72. RVOSimulator rvoSim = FindObjectOfType(typeof(RVOSimulator)) as RVOSimulator;
  73. if (rvoSim == null) {
  74. Debug.LogError("No RVOSimulator could be found in the scene. Please add a RVOSimulator component to any GameObject");
  75. return;
  76. }
  77. sim = rvoSim.GetSimulator();
  78. GetComponent<MeshFilter>().mesh = mesh;
  79. CreateAgents(agentCount);
  80. }
  81. public void OnGUI () {
  82. if (GUILayout.Button("2")) CreateAgents(2);
  83. if (GUILayout.Button("10")) CreateAgents(10);
  84. if (GUILayout.Button("100")) CreateAgents(100);
  85. if (GUILayout.Button("500")) CreateAgents(500);
  86. if (GUILayout.Button("1000")) CreateAgents(1000);
  87. if (GUILayout.Button("5000")) CreateAgents(5000);
  88. GUILayout.Space(5);
  89. if (GUILayout.Button("Random Streams")) {
  90. type = RVOExampleType.RandomStreams;
  91. CreateAgents(agents != null ? agents.Count : 100);
  92. }
  93. if (GUILayout.Button("Line")) {
  94. type = RVOExampleType.Line;
  95. CreateAgents(agents != null ? Mathf.Min(agents.Count, 100) : 10);
  96. }
  97. if (GUILayout.Button("Circle")) {
  98. type = RVOExampleType.Circle;
  99. CreateAgents(agents != null ? agents.Count : 100);
  100. }
  101. if (GUILayout.Button("Point")) {
  102. type = RVOExampleType.Point;
  103. CreateAgents(agents != null ? agents.Count : 100);
  104. }
  105. if (GUILayout.Button("Crossing")) {
  106. type = RVOExampleType.Crossing;
  107. CreateAgents(agents != null ? agents.Count : 100);
  108. }
  109. }
  110. private float uniformDistance (float radius) {
  111. float v = Random.value + Random.value;
  112. if (v > 1) return radius * (2-v);
  113. else return radius * v;
  114. }
  115. /// <summary>Create a number of agents in circle and restart simulation</summary>
  116. public void CreateAgents (int num) {
  117. this.agentCount = num;
  118. agents = new List<IAgent>(agentCount);
  119. goals = new List<Vector3>(agentCount);
  120. colors = new List<Color>(agentCount);
  121. sim.ClearAgents();
  122. if (type == RVOExampleType.Circle) {
  123. float circleRad = Mathf.Sqrt(agentCount * radius * radius * 4 / Mathf.PI) * exampleScale * 0.05f;
  124. for (int i = 0; i < agentCount; i++) {
  125. Vector3 pos = new Vector3(Mathf.Cos(i * Mathf.PI * 2.0f / agentCount), 0, Mathf.Sin(i * Mathf.PI * 2.0f / agentCount)) * circleRad * (1 + Random.value * 0.01f);
  126. IAgent agent = sim.AddAgent(new Vector2(pos.x, pos.z), pos.y);
  127. agents.Add(agent);
  128. goals.Add(-pos);
  129. colors.Add(AstarMath.HSVToRGB(i * 360.0f / agentCount, 0.8f, 0.6f));
  130. }
  131. } else if (type == RVOExampleType.Line) {
  132. for (int i = 0; i < agentCount; i++) {
  133. Vector3 pos = new Vector3((i % 2 == 0 ? 1 : -1) * exampleScale, 0, (i / 2) * radius * 2.5f);
  134. IAgent agent = sim.AddAgent(new Vector2(pos.x, pos.z), pos.y);
  135. agents.Add(agent);
  136. goals.Add(new Vector3(-pos.x, pos.y, pos.z));
  137. colors.Add(i % 2 == 0 ? Color.red : Color.blue);
  138. }
  139. } else if (type == RVOExampleType.Point) {
  140. for (int i = 0; i < agentCount; i++) {
  141. Vector3 pos = new Vector3(Mathf.Cos(i * Mathf.PI * 2.0f / agentCount), 0, Mathf.Sin(i * Mathf.PI * 2.0f / agentCount)) * exampleScale;
  142. IAgent agent = sim.AddAgent(new Vector2(pos.x, pos.z), pos.y);
  143. agents.Add(agent);
  144. goals.Add(new Vector3(0, pos.y, 0));
  145. colors.Add(AstarMath.HSVToRGB(i * 360.0f / agentCount, 0.8f, 0.6f));
  146. }
  147. } else if (type == RVOExampleType.RandomStreams) {
  148. float circleRad = Mathf.Sqrt(agentCount * radius * radius * 4 / Mathf.PI) * exampleScale * 0.05f;
  149. for (int i = 0; i < agentCount; i++) {
  150. float angle = Random.value * Mathf.PI * 2.0f;
  151. float targetAngle = Random.value * Mathf.PI * 2.0f;
  152. Vector3 pos = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * uniformDistance(circleRad);
  153. IAgent agent = sim.AddAgent(new Vector2(pos.x, pos.z), pos.y);
  154. agents.Add(agent);
  155. goals.Add(new Vector3(Mathf.Cos(targetAngle), 0, Mathf.Sin(targetAngle)) * uniformDistance(circleRad));
  156. colors.Add(AstarMath.HSVToRGB(targetAngle * Mathf.Rad2Deg, 0.8f, 0.6f));
  157. }
  158. } else if (type == RVOExampleType.Crossing) {
  159. float distanceBetweenGroups = exampleScale * radius * 0.5f;
  160. int directions = (int)Mathf.Sqrt(agentCount / 25f);
  161. directions = Mathf.Max(directions, 2);
  162. const int AgentsPerDistance = 10;
  163. for (int i = 0; i < agentCount; i++) {
  164. float angle = ((i % directions)/(float)directions) * Mathf.PI * 2.0f;
  165. var dist = distanceBetweenGroups * ((i/(directions*AgentsPerDistance) + 1) + 0.3f*Random.value);
  166. Vector3 pos = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * dist;
  167. IAgent agent = sim.AddAgent(new Vector2(pos.x, pos.z), pos.y);
  168. agent.Priority = (i % directions) == 0 ? 1 : 0.01f;
  169. agents.Add(agent);
  170. goals.Add(-pos.normalized * distanceBetweenGroups * 3);
  171. colors.Add(AstarMath.HSVToRGB(angle * Mathf.Rad2Deg, 0.8f, 0.6f));
  172. }
  173. }
  174. SetAgentSettings();
  175. verts = new Vector3[4*agents.Count];
  176. uv = new Vector2[verts.Length];
  177. tris = new int[agents.Count*2*3];
  178. meshColors = new Color[verts.Length];
  179. }
  180. void SetAgentSettings () {
  181. for (int i = 0; i < agents.Count; i++) {
  182. IAgent agent = agents[i];
  183. agent.Radius = radius;
  184. agent.AgentTimeHorizon = agentTimeHorizon;
  185. agent.ObstacleTimeHorizon = obstacleTimeHorizon;
  186. agent.MaxNeighbours = maxNeighbours;
  187. agent.DebugDraw = i == 0 && debug;
  188. }
  189. }
  190. public void Update () {
  191. if (agents == null || mesh == null) return;
  192. if (agents.Count != goals.Count) {
  193. Debug.LogError("Agent count does not match goal count");
  194. return;
  195. }
  196. SetAgentSettings();
  197. // Make sure the array is large enough
  198. if (interpolatedVelocities == null || interpolatedVelocities.Length < agents.Count) {
  199. var velocities = new Vector2[agents.Count];
  200. var directions = new Vector2[agents.Count];
  201. // Copy over the old velocities
  202. if (interpolatedVelocities != null) for (int i = 0; i < interpolatedVelocities.Length; i++) velocities[i] = interpolatedVelocities[i];
  203. if (interpolatedRotations != null) for (int i = 0; i < interpolatedRotations.Length; i++) directions[i] = interpolatedRotations[i];
  204. interpolatedVelocities = velocities;
  205. interpolatedRotations = directions;
  206. }
  207. for (int i = 0; i < agents.Count; i++) {
  208. IAgent agent = agents[i];
  209. // Move agent
  210. // This is the responsibility of this script, not the RVO system
  211. Vector2 pos = agent.Position;
  212. var deltaPosition = Vector2.ClampMagnitude(agent.CalculatedTargetPoint - pos, agent.CalculatedSpeed * Time.deltaTime);
  213. pos += deltaPosition;
  214. agent.Position = pos;
  215. // All agents are on the same plane
  216. agent.ElevationCoordinate = 0;
  217. // Set the desired velocity for all agents
  218. var target = new Vector2(goals[i].x, goals[i].z);
  219. var dist = (target - pos).magnitude;
  220. agent.SetTarget(target, Mathf.Min(dist, maxSpeed), maxSpeed*1.1f);
  221. interpolatedVelocities[i] += deltaPosition;
  222. if (interpolatedVelocities[i].magnitude > maxSpeed*0.1f) {
  223. interpolatedVelocities[i] = Vector2.ClampMagnitude(interpolatedVelocities[i], maxSpeed*0.1f);
  224. interpolatedRotations[i] = Vector2.Lerp(interpolatedRotations[i], interpolatedVelocities[i], agent.CalculatedSpeed * Time.deltaTime*4f);
  225. }
  226. //Debug.DrawRay(new Vector3(pos.x, 0, pos.y), new Vector3(interpolatedVelocities[i].x, 0, interpolatedVelocities[i].y) * 10);
  227. // Create a square with the "forward" direction along the agent's velocity
  228. Vector3 forward = new Vector3(interpolatedRotations[i].x, 0, interpolatedRotations[i].y).normalized * agent.Radius;
  229. if (forward == Vector3.zero) forward = new Vector3(0, 0, agent.Radius);
  230. Vector3 right = Vector3.Cross(Vector3.up, forward);
  231. Vector3 orig = new Vector3(agent.Position.x, agent.ElevationCoordinate, agent.Position.y) + renderingOffset;
  232. int vc = 4*i;
  233. int tc = 2*3*i;
  234. verts[vc+0] = (orig + forward - right);
  235. verts[vc+1] = (orig + forward + right);
  236. verts[vc+2] = (orig - forward + right);
  237. verts[vc+3] = (orig - forward - right);
  238. uv[vc+0] = (new Vector2(0, 1));
  239. uv[vc+1] = (new Vector2(1, 1));
  240. uv[vc+2] = (new Vector2(1, 0));
  241. uv[vc+3] = (new Vector2(0, 0));
  242. meshColors[vc+0] = colors[i];
  243. meshColors[vc+1] = colors[i];
  244. meshColors[vc+2] = colors[i];
  245. meshColors[vc+3] = colors[i];
  246. tris[tc+0] = (vc + 0);
  247. tris[tc+1] = (vc + 1);
  248. tris[tc+2] = (vc + 2);
  249. tris[tc+3] = (vc + 0);
  250. tris[tc+4] = (vc + 2);
  251. tris[tc+5] = (vc + 3);
  252. }
  253. //Update the mesh
  254. mesh.Clear();
  255. mesh.vertices = verts;
  256. mesh.uv = uv;
  257. mesh.colors = meshColors;
  258. mesh.triangles = tris;
  259. mesh.RecalculateNormals();
  260. }
  261. }
  262. }