npc_agent.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #!/usr/bin/env python
  2. # This work is licensed under the terms of the MIT license.
  3. # For a copy, see <https://opensource.org/licenses/MIT>.
  4. """
  5. This module provides an NPC agent to control the ego vehicle
  6. """
  7. from __future__ import print_function
  8. import carla
  9. from agents.navigation.basic_agent import BasicAgent
  10. from srunner.autoagents.autonomous_agent import AutonomousAgent
  11. from srunner.scenariomanager.carla_data_provider import CarlaDataProvider
  12. class NpcAgent(AutonomousAgent):
  13. """
  14. NPC autonomous agent to control the ego vehicle
  15. """
  16. _agent = None
  17. _route_assigned = False
  18. def setup(self, path_to_conf_file):
  19. """
  20. Setup the agent parameters
  21. """
  22. self._route_assigned = False
  23. self._agent = None
  24. def sensors(self):
  25. """
  26. Define the sensor suite required by the agent
  27. :return: a list containing the required sensors in the following format:
  28. [
  29. {'type': 'sensor.camera.rgb', 'x': 0.7, 'y': -0.4, 'z': 1.60, 'roll': 0.0, 'pitch': 0.0, 'yaw': 0.0,
  30. 'width': 300, 'height': 200, 'fov': 100, 'id': 'Left'},
  31. {'type': 'sensor.camera.rgb', 'x': 0.7, 'y': 0.4, 'z': 1.60, 'roll': 0.0, 'pitch': 0.0, 'yaw': 0.0,
  32. 'width': 300, 'height': 200, 'fov': 100, 'id': 'Right'},
  33. {'type': 'sensor.lidar.ray_cast', 'x': 0.7, 'y': 0.0, 'z': 1.60, 'yaw': 0.0, 'pitch': 0.0, 'roll': 0.0,
  34. 'id': 'LIDAR'}
  35. """
  36. sensors = [
  37. {'type': 'sensor.camera.rgb', 'x': 0.7, 'y': -0.4, 'z': 1.60, 'roll': 0.0, 'pitch': 0.0, 'yaw': 0.0,
  38. 'width': 300, 'height': 200, 'fov': 100, 'id': 'Left'},
  39. ]
  40. return sensors
  41. def run_step(self, input_data, timestamp):
  42. """
  43. Execute one step of navigation.
  44. """
  45. control = carla.VehicleControl()
  46. control.steer = 0.0
  47. control.throttle = 0.0
  48. control.brake = 0.0
  49. control.hand_brake = False
  50. if not self._agent:
  51. hero_actor = None
  52. for actor in CarlaDataProvider.get_world().get_actors():
  53. if 'role_name' in actor.attributes and actor.attributes['role_name'] == 'hero':
  54. hero_actor = actor
  55. break
  56. if hero_actor:
  57. self._agent = BasicAgent(hero_actor)
  58. return control
  59. if not self._route_assigned:
  60. if self._global_plan:
  61. plan = []
  62. for transform, road_option in self._global_plan_world_coord:
  63. wp = CarlaDataProvider.get_map().get_waypoint(transform.location)
  64. plan.append((wp, road_option))
  65. self._agent._local_planner.set_global_plan(plan) # pylint: disable=protected-access
  66. self._route_assigned = True
  67. else:
  68. control = self._agent.run_step()
  69. return control