Esempio n. 1
0
 /// <summary>
 /// If connected, get the screenshot file path from the python script over the socket and remove any invalid characters from the path.
 /// </summary>
 /// /// <param name="vehicle">The vehicle to create.</param>
 void Start()
 {
     if (Settings.IsBenchmark())
     {
         Debug.Log("Running Benchmark");
         SocketManager.GetInstance().SetSocket(new MockSocket());
         StartCoroutine(RunBenchmark());
     }
     if (SocketManager.GetInstance().Connect())
     {
         screenshotPath = string.Concat(SocketManager.GetInstance().ReceiveString().Replace('\\', '/').Split(System.IO.Path.GetInvalidPathChars()));
         TrafficLightManager.GetInstance().RefreshTrafficLightsAndJunctions();
         SocketManager.GetInstance().Send(TrafficLightManager.GetInstance().GetJunctions().Max(j => j.GetJunctionStates().Length) + "");
         StartCoroutine(MainLoop());
     }
     else
     {
         Debug.Log("Unable to connect to the Python Script. Running the demo instead.");
         if (SumoManager.GetInstance() == null || !SumoManager.GetInstance().IsConnected() || !SumoManager.GetInstance().IsControlledBySumo(SumoLinkControlPoint.TRAFFIC_LIGHTS))
         {
             TrafficLightManager.GetInstance().RunDemo();
         }
     }
     densityLengthConstant = FindObjectsOfType <Path>().Select(path => path.GetDistanceUntilDensityMeasurePointInKM()).Sum();
 }
Esempio n. 2
0
    public void SetScreenshot(Camera camera, Texture2D screenshot)
    {
        byte[]   bytes    = screenshot.EncodeToPNG();
        Junction junction = TrafficLightManager.GetInstance().GetJunctions().ToList().Find(j => j.GetJunctionCamera() == camera);

        File.WriteAllBytes(GetScreenshotFilePath(screenshotPath, junction.junctionId, GetJunctionScreenshotCount(junction)), bytes);
    }
Esempio n. 3
0
    public IEnumerator TrafficLightNodeTest()
    {
        DisableLoops();
        yield return(null);

        TrafficLightManager trafficLightManager = (TrafficLightManager)GameObject.FindObjectOfType(typeof(TrafficLightManager));
        GameObject          pathObject          = new GameObject("TestPath", typeof(Path));
        GameObject          node1        = new GameObject("1");
        GameObject          node2        = new GameObject("2");
        GameObject          trafficLight = new GameObject("TrafficLight", typeof(TrafficLight));

        pathObject   = GameObject.Instantiate(pathObject);
        node1        = GameObject.Instantiate(node1, pathObject.transform);
        node2        = GameObject.Instantiate(node2, pathObject.transform);
        trafficLight = GameObject.Instantiate(trafficLight);

        trafficLightManager.trafficLights    = new TrafficLight[1];
        trafficLightManager.trafficLights[0] = trafficLight.GetComponent <TrafficLight>();
        trafficLightManager.trafficLights[0].stopNodes.Add(node2.transform);

        Assert.False(trafficLightManager.IsStopNode(node1.transform));
        Assert.True(trafficLightManager.IsStopNode(node2.transform));

        Assert.AreEqual(trafficLightManager.trafficLights[0], trafficLightManager.GetTrafficLightFromStopNode(node2.transform));
    }
Esempio n. 4
0
    public IEnumerator VehicleEngineDestroyTest()
    {
        yield return(null);

        DisableLoops();
        VehicleFactory vehicleFactory = (VehicleFactory)GameObject.FindObjectOfType(typeof(VehicleFactory));

        foreach (TrafficLight trafficLight in TrafficLightManager.GetInstance().trafficLights)
        {
            trafficLight.SetColour(TrafficLight.LightColour.GREEN);
        }
        Rigidbody vehicle        = vehicleFactory.SpawnVehicle(vehicleFactory.GetRandomVehicle(), vehicleFactory.GetRandomUnusedPath());
        bool      carIsDestroyed = false;

        for (int i = 0; i <= TIME_OUT_DESTROY_TIME; i = i + 5)
        {
            yield return(new WaitForSeconds(5));

            if (vehicle == null)
            {
                carIsDestroyed = true;
                break;
            }
        }
        Assert.True(carIsDestroyed);
    }
Esempio n. 5
0
 /// <summary>
 /// Checks and adjusts the speed accordingly.
 /// Speed in kilometers per hour
 /// </summary>
 private void SpeedCheck()
 {
     // If starting to turn
     if (Math.Abs(wheelColliderFrontLeft.steerAngle) > 2)
     {
         SetTargetSpeed(maxSpeedTurning);
     }
     else
     {
         SetTargetSpeed(maxSpeed);
     }
     if (currentNodeNumber + 1 < path.nodes.Count)
     {
         // If next node is a traffic light
         if (TrafficLightManager.GetInstance().IsStopNode(path.nodes[currentNodeNumber + 1]))
         {
             SetTargetSpeed(maxSpeedApproachingLightsLastNode);
         }
     }
     if (currentNodeNumber + 2 < path.nodes.Count)
     {
         // If 2nd to next node is a traffic light
         if (TrafficLightManager.GetInstance().IsStopNode(path.nodes[currentNodeNumber + 2]))
         {
             SetTargetSpeed(maxSpeedApproachingLightsSecondLastNode);
         }
     }
 }
Esempio n. 6
0
    /// <summary>
    /// Resets all the traffic lights to red and then waits.
    /// </summary>
    public IEnumerator Reset()
    {
        TrafficLightManager.GetInstance().SetAllToRed();
        yield return(new WaitForSeconds(20));

        Time.timeScale = 0;
    }
Esempio n. 7
0
 public int Receive(byte[] buffer)
 {
     if (receiveCounter == 0)
     {
         string screenshotPath = System.IO.Path.Combine(Application.dataPath, "Screenshots");
         if (!Directory.Exists(screenshotPath))
         {
             Directory.CreateDirectory(screenshotPath);
         }
         PushDataIntoBuffer(buffer, screenshotPath);
     }
     else
     {
         List <PythonManager.PythonAction> pythonActionsList = new List <PythonManager.PythonAction>();
         foreach (Junction junction in TrafficLightManager.GetInstance().GetJunctions())
         {
             pythonActionsList.Add(new PythonManager.PythonAction(junction.junctionId, Random.Range(0, junction.GetJunctionStates().Length)));
         }
         PythonManager.PythonActions pythonActions = new PythonManager.PythonActions();
         pythonActions.actions = pythonActionsList.ToArray();
         PushDataIntoBuffer(buffer, JsonUtility.ToJson(pythonActions));
     }
     receiveCounter++;
     return(buffer.Length);
 }
 // Start is called before the first frame update
 private void Start()
 {
     TrafficLightManager = TrafficLightManager.Instance;
     WarningLightManager = SpecialObjectManager.Instance;
     Debug.Log("Connecting to " + BrokerHostname);
     Connect();
     Client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
     byte[] qosLevels = { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE };
     Client.Subscribe(new string[] { TeamId + "/#" }, qosLevels);
 }
Esempio n. 9
0
    public static PositionPair get_destination(TrafficLightManager moving_thing, Tilemap tilemap, Vector2 offset)
    {
        // modify by offset for a person boarding a train (so hes not standing on the tracks)
        Vector3Int   tile_coord       = new Vector3Int(moving_thing.tile_position[0], moving_thing.tile_position[1], 0);
        Tile         track_tile       = (Tile)tilemap.GetTile(tile_coord);
        Vector2      tile_world_coord = tilemap.GetCellCenterWorld(tile_coord);
        PositionPair pos_pair         = get_next_tile_pos(tilemap, track_tile, moving_thing, tile_coord, offset);
        Tile         city_tile        = (Tile)city_tilemap.GetTile(tile_coord);

        return(pos_pair);
    }
    private void Awake()
    {
        if (_instance == null)
        {
            _instance = this;
        }

        if (_instance != this)
        {
            DestroyImmediate(gameObject);
        }
    }
Esempio n. 11
0
    public void DisableLoops()
    {
        TrafficLightManager trafficLightManager = (TrafficLightManager)GameObject.FindObjectOfType(typeof(TrafficLightManager));

        trafficLightManager.StopAllCoroutines();
        PythonManager.GetInstance().StopAllCoroutines();
        PedestrianFactory pedestrianFactory = (PedestrianFactory)GameObject.FindObjectOfType(typeof(PedestrianFactory));

        if (pedestrianFactory != null)
        {
            pedestrianFactory.StopAllCoroutines();
        }
    }
Esempio n. 12
0
    public IEnumerator VehicleEngineStopTest()
    {
        DisableLoops();
        VehicleFactory vehicleFactory = (VehicleFactory)GameObject.FindObjectOfType(typeof(VehicleFactory));

        TrafficLightManager.GetInstance().SetAllToRed();
        Rigidbody     vehicle       = vehicleFactory.SpawnVehicle(vehicleFactory.GetRandomVehicle(), vehicleFactory.GetRandomUnusedPath());
        VehicleEngine vehicleEngine = vehicle.GetComponent <VehicleEngine>();

        yield return(new WaitForSeconds(STOP_LIGHT_TIME));

        Assert.True(vehicleEngine.GetEngineStatus() == VehicleEngine.EngineStatus.STOP || vehicleEngine.GetEngineStatus() == VehicleEngine.EngineStatus.HARD_STOP);
    }
Esempio n. 13
0
    /// <summary>
    /// Sends the file path as a string to the socket using the SocketManager.
    /// </summary>
    public IEnumerator SendScreenshots()
    {
        List <PythonScreenshot> screenshots = new List <PythonScreenshot>();

        foreach (Junction junction in TrafficLightManager.GetInstance().GetJunctions())
        {
            screenshots.Add(new PythonScreenshot(junction.junctionId, GetScreenshotFilePath("", junction.junctionId, GetJunctionScreenshotCount(junction))));
        }
        PythonScreenshots pythonScreenshots = new PythonScreenshots(screenshots);

        SocketManager.GetInstance().Send(JsonUtility.ToJson(pythonScreenshots));
        yield return(null);
    }
Esempio n. 14
0
 private void CheckTrafficLightIsGreen(string id)
 {
     foreach (TrafficLight trafficLight in TrafficLightManager.GetInstance().GetTrafficLights())
     {
         if (trafficLight.GetTrafficLightId().Equals(id))
         {
             Assert.AreEqual(TrafficLight.LightColour.GREEN, trafficLight.GetCurrentLightColour());
         }
         else
         {
             Assert.AreEqual(TrafficLight.LightColour.RED, trafficLight.GetCurrentLightColour());
         }
     }
 }
Esempio n. 15
0
    public IEnumerator TrafficLightFirstEventTest()
    {
        DisableLoops();
        TrafficLightManager trafficLightManager = (TrafficLightManager)GameObject.FindObjectOfType(typeof(TrafficLightManager));

        trafficLightManager.StartCoroutine(trafficLightManager.FirstEvent());
        yield return(null);

        foreach (TrafficLight trafficLight in trafficLightManager.GetTrafficLights())
        {
            Assert.AreEqual(TrafficLight.LightColour.RED, trafficLight.GetCurrentLightColour());
        }
        trafficLightManager.StopAllCoroutines();
    }
Esempio n. 16
0
    /// <summary>
    /// Gets the action which is an int sent by the python script.
    /// It uses the int by converting it into a traffic light id.
    /// All traffic lights are then set to red and it waits.
    /// Once the wait is over that traffic light with the specified ID is then changed to green.
    /// </summary>
    public IEnumerator GetActions()
    {
        string        dataString    = SocketManager.GetInstance().ReceiveString();
        PythonActions pythonActions = JsonUtility.FromJson <PythonActions>(dataString);

        TrafficLightManager.GetInstance().SetAllToRed();
        Time.timeScale = 1;
        yield return(new WaitForSeconds(10));

        foreach (PythonAction pythonAction in pythonActions.actions)
        {
            TrafficLightManager.GetInstance().GetJunction(pythonAction.junctionId).SetJunctionState(pythonAction.action + 1);
        }
        yield return(null);
    }
Esempio n. 17
0
 public void SetJunctionState(JunctionState junctionState)
 {
     this.currentState = junctionState.GetStateNumber();
     foreach (JunctionState.TrafficLightState trafficLightState in junctionState.GetTrafficLightStates())
     {
         TrafficLightManager.GetInstance().GetTrafficLight(trafficLightState.GetTrafficLightId()).SetColour(trafficLightState.GetLightColour());
     }
     if (junctionState.GetPedestrianCrossingStates() != null)
     {
         foreach (JunctionState.PedestrianCrossingState pedestrianCrossingState in junctionState.GetPedestrianCrossingStates())
         {
             PedestrianManager.GetInstance().GetPedestrianCrossing(pedestrianCrossingState.GetPedestrianCrossingId()).SetAllowCrossing(pedestrianCrossingState.AllowCrossing());
         }
     }
 }
Esempio n. 18
0
    /// <summary>
    /// Runs on the initial load of this script
    /// </summary>
    private void Start()
    {
        SensorManager        = SensorManager.Instance;
        TrafficLightManager  = TrafficLightManager.Instance;
        SpecialObjectManager = SpecialObjectManager.Instance;
        TrafficSpawnManager  = TrafficSpawnManager.Instance;
        PathName             = Path.PathSequence[0].parent.parent.parent.name;
        LightName            = GetCurrentTrafficlight();

        //Make sure there is a path assigned
        if (Path == null)
        {
            Debug.LogError("Movement Path cannot be null, I must have a path to follow.", gameObject);
            return;
        }
    }
Esempio n. 19
0
    /// <summary>
    /// Takes a screen shot and then stores it in within the screenshots folder.
    /// </summary>
    public IEnumerator TakeScreenshots()
    {
        foreach (Junction junction in TrafficLightManager.GetInstance().GetJunctions())
        {
            Camera camera = junction.GetJunctionCamera();
            if (camera == null)
            {
                throw new System.Exception("Unable to get camera for junction: " + junction.junctionId);
            }
            junctionShotCount[junction] = GetJunctionScreenshotCount(junction) + 1;
            CameraManager cameraManager = camera.GetComponent <CameraManager>();
            cameraManager.SetRenderScreenshot();
            camera.Render();
        }

        yield return(null);
    }
Esempio n. 20
0
    public IEnumerator TrafficLightFireNextEventTest()
    {
        DisableLoops();
        TrafficLightManager trafficLightManager = (TrafficLightManager)GameObject.FindObjectOfType(typeof(TrafficLightManager));

        foreach (Junction junction in trafficLightManager.GetJunctions())
        {
            junction.SetJunctionState(junction.GetFirstJunctionState());
            for (int i = 1; i < junction.GetJunctionStates().Length; i++)
            {
                trafficLightManager.StartCoroutine(trafficLightManager.FireNextEvent());
                yield return(new WaitForSeconds(6));

                Assert.AreEqual(i + 1, junction.GetCurrentState());
            }
        }
        trafficLightManager.StopAllCoroutines();
    }
Esempio n. 21
0
    /// <summary>
    /// The update method to check and update values for the vehicle.
    /// </summary>
    private void FixedUpdate()
    {
        if (path == null)
        {
            return;
        }
        if (Vector3.Distance(transform.TransformPoint(0, 0, nodeReadingOffset), currentNode.position) < 3f)
        {
            NextNode();
        }
        if (currentNodeNumber == path.nodes.Count - 1)
        {
            Destroy();
            return;
        }
        ApplySteer();
        WheelCollider nonePoweredWheel = GetComponentsInChildren <WheelCollider>().First(wheel => wheel != wheelColliderFrontLeft && wheel != wheelColliderFrontRight);

        currentSpeed = 2 * Mathf.PI * nonePoweredWheel.radius * nonePoweredWheel.rpm * 60 / 1000;
        SpeedCheck();
        SensorCheck();
        TrafficLight trafficLight = TrafficLightManager.GetInstance().GetTrafficLightFromStopNode(currentNode);

        if ((trafficLight != null && trafficLight.IsCurrentLightColour(TrafficLight.LightColour.RED)) || this.gameObject.tag == "hap")
        {
            SetEngineStatus(EngineStatus.HARD_STOP);
        }
        else if (currentSpeed < targetSpeed && currentSpeed < maxSpeed)
        {
            SetEngineStatus(EngineStatus.ACCELERATE);
        }
        else
        {
            SetEngineStatus(EngineStatus.STOP);
        }
        if (startDelayTime == -1 && trafficLight != null)
        {
            startDelayTime = Time.time;
        }
    }
Esempio n. 22
0
    private new void DisableLoops()
    {
        // Optimize time by removing unneeded particles
        foreach (ParticleSystem particleSystem in GameObject.FindObjectsOfType <ParticleSystem>())
        {
            particleSystem.Stop();
        }
        TrafficLightManager trafficLightManager = (TrafficLightManager)GameObject.FindObjectOfType(typeof(TrafficLightManager));

        trafficLightManager.enabled = false;
        trafficLightManager.StopAllCoroutines();
        VehicleFactory vehicleFactory = (VehicleFactory)GameObject.FindObjectOfType(typeof(VehicleFactory));

        vehicleFactory.StopAllCoroutines();
        PythonManager.GetInstance().StopAllCoroutines();
        PedestrianFactory pedestrianFactory = (PedestrianFactory)GameObject.FindObjectOfType(typeof(PedestrianFactory));

        if (pedestrianFactory != null)
        {
            pedestrianFactory.StopAllCoroutines();
        }
    }
Esempio n. 23
0
        static void Main(string[] args)
        {
#if false
            var manager = new NoInheritance.NoPolymorphManager();
            manager.DoYourThing();
#elif false
            var manager = new BadPolymorphManager();
            manager.DoYourThing();
#elif false
            var manager = new VirtualInheritance.VirtualPolymorphManager();
            manager.DoYourThing();
#elif false
            var manager = new AbstractInheritance.AbstractPolymorphManager();
            manager.DoYourThing();
#elif false
            //ILogger logger = new DebugLogger();
            ILogger logger  = new ConsoleLogger();
            var     manager = new GoodLiskovManager(logger);
            manager.DoYourThing();
#elif false
            //ILogger logger = new DebugLogger();
            ILogger logger  = new ConsoleLogger();
            var     manager = new BadLiskovManager(logger);
            manager.DoYourThing();
#elif false
            var manager = new ObserverManager();
            manager.DoYourThing();
#elif true
            //ILogger logger = new DebugLogger();
            ILogger       logger = new ConsoleLogger();
            ITrafficLight lights = new RawTrafficLight(logger);
            //ITrafficLight lights = new CoolTrafficLight(logger);
            var manager = new TrafficLightManager(logger, lights);
            manager.DoYourThing();
#endif
        }
Esempio n. 24
0
        public void ShowGUI(bool viewOnly)
        {
            try {
                TrafficLightSimulationManager tlsMan  = TrafficLightSimulationManager.Instance;
                TrafficPriorityManager        prioMan = TrafficPriorityManager.Instance;
                TrafficLightManager           tlm     = TrafficLightManager.Instance;

                bool clicked = !viewOnly?MainTool.CheckClicked() : false;

                var hoveredSegment = false;
                //Log.Message("_guiPrioritySigns called. num of prio segments: " + TrafficPriority.PrioritySegments.Count);

                HashSet <ushort> nodeIdsWithSigns = new HashSet <ushort>();
                foreach (ushort segmentId in currentPrioritySegmentIds)
                {
                    var trafficSegment = prioMan.TrafficSegments[segmentId];
                    if (trafficSegment == null)
                    {
                        continue;
                    }
                    SegmentGeometry geometry = SegmentGeometry.Get(segmentId);

                    prioritySegments[0] = null;
                    prioritySegments[1] = null;

                    if (tlsMan.GetNodeSimulation(trafficSegment.Node1) == null)
                    {
                        SegmentEnd tmpSeg1   = prioMan.GetPrioritySegment(trafficSegment.Node1, segmentId);
                        bool       startNode = geometry.StartNodeId() == trafficSegment.Node1;
                        if (tmpSeg1 != null && !geometry.IsOutgoingOneWay(startNode))
                        {
                            prioritySegments[0] = tmpSeg1;
                            nodeIdsWithSigns.Add(trafficSegment.Node1);
                            prioMan.AddPriorityNode(trafficSegment.Node1);
                        }
                    }
                    if (tlsMan.GetNodeSimulation(trafficSegment.Node2) == null)
                    {
                        SegmentEnd tmpSeg2   = prioMan.GetPrioritySegment(trafficSegment.Node2, segmentId);
                        bool       startNode = geometry.StartNodeId() == trafficSegment.Node2;
                        if (tmpSeg2 != null && !geometry.IsOutgoingOneWay(startNode))
                        {
                            prioritySegments[1] = tmpSeg2;
                            nodeIdsWithSigns.Add(trafficSegment.Node2);
                            prioMan.AddPriorityNode(trafficSegment.Node2);
                        }
                    }

                    //Log.Message("init ok");

                    foreach (var prioritySegment in prioritySegments)
                    {
                        if (prioritySegment == null)
                        {
                            continue;
                        }

                        var nodeId = prioritySegment.NodeId;
                        //Log.Message("_guiPrioritySigns: nodeId=" + nodeId);

                        var nodePositionVector3 = Singleton <NetManager> .instance.m_nodes.m_buffer[nodeId].m_position;
                        var camPos = Singleton <SimulationManager> .instance.m_simulationView.m_position;
                        var diff   = nodePositionVector3 - camPos;
                        if (diff.magnitude > TrafficManagerTool.PriorityCloseLod)
                        {
                            continue;                             // do not draw if too distant
                        }
                        if (Singleton <NetManager> .instance.m_segments.m_buffer[segmentId].m_startNode == (ushort)nodeId)
                        {
                            nodePositionVector3.x += Singleton <NetManager> .instance.m_segments.m_buffer[segmentId].m_startDirection.x * 10f;
                            nodePositionVector3.y += Singleton <NetManager> .instance.m_segments.m_buffer[segmentId].m_startDirection.y * 10f;
                            nodePositionVector3.z += Singleton <NetManager> .instance.m_segments.m_buffer[segmentId].m_startDirection.z * 10f;
                        }
                        else
                        {
                            nodePositionVector3.x += Singleton <NetManager> .instance.m_segments.m_buffer[segmentId].m_endDirection.x * 10f;
                            nodePositionVector3.y += Singleton <NetManager> .instance.m_segments.m_buffer[segmentId].m_endDirection.y * 10f;
                            nodePositionVector3.z += Singleton <NetManager> .instance.m_segments.m_buffer[segmentId].m_endDirection.z * 10f;
                        }

                        var nodeScreenPosition = Camera.main.WorldToScreenPoint(nodePositionVector3);
                        nodeScreenPosition.y = Screen.height - nodeScreenPosition.y;
                        if (nodeScreenPosition.z < 0)
                        {
                            continue;
                        }
                        var zoom            = 1.0f / diff.magnitude * 100f * MainTool.GetBaseZoom();
                        var size            = 110f * zoom;
                        var guiColor        = GUI.color;
                        var nodeBoundingBox = new Rect(nodeScreenPosition.x - size / 2, nodeScreenPosition.y - size / 2, size, size);
                        hoveredSegment = !viewOnly && TrafficManagerTool.IsMouseOver(nodeBoundingBox);

                        if (hoveredSegment)
                        {
                            // mouse hovering over sign
                            guiColor.a = 0.8f;
                        }
                        else
                        {
                            guiColor.a = 0.5f;
                            size       = 90f * zoom;
                        }
                        var nodeDrawingBox = new Rect(nodeScreenPosition.x - size / 2, nodeScreenPosition.y - size / 2, size, size);

                        GUI.color = guiColor;

                        bool setUndefinedSignsToMainRoad = false;
                        switch (prioritySegment.Type)
                        {
                        case SegmentEnd.PriorityType.Main:
                            GUI.DrawTexture(nodeDrawingBox, TrafficLightToolTextureResources.SignPriorityTexture2D);
                            if (clicked && hoveredSegment)
                            {
                                //Log._Debug("Click on node " + nodeId + ", segment " + segmentId + " to change prio type (1)");
                                //Log.Message("PrioritySegment.Type = Yield");
                                prioritySegment.Type        = SegmentEnd.PriorityType.Yield;
                                setUndefinedSignsToMainRoad = true;
                                clicked = false;
                            }
                            break;

                        case SegmentEnd.PriorityType.Yield:
                            GUI.DrawTexture(nodeDrawingBox, TrafficLightToolTextureResources.SignYieldTexture2D);
                            if (clicked && hoveredSegment)
                            {
                                //Log._Debug("Click on node " + nodeId + ", segment " + segmentId + " to change prio type (2)");
                                prioritySegment.Type        = SegmentEnd.PriorityType.Stop;
                                setUndefinedSignsToMainRoad = true;
                                clicked = false;
                            }

                            break;

                        case SegmentEnd.PriorityType.Stop:
                            GUI.DrawTexture(nodeDrawingBox, TrafficLightToolTextureResources.SignStopTexture2D);
                            if (clicked && hoveredSegment)
                            {
                                //Log._Debug("Click on node " + nodeId + ", segment " + segmentId + " to change prio type (3)");
                                prioritySegment.Type = SegmentEnd.PriorityType.Main;
                                clicked = false;
                            }
                            break;

                        case SegmentEnd.PriorityType.None:
                            if (viewOnly)
                            {
                                break;
                            }
                            GUI.DrawTexture(nodeDrawingBox, TrafficLightToolTextureResources.SignNoneTexture2D);

                            if (clicked && hoveredSegment)
                            {
                                //Log._Debug("Click on node " + nodeId + ", segment " + segmentId + " to change prio type (4)");
                                //Log.Message("PrioritySegment.Type = None");
                                prioritySegment.Type = GetNumberOfMainRoads(nodeId, ref Singleton <NetManager> .instance.m_nodes.m_buffer[nodeId]) >= 2
                                                                                ? SegmentEnd.PriorityType.Yield
                                                                                : SegmentEnd.PriorityType.Main;
                                if (prioritySegment.Type == SegmentEnd.PriorityType.Yield)
                                {
                                    setUndefinedSignsToMainRoad = true;
                                }
                                clicked = false;
                            }
                            break;
                        }

                        if (setUndefinedSignsToMainRoad)
                        {
                            foreach (var otherPrioritySegment in prioMan.GetPrioritySegments(nodeId))
                            {
                                if (otherPrioritySegment.SegmentId == prioritySegment.SegmentId)
                                {
                                    continue;
                                }
                                if (otherPrioritySegment.Type == SegmentEnd.PriorityType.None)
                                {
                                    otherPrioritySegment.Type = SegmentEnd.PriorityType.Main;
                                }
                            }
                        }
                    }
                }

                if (viewOnly)
                {
                    return;
                }

                ushort hoveredExistingNodeId = 0;
                foreach (ushort nodeId in nodeIdsWithSigns)
                {
                    var nodePositionVector3 = Singleton <NetManager> .instance.m_nodes.m_buffer[nodeId].m_position;
                    var camPos = Singleton <SimulationManager> .instance.m_simulationView.m_position;
                    var diff   = nodePositionVector3 - camPos;
                    if (diff.magnitude > TrafficManagerTool.PriorityCloseLod)
                    {
                        continue;
                    }

                    // draw deletion button
                    var nodeScreenPosition = Camera.main.WorldToScreenPoint(nodePositionVector3);
                    nodeScreenPosition.y = Screen.height - nodeScreenPosition.y;
                    if (nodeScreenPosition.z < 0)
                    {
                        continue;
                    }
                    var zoom            = 1.0f / diff.magnitude * 100f * MainTool.GetBaseZoom();
                    var size            = 90f * zoom;
                    var nodeBoundingBox = new Rect(nodeScreenPosition.x - size / 2, nodeScreenPosition.y - size / 2, size, size);

                    var guiColor          = GUI.color;
                    var nodeCenterHovered = TrafficManagerTool.IsMouseOver(nodeBoundingBox);
                    if (nodeCenterHovered)
                    {
                        hoveredExistingNodeId = nodeId;
                        guiColor.a            = 0.8f;
                    }
                    else
                    {
                        guiColor.a = 0.5f;
                    }
                    GUI.color = guiColor;

                    GUI.DrawTexture(nodeBoundingBox, TrafficLightToolTextureResources.SignRemoveTexture2D);
                }

                // add a new or delete a priority segment node
                if (HoveredNodeId != 0 || hoveredExistingNodeId != 0)
                {
                    bool delete = false;
                    if (hoveredExistingNodeId != 0)
                    {
                        delete = true;
                    }

                    // determine if we may add new priority signs to this node
                    bool ok = false;
                    TrafficLightSimulation nodeSim = tlsMan.GetNodeSimulation(HoveredNodeId);
                    if ((Singleton <NetManager> .instance.m_nodes.m_buffer[HoveredNodeId].m_flags & NetNode.Flags.TrafficLights) == NetNode.Flags.None)
                    {
                        // no traffic light set
                        ok = true;
                    }
                    else if (nodeSim == null || !nodeSim.IsTimedLight())
                    {
                        ok = true;
                    }

                    if (!Flags.mayHaveTrafficLight(HoveredNodeId))
                    {
                        ok = false;
                    }

                    if (clicked)
                    {
                        Log._Debug("_guiPrioritySigns: hovered+clicked @ nodeId=" + HoveredNodeId + "/" + hoveredExistingNodeId + " ok=" + ok);

                        if (delete)
                        {
                            prioMan.RemovePrioritySegments(hoveredExistingNodeId);
                            RefreshCurrentPrioritySegmentIds();
                        }
                        else if (ok)
                        {
                            //if (!prioMan.IsPriorityNode(HoveredNodeId)) {
                            Log._Debug("_guiPrioritySigns: adding prio segments @ nodeId=" + HoveredNodeId);
                            tlsMan.RemoveNodeFromSimulation(HoveredNodeId, false, true);
                            tlm.RemoveTrafficLight(HoveredNodeId);
                            prioMan.AddPriorityNode(HoveredNodeId);
                            RefreshCurrentPrioritySegmentIds();
                            //}
                        }
                        else if (nodeSim != null && nodeSim.IsTimedLight())
                        {
                            MainTool.ShowTooltip(Translation.GetString("NODE_IS_TIMED_LIGHT"), Singleton <NetManager> .instance.m_nodes.m_buffer[HoveredNodeId].m_position);
                        }
                    }
                }
            } catch (Exception e) {
                Log.Error(e.ToString());
            }
        }
Esempio n. 25
0
    public IEnumerator VehicleEngineSpeedTest()
    {
        yield return(null);

        DisableLoops();
        VehicleFactory vehicleFactory = (VehicleFactory)GameObject.FindObjectOfType(typeof(VehicleFactory));

        foreach (TrafficLight trafficLight in TrafficLightManager.GetInstance().trafficLights)
        {
            trafficLight.SetColour(TrafficLight.LightColour.GREEN);
        }
        Path pathWithTurning = null;

        foreach (Path path in vehicleFactory.paths)
        {
            float xRange = path.nodes.Select(node => node.position.x).Max() - path.nodes.Select(node => node.position.x).Min();
            float zRange = path.nodes.Select(node => node.position.z).Max() - path.nodes.Select(node => node.position.z).Min();
            // Path has turning
            if (xRange != 0 && zRange != 0)
            {
                pathWithTurning = path;
                break;
            }
        }
        if (pathWithTurning == null)
        {
            Assert.Inconclusive("Unable to test. No paths with turnings.");
        }
        Rigidbody     vehicle        = vehicleFactory.SpawnVehicle(vehicleFactory.GetRandomVehicle(), pathWithTurning);
        VehicleEngine vehicleEngine  = vehicle.GetComponent <VehicleEngine>();
        bool          carIsDestroyed = false;

        for (int i = 0; i <= TIME_OUT_DESTROY_TIME; i = i + 5)
        {
            yield return(new WaitForSeconds(5));

            if (vehicle == null)
            {
                carIsDestroyed = true;
                break;
            }

            if (Math.Abs(vehicleEngine.wheelColliderFrontLeft.steerAngle) > 2)
            {
                Assert.AreEqual(vehicleEngine.maxSpeedTurning, vehicleEngine.targetSpeed, "Turning Speed");
            }

            if (vehicleEngine.currentNodeNumber + 1 < vehicleEngine.path.nodes.Count)
            {
                // If next node is a traffic light
                if (TrafficLightManager.GetInstance().IsStopNode(vehicleEngine.path.nodes[vehicleEngine.currentNodeNumber + 1]))
                {
                    Assert.AreEqual(vehicleEngine.maxSpeedApproachingLightsLastNode, vehicleEngine.targetSpeed, "Speed Approaching last node");
                }
            }
            if (vehicleEngine.currentNodeNumber + 2 < vehicleEngine.path.nodes.Count)
            {
                // If 2nd to next node is a traffic light
                if (TrafficLightManager.GetInstance().IsStopNode(vehicleEngine.path.nodes[vehicleEngine.currentNodeNumber + 2]))
                {
                    Assert.AreEqual(vehicleEngine.maxSpeedApproachingLightsSecondLastNode, vehicleEngine.targetSpeed, "Speed Approaching second to last node");
                }
            }
        }
        Assert.True(carIsDestroyed);
    }
Esempio n. 26
0
 void Awake()
 {
     RefreshTrafficLightsAndJunctions();
     instance = this;
 }
Esempio n. 27
0
    /**
      * Methods
      */
    void Start()
    {
        LoadMaterials();

        _timeDisplay = e_RemainingTimeDisplay;
        _timeDisplayRenderer = e_RemainingTimeDisplayRenderer;

        _greenTime = e_GreenTime;
        _yellowTime = e_YellowTime;
        _redTime = e_RedTime;

        _greenLight = e_GreenLight;
        _yellowLight = e_YellowLight;
        _redLight = e_RedLight;

        _engine = e_TrafficLightEngine;

        _lightTimer = new Clock();

        Reset ();

        Active = false;
        UpdateLight();
    }
Esempio n. 28
0
    void Start()
    {
        vehicleFactory = FindObjectOfType <VehicleFactory>();
        string filePath = System.IO.Path.Combine(Application.dataPath, "Sumo");

        ImportAndGenerate.parseXMLfiles(filePath);
        ImportAndGenerate.CreateStreetNetwork();
        client = new TraCIClient();
        if (client.Connect(ip, port))
        {
            Debug.Log("Connected to Sumo");
            connected = true;
        }
        else
        {
            Debug.Log("Unable to connect to Sumo");
            this.enabled = false;
            return;
        }
        FindObjectOfType <CameraManager>().frameRate = 60;
        StartCoroutine(Run());
        vehicleFactory.StopAllCoroutines();
        TrafficLightManager.GetInstance().RefreshTrafficLightsAndJunctions();

        // Traffic Flow
        if (!IsControlledBySumo(SumoLinkControlPoint.TRAFFIC_FLOW))
        {
            StartCoroutine(RunTraffic3DTrafficFlow());
        }

        // Traffic Lights
        List <string> junctionIds = client.TrafficLight.GetIdList().Content;

        foreach (string id in junctionIds)
        {
            List <string> controlledLanes = client.TrafficLight.GetControlledLanes(id).Content;
            string        currentState    = client.TrafficLight.GetState(id).Content;
            for (int i = 0; i < controlledLanes.Count; i++)
            {
                TrafficLight trafficLight = TrafficLightManager.GetInstance().GetTrafficLight(controlledLanes[i]);
                if (trafficLight != null)
                {
                    SumoTrafficLight sumoTrafficLight = sumoTrafficLights.Find(s => s.trafficLight.trafficLightId.Equals(trafficLight.trafficLightId));
                    if (sumoTrafficLight == null)
                    {
                        sumoTrafficLights.Add(new SumoTrafficLight(trafficLight, id, new HashSet <int>()
                        {
                            i
                        }));
                    }
                    else
                    {
                        sumoTrafficLight.AddIndexState(i);
                    }
                }
            }
            // Remove all current traffic light programs in Sumo
            if (!IsControlledBySumo(SumoLinkControlPoint.TRAFFIC_LIGHTS))
            {
                client.TrafficLight.SetRedYellowGreenState(id, new string('r', currentState.Length));
                client.TrafficLight.SetPhaseDuration(id, Double.MaxValue);
            }
        }
        if (IsControlledBySumo(SumoLinkControlPoint.TRAFFIC_LIGHTS))
        {
            TrafficLightManager.GetInstance().StopAllCoroutines();
            StartCoroutine(RunTrafficLights());
        }
        else
        {
            TrafficLightManager.GetInstance().trafficLightChangeEvent += ChangeSumoTrafficLights;

            foreach (tlLogicType tlLogicType in ImportAndGenerate.trafficLightPrograms.Values)
            {
                int      stateCounter = 0;
                Junction junction     = FindObjectsOfType <Junction>().ToList().Find(j => j.junctionId.Equals(tlLogicType.id));
                List <SumoTrafficLight> sumoTrafficLightsForJunction = sumoTrafficLights.FindAll(sumoTrafficLight => sumoTrafficLight.junctionId.Equals(tlLogicType.id));
                foreach (object obj in tlLogicType.Items)
                {
                    if (obj is phaseType)
                    {
                        stateCounter++;
                        GameObject stateObject = new GameObject("State" + stateCounter);
                        stateObject.transform.SetParent(junction.gameObject.transform);
                        JunctionState junctionState = stateObject.AddComponent <JunctionState>();
                        junctionState.stateNumber        = stateCounter;
                        junctionState.trafficLightStates = new JunctionState.TrafficLightState[sumoTrafficLightsForJunction.Count()];
                        int       trafficLightStateCounter = 0;
                        phaseType phase = (phaseType)obj;

                        foreach (SumoTrafficLight sumoTrafficLight in sumoTrafficLightsForJunction)
                        {
                            TrafficLight.LightColour lightColour = sumoTrafficLight.GetLightColourFromStateString(phase.state);
                            junctionState.trafficLightStates[trafficLightStateCounter] = new JunctionState.TrafficLightState(sumoTrafficLight.trafficLight.trafficLightId, lightColour);
                            trafficLightStateCounter++;
                        }
                    }
                }
            }
        }
    }
        public void ShowGUI(bool viewOnly)
        {
            try {
                IExtSegmentManager            segMan    = Constants.ManagerFactory.ExtSegmentManager;
                IExtSegmentEndManager         segEndMan = Constants.ManagerFactory.ExtSegmentEndManager;
                TrafficLightSimulationManager tlsMan    = TrafficLightSimulationManager.Instance;
                TrafficPriorityManager        prioMan   = TrafficPriorityManager.Instance;
                TrafficLightManager           tlm       = TrafficLightManager.Instance;

                Vector3 camPos = Constants.ServiceFactory.SimulationService.CameraPosition;

                bool clicked = !viewOnly?MainTool.CheckClicked() : false;

                ushort removedNodeId    = 0;
                bool   showRemoveButton = false;
                foreach (ushort nodeId in currentPriorityNodeIds)
                {
                    if (!Constants.ServiceFactory.NetService.IsNodeValid(nodeId))
                    {
                        continue;
                    }

                    if (!MainTool.IsNodeWithinViewDistance(nodeId))
                    {
                        continue;
                    }

                    Vector3 nodePos = default(Vector3);
                    Constants.ServiceFactory.NetService.ProcessNode(nodeId, delegate(ushort nId, ref NetNode node) {
                        nodePos = node.m_position;
                        return(true);
                    });

                    for (int i = 0; i < 8; ++i)
                    {
                        ushort segmentId = 0;
                        Constants.ServiceFactory.NetService.ProcessNode(nodeId, delegate(ushort nId, ref NetNode node) {
                            segmentId = node.GetSegment(i);
                            return(true);
                        });

                        if (segmentId == 0)
                        {
                            continue;
                        }

                        bool          startNode = (bool)Constants.ServiceFactory.NetService.IsStartNode(segmentId, nodeId);
                        ExtSegment    seg       = segMan.ExtSegments[segmentId];
                        ExtSegmentEnd segEnd    = segEndMan.ExtSegmentEnds[segEndMan.GetIndex(segmentId, startNode)];

                        if (seg.oneWay && segEnd.outgoing)
                        {
                            continue;
                        }

                        // calculate sign position
                        Vector3 signPos = nodePos;

                        Constants.ServiceFactory.NetService.ProcessSegment(segmentId, delegate(ushort sId, ref NetSegment segment) {
                            signPos += 10f * (startNode ? segment.m_startDirection : segment.m_endDirection);
                            return(true);
                        });

                        Vector3 signScreenPos;
                        if (!MainTool.WorldToScreenPoint(signPos, out signScreenPos))
                        {
                            continue;
                        }

                        // draw sign and handle input
                        PriorityType sign = prioMan.GetPrioritySign(segmentId, startNode);
                        if (viewOnly && sign == PriorityType.None)
                        {
                            continue;
                        }
                        if (!viewOnly && sign != PriorityType.None)
                        {
                            showRemoveButton = true;
                        }

                        if (MainTool.DrawGenericSquareOverlayTexture(TextureResources.PrioritySignTextures[sign], camPos, signPos, 90f, !viewOnly) && clicked)
                        {
                            PriorityType?newSign = null;
                            switch (sign)
                            {
                            case PriorityType.Main:
                                newSign = PriorityType.Yield;
                                break;

                            case PriorityType.Yield:
                                newSign = PriorityType.Stop;
                                break;

                            case PriorityType.Stop:
                                newSign = PriorityType.Main;
                                break;

                            case PriorityType.None:
                            default:
                                newSign = prioMan.CountPrioritySignsAtNode(nodeId, PriorityType.Main) >= 2 ? PriorityType.Yield : PriorityType.Main;
                                break;
                            }

                            if (newSign != null)
                            {
                                SetPrioritySign(segmentId, startNode, (PriorityType)newSign);
                            }
                        }                 // draw sign
                    }                     // foreach segment end

                    if (viewOnly)
                    {
                        continue;
                    }

                    // draw remove button and handle click
                    if (showRemoveButton && MainTool.DrawHoverableSquareOverlayTexture(TextureResources.SignRemoveTexture2D, camPos, nodePos, 90f) && clicked)
                    {
                        prioMan.RemovePrioritySignsFromNode(nodeId);
                        Log._Debug($"PrioritySignsTool.ShowGUI: Removed priority signs from node {nodeId}");
                        removedNodeId = nodeId;
                    }
                }                 // foreach node

                if (removedNodeId != 0)
                {
                    currentPriorityNodeIds.Remove(removedNodeId);
                    SelectedNodeId = 0;
                }
            } catch (Exception e) {
                Log.Error(e.ToString());
            }
        }
Esempio n. 30
0
    private void Awake()
    {
        base.Awake();
        c = 2;
        initial_building_lot_name      = choose_random_initial_building_lot();
        Traffic_Light_Manager_Instance = Instantiate(TrafficLightManager);
        traffic_manager = Traffic_Light_Manager_Instance.GetComponent <TrafficLightManager>();
        Traffic_Light_Manager_Instance.transform.parent = gameObject.transform; // only activate when this city is activated
        total_room                 = 0;
        bldg_add_index             = 0;
        unapplied_reputation_count = 0;
        total_review_count         = 0;
        last_checked_reputation    = reputation;
        West_Station               = new Station(CityManager.west_start_outer, CityManager.west_start_inner, RouteManager.Orientation.West, RouteManager.shipyard_track_tilemap2, RouteManager.shipyard_track_tilemap);
        North_Station              = new Station(CityManager.north_start_outer, CityManager.north_start_inner, RouteManager.Orientation.North, RouteManager.shipyard_track_tilemap, RouteManager.shipyard_track_tilemap2);
        East_Station               = new Station(CityManager.east_start_outer, CityManager.east_start_inner, RouteManager.Orientation.East, RouteManager.shipyard_track_tilemap2, RouteManager.shipyard_track_tilemap);
        South_Station              = new Station(CityManager.south_start_outer, CityManager.south_start_inner, RouteManager.Orientation.South, RouteManager.shipyard_track_tilemap, RouteManager.shipyard_track_tilemap2);
        city_tilemap_go            = GameManager.city_tilemap_go;
        city_tilemap               = city_tilemap_go.GetComponent <Tilemap>();
        city_room_matrix           = new Room[board_width, board_height];
        city_board                 = new GameObject[board_width, board_height]; // zero out the negative tile coordinates
        inventory_item_board       = new Inventory_Item[board_width, board_height];
        north_bl         = Instantiate(BuildingLot);
        east_bl          = Instantiate(BuildingLot);
        west_bl          = Instantiate(BuildingLot);
        south_bl         = Instantiate(BuildingLot);
        start_reputation = PersonManager.reputation; // 0
        //remove_lot_btn = GameObject.Find("Remove Lot Button").GetComponent<Button>();
        //remove_lot_btn.onClick.AddListener(delegate { remove_lot(1); });

        north_bl.GetComponent <BuildingLot>().init_building_lot
        (
            "Building Lot North",
            new Vector2Int(2, 8),
            4,
            RouteManager.Orientation.North,
            RouteManager.Orientation.South,
            new List <Station_Track> {
            North_Station.inner_track, North_Station.outer_track
        },
            new int[] { 6, 0, 5 }
        );
        east_bl.GetComponent <BuildingLot>().init_building_lot
        (
            "Building Lot East",
            new Vector2Int(11, 8),
            4,
            RouteManager.Orientation.East,
            RouteManager.Orientation.West,
            new List <Station_Track> {
            East_Station.inner_track, East_Station.outer_track
        },
            new int[] { 6, 12, 16 }
        );
        west_bl.GetComponent <BuildingLot>().init_building_lot
        (
            "Building Lot West",
            new Vector2Int(2, 2),
            4,
            //RouteManager.Orientation.East,
            RouteManager.Orientation.West,
            RouteManager.Orientation.East,
            new List <Station_Track> {
            West_Station.inner_track, West_Station.outer_track
        },
            new int[] { 4, 0, 4 }
        );
        south_bl.GetComponent <BuildingLot>().init_building_lot
        (
            "Building Lot South",
            new Vector2Int(11, 2),
            4,
            //RouteManager.Orientation.East,
            RouteManager.Orientation.South,
            RouteManager.Orientation.North,
            new List <Station_Track> {
            South_Station.inner_track, South_Station.outer_track
        },
            new int[] { 4, 11, 16 }
        );

        building_map = new Dictionary <string, GameObject>()
        {
            { "Building Lot North", north_bl },
            { "Building Lot East", east_bl },
            { "Building Lot West", west_bl },
            { "Building Lot South", south_bl },
        };
    }