using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Events; #if GLEY_TRAFFIC_SYSTEM using TrafficManager = Gley.TrafficSystem.Internal.TrafficManager; #endif namespace Gley.TrafficSystem { public static class API { #region TrafficManager /// /// Initialize the traffic system /// /// Camera that follows the player or the player itself. /// Maximum number of traffic vehicles active at the same time. /// Available vehicles asset. public static void Initialize(Transform activeCamera, int nrOfVehicles, VehiclePool vehiclePool) { Initialize(activeCamera, nrOfVehicles, vehiclePool, new TrafficOptions()); } /// /// Initialize the traffic system /// /// Camera that follows the player or the player itself. /// Maximum number of traffic vehicles active at the same time. /// Available vehicles asset. /// An object used to store the initialization parameters. public static void Initialize(Transform activeCamera, int nrOfVehicles, VehiclePool vehiclePool, TrafficOptions trafficOptions) { Initialize(new Transform[] { activeCamera }, nrOfVehicles, vehiclePool, trafficOptions); } /// /// Initialize the traffic system /// /// Camera that follows the player or the player itself. /// Maximum number of traffic vehicles active at the same time. /// Available vehicles asset. /// An object used to store the initialization parameters. public static void Initialize(Transform[] activeCameras, int nrOfVehicles, VehiclePool vehiclePool, TrafficOptions trafficOptions) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.Initialize(activeCameras, nrOfVehicles, vehiclePool, trafficOptions); #endif } /// /// Check if the Traffic System is initialized /// /// true if initialized public static bool IsInitialized() { #if GLEY_TRAFFIC_SYSTEM if (TrafficManager.Exists) { return TrafficManager.Instance.IsInitialized(); } #endif return false; } /// /// Update the active camera that is used to remove vehicles when are not in view /// /// Represents the camera or the player prefab public static void SetCamera(Transform activeCamera) { SetCameras(new Transform[] { activeCamera }); } /// /// Update active cameras that are used to remove vehicles when are not in view /// this is used in multiplayer/split screen setups /// /// Represents the cameras or the players from your game public static void SetCameras(Transform[] activeCameras) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.UpdateCamera(activeCameras); #endif } /// /// All traffic vehicles in the scene will decelerate and change lanes towards the edge of the road to create space for special vehicles such as police or ambulances. /// /// If true vehicle will drive on the side of the road. /// Specifies the road side. public static void ClearPathForSpecialVehicles(bool active, RoadSide side) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.ClearPathForSpecialVehicles(active, side); #endif } /// /// When this method is called, the vehicle passed as param is no longer controlled by the traffic system /// until it is out of view and respawned /// /// The vehicle to be removed from the Traffic System. public static void StopVehicleDriving(GameObject vehicle) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.StopVehicleDriving(vehicle); #endif } /// /// Adds a vehicle and sets a predefined path to destination /// /// A Vector3 for the initial position. The vehicle will be placed on the closest waypoint from this position. /// The type of the vehicle to be instantiated. /// A Vector3 for the destination position. The closest waypoint from this position will be the destination of the vehicle. public static void AddVehicleWithPath(Vector3 position, VehicleTypes vehicleType, Vector3 destination) { AddVehicleWithPath(position, vehicleType, destination, null); } /// /// Adds a vehicle and sets a predefined path to destination /// /// A Vector3 for the initial position. The vehicle will be placed on the closest waypoint from this position. /// The type of the vehicle to be instantiated. /// A Vector3 for the destination position. The closest waypoint from this position will be the destination of the vehicle. /// Callback triggered after initialization. It returns the VehicleComponent and the waypoint index where the vehicle was instantiated. public static void AddVehicleWithPath(Vector3 position, VehicleTypes vehicleType, Vector3 destination, UnityAction completeMethod) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.AddVehicleWithPath(position, vehicleType, destination, completeMethod); #endif } /// /// Remove a specific vehicle from scene /// /// Root GameObject of the vehicle to remove public static void RemoveVehicle(GameObject vehicle) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.RemoveVehicle(vehicle); #endif } /// /// Remove a specific vehicle from scene /// /// Index of the vehicle to remove public static void RemoveVehicle(int vehicleIndex) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.RemoveVehicle(vehicleIndex, true); #endif } /// /// Removes all the vehicles from a given area. /// /// The center of the circle to remove vehicles from. /// The radius in meters of the circle to remove vehicles from. public static void ClearTrafficOnArea(Vector3 center, float radius) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.ClearTrafficOnArea(center, radius); #endif } /// /// Set how far away active intersections should be -> default is 1 /// If set to 2 -> intersections will update on a 2 square distance from the player /// /// How many squares away should intersections be updated public static void SetActiveSquares(int level) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.SetActiveSquaresLevel(level); #endif } #endregion #region Density /// /// Modify max number of active vehicles /// /// New max number of vehicles, needs to be less than the initialization max number of vehicles public static void SetTrafficDensity(int nrOfVehicles) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.DensityManager?.SetTrafficDensity(nrOfVehicles); #endif } /// /// Disable all waypoints on the specified area to stop vehicles to go in a certain area for a limited amount of time /// /// The center of the circle to disable waypoints from. /// The radius in meters of the circle to disable waypoints from. public static void DisableAreaWaypoints(Vector3 center, float radius) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.DensityManager?.DisableAreaWaypoints(new Area(center, radius)); #endif } /// /// This will instantiate an excluded vehicle, the vehicle will work normally, but when it is removed it will not be instantiated again /// If the index sent as parameter is not an excluded vehicle, it will be ignored /// Call AddExcludedVehicleToSystem to make it behave normally /// /// Index of the excluded vehicle /// It will be instantiated at the closest waypoint from the position sent as parameter public static void AddExcludedVehicle(int vehicleIndex, Vector3 position) { AddExcludedVehicle(vehicleIndex, position, null); } /// /// This will instantiate an excluded vehicle, the vehicle will work normally, but when it is removed it will not be instantiated again /// If the index sent as parameter is not an excluded vehicle, it will be ignored /// Call AddExcludedVehicleToSystem to make it behave normally /// /// Index of the excluded vehicle /// It will be instantiated at the closest waypoint from the position sent as parameter /// Callback triggered after instantiation. It returns the VehicleComponent and the waypoint index where the vehicle was instantiated. public static void AddExcludedVehicle(int vehicleIndex, Vector3 position, UnityAction completeMethod) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.DensityManager?.AddExcludedVehicle(vehicleIndex, position, completeMethod); #endif } /// /// Add a traffic vehicle to the closest waypoint from the given position /// This method will wait until that vehicle type is available and the closest waypoint will be free to add a new vehicle on it. /// The method will run in background until the new vehicle is added. /// /// The position where to add a new vehicle /// The type of vehicle to add public static void AddVehicle(Vector3 position, VehicleTypes vehicleType) { AddVehicle(position, vehicleType, null); } /// /// Add a traffic vehicle to the closest waypoint from the given position /// This method will wait until that vehicle type is available and the closest waypoint will be free to add a new vehicle on it. /// The method will run in background until the new vehicle is added. /// /// The position where to add a new vehicle /// The type of vehicle to add /// Callback triggered after instantiation. It returns the VehicleComponent and the waypoint index where the vehicle was instantiated. public static void AddVehicle(Vector3 position, VehicleTypes vehicleType, UnityAction completeMethod) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.DensityManager?.AddVehicleAtPosition(position, vehicleType, completeMethod, null); #endif } #endregion #region TrafficVehicles /// /// Turn all vehicle lights on or off /// /// If true, lights are on public static void UpdateVehicleLights(bool on) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.AllVehiclesDataHandler?.UpdateVehicleLights(on); #endif } /// /// Control the engine volume from your master volume /// /// Current engine AudioSource volume public static void SetEngineVolume(float volume) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.SoundManager?.UpdateMasterVolume(volume); #endif } /// /// After the vehicle is disabled, it will not be instantiated anymore by the Traffic System /// /// Index of the vehicle to be excluded public static void ExcludeVehicleFromSystem(int vehicleIndex) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.DensityManager?.ExcludeVehicleFromSystem(vehicleIndex); #endif } /// /// Add a previously excluded vehicle back to the Traffic System /// /// Index of the vehicle to be added back to the system public static void AddExcludedVehicleToSystem(int vehicleIndex) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.DensityManager?.AddExcludecVehicleToSystem(vehicleIndex); #endif } /// /// Gets the index of a vehicle GameObject. /// /// The root GameObject of a traffic vehicle. /// The list index of the vehicle (-1 = error) public static int GetVehicleIndex(GameObject vehicle) { #if GLEY_TRAFFIC_SYSTEM if (TrafficManager.Instance.AllVehiclesDataHandler != null) { return TrafficManager.Instance.AllVehiclesDataHandler.GetVehicleIndex(vehicle); } #endif return -1; } /// /// Gets the Vehicle Component from the vehicle with the index passed as a parameter. /// /// The index of the vehicle to get the component from. /// the component from the vehicle with the index passed as a parameter. public static VehicleComponent GetVehicleComponent(int vehicleIndex) { #if GLEY_TRAFFIC_SYSTEM if (TrafficManager.Instance.AllVehiclesDataHandler != null) { return TrafficManager.Instance.AllVehiclesDataHandler.GetVehicle(vehicleIndex); } #endif return null; } /// /// Returns a list of all excluded vehicles. /// /// A list of all VehicleComponents that are currently excluded public static List GetExcludedVehicleList() { #if GLEY_TRAFFIC_SYSTEM return TrafficManager.Instance.AllVehiclesDataHandler?.GetExcludedVehicleList(); #else return null; #endif } /// /// Converts the excluded vehicle GameObject into its corresponding vehicle index. /// /// The root GameObject of an excluded vehicle. /// The vehicle index (-1 = error) public static int GetExcludedVehicleIndex(GameObject vehicle) { #if GLEY_TRAFFIC_SYSTEM if (TrafficManager.Instance.AllVehiclesDataHandler != null) { return TrafficManager.Instance.AllVehiclesDataHandler.GetExcludedVehicleIndex(vehicle); } #endif return -1; } /// ///If a vehicle detects a collider and that collider is destroyed by another script, ///the OnTriggerExit method is not automatically triggered. ///In such cases, this method needs to be manually invoked to remove the obstacle in front of the traffic vehicle. /// /// The removed collider. public static void TriggerColliderRemovedEvent(Collider collider) { #if GLEY_TRAFFIC_SYSTEM TriggerColliderRemovedEvent(new Collider[] { collider }); #endif } public static void TriggerColliderRemovedEvent(Collider[] collider) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.AllVehiclesDataHandler?.TriggerColliderRemovedEvent(collider); #endif } /// /// Get a list of all vehicles used by the Traffic System. /// /// A list with all vehicle components [Obsolete("GetVehicleList is deprecated, please use GetAllVehicles instead.")] public static List GetVehicleList() { #if GLEY_TRAFFIC_SYSTEM return TrafficManager.Instance.AllVehiclesDataHandler?.GetAllVehicles().ToList(); #else return null; #endif } public static VehicleComponent[] GetAllVehicles() { #if GLEY_TRAFFIC_SYSTEM return TrafficManager.Instance.AllVehiclesDataHandler?.GetAllVehicles(); #else return null; #endif } /// /// Get the current speed in km/h of the vehicle /// /// The index of the vehicle /// public static float GetVehicleSpeed(int vehicleIndex) { #if GLEY_TRAFFIC_SYSTEM if (TrafficManager.Instance.AllVehiclesDataHandler != null) { return TrafficManager.Instance.AllVehiclesDataHandler.GetCurrentSpeed(vehicleIndex); } #endif return 0; } /// /// Get the current state of the vehicle /// /// The index of the vehicle /// public static DriveActions GetVehicleState(int vehicleIndex) { #if GLEY_TRAFFIC_SYSTEM if (TrafficManager.Instance.AllVehiclesDataHandler != null) { return TrafficManager.Instance.AllVehiclesDataHandler.GetCurrentAction(vehicleIndex); } #endif return DriveActions.Continue; } /// /// Completely remove a vehicle from the traffic system. Scripts will no longer interact with the vehicle sent as parameter /// /// The index of the vehicle. public static void RemoveVehicleControl(int vehicleIndex) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.RemoveVehicleControl(vehicleIndex); #endif } /// /// Return a previously removed vehicle back to the traffic system. /// /// The index of the vehicle. public static void AddVehicleControl(int vehicleIndex) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.AddVehicleControl(vehicleIndex); #endif } #endregion #region Waypoint /// /// Enable all disabled area waypoints /// public static void EnableAllWaypoints() { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.WaypointManager?.EnableAllWaypoints(); #endif } /// /// A specific predefined path can be assigned to any active vehicle within the Traffic System. /// /// /// public static void SetVehiclePath(int vehicleIndex, Queue pathWaypoints) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.WaypointManager?.SetAgentPath(vehicleIndex, pathWaypoints); #endif } /// /// Remove a predefined path for a vehicle. /// /// The index of the vehicle to remove the path from. public static void RemoveVehiclePath(int vehicleIndex) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.WaypointManager?.RemoveAgentPath(vehicleIndex); #endif } /// /// Returns the Waypoint object for a given waypoint index. /// /// The index of the waypoint. /// The Waypoint object at the index position inside the waypoint list public static Internal.TrafficWaypoint GetWaypointFromIndex(int waypointIndex) { #if GLEY_TRAFFIC_SYSTEM return TrafficManager.Instance.TrafficWaypointsDataHandler?.GetWaypointFromIndex(waypointIndex); #else return null; #endif } /// /// Add from code an event on a specific waypoint. /// /// The index of the waypoint on which to add the event. /// The event data is utilized to recognize and respond to the event. public static void AddWaypointEvent(int waypointIndex, string data) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.TrafficWaypointsDataHandler?.SetEventData(waypointIndex, data); #endif } /// /// Remove an event from a waypoint. /// /// The waypoint to remove the event from. public static void RemoveWaypointEvent(int waypointIndex) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.TrafficWaypointsDataHandler?.SetEventData(waypointIndex, null); #endif } #endregion #region Intersection /// /// Force a road from a traffic light intersection to change to green /// /// Name of the intersection to change /// The road index to change /// If true that road will stay green until this param is set back to false public static void SetIntersectionRoadToGreen(string intersectionName, int roadIndex, bool doNotChangeAgain = false) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.AllIntersectionsHandler?.SetRoadToGreen(intersectionName, roadIndex, doNotChangeAgain); #endif } #endregion #region DrivingAI /// /// Enable/disable hazard lights for a vehicle /// /// The index of the vehicle /// True - means hazard lights are on public static void SetHazardLights(int vehicleIndex, bool activate) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.DrivingAI?.SetHazardLights(vehicleIndex, activate); #endif } /// /// Add an external driving action to a traffic vehicle to customize its behavior. /// /// The index of the vehicle. /// The DriveAction action to be added /// If true, all the preexisting actions for that vehicle will be cleared and just the current one will be added. public static void AddDrivingAction(int vehicleIndex, DriveActions action, bool force) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.DrivingAI?.AddDriveAction(vehicleIndex, action, force); #endif } /// /// Remove a specific drive action from a vehicle. /// /// The index of the vehicle. /// Action to remove public static void RemoveDrivingAction(int vehicleIndex, DriveActions action) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.DrivingAI?.RemoveDriveAction(vehicleIndex, action); #endif } /// /// Force a traffic vehicle to change the lane in the indicated direction. /// /// If true the ChangeLane action will be added to the vehicle, otherwise it will be removed. /// The index of the vehicle. /// The road side for changing the lane. public static void ChangeLane(bool active, int vehicleIndex, RoadSide side = RoadSide.Any) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.DrivingAI?.ChangeLane(active, vehicleIndex, side); #endif } #endregion #region PathFinding /// /// Calculates a path from the current position of the vehicle to a specified destination. /// /// The index of the vehicle. /// The destination position. public static void SetDestination(int vehicleIndex, Vector3 position) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.SetDestination(vehicleIndex, position); #endif } /// /// Returns a waypoint path between a start position and an end position for a specific vehicle type. /// /// A Vector3 for the initial position. /// A Vector3 for the final position. /// The vehicle type for which this path is intended. /// The waypoint indexes of the path between startPosition and endPosition. public static List GetPath(Vector3 startPosition, Vector3 endPosition, VehicleTypes vehicleType) { #if GLEY_TRAFFIC_SYSTEM return TrafficManager.Instance.PathFindingManager?.GetPath(startPosition, endPosition, vehicleType); #else return null; #endif } #endregion #region Crossings /// /// Inform the priority pedestrian crossing that pedestrians started to cross /// /// The name of the street crossing /// Stop the cars /// Currently not used, no automatic update implemented public static void SetPriorityCrossingStopState(string crossingName, bool stop, bool stopUpdate = true) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.AllIntersectionsHandler.SetPriorityCrossingState(crossingName, stop, stopUpdate); #endif } /// /// Get the state stop state of a crossing /// /// The name of the street crossing /// true -> cars will stop public static bool GetPriorityCrossingStopState(string crossingName) { #if GLEY_TRAFFIC_SYSTEM if (TrafficManager.Instance.AllIntersectionsHandler != null) { return TrafficManager.Instance.AllIntersectionsHandler.IsPriorityCrossingRed(crossingName); } #endif return false; } /// /// Get the color of the vehicle traffic light /// /// The name of the crossing to check /// The color of the traffic light public static TrafficLightsColor GetTrafficLightsCrossingState(string crossingName) { #if GLEY_TRAFFIC_SYSTEM if (TrafficManager.Instance.AllIntersectionsHandler != null) { return TrafficManager.Instance.AllIntersectionsHandler.GetTrafficLightsCrossingState(crossingName); } #endif return TrafficLightsColor.Red; } /// /// Manually set the traffic light crossing state. The crossing will change instantly to the new color. /// /// The name of the crossing to change. /// The new color. /// Stop crossing from automatically changing colors from now on. public static void SetTrafficLightsCrossingState(string crossingName, TrafficLightsColor newColor, bool stopUpdate = false) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.AllIntersectionsHandler.SetCrossingState(crossingName, newColor, stopUpdate, TrafficManager.Instance.TimeManager.RealTimeSinceStartup); #endif } /// /// Provides access to the waypoint data stored inside the grid. Useful for extending the plugin. /// /// An instance of GridDataHandler internal static UrbanSystem.Internal.GridDataHandler GetGridDataHandler() { #if GLEY_TRAFFIC_SYSTEM return TrafficManager.Instance.GridDataHandler; #else return null; #endif } #endregion /// /// Instantiates a vehicle on the specified position with an initial velocity. /// /// The index of the vehicle to be instantiated. Can be active or inactive at the time of instantiation. /// The vehicle will be instantiated with the front wheels on this position. /// The rotation of the instantiated vehicle. /// The initial linear velocity. /// The initial angular velocity. /// The waypoint the vehicle will go towards. public static void InstantiateTrafficVehicle(int vehicleIndex, Vector3 frontWheelsPosition, Quaternion vehicleRotation, Vector3 initialVelocity, Vector3 initialAngularVelocity, int nextWaypointIndex) { #if GLEY_TRAFFIC_SYSTEM TrafficManager.Instance.InstantiateTrafficVehicle(vehicleIndex, frontWheelsPosition, vehicleRotation, initialVelocity, initialAngularVelocity, nextWaypointIndex); #endif } /// /// Get the closest waypoint to a position. Uses a direction vector to select the correct lane. /// /// The position from which the closest waypoint will be selected. /// The moving direction. /// The index of the closest waypoint public static int GetClosestWaypoint(Vector3 position, Vector3 direction) { #if GLEY_TRAFFIC_SYSTEM return TrafficManager.Instance.GetClosestWaypoint(position, direction); #else return -1; #endif } } }