source: proiecte/ptvs/src/vnsim/core/Engine.java @ 114

Last change on this file since 114 was 114, checked in by (none), 14 years ago
File size: 68.2 KB
Line 
1package vnsim.core;
2
3
4import java.io.BufferedWriter;
5import java.io.DataInputStream;
6import java.io.DataOutputStream;
7import java.io.File;
8import java.io.FileInputStream;
9import java.io.FileOutputStream;
10import java.io.FileWriter;
11import java.io.IOException;
12import java.io.PrintWriter;
13import java.util.ArrayList;
14import java.util.Collections;
15import java.util.Iterator;
16import java.util.ListIterator;
17import java.util.Random;
18import java.util.Vector;
19import java.util.concurrent.ExecutorService;
20import java.util.concurrent.Executors;
21
22import vnsim.applications.adaptiveTL.IntersectionCarRecord;
23import vnsim.applications.adaptiveTL.WirelessTrafficLight;
24import vnsim.applications.emissions.EmissionsTrafficLight;
25import vnsim.applications.ezcab.EzcabCar;
26import vnsim.applications.ezcab.EzcabClient;
27import vnsim.applications.trafficview.SimulatedCarInfo;
28import vnsim.core.events.CleanupEvent;
29import vnsim.core.events.Event;
30import vnsim.core.events.GPSEvent;
31import vnsim.core.events.ReceiveEvent;
32import vnsim.core.events.SendEvent;
33import vnsim.core.events.UnicastSendEvent;
34import vnsim.map.object.Globals;
35import vnsim.map.object.Map;
36import vnsim.map.object.PeanoKey;
37import vnsim.map.object.Point;
38import vnsim.map.object.Road;
39import vnsim.map.utils.GPSutil;
40import vnsim.network.RadioDev;
41import vnsim.network.dsrc.Application;
42import vnsim.network.dsrc.CarRunningDSRC;
43import vnsim.network.dsrc.DSRCStatisticComponent;
44import vnsim.network.dsrc.DSRCStatistics;
45import vnsim.network.dsrc.EmergencyRequest;
46import vnsim.network.dsrc.MAC80211;
47import vnsim.network.dsrc.WirelessPhy;
48import vnsim.network.propagation.Ricean;
49import vnsim.network.scft.CarRunningSCFT;
50import vnsim.vehicular.emissions.EmissionsResults;
51import vnsim.vehicular.generator.EntryFlowVariation;
52import vnsim.vehicular.generator.Mobility;
53import vnsim.vehicular.generator.NewCarEvent;
54import vnsim.vehicular.routePlan.RoutingConstants;
55import vnsim.vehicular.routePlan.cityRouting.CarToIntersectionComm;
56import vnsim.vehicular.routePlan.cityRouting.CityTrafficLight;
57import vnsim.vehicular.routePlan.cityRouting.IntersectionNode;
58import vnsim.vehicular.routePlan.cityRouting.RoadSegmentCost;
59import vnsim.vehicular.routePlan.cityRouting.Server;
60import vnsim.vehicular.routePlan.infrastructureRouted.DelayRecord;
61import vnsim.vehicular.routePlan.infrastructureRouted.GuidanceRequest;
62import vnsim.vehicular.routePlan.infrastructureRouted.InfrastructureNode;
63import vnsim.vehicular.routePlan.selfRouted.QueryGeneration;
64import vnsim.vehicular.scenarios.EntryExitScenario;
65import vnsim.vehicular.scenarios.EntryScenario;
66import vnsim.vehicular.scenarios.Route;
67import vnsim.vehicular.simulator.AggresivePersonality;
68import vnsim.vehicular.simulator.CalmPersonality;
69import vnsim.vehicular.simulator.CarInstance;
70import vnsim.vehicular.simulator.Personality;
71import vnsim.vehicular.simulator.RegularPersonality;
72import vnsim.vehicular.simulator.SortedCarVector;
73import vnsim.vehicular.simulator.intersections.Intersection;
74import vnsim.vehicular.simulator.intersections.IntersectionWithTrafficLights;
75
76
77
78/**
79 *
80 * The Engine class is the main class that controlls the simulation. It manages
81 * the list of entities (cars, trafficlights) and the list of events and passes the
82 * control to the mobility layer or communication layer when needed.
83 *
84 * @author Victor Gradinescu
85 *
86 */
87
88public class Engine {
89       
90       
91        /**
92         * PTVS Project
93         */
94        public ExecutorService executor[];/////////////////////////////////////// thread pool with Executors ////////////////////
95       
96        public void start(Event e, int i) throws IOException {
97           
98              executor[i].submit(new EventProcessingThread(this,e));
99          }
100       
101        int dimens;
102       
103        public static int numThreads;
104        ///////////////////////end PTVS Project/////////////////////////////////////////////////////
105       
106       
107        /* EZCab - file informations about the client */
108        public static BufferedWriter bwClient, bwCab;
109       
110        public static double WIRELESS_RANGE = 0.1;
111        public static double EXTENDED_WIRELESS_RANGE = 1.0;
112
113//      Petroaca - simulation protocol type ( 802.11 or DSRC )
114        public static int simulationProtocol=Globals.PROTOCOL_80211;
115       
116        //Petroaca - propagation type ( tworay or shadowing )
117        public static int propagationModel=Globals.TWO_RAY_GROUND;
118       
119        //Petroaca - the Ricean propagation module
120        public static Ricean riceanModule;
121       
122        DataInputStream dis = null;
123
124        public int fps;
125
126        static Vector<Event> eventQueue = null;
127        static int nrEvThreads = 0;
128       
129        //Petroaca - the DSRC emergency channel
130        ArrayList<Event> eventQueueEmergency = null;
131       
132        public boolean pauseFlag = true;
133
134
135        boolean doneFlag = false,doneFlagEmergency=false;
136
137        public ArrayList<SimulatedCarInfo> cars = null;
138
139        public int crtTime = 0;
140
141        public long t0 = 0L;
142
143        public boolean withGUI, startedWithGUI;
144
145        boolean runtimeMobility;
146
147        public boolean disableComm = false;
148
149        File fText = null, fBin = null;
150
151        PrintWriter pwText = null;
152
153        DataOutputStream outBin = null;
154
155        long prevRealSec = 0; 
156        double lastSimSecond = 0.0;
157       
158        int eventsTime = 0, mobilityTime = 0, cleanupTime = 0, netTime = 0, codeTime = 0;
159
160
161        int schedTime = 0,  moveTime = 0, semTime = 0;
162
163
164        public double maxControlDelay = 0;
165       
166        public int mycnt = 0;
167        public long fincars;
168        public long crossedCars;
169        public double totalkm, totalControlDelay;
170        public EmissionsResults totalEM = new EmissionsResults();
171        private long totalTime;
172       
173        public static int created = 0;
174
175        // Routing
176        public static int simulationType = 0;
177        public static int applicationType = 0;
178        int jammed;
179
180        public ArrayList<SimulatedCarInfo> infrastructure = null;
181       
182        Object event;
183
184        //City Routing
185        private Server server= new Server(); 
186       
187        /**
188         *
189         *
190         * @param withGUI If the simulator is run at the same time with GUI, the code
191         * will have to be synchronized
192         * @param runtimeMobility
193         */
194        public Engine(boolean withGUI, boolean runtimeMobility) 
195        {
196                try {
197                        FileWriter fwClient = new FileWriter("client_request.txt");
198                        bwClient = new BufferedWriter(fwClient);
199                        FileWriter fwCab        = new FileWriter("client_answers.txt");
200                        bwCab    = new BufferedWriter(fwCab); 
201                } catch (IOException e1) {
202                        e1.printStackTrace();
203                }
204                this.withGUI = withGUI;
205                this.startedWithGUI = withGUI;
206                this.runtimeMobility = runtimeMobility;
207                // init();
208                prevRealSec = t0 = System.currentTimeMillis();
209       
210        }
211
212        /*
213         * Load the map, initialize eventqueue, init
214         */
215        public void init() {
216
217                Map map = Globals.map;
218               
219                //System.out.println("roads.size: "+map.roads.size()+" : "+map.roads.get(0).getName());
220               
221                //Road road = (Road)map.roads.get(0);
222               
223                //System.out.println("road.points: "+road.points);
224               
225                //System.out.println("strada:"+road.getName()+":"+" road.crosses.size(): "+road.crosses.size());
226               
227                       
228               
229               
230               
231                /**
232                 * PTVS project
233                 */
234                ArrayList<Intersection> intersectii = map.allIntersections;
235                numThreads=intersectii.size();
236                               
237                executor=new ExecutorService[numThreads];
238               
239                for(int i=0;i<numThreads;i++){
240                        executor[i] = Executors.newFixedThreadPool(1); // un singur thread e mereu refolosit pt fiecare intersectie.. ar putea fi mai multe
241                }
242                ///////////////////////end PTVS Project/////////////////////////////////////////////////////
243               
244               
245                for(int q=0;q<intersectii.size();q++){
246                        System.out.println("intersectia "+q+": "+" nume: "+intersectii.get(q).toString()+" "+intersectii.get(q).getMapPoint());
247                }
248               
249                System.out.println(".........................aici4.........");
250               
251                //***************************************************************
252               
253                if (map.roads.get(0).getName().startsWith("Iuliu") || map.roads.get(0).getName().startsWith("Dr"))
254                {
255                       
256                        Globals.monitorWTL = (WirelessTrafficLight)map.allIntersections.get(1);
257                }
258                pauseFlag = false;
259                doneFlag = false;
260
261                // the positions of the cars may be updated by a mobility module by
262                // recomputing positions at each step or can be updated by reading a
263                // traces file
264                if (!runtimeMobility) 
265                {
266                        try 
267                        {
268                                if (dis != null) {
269                                        dis.close();
270                                }
271                                dis = new DataInputStream(new FileInputStream(Globals.inFile));
272                        } 
273                        catch (IOException e) 
274                        {
275                                System.err.println("Error reading scenario; file error"+ Globals.inFile);
276                                e.printStackTrace();
277                                System.exit(0);
278                        }
279                        try 
280                        {
281                                fps = dis.readInt();
282                        } 
283                        catch (IOException e)
284                        {
285                                System.err.println("Error reading file " + Globals.inFile);
286                                e.printStackTrace();
287                        }
288                }
289                else 
290                {
291                        fps = Globals.executionFPS;
292
293                        Globals.WIRELESS_TRANSMISSION_FRAMES = (int) Math
294                                        .ceil((double) Globals.WIRELESS_TRANSMISSION_TIME
295                                                        / (1000 / Globals.executionFPS));
296
297                }
298
299                // init cars and events
300                eventQueue = new Vector<Event>();
301               
302               
303                cars = new ArrayList<SimulatedCarInfo>();
304               
305       
306
307                //Petroaca - if DSRC simulation then initialize the emergency event queue
308                if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
309                        eventQueueEmergency = new ArrayList<Event>();
310               
311                crtTime = 0;
312
313                if (!runtimeMobility) {
314                        readScenarioPhase();
315                } else {
316                        // Mobility.initCarsTest(this);
317                        // Mobility.initCarsAutostrada(this);
318//                      Mobility.initCars(this);
319                }
320
321                synchronized (eventQueue) {
322                       
323                                eventQueue.add(new GPSEvent(0));
324                                                               
325                                eventQueue.add(new CleanupEvent(1));
326                               
327                                Iterator<SimulatedCarInfo> it = cars.iterator();
328                                while (it.hasNext()) 
329                                {
330                                        System.out.println("nu ai cum sa intri pe aici!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! cars este vida");
331                                        SimulatedCarInfo r = it.next();
332                               
333                                schedEvent(new SendEvent(4, r,
334                                                SimulatedCarInfo.STANDARD_MESSAGE_ID));
335                                }
336                               
337                                // cod comentat deaorece vroiam sa vad daca se calculeaza cum trebuie intersectia cea mai apropiata
338                                // si partea asta face ca semafoarele din toate intersectiile sa genereze evenimente
339                               
340                                /* Szekeres A. START_MODIFY - add broadcast event for each traffic light*/
341                        for(int i=0;i<Globals.map.allIntersections.size();i++) {
342                                Intersection sender = Globals.map.allIntersections.get(i);
343                                if (sender instanceof EmissionsTrafficLight)
344                                {
345                                        ((EmissionsTrafficLight)sender).init();
346                                        schedEvent(new SendEvent(4, (EmissionsTrafficLight)sender, (int)Globals.PROT_TL_FEEDBACK));
347                                }
348                        }                       
349                                /* Szekeres A. STOP_MODIFY */
350                }
351               
352               
353                try 
354                {
355                        if (runtimeMobility && outputToFile) 
356                        {
357
358                                fText = new File(Globals.inFile + ".txt");
359                                fBin = new File(Globals.inFile);
360                                fText.createNewFile();
361                                fBin.createNewFile();
362                                pwText = new PrintWriter(new FileOutputStream(fText));
363                                outBin = new DataOutputStream(new FileOutputStream(fBin));
364
365                                pwText.println("" + Globals.FPS);
366                                outBin.writeInt(Globals.FPS);
367                        }
368                }
369                catch (IOException e) 
370                {
371                        System.err.println("Error reading scenario; file error"
372                                        + Globals.inFile);
373                        e.printStackTrace();
374                        System.exit(0);
375                }
376
377                if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
378                        DelayRecord.initDelays();
379                        this.infrastructure=new ArrayList<SimulatedCarInfo>();
380                        //create a fixed node for every intersection
381                        InfrastructureNode.createInfrastructureNodes();
382                }
383
384                //Petroaca - instantiate the ricean propagation module
385                try
386                {
387                  if(Engine.propagationModel==Globals.RICEAN)
388                        Engine.riceanModule=new Ricean(Globals.RICEAN_FILE_NAME,true);
389                }
390                catch(IOException ioe){System.out.println("Ricean file io error:"+ioe.getMessage());System.exit(1);}
391               
392                System.out.println(">>> Engine initialized - "+eventQueue.size()+" events in the queue");
393                System.out.println("CARS:"+cars);
394                System.out.println("Events:"+eventQueue);
395                 
396               
397                System.out.println();
398               
399                /*Road r = Globals.map.roads.get(1);
400                System.out.print("road:"+r.getName());
401                System.out.println("  r.points.size():"+r.points.size());
402               
403                Point p1 = r.points.get(r.points.size()-1);
404                System.out.println(p1);
405                Point p2 = r.points.get(r.points.size()-2);
406                System.out.println(p2);
407               
408                System.out.println("distanta: " +(p1.getDistance() - p2.getDistance()));
409                System.out.println("distanta: " +GPSutil.distance(p1, p2));*/
410                System.out.println("__________________end init____________________________\n");
411                               
412
413        }
414
415        /**
416         * Reset simulation
417         */
418        public void reset()
419        {
420                eventQueue = new Vector<Event>();
421                cars = new ArrayList<SimulatedCarInfo>();
422
423                //Petroaca - if DSRC simulation also reset the emergency channel
424                if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
425                        eventQueueEmergency = new ArrayList<Event>();
426               
427                crtTime = 0;
428
429        }
430       
431        /**
432         * Turn on communication by scheduling transmission events for each car.
433         *
434         */
435        public void restartCommunication() {
436                disableComm = false;
437                synchronized (eventQueue) {
438                        // eventQueue.add(new CleanupEvent(crtTime+1));
439
440                        schedEvent(new CleanupEvent(crtTime + 1));
441
442                        synchronized (cars) 
443                        {
444                                Iterator<SimulatedCarInfo> it = cars.iterator();
445                                while (it.hasNext()) {
446                                        SimulatedCarInfo r = it.next();
447                                        schedEvent(new SendEvent(crtTime + 2, r, SimulatedCarInfo.STANDARD_MESSAGE_ID));
448                                }
449                        }
450                }
451               
452//              Petroaca - if DSRC simulation also reset the emergency channel
453                if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
454                        eventQueueEmergency = new ArrayList<Event>();
455        }
456
457        /**
458         * Start simulation, execute events from queue continously
459         *
460         */
461        public void play() {
462                // supposed to be in the init()
463                // between init and play() Globals.map.allIntersections is changing
464                // need to find a fix
465               
466                if (Engine.simulationType == RoutingConstants.DYNAMIC_CITY_ROUTE) {
467                        CityTrafficLight.upgradeToCityTL();
468                        RoadSegmentCost.initRoadSegmentsCost();
469                        this.infrastructure=new ArrayList<SimulatedCarInfo>();
470                        //create a fixed node for every intersection
471                        IntersectionNode.createIntersectionNodes(server);
472                        server.init();
473                }
474               
475                prevRealSec = t0 = System.currentTimeMillis();
476                pauseFlag = false;
477                while (!pauseFlag && !doneFlag) {
478                        step();                 
479                }
480        }
481
482        /**
483         * Execute all the events for the following <seconds> s
484         *
485         */
486        public void play(int seconds) {
487                int frames = seconds * fps;
488                pauseFlag = false;
489                for (int i = 0; i < frames && !pauseFlag && !doneFlag; i++) {
490                        step();
491                }
492        }
493
494        /**
495         * Request the interruption of the continous execution of events
496         *
497         */
498        public void pause() {
499                pauseFlag = true;
500        }
501
502        /**
503         * Execute all the events for the current moment of time (virtual time)
504         *
505         */
506        double dec1(double x){
507                return (double)((int)(x * 10)) / 10;
508        }
509       
510       
511        long lastTime = -1;
512       
513       
514
515       
516        ////////////////////////////////////// step ///////////////////////////////////////////////////////////
517        /**
518         * Process the events for the current step of the simulation
519         *
520         */
521       
522       
523        /**
524         * PTVS
525         */
526       
527       
528        public void step() {
529               
530                int cnt = 0;
531               
532                if(Globals.SOCIALNETWORK == 1){
533                        double sec = vnsim.socialNet.GlobalNetwork.nextReconfigurationTime*Globals.SECOND;
534                }
535                       
536                if (crtTime >  3.5 * Globals.HOUR){     //nu rulez mai mult de 3 ore juma
537                        doneFlag = true;
538                        System.exit(0);
539                        return;
540                }
541                if (withGUI) {
542                        synchronized (Globals.mutex) {
543                                if (Globals.flag == 1) {
544                                        try {
545                                                Globals.mutex.wait();
546                                        } catch (Exception e) {
547                                               
548                                        }
549                                }
550                                Globals.flag = 0;
551                        }
552                }
553
554                long t1 = System.currentTimeMillis();
555                if (crtTime % Globals.SECOND == 0)
556                {
557                        lastSimSecond = (double)(t1-prevRealSec)/1000;
558                        prevRealSec = t1;
559                        if (lastSimSecond < 1)
560                                try{
561                                        Thread.sleep(100);//(int)((1.0 - lastSimSecond)*1000));
562                                }catch(Exception e){
563                                       
564                                }
565                }       
566               
567                if (crtTime % Globals.MINUTE == 0){
568
569                        Globals.packets = 0;
570                        Globals.collided = 0;
571                        Globals.lost = 0;
572                       
573                        System.out.println((crtTime / Globals.MINUTE) + " sim min;\t" +
574                                        "simulation time: "+ (System.currentTimeMillis() - t0) +"\t" +
575                                        " cars: "+cars.size() + " created " + created);
576
577                        Globals.volume = 0;
578                        Globals.demand = 0;
579                       
580                        //Petroaca
581                        if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
582                        {
583                                DSRCStatistics.addStatistic(new DSRCStatisticComponent(0,Globals.DSRC_PACKETS_LOST_WEAK,Globals.DSRC_PACKETS_TOTAL,Globals.DSRC_PACKETS_LOST_CORRUPTED,Globals.DSRC_PACKETS_LOST_COLLISION,Globals.DSRC_PACKETS_LOST_TX,Globals.DSRC_PACKETS_LOST_RX,Globals.DSRC_PACKETS_LOST_PER,Globals.DSRC_PACKETS_RECEIVED_OK
584                                                ,0,0,Globals.CUMMULATIVE_PACKETS_FV,Globals.CUMMULATIVE_PACKETS_NFV,Globals.CUMMULATIVE_PACKETS_LAV,Globals.CUMMULATIVE_PACKETS_RAV,Globals.IRT_FV,Globals.IRT_NFV,Globals.IRT_LAV,Globals.IRT_RAV,0,0,0,0,cars.size(),Globals.EMERGENCY_RECEIVED,Globals.EMERGENCY_SENT));
585                               
586                               
587                                Globals.DSRC_PACKETS_LOST_WEAK=0;
588                                Globals.DSRC_PACKETS_LOST_COLLISION=0;
589                                Globals.DSRC_PACKETS_LOST_TX=0;
590                                Globals.DSRC_PACKETS_LOST_RX=0;
591                                Globals.DSRC_PACKETS_LOST_PER=0;
592                                Globals.DSRC_PACKETS_LOST_CORRUPTED=0;
593                                Globals.DSRC_PACKETS_RECEIVED_OK=0;
594                                Globals.DSRC_PACKETS_TOTAL=0;
595                                Globals.DSRC_PACKETS_SEND_FALIURE_RX=0;
596                                Globals.DSRC_PACKETS_SEND_FALIURE_NOISE=0;
597                                Globals.DSRC_SEND=0;
598                               
599                                //System.out.println((crtTime / Globals.MINUTE)+ " min\t"+"FV:"+Globals.CUMMULATIVE_PACKETS_FV+" NFV:"+Globals.CUMMULATIVE_PACKETS_NFV+" LAV:"+Globals.CUMMULATIVE_PACKETS_LAV+" RAV:"+Globals.CUMMULATIVE_PACKETS_RAV+" EMERGENCY_RECV:"+Globals.EMERGENCY_RECEIVED+" EMERGENCY_SENT:"+Globals.EMERGENCY_SENT);
600                               
601                                Globals.CUMMULATIVE_PACKETS_RAV=0;
602                                Globals.CUMMULATIVE_PACKETS_LAV=0;
603                                Globals.CUMMULATIVE_PACKETS_FV=0;
604                                Globals.CUMMULATIVE_PACKETS_NFV=0;
605                                Globals.IRT_FV=0;
606                                Globals.IRT_NFV=0;
607                                Globals.IRT_LAV=0;
608                                Globals.IRT_RAV=0;
609                                Globals.EMERGENCY_RECEIVED=0;
610                                Globals.EMERGENCY_SENT=0;
611                               
612                                /*System.out.println("END DSRC DATA------------------------------");*/
613                        }       
614                }               
615                if (crtTime % (5 * Globals.MINUTE) == 0){
616                        if (lastTime == -1)
617                                lastTime = t0;
618                        long realTime = t1 - lastTime;
619                        lastTime = t1;
620
621                        eventsTime = 0;
622                        codeTime = 0;
623                        cleanupTime = 0;
624                        mobilityTime = 0;
625                       
626                        Globals.pw.flush();
627                       
628                        Globals.demo.st.clearInfo();
629                        Globals.demo.st.addInfo("Avg Delay "+ dec1(totalControlDelay/(fincars*60))+" min");
630                        Globals.demo.st.addInfo("Max Delay "+dec1(maxControlDelay / 60)+" min");
631                        Globals.demo.st.addInfo("Fuel: " + dec1( ( totalEM.fc * 100) / (1000 * totalkm)) + " L/100 km");
632                        Globals.demo.st.addInfo("CO2: " + dec1((totalEM.co2 * 20 )/ 1000)+" kg/h");
633                        Globals.demo.st.addInfo("CO: " + dec1((totalEM.co * 20 )/ 1000)+" kg/h");
634                        Globals.demo.st.addInfo("HC: " + dec1((totalEM.hc * 20 )/ 1000)+" kg/h");
635                        Globals.demo.st.addInfo("NOx: " + dec1((totalEM.nox * 20 )/ 1000)+" kg/h");
636                       
637
638                        if (fincars>0) {
639                                Globals.pwxc.println( "min " + (crtTime / Globals.MINUTE) +
640                                                "  cars: " + fincars + 
641                                                "  total time: " + totalTime +
642                                                "  total km: " + totalkm +
643                                                "  time/car: " + totalTime / fincars +
644                                                "  L/100: "+ ( (totalEM.fc * 100) / ( 1000 * totalkm)) +
645                                                "  fc: " + (totalEM.fc / fincars) +
646                                                "  co2: " + (totalEM.co2 / fincars) +
647                                                "  co: " + (totalEM.co / fincars) +
648                                                "  hc: " + (totalEM.hc / fincars) +
649                                                "  nox: " + (totalEM.nox / fincars)
650                                                );
651                                Globals.pwxc.flush();
652                        }
653                }               
654               
655               
656                if (startedWithGUI) {
657                        Globals.demo.st.setCount(crtTime);
658                        Globals.demo.st.setCurrentTime(System.currentTimeMillis() - t0);
659                        Globals.demo.st.setSimulationTime((float) ((crtTime * 1000) / fps));
660                        //Globals.demo.st.setSemTime(mycnt);
661                        Globals.demo.st.setNrEvents(eventQueue.size() + nrEvThreads);
662                        Globals.demo.st.setCarsNo(cars.size());                 
663                }
664               
665                long t2 = System.currentTimeMillis();
666               
667//              Petroaca - if DSRC simualtion play the events in emergency channel as well
668               
669                if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC && Globals.MULTI_CHANNEL)
670                {
671                        while (true) {
672                                if (eventQueueEmergency.size() == 0) {
673                                        doneFlagEmergency = true;
674                                        break;
675                                }
676                               
677                                Event e = (Event) eventQueueEmergency.get(0);
678                                if (e.getTime() == crtTime) {
679                                        playEventEmergency();
680                                        //cnt++;
681                                } else
682                                        break;
683                        }
684                }
685               
686                /*while (true) {
687                        if (eventQueue.size() == 0) {
688                                doneFlag = true;
689                                return;
690                        }
691                       
692                        Event e = (Event) eventQueue.get(0);
693                        if (e.getTime() == crtTime) {
694                                playEvent(null);
695                                cnt++;
696                        } else
697                                break;
698                }*/
699
700               
701                /**
702                 * PTVS Project
703                 * we know how many intersections i have, to start as many threads as intersections i have
704                 */
705                Map map = Globals.map;
706                ArrayList<Intersection> intersectii = map.allIntersections;
707                numThreads=intersectii.size();
708               
709                //v1 - noThreads = noIntersections
710                //Runnable processingThreads[] = new Runnable[numThreads];
711                //
712                //System.out.println("numThreads:"+numThreads);
713               
714               
715                 
716               
717                while (true) {
718                       
719                        if (eventQueue.size() == 0) {
720                                doneFlag = true;
721                                System.out.println("\ndoneFlag = true ");
722                                return;
723                        }
724                       
725                        // extrag un eveniment din coada !!!!! acum doar il extrag.. cand intru in playEvent il si scot cu remove(0)
726                        Event e = (Event) eventQueue.get(0);
727                        if (e == null) continue;
728                       
729                        if (e.getTime() == crtTime) {
730                                //System.out.println("------------->> e.getTime() == crtTime== "+crtTime);
731                               
732                        }
733                       
734                        if(dimens!=eventQueue.size()){
735                               
736                                System.out.println("\n----------- number of events in the queue:" +eventQueue.size());
737                                dimens = eventQueue.size();
738                        }
739                       
740                       
741                        /**
742                         * PTVS Project
743                         *
744                         * we have an array of threads for processing events based on location (intersection)
745                         * i process only receive and send messages
746                         */
747                       
748               
749                        if((e instanceof SendEvent) || (e instanceof ReceiveEvent)){
750                               
751                                synchronized (eventQueue) {
752                                        e = eventQueue.remove(0);
753                                        nrEvThreads++;
754                                        //System.out.println("remove from eventQueue");
755                                }
756                               
757                                /**
758                                 * PTVS Project
759                                 * i should know the location of the event
760                                 */                     
761                                Road r = null;
762                                Point p = null;
763                                if(e instanceof SendEvent){
764                                        SendEvent se=(SendEvent)e;
765                                        r = (Road) Globals.map.roads.get(se.sender.getRoadIdx());       //aflu strada pe care se afla senderul
766                                        p = (Point) r.points.get(se.sender.getPointIdx());                      //aflu punctul unde se afla senderul
767                                }
768                                if(e instanceof ReceiveEvent){
769                                        ReceiveEvent re=(ReceiveEvent)e;
770                                        r = (Road) Globals.map.roads.get(re.sender.getRoadIdx());
771                                        p = (Point) r.points.get(re.sender.getPointIdx());
772                                }
773                               
774                                //System.out.println("p:"+p);
775                               
776                                /**
777                                 * PTVS Project
778                                 * from intersections array, i find the closest one
779                                 */
780                                double MIN_DIST=Double.MAX_VALUE;
781                                int indexClosestIntersection=0;
782                                double distanta;
783                                for(int i=0;i<intersectii.size();i++){ 
784                                        Intersection intersectie = intersectii.get(i);
785                                        if(r.getPoints().contains(intersectie.getMapPoint())){ //iau in calcul doar intersectiile aflate pe strada pe care sunt
786                                                distanta=GPSutil.distance(p, intersectie.getMapPoint());
787                                                if (distanta < MIN_DIST){
788                                                        MIN_DIST=distanta;
789                                                        indexClosestIntersection=i;                                             
790                                                }
791                                        }
792                                               
793                                }
794                               
795                                /**
796                                 * PTVS Project
797                                 * i will assign a thread for the event
798                                 */
799                               
800                               
801                                if (e.getTime() == crtTime) {
802                               
803                                        if(e instanceof SendEvent){             
804                                               
805                                                        System.out.print("SendEvent: ");
806                                                        //processingThreads[indexClosestIntersection] = new SendEventProcessingThread(e,this);
807                                                }
808                                        else {                                 
809                                                        System.out.print("ReceiveEvent: ");
810                                                        //processingThreads[indexClosestIntersection] = new ReceiveEventProcessingThread(e,this);
811                                                }
812                                       
813                                        System.out.println("Processing thread "+indexClosestIntersection+" from intersection "+intersectii.get(indexClosestIntersection));
814                                       
815                                        try {
816                                                start(e,indexClosestIntersection);
817                                                cnt++;
818                                               
819                                        } catch (IOException e1) {
820                                                System.out.println("aici exceptie");
821                                                e1.printStackTrace();
822                                        }
823                                       
824                                        //new Thread(processingThreads[indexClosestIntersection]).start();
825                                       
826                                }
827                                else
828                                        break;
829                        }
830                       
831                        else if (e.getTime() == crtTime) {
832                                System.out.println("OtherEvent ");
833                                playEvent(null);
834                                cnt++;
835                               
836                        } else
837                                break;
838                       
839                       
840                }
841               
842                ///////////////////////end PTVS Project/////////////////////////////////////////////////////
843               
844                //increment simulation time
845                crtTime++;
846                //System.out.println("Increment crtTime!  crtTime:"+crtTime);
847               
848                long t3 = System.currentTimeMillis();
849                if (crtTime % (Globals.executionFPS / Globals.FPS) == 0)
850                        if (!runtimeMobility)
851                                readScenarioPhase();
852                        else
853                                generateScenarioPhase();
854               
855                checkCreateNewCars();
856               
857                long t4 = System.currentTimeMillis();
858                eventsTime += t3 - t2;
859                mobilityTime += t4 - t3;
860
861                if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
862                        if (crtTime % 100 == 0) {
863                                for (int i = 0; i < this.infrastructure.size(); i++) {
864                                       
865                                        ((InfrastructureNode) this.infrastructure.get(i)).updateDelays();
866                                }
867                        }
868                }
869                if (Engine.simulationType == RoutingConstants.DYNAMIC_CITY_ROUTE) {
870                        for (int i = 0; i < this.infrastructure.size(); i++) {
871                                ((IntersectionNode) infrastructure.get(i)).step(crtTime);
872                        }
873                        server.step(crtTime);
874                }
875        }
876        //////////////////////////////////////////////end metoda step////////////////////////////////////
877
878        static Random random = new Random();
879
880        public static int lastCarID = 0;
881
882        /**
883         * Insert new cars at the map entry points according to the scheduled flow.
884         *
885         */
886        private void checkCreateNewCars(){
887
888                int percent;
889//              should create some new cars?
890                NewCarEvent first=Mobility.events.first();
891                while(first!=null && first.timestamp==crtTime) {
892                        //create this one
893                        EntryScenario es=Mobility.entryScenarios.get(first.index);
894
895                        int roadIndexSrc=es.entry.roadIdx;
896                        int pointIndexSrc=es.entry.ptIdx;
897
898                        int ID=lastCarID;
899                        lastCarID++;
900
901                        //which exit is the car going towards?
902                        double rand;
903                        rand=(random.nextDouble())*100;
904                        int i=0;
905                        int sum=0;
906                        while(i<es.entryExits.size()) {
907                                sum+=es.entryExits.elementAt(i).percentOfFlow;
908                                if(rand<sum) {
909                                        //this is the chosen exit
910                                        break;
911                                }
912                                i++;
913                        }
914                        EntryExitScenario ees=null;
915                        if(i==es.entryExits.size()) {
916                                //last exit chosen
917                                ees=es.entryExits.lastElement();
918                        } else 
919                                ees=es.entryExits.elementAt(i);
920
921                        int roadIndexDst=ees.exit.roadIdx;
922                        int pointIndexDst=ees.exit.ptIdx;
923
924                        //which route is the car choosing?
925                        rand=(random.nextDouble())*100;
926                        i=0;
927                        sum=0;
928                        while(i<ees.percentsEachRoute.size()) {
929                                sum+=ees.percentsEachRoute.elementAt(i);
930                                if(rand<sum) {
931                                        //this is the chosen route
932                                        break;
933                                }
934                                i++;
935                        }
936                        Route r=null;
937                        if(i==ees.percentsEachRoute.size()) {
938                                //last route chosen
939                                r=ees.routes.lastElement();
940                        } else 
941                                r=ees.routes.elementAt(i);
942
943                        for(i=0;i<Globals.map.roads.get(roadIndexSrc).laneNo;i++) {
944                                //one vehicle on each lane
945
946                                Personality personality;
947                                rand=(random.nextDouble())*100;
948                                if(rand<es.percentsDriverTypes.elementAt(0)) 
949                                {
950                                        personality=new CalmPersonality();
951                                } else if(rand<es.percentsDriverTypes.elementAt(0)+es.percentsDriverTypes.elementAt(1)) {
952                                        personality=new RegularPersonality();
953                                } else {
954                                        personality=new AggresivePersonality();
955                                }
956                               
957                                CarInstance car = null;
958                                if (simulationType == RoutingConstants.INITIALLY_PROVIDED_ROUTE || simulationType == RoutingConstants.ROUTING_SCFT) {
959                                       
960                                        car = Mobility.createNewCar(roadIndexSrc,
961                                                        pointIndexSrc, 0, i + 1, 0.0, personality, /*personality.getWantedSpeed(roadIndexSrc)*/ 0.0, ID,
962                                                        roadIndexDst, pointIndexDst, r.route);
963                                       
964                                        System.out.println("Finished creating new car "+car);
965                                       
966                                        double d =0;
967                                        if(car!=null)
968                                                d = car.getDistanceToCarInFront();
969                                        if (d < 10 && d!=0) {
970                                                // closer than 5 meters --> do not create
971                                                // System.out.println("Skipping creation...");
972                                                Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad.remove(car.ID);
973                                                continue;
974                                        }
975                                }
976
977                                if (Engine.simulationType == RoutingConstants.DYNAMIC_SELF_ROUTE) {
978                                        System.out.println("Dynamic; we are here");
979                                        percent = random.nextInt(100);
980                                        percent = (int) Math.abs((double) percent);
981                                        if (percent <= Globals.routePlanConstants.percentBestRoute) {
982                                                percent = 1;
983                                        } else {
984                                                percent = 0;
985                                        }
986                                        car = Mobility.createNewCar(roadIndexSrc, pointIndexSrc, 0,
987                                                        i + 1, 0.0, personality, 0.0, ID, roadIndexDst,
988                                                        pointIndexDst, r.route, percent);
989                                        if (car == null) {
990                                       
991                                                continue;
992                                        }
993                                        double d = car.getDistanceToCarInFront();
994                                        if (d < 10) {
995                                                // closer than 10 meters --> do not create
996                                               
997                                                Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad.remove(car.ID);                                         
998                                                continue;
999                                        }
1000
1001                                }
1002                                if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
1003
1004                                        car = Mobility.createNewCarCommunicatingWithInfrastucture(
1005                                                        roadIndexSrc, pointIndexSrc, 0, i + 1, 0.0,
1006                                                        personality, 0.0, ID, roadIndexDst, pointIndexDst,
1007                                                        r.route);
1008                                        if (car == null) {
1009                                               
1010                                                continue;
1011                                        }
1012                                        double d = car.getDistanceToCarInFront();
1013                                        if (d < 10) {
1014                                                // closer than 10 meters --> do not create                                             
1015                                                Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad
1016                                                                .remove(car.ID);
1017                                               
1018
1019                                                continue;
1020                                        }
1021
1022                                }
1023                               
1024                                //create new ezcab client (entity)
1025                               
1026                                if (Engine.simulationType == RoutingConstants.DYNAMIC_CITY_ROUTE) {
1027
1028                                        car = Mobility.createNewCityCarCommunicatingWithInfrastucture(
1029                                                        roadIndexSrc, pointIndexSrc, 0, i + 1, 0.0,
1030                                                        personality, 0.0, ID, roadIndexDst, pointIndexDst,
1031                                                        r.route);
1032                                        if (car == null) {                                     
1033                                                continue;
1034                                        }
1035                                        double d = car.getDistanceToCarInFront();
1036                                        if (d < 10) {
1037                                                // closer than 10 meters --> do not create                                             
1038                                                Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad
1039                                                                .remove(car.ID);
1040                                               
1041
1042                                                continue;
1043                                        }
1044
1045                                }
1046
1047                                ID = lastCarID;
1048                                lastCarID++;
1049                                this.addCar(car);
1050                        }
1051                        Mobility.events.removeFirst();
1052                       
1053                        try {
1054                                EntryFlowVariation efv=Mobility.entryFlowVariations.get(first.index);
1055                               
1056                                if(efv.getFirstMom()<crtTime && efv.getFirstMom()!=-1) {
1057                                        int newFlow=efv.getFirstValue();
1058                                        int old=first.period;
1059                                        first.period=(int)((double)(3600 * Globals.SECOND) / newFlow);
1060                                        System.out.print("TIME="+crtTime+"; CHANGING PERIOD FOR ENTRY="+first.index+" FROM: "+old+" TO: "+first.period);
1061                                        efv.removeFirst();
1062                                }
1063                        } catch (Exception ex) {
1064                               
1065                        }
1066                        if(Globals.SOCIALNETWORK == 0 )
1067                                Mobility.events.addEvent(new NewCarEvent(first.timestamp
1068                                                + first.period, first.index, first.period));
1069                        first = Mobility.events.first();
1070                }
1071        }
1072
1073////////////////////////////////////////// playEvent ////////////////////////////////////////////////////////////////   
1074
1075        long messagesSize = 0;
1076        long carInfosSize = 0;
1077        /**
1078         * Execute the following event in the eventQueue
1079         *
1080         */
1081        public void playEvent(Event ev) {
1082        //public void playEvent() {
1083               
1084                //System.out.println(">> Thread:"+Thread.currentThread().getName());
1085               
1086                if (eventQueue.size() == 0) {
1087                        doneFlag = true;
1088                        return;
1089                }
1090
1091                Event e = null;
1092                if (ev == null) {
1093                        synchronized (eventQueue) {
1094                                e = eventQueue.remove(0);
1095                                //System.out.println("remove from eventQueue");
1096                        }
1097                } else {
1098                        e = ev;
1099                        synchronized (eventQueue) { nrEvThreads--; }
1100                }
1101                //System.out.print(e.toString()+", ");
1102                //System.out.flush();
1103                               
1104                if (e instanceof GPSEvent) {    //////////// eveniment GPS
1105                       
1106                        Iterator<SimulatedCarInfo> it = cars.iterator();
1107                        while (it.hasNext()) {
1108                                SimulatedCarInfo r = it.next();
1109                                r.update();
1110                        }
1111                        GPSEvent newEvent = new GPSEvent(crtTime + fps);
1112                        schedEvent(newEvent);
1113                }
1114                if (e instanceof CleanupEvent) {        //////////// eveniment CLEANUP
1115
1116                        long t1 = System.currentTimeMillis();
1117                        long deleted = 0;
1118                        Iterator<SimulatedCarInfo> it = cars.iterator();
1119                        while (it.hasNext()) {
1120                                SimulatedCarInfo r = it.next();
1121synchronized (r.trafficDB) {
1122                                Iterator<CarInfo> j = r.trafficDB.iterator();
1123                                while (j.hasNext()) {
1124                                        CarInfo neighbor = j.next();
1125                                        if ( (crtTime - neighbor.getTimestamp() > Globals.NEIGHBOR_EXPIRES && neighbor.state != 3) ||
1126                                                        (neighbor.state == 3 && crtTime - neighbor.getTimestamp() > Globals.PROMISCUOUS_NEIGHBOR_EXPIRES)){
1127                                                j.remove();
1128                                        }
1129                                }
1130}
1131                                carInfosSize += r.trafficDB.size();
1132                        }
1133                        for (int j = 0; j < Globals.map.lightsIndices.size(); j++) {
1134                                WirelessTrafficLight wtl = (WirelessTrafficLight) Globals.map.allIntersections
1135                                                .get(Globals.map.lightsIndices.get(j));
1136                               
1137                                synchronized(wtl.trafficDB){
1138                                        Iterator<IntersectionCarRecord> wtlit = wtl.trafficDB.iterator();
1139                                        while (wtlit.hasNext()) {
1140                                                IntersectionCarRecord icr = wtlit.next();
1141                                                if (!icr.isPassed() && crtTime - icr.getCar().getTimestamp() > Globals.HOUR 
1142                                                                && icr.getCar().state != 3){
1143                                                        icr.segment.cars.remove(icr);
1144                                                        wtlit.remove();
1145                                                        deleted++;
1146                                                }
1147                                                if (icr.isPassed() && crtTime - icr.getCar().getTimestamp() > Globals.TRAFFICLIGHT_NEIGHBOR_EXPIRES){
1148                                                        icr.segment.cars.remove(icr);
1149                                                        wtlit.remove();
1150                                                }
1151                                        }
1152                                }
1153                        }
1154                        long t2 = System.currentTimeMillis();
1155                        cleanupTime += t2 - t1;
1156                        if (!disableComm) {
1157                                CleanupEvent newCleanupEvent = new CleanupEvent(crtTime + fps);
1158                                schedEvent(newCleanupEvent);
1159                        }
1160                        messagesSize = 0;
1161                }
1162               
1163                if (e instanceof SendEvent) {   /////////////////////////////// eveniment SEND
1164                       
1165                        SendEvent se = (SendEvent) e;
1166                        Communicator sender = se.getSender();
1167                       
1168                        long t1 = System.currentTimeMillis();   
1169                       
1170                        // senderul e un SimulatedCarInfo
1171                       
1172                        if (se.getMessage() == null){
1173                                byte[] message = sender.prepareMessage(se.getMessageType());
1174                                se.setMessage(message);
1175                                if (se.getMessage() == null){
1176                                        if (sender.isPromiscuousMode() && sender.isPeriodicalMessage(se.getMessageType()) && !disableComm) {
1177                                                int eventPeriod = sender.getPeriod(se.getMessageType());
1178                                                if (eventPeriod != -1)
1179                                                        schedEvent(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
1180                                        }
1181                                        return;
1182                                }
1183                                messagesSize += message.length;
1184                                long t2 = System.currentTimeMillis();
1185                                codeTime += t2 - t1;
1186
1187                                if (sender.isPeriodicalMessage(se.getMessageType()) && !disableComm) {
1188                                        int eventPeriod = sender.getPeriod(se.getMessageType());
1189                                        if (eventPeriod != -1)
1190                                                schedEvent(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
1191                                }
1192                        }
1193                       
1194                        //Petroaca - the DSRC impl
1195                        if(Engine.simulationProtocol==Globals.PROTOCOL_80211)
1196                        {
1197                               
1198                                if (!sender.mediumAvailable(crtTime)) {
1199                                        e.setTime(crtTime + 1);
1200                                        schedEvent(e);
1201                                       
1202                                        return;
1203                                }
1204                               
1205                                sender.getRadio().setRadioTxMode();
1206                                simulateCommunication(se);
1207                       
1208                        }
1209                        else
1210                        {
1211                                if(sender instanceof CarRunningDSRC)
1212                                {
1213                                        MAC80211 macs=((CarRunningDSRC)sender).getMac();
1214                                        WirelessPhy phys=((CarRunningDSRC)sender).getPhysical();
1215                                       
1216                                        macs.refreshFrameTime(crtTime);
1217                                        phys.refreshFrameTime(crtTime);
1218                                       
1219                                        if(macs.sendToPhysical(se.getMessage(),crtTime)!=null)
1220                                        {
1221                                                phys.sendToChannel(se.getMessage(),crtTime);
1222                                                macs.setChannelState(Globals.CCA_BUSY);
1223                                                simulateCommunication(se);
1224                                        }
1225                                        else
1226                                        {
1227                                       
1228                                                e.setTime(crtTime+1);
1229                                                schedEvent(e);
1230                                               
1231                                        }
1232                                        return;
1233                                } 
1234                                else
1235                                {
1236                                        if (!sender.mediumAvailable(crtTime)) {
1237                                                e.setTime(crtTime + 1);
1238                                                schedEvent(e);
1239                                               
1240                                                return;
1241                                        }
1242                                       
1243                                        sender.getRadio().setRadioTxMode();
1244                                        simulateCommunication(se);
1245                                }
1246                        }
1247                }
1248               
1249                if (e instanceof ReceiveEvent) {        //////////////////////// eveniment RECEIVE
1250                        ReceiveEvent re = (ReceiveEvent) e;
1251
1252                                long t1 = System.currentTimeMillis();
1253                               
1254                                //Petroaca - the DSRC impl
1255                                if(Engine.simulationProtocol==Globals.PROTOCOL_80211){
1256                                        RadioDev rxradio = re.receiver.getRadio();
1257                                        ReceiveEvent goodSignal = rxradio.receive(re.signals);
1258                                        re.receiver.removeReceiveEventForTime(re.getTime());
1259                               
1260                                        if (goodSignal != null){
1261                                                        re.receiver.onReceive(goodSignal.getMessage(), goodSignal.getMessageObject(), goodSignal.sender);
1262                                                }
1263                                }
1264                                else
1265                                {
1266                                        if(re.receiver instanceof CarRunningDSRC)
1267                                        {
1268                                                MAC80211 macr=((CarRunningDSRC)re.receiver).getMac();
1269                                                WirelessPhy phyr=((CarRunningDSRC)re.receiver).getPhysical();
1270                                                Application appr=((CarRunningDSRC)re.receiver).getAppLayer();
1271                                               
1272                                                if(Globals.DIFFERENTIAL_CW)
1273                                                        macr.recalculateCW(phyr.getTotalReceivedPackets(),crtTime);
1274                                               
1275                                                macr.refreshFrameTime(crtTime);
1276                                                phyr.refreshFrameTime(crtTime);
1277                                                appr.refreshApplication(crtTime);
1278                                               
1279                                                ReceiveEvent best=phyr.recvFromChannel(re.signals,crtTime);
1280                                                re.receiver.removeReceiveEventForTime(re.getTime());
1281                                               
1282                                                double sinr=phyr.getSINR();
1283                                                if(best!=null)
1284                                                {
1285                                                        macr.setChannelState(Globals.CCA_BUSY); 
1286                                                       
1287                                                        if(macr.recvFromPhysical(best,sinr,crtTime)!=null)
1288                                                        {
1289                                                                appr.ForwardCollisionWarning(best.getMessage(),((CarInfo)re.receiver));
1290                                                                //appr.LaneChangeAssistance(best.getMessage(),((CarInfo)re.receiver));
1291                                                                re.receiver.onReceive(best.getMessage(), best.getMessageObject(), best.sender);
1292                                                        }
1293                                                }
1294                                        }
1295                                        else
1296                                        {
1297                                                RadioDev rxradio = re.receiver.getRadio();
1298                                                ReceiveEvent goodSignal = rxradio.receive(re.signals);
1299                                                re.receiver.removeReceiveEventForTime(re.getTime());
1300                                       
1301                                                if (goodSignal != null){
1302                                                                re.receiver.onReceive(goodSignal.getMessage(), goodSignal.getMessageObject(), goodSignal.sender);
1303                                                        }
1304                                        }
1305                                }       
1306                               
1307                                long t2 = System.currentTimeMillis();
1308                                codeTime += t2 - t1;
1309                        }
1310        }
1311
1312
1313        public void playEventEmergency()
1314        {
1315                if (eventQueueEmergency.size() == 0) {
1316                        doneFlagEmergency = true;
1317                        return;
1318                }
1319
1320                Event e = null;
1321                synchronized (eventQueueEmergency) {
1322                        e = eventQueueEmergency.remove(0);
1323                }
1324               
1325                if (e instanceof SendEvent) {
1326                        SendEvent se = (SendEvent) e;
1327                        Communicator sender = se.getSender();
1328                       
1329                        long t1 = System.currentTimeMillis();   
1330                       
1331                       
1332                        if (se.getMessage() == null){
1333                                byte[] message = sender.prepareMessage(se.getMessageType());
1334                                se.setMessage(message);
1335                                if (se.getMessage() == null){
1336        //                              System.out.println("null message"+se.sender + " "+se.sender.getClass());
1337                                        if (sender.isPromiscuousMode() && sender.isPeriodicalMessage(se.getMessageType()) && !disableComm) {
1338                                                int eventPeriod = sender.getPeriod(se.getMessageType());
1339                                                if (eventPeriod != -1)
1340                                                        schedEventEmergency(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
1341                                        }
1342                                        return;
1343                                }
1344                                messagesSize += message.length;
1345                                long t2 = System.currentTimeMillis();
1346                                codeTime += t2 - t1;
1347
1348                                if (sender.isPeriodicalMessage(se.getMessageType()) && !disableComm) {
1349                                        int eventPeriod = sender.getPeriod(se.getMessageType());
1350                                        if (eventPeriod != -1)
1351                                                schedEventEmergency(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
1352                                }
1353                        }
1354                       
1355                        //Petroaca - the DSRC impl
1356                                if(sender instanceof CarRunningDSRC)
1357                                {
1358                                        MAC80211 macs=((CarRunningDSRC)sender).getMac();
1359                                        WirelessPhy phys=((CarRunningDSRC)sender).getPhysical();
1360                                       
1361                                        macs.refreshFrameTime(crtTime);
1362                                        phys.refreshFrameTime(crtTime);
1363                                       
1364                                        if(macs.sendToPhysical(se.getMessage(),crtTime)!=null)
1365                                        {
1366                                                phys.sendToChannel(se.getMessage(),crtTime);
1367                                                macs.setChannelState(Globals.CCA_BUSY);
1368                                                simulateCommunicationEmergency(se);
1369                                        }
1370                                        else
1371                                        {
1372                                       
1373                                                e.setTime(crtTime+1);
1374                                                schedEventEmergency(e);
1375                                               
1376                                        }
1377                                        return;
1378                                }
1379                               
1380                                if(sender instanceof CarRunningDSRC)
1381                                {
1382                                        return;
1383                                }
1384                                else
1385                                {
1386                                        return;
1387                                }
1388                        }
1389                       
1390                if (e instanceof ReceiveEvent) {
1391                        ReceiveEvent re = (ReceiveEvent) e;
1392                       
1393                        long t1 = System.currentTimeMillis();
1394                       
1395                        //Petroaca - the DSRC impl
1396                               
1397                                        if(re.receiver instanceof CarRunningDSRC)
1398                                        {
1399                                                MAC80211 macr=((CarRunningDSRC)re.receiver).getMac();
1400                                                WirelessPhy phyr=((CarRunningDSRC)re.receiver).getPhysical();
1401                                                Application appr=((CarRunningDSRC)re.receiver).getAppLayer();
1402                                                appr.refreshApplication(crtTime);
1403                                               
1404                                                if(Globals.DIFFERENTIAL_CW)
1405                                                        macr.recalculateCW(phyr.getTotalReceivedPackets(),crtTime);
1406                                               
1407                                                macr.refreshFrameTime(crtTime);
1408                                                phyr.refreshFrameTime(crtTime);
1409                                               
1410                                                ReceiveEvent best=phyr.recvFromChannel(re.signals,crtTime);
1411                                                ((SimulatedCarInfo)re.receiver).removeReceiveEventEmergencyForTime(re.getTime());
1412                                               
1413                                                double sinr=phyr.getSINR();
1414                                                if(best!=null)
1415                                                {
1416                                                        macr.setChannelState(Globals.CCA_BUSY); 
1417                                                       
1418                                                        if(macr.recvFromPhysical(best,sinr,crtTime)!=null)
1419                                                        {
1420                                                                //appr.ForwardCollisionWarning(best.getMessage(),((CarInfo)re.receiver));
1421                                                                //appr.LaneChangeAssistance(best.getMessage(),((CarInfo)re.receiver));
1422                                                                re.receiver.onReceive(best.getMessage(), best.getMessageObject(), best.sender);
1423                                                        }
1424                                                }
1425                                        }
1426                                        long t2 = System.currentTimeMillis();
1427                                        codeTime += t2 - t1;
1428                                }       
1429        }
1430       
1431        /**
1432         * Applications may schedule dynamically communication events using this method
1433         * to insert new events in the queue.
1434         *
1435         * @param e Event to schedule
1436         */
1437        public void schedEvent(Event e) {
1438
1439                long t1 = System.currentTimeMillis();
1440
1441                if (e instanceof ReceiveEvent) {
1442                        ReceiveEvent re = (ReceiveEvent) e;
1443                        ReceiveEvent existing = re.receiver.getReceiveEventForTime(e.getTime());
1444                        //getReceiveEventForTime returneaza evenimentele receive petrecute la momentul e.getTime()
1445                       
1446                        if (existing == null){
1447                                re.receiver.addReceiveEventForTime(re);
1448                        }else{
1449                                existing.signals.add(re);
1450                                return;
1451                        }
1452                }
1453               
1454                // cauta evenimetul in coada, ii gaseste pozitia corecta in lista de evenimente si il adauga
1455                // ce face de fapt? de ce cauta un eveniment si il readauga tot pe el in lista???
1456                int idx = Collections.binarySearch(eventQueue, e);
1457                synchronized (eventQueue) {
1458                        if (idx >= 0) {
1459                                // advance till the end of the sequence of equal events
1460                                if (eventQueue.get(idx).equals(e))
1461                                        idx++;
1462                                eventQueue.add(idx, e);
1463                                //System.out.println("add in eventQueue..");
1464                        } else {
1465                                eventQueue.add(-(idx + 1), e);
1466                                //System.out.println("add in eventQueue....");
1467                        }
1468                }
1469                long t2 = System.currentTimeMillis();
1470                schedTime += t2 - t1;
1471        }
1472
1473        //Petroaca - the message scheduler for the emergency channel
1474        public void schedEventEmergency(Event e)
1475        {
1476                long t1 = System.currentTimeMillis();
1477
1478                if (e instanceof ReceiveEvent) {
1479                        ReceiveEvent re = (ReceiveEvent) e;
1480                        ReceiveEvent existing = ((SimulatedCarInfo)re.receiver).getReceiveEventEmergencyForTime(e.getTime());
1481                        if (existing == null){
1482                                ((SimulatedCarInfo)re.receiver).addReceiveEventEmergencyForTime(re);
1483                        }else{
1484                                existing.signals.add(re);
1485                                return;
1486                        }
1487                }
1488               
1489                int idx = Collections.binarySearch(eventQueueEmergency, e);
1490                synchronized (eventQueueEmergency) {
1491                        if (idx >= 0) {
1492                                // advance till the end of the sequence of equal events
1493                                if (eventQueueEmergency.get(idx).equals(e))
1494                                        idx++;
1495                                eventQueueEmergency.add(idx, e);
1496                        } else {
1497                                eventQueueEmergency.add(-(idx + 1), e);
1498                        }
1499                }
1500                long t2 = System.currentTimeMillis();
1501                schedTime += t2 - t1;
1502        }
1503       
1504        /**
1505         * Generate the receive events corresponding to one send event, for the cars
1506         * in the wireless range of the sending car.
1507         *
1508         */
1509        public void simulateCommunication(SendEvent e) {
1510               
1511                Road r1 = null;
1512                Point p1 = null;
1513                r1 = (Road) Globals.map.roads.get(e.sender.getRoadIdx());
1514                p1 = (Point) r1.points.get(e.sender.getPointIdx());
1515               
1516                if (e instanceof UnicastSendEvent) {
1517                        long t1 = System.currentTimeMillis();
1518                        Iterator<SimulatedCarInfo> it = cars.iterator();
1519                        ReceiveEvent re = null;
1520                        while (it.hasNext()) {
1521                                SimulatedCarInfo r = it.next();
1522                                if (r.vehicleId == ((UnicastSendEvent) e).getReceiverId()) {
1523                                        Road r2 = (Road) Globals.map.roads.get(r.getRealPos().getRoadIdx());
1524                                        Point p2 = (Point) r2.points.get(r.getRealPos().getPointIdx());
1525
1526                                        // MODIFIED BY CRISTI!!!
1527                                        // ReceiveEvent er = new ReceiveEvent(e.getTime() + 1, r, e.getMessage());
1528
1529                                        re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1530                                        re.setUnicast(true);
1531
1532                                        schedEvent(re);
1533                                        if (GPSutil.distance(p1, p2) < WIRELESS_RANGE) {
1534                                        } else {
1535                                                System.out.println("EROARE! DISTANCE="+ GPSutil.distance(p1, p2));
1536                                        }
1537                                        // END MODIFIED!!!
1538                                        return;
1539                                }
1540                        }
1541                       
1542                       
1543                        re.setSender(e.getSender());
1544                       
1545                        schedEvent(re);
1546
1547                        long t2 = System.currentTimeMillis();
1548                        netTime += t2 - t1;
1549
1550                } else {
1551                       
1552                        long tmp = 0;
1553                        long t3 = System.currentTimeMillis();
1554                        long t4;
1555
1556//                      re = new ReceiveEvent(e.getTime() + 1, e.getSender(), e.getMessage());
1557                       
1558
1559                        int cnt3 = 0;
1560                        int pkcnt = 0;
1561                        PeanoKey pk = Globals.map.peanoKeys.get(p1.getPeanoKeyIdx());
1562
1563                        ListIterator<PeanoKey> pkit = Globals.map.peanoKeys.listIterator(p1.getPeanoKeyIdx());
1564                        PeanoKey maxpk = null;
1565                       
1566                        double wifirange;
1567                        if (e.sender instanceof WirelessTrafficLight){
1568                                maxpk = GPSutil.getMaxSearchBoundPK(p1,Engine.EXTENDED_WIRELESS_RANGE);
1569                                wifirange = EXTENDED_WIRELESS_RANGE;
1570                        }else{
1571                                wifirange = WIRELESS_RANGE;
1572                                maxpk = pk.getMaxpk();
1573                        }
1574                       
1575                        PeanoKey pkx = null;
1576                        for (pkx = pkit.next(); pkit.hasNext(); pkx = pkit.next()) {
1577                                pkcnt++;
1578                                // long tc1 = System.currentTimeMillis();
1579                                if (pkx.compareTo(maxpk) > 0)
1580                                        break;
1581                                // long tc2 = System.currentTimeMillis();
1582                                // comp += (tc2-tc1);
1583
1584                                if (pkx.getCars() != null) {
1585                                        Road r2 = (Road) Globals.map.roads.get(pkx.getRoadIndex());
1586                                        Point p2 = (Point) r2.points.get(pkx.getPointIndex());
1587                                        if (GPSutil.distance(p1, p2) < 5 * wifirange) {
1588                                                cnt3 += pkx.getCars().size();
1589                                                Iterator<SimulatedCarInfo> it = pkx.getCars().iterator();
1590                                                while (it.hasNext()) {
1591                                                        SimulatedCarInfo r = it.next();
1592                                                        if (e.sender instanceof SimulatedCarInfo)
1593                                                                if (r.getVehicleId() == ((SimulatedCarInfo)e.sender).getVehicleId())
1594                                                                        continue;
1595                                                        r.setLastMediumTransmition(crtTime);
1596                                                       
1597                                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1598                                                        re.setSender(e.getSender());
1599                                                        schedEvent(re);
1600                                                }
1601                                        }
1602                                }
1603                        }
1604                        PeanoKey minpk = null;
1605                        if (e.sender instanceof WirelessTrafficLight)
1606                                minpk = GPSutil.getMaxSearchBoundPK(p1,-Engine.EXTENDED_WIRELESS_RANGE);
1607                        else
1608                                minpk = pk.getMinpk();
1609                       
1610                        pkit = Globals.map.peanoKeys.listIterator(p1.getPeanoKeyIdx());
1611
1612                        if (pkit.hasPrevious()){
1613                                pkx = pkit.previous();
1614                        }
1615                        for (; pkit.hasPrevious(); pkx = pkit.previous()) {
1616                                pkcnt++;
1617                                // long tc1 = System.currentTimeMillis();
1618                                if (pkx.compareTo(minpk) < 0) {
1619                                        break;
1620                                }
1621                                // long tc2 = System.currentTimeMillis();
1622                                // comp += (tc2-tc1);
1623
1624                                if (pkx.getCars() != null) {
1625                                        Road r2 = (Road) Globals.map.roads.get(pkx.getRoadIndex());
1626                                        Point p2 = (Point) r2.points.get(pkx.getPointIndex());
1627                                        double distance = GPSutil.distance(p1, p2);
1628                                        if (distance < 5 * wifirange) {
1629                                                Iterator<SimulatedCarInfo> it = pkx.getCars().iterator();
1630                                                cnt3 += pkx.getCars().size();
1631                                                while (it.hasNext()) {
1632                                                        SimulatedCarInfo r = it.next();
1633                                                       
1634                                                        r.setLastMediumTransmition(crtTime);
1635                                               
1636                                                        if (e.sender instanceof SimulatedCarInfo)
1637                                                                if (r.getVehicleId() == ((SimulatedCarInfo)e.sender).getVehicleId())
1638                                                                        continue;
1639                                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1640                                                        re.setSender(e.getSender());
1641                                                        schedEvent(re);
1642                                                }
1643                                        }
1644                                }
1645                        }
1646                       
1647                        for (int j = 0; j < Globals.map.lightsIndices.size(); j++) {
1648                                WirelessTrafficLight wtl = (WirelessTrafficLight) Globals.map.allIntersections
1649                                                .get(Globals.map.lightsIndices.get(j));
1650                                long t1sem = System.currentTimeMillis();
1651
1652                                if (GPSutil.distance(p1, wtl.getMapPoint()) < 5 * WIRELESS_RANGE) {
1653                                        wtl.setLastMediumTransmition(crtTime);
1654                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, wtl, e.getMessage(), e.getMessageObject(), e.getMessageType());
1655                                        re.setSender(e.getSender());
1656                                        schedEvent(re);
1657                                }
1658                                long t2sem = System.currentTimeMillis();
1659                                semTime += (t2sem - t1sem);
1660                        }
1661                       
1662                        t4 = System.currentTimeMillis();
1663                        tmp += t4 - t3;
1664                        netTime += tmp;
1665                }
1666        }
1667
1668        //Petroaca - the communication simulation for the emergency channel
1669        public void simulateCommunicationEmergency(SendEvent e) {
1670
1671                Road r1 = null;
1672                Point p1 = null;
1673                r1 = (Road) Globals.map.roads.get(e.sender.getRoadIdx());
1674                p1 = (Point) r1.points.get(e.sender.getPointIdx());
1675               
1676                if (e instanceof UnicastSendEvent) {
1677                        long t1 = System.currentTimeMillis();
1678                        Iterator<SimulatedCarInfo> it = cars.iterator();
1679                        ReceiveEvent re = null;
1680                        while (it.hasNext()) {
1681                                SimulatedCarInfo r = it.next();
1682                                if (r.vehicleId == ((UnicastSendEvent) e).getReceiverId()) {
1683                                        Road r2 = (Road) Globals.map.roads.get(r.getRealPos()
1684                                                        .getRoadIdx());
1685                                        Point p2 = (Point) r2.points.get(r.getRealPos()
1686                                                        .getPointIdx());
1687
1688                                        // MODIFIED BY CRISTI!!!
1689                                        // ReceiveEvent er = new ReceiveEvent(e.getTime() + 1, r,
1690                                        // e.getMessage());
1691
1692                                        re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1693                                        re.setUnicast(true);
1694
1695                                        schedEventEmergency(re);
1696                                        if (GPSutil.distance(p1, p2) < WIRELESS_RANGE) {
1697                                        } else {
1698                                                System.out.println("EROARE! DISTANCE="
1699                                                                + GPSutil.distance(p1, p2));
1700                                        }
1701                                        // END MODIFIED!!!
1702                                        return;
1703                                }
1704                        }
1705                       
1706                        re.setSender(e.getSender());
1707                        schedEventEmergency(re);
1708
1709                        long t2 = System.currentTimeMillis();
1710                        netTime += t2 - t1;
1711
1712                } else {
1713                       
1714                        long tmp = 0;
1715                        long t3 = System.currentTimeMillis();
1716                        long t4;
1717
1718//                      re = new ReceiveEvent(e.getTime() + 1, e.getSender(), e
1719//                                      .getMessage());
1720                       
1721
1722                        int cnt3 = 0;
1723                        int pkcnt = 0;
1724                        PeanoKey pk = Globals.map.peanoKeys.get(p1.getPeanoKeyIdx());
1725
1726                        ListIterator<PeanoKey> pkit = Globals.map.peanoKeys
1727                                        .listIterator(p1.getPeanoKeyIdx());
1728                        PeanoKey maxpk = null;
1729                       
1730                        double wifirange;
1731                        if (e.sender instanceof WirelessTrafficLight){
1732                                maxpk = GPSutil.getMaxSearchBoundPK(p1,Engine.EXTENDED_WIRELESS_RANGE);
1733                                wifirange = EXTENDED_WIRELESS_RANGE;
1734                        }else{
1735                                wifirange = WIRELESS_RANGE;
1736                                maxpk = pk.getMaxpk();
1737                        }
1738                        PeanoKey pkx = null;
1739                        for (pkx = pkit.next(); pkit.hasNext(); pkx = pkit.next()) {
1740                                pkcnt++;
1741                                // long tc1 = System.currentTimeMillis();
1742                                if (pkx.compareTo(maxpk) > 0)
1743                                        break;
1744                                // long tc2 = System.currentTimeMillis();
1745                                // comp += (tc2-tc1);
1746
1747                                if (pkx.getCars() != null) {
1748                                        Road r2 = (Road) Globals.map.roads.get(pkx
1749                                                        .getRoadIndex());
1750                                        Point p2 = (Point) r2.points.get(pkx.getPointIndex());
1751                                        if (GPSutil.distance(p1, p2) < 5 * wifirange) {
1752                                                cnt3 += pkx.getCars().size();
1753                                                Iterator<SimulatedCarInfo> it = pkx.getCars()
1754                                                                .iterator();
1755                                                while (it.hasNext()) {
1756                                                        SimulatedCarInfo r = it.next();
1757                                                        if (e.sender instanceof SimulatedCarInfo)
1758                                                                if (r.getVehicleId() == ((SimulatedCarInfo)e.sender)
1759                                                                        .getVehicleId())
1760                                                                        continue;
1761                                                        r.setLastMediumTransmition(crtTime);
1762                                                       
1763                                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1764                                                        re.setSender(e.getSender());
1765                                                        schedEventEmergency(re);
1766                                                }
1767                                        }
1768                                }
1769                        }
1770                        PeanoKey minpk = null;
1771                        if (e.sender instanceof WirelessTrafficLight)
1772                                minpk = GPSutil.getMaxSearchBoundPK(p1,-Engine.EXTENDED_WIRELESS_RANGE);
1773                        else
1774                                minpk = pk.getMinpk();
1775                       
1776                        pkit = Globals.map.peanoKeys.listIterator(p1.getPeanoKeyIdx());
1777
1778                        if (pkit.hasPrevious()){
1779                                pkx = pkit.previous();
1780                        }
1781                        for (; pkit.hasPrevious(); pkx = pkit
1782                                        .previous()) {
1783                                pkcnt++;
1784                                // long tc1 = System.currentTimeMillis();
1785                                if (pkx.compareTo(minpk) < 0) {
1786                                        break;
1787                                }
1788                                // long tc2 = System.currentTimeMillis();
1789                                // comp += (tc2-tc1);
1790
1791                                if (pkx.getCars() != null) {
1792                                        Road r2 = (Road) Globals.map.roads.get(pkx
1793                                                        .getRoadIndex());
1794                                        Point p2 = (Point) r2.points.get(pkx.getPointIndex());
1795                                        double distance = GPSutil.distance(p1, p2);
1796                                        if (distance < 5 * wifirange) {
1797                                                Iterator<SimulatedCarInfo> it = pkx.getCars()
1798                                                                .iterator();
1799                                                cnt3 += pkx.getCars().size();
1800                                                while (it.hasNext()) {
1801                                                        SimulatedCarInfo r = it.next();
1802                                                        r.setLastMediumTransmition(crtTime);
1803                                               
1804                                                        if (e.sender instanceof SimulatedCarInfo)
1805                                                                if (r.getVehicleId() == ((SimulatedCarInfo)e.sender)
1806                                                                        .getVehicleId())
1807                                                                        continue;
1808                                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1809                                                        re.setSender(e.getSender());
1810                                                        schedEventEmergency(re);
1811                                                }
1812                                        }
1813                                }
1814                        }
1815                       
1816                        t4 = System.currentTimeMillis();
1817                        tmp += t4 - t3;
1818                        netTime += tmp;
1819                }
1820        }
1821       
1822        /**
1823         * Adds a new car to the simulation.
1824         *
1825         * @param car The object that stores the physical behaviour of the vehicle to add
1826         */
1827        public void addCar(CarInstance car) 
1828        {
1829                if (car == null)
1830                        return;
1831               
1832                car.timestamp = crtTime;
1833                created ++;
1834                synchronized (cars) 
1835                {
1836                        SimulatedCarInfo dc = null;
1837                        if (crtTime == 0) {
1838//                              dc = new SimulatedCarInfo(car.ID, car.getLane(),
1839//                                              car.getSpeed(), car.getRoadIdx(), car.getPointIdx(),
1840//                                              car.getDirection(), car.getOffset());
1841                                /*
1842                                dc = new CarRunningVITP(car.ID, car.getLane(), car.getSpeed(),
1843                                                car.getRoadIdx(), car.getPointIdx(),
1844                                                car.getDirection(), car.getOffset());
1845                                */
1846                                //EZcab car
1847                                if (applicationType == Globals.PROT_EZCAB){
1848                                        dc=new EzcabCar(car.ID, car.getLane(), car.getSpeed(),
1849                                                        car.getRoadIdx(), car.getPointIdx(),
1850                                                        car.getDirection(), car.getOffset());
1851                                        System.out.println("new ezcab car created");
1852                                }
1853                                else if (simulationType == RoutingConstants.ROUTING_SCFT) 
1854                                        dc=new CarRunningSCFT(car.ID, car.getLane(), car.getSpeed(),
1855                                                        car.getRoadIdx(), car.getPointIdx(),
1856                                                        car.getDirection(), car.getOffset());
1857                                else
1858                                        dc=new CarRunningDSRC(car.ID, car.getLane(), car.getSpeed(),
1859                                                car.getRoadIdx(), car.getPointIdx(),
1860                                                car.getDirection(), car.getOffset());
1861                               
1862                                dc.setTimestamp(crtTime);
1863                                dc.setRealPos(car);
1864                                cars.add(dc);
1865                                dc.init();
1866                        } 
1867                        else 
1868                        {
1869                                int poz = cars.indexOf(new SimulatedCarInfo(car.ID));
1870                                if (poz == -1) 
1871                                {
1872                                        /*     
1873                                        dc = new CarRunningVITP(car.ID, car.getLane(), car
1874                                                        .getSpeed(), car.getRoadIdx(), car.getPointIdx(),
1875                                                        car.getDirection(), car.getOffset());
1876                                                        */
1877                                        //Ezcab
1878                                        if (applicationType == Globals.PROT_EZCAB){
1879                                                if(System.currentTimeMillis() % 2 == 0){
1880                                                        dc = new EzcabClient(car.ID, car.getLane(), 1.0, //a minimum speed
1881                                                                        car.getRoadIdx(), car.getPointIdx(),
1882                                                                        car.getDirection(), car.getOffset());
1883                                                       
1884//                                                      dc=new EzcabCar(car.ID, car.getLane(), car.getSpeed(),
1885//                                                                      car.getRoadIdx(), car.getPointIdx(),
1886//                                                                      car.getDirection(), car.getOffset());
1887                                                        //System.out.println("new client created");
1888                                                }
1889                                                else {
1890                                                        dc=new EzcabCar(car.ID, car.getLane(), car.getSpeed(),
1891                                                                        car.getRoadIdx(), car.getPointIdx(),
1892                                                                        car.getDirection(), car.getOffset());
1893                                                       
1894//                                                      dc = new EzcabClient(car.ID, car.getLane(), 1.0, //a minimum speed
1895//                                                                      car.getRoadIdx(), car.getPointIdx(),
1896//                                                                      car.getDirection(), car.getOffset());
1897                                                        //System.out.println("new ezcab car created");
1898                                                }
1899                                        }
1900                                        else if (simulationType == RoutingConstants.ROUTING_SCFT) 
1901                                                dc=new CarRunningSCFT(car.ID, car.getLane(), car.getSpeed(),
1902                                                                car.getRoadIdx(), car.getPointIdx(),
1903                                                                car.getDirection(), car.getOffset());
1904                                        else
1905                                                dc=new CarRunningDSRC(car.ID, car.getLane(), car.getSpeed(),
1906                                                        car.getRoadIdx(), car.getPointIdx(),
1907                                                        car.getDirection(), car.getOffset());
1908//                                      dc = new SimulatedCarInfo(car.ID, car.getLane(), car
1909//                                                      .getSpeed(), car.getRoadIdx(), car.getPointIdx(),
1910//                                                      car.getDirection(), car.getOffset());
1911                                       
1912                                        dc.setTimestamp(crtTime);
1913                                        dc.setRealPos(car);
1914                                        int t = 1 + random.nextInt(fps / 2 - 5);
1915                                        schedEvent(new SendEvent(crtTime + t, dc,SimulatedCarInfo.STANDARD_MESSAGE_ID));
1916                                        cars.add(dc);
1917                                        dc.init();                                     
1918                                } 
1919                                else 
1920                                {
1921                                        ((SimulatedCarInfo) cars.get(poz)).setRealPos(car);
1922                                }
1923                        }
1924                }
1925        }
1926
1927        /*
1928         * Read a scenario phase from a traces file. Update the vehicle's position
1929         * for the current step.
1930         *
1931         */
1932        public void readScenarioPhase() {
1933                int nrCars = 0;
1934                try {
1935                        int vehId, rdIdx, ptIdx;
1936                        byte dir, lane, speed;
1937                        double offset;
1938                        nrCars = dis.readInt();
1939                        // System.out.println(nrCars+" masini");
1940
1941                        synchronized (cars) 
1942                        {
1943                                for (int i = 0; i < nrCars; i++) 
1944                                {
1945                                        vehId   = dis.readInt();
1946                                        rdIdx   = dis.readInt();
1947                                        ptIdx   = dis.readInt();
1948                                        offset  = dis.readDouble();
1949                                        dir             = (byte) dis.readInt();
1950                                        lane    = (byte) dis.readInt();
1951                                        speed   = (byte) dis.readDouble();
1952
1953                                        SimulatedCarInfo dc = null;
1954                                        if (crtTime == 0) {
1955                                                /*     
1956                                                dc = new CarRunningVITP(vehId, lane, speed,
1957                                                                (short) rdIdx, (short) ptIdx, dir, offset);
1958                                                */
1959                                                //create ezcab car
1960                                                if (applicationType == Globals.PROT_EZCAB){
1961                                                        dc = new EzcabCar(vehId, lane, speed,
1962                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1963                                                        System.out.println("new ezcab car");
1964                                                }
1965                                                else if (simulationType == RoutingConstants.ROUTING_SCFT)
1966                                                        dc = new CarRunningSCFT(vehId, lane, speed,
1967                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1968                                                else
1969                                                        dc = new CarRunningDSRC(vehId, lane, speed,
1970                                                                (short) rdIdx, (short) ptIdx, dir, offset);
1971                                                // dc = new SimulatedCarInfo(vehId, lane, speed,
1972                                                // (short)rdIdx, (short)ptIdx, dir, offset);
1973                                                dc.setTimestamp(crtTime);
1974                                                dc.setRealPos(new CarInstance((CarInfo) dc));
1975                                                cars.add(dc);
1976                                                dc.init();
1977                                        } else {
1978                                                int poz = cars.indexOf(new SimulatedCarInfo(vehId));
1979                                                if (poz == -1) {
1980                                                        /*     
1981                                                        dc = new CarRunningVITP(vehId, lane, speed,
1982                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1983                                                        */
1984                                                        //create new ezcab car or client
1985                                                        if (applicationType == Globals.PROT_EZCAB){
1986                                                                if(System.currentTimeMillis() % 2 == 0){
1987                                                                        dc = new EzcabClient(vehId, lane, 1.0, //minimum allowed speed
1988                                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1989//                                                                      dc = new EzcabCar(vehId, lane, speed,
1990//                                                                                      (short) rdIdx, (short) ptIdx, dir, offset);
1991                                                                        //System.out.println("new ezcab client created");
1992                                                                }
1993                                                                else{
1994                                                                        dc = new EzcabCar(vehId, lane, speed,
1995                                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1996//                                                                      dc = new EzcabClient(vehId, lane, 1.0, //minimum allowed speed
1997//                                                                                      (short) rdIdx, (short) ptIdx, dir, offset);
1998                                                                        //System.out.println("new ezcab car created");
1999                                                                }
2000                                                        }
2001                                                        else if (simulationType == RoutingConstants.ROUTING_SCFT)
2002                                                                dc = new CarRunningSCFT(vehId, lane, speed,
2003                                                                                (short) rdIdx, (short) ptIdx, dir, offset);
2004                                                        else
2005                                                                dc = new CarRunningDSRC(vehId, lane, speed,
2006                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
2007                                                        // dc = new SimulatedCarInfo(vehId, lane, speed,
2008                                                        // (short)rdIdx, (short)ptIdx, dir, offset);
2009                                                        dc.setTimestamp(crtTime);
2010                                                        dc.setRealPos(new CarInstance((CarInfo) dc));
2011                                                        cars.add(dc);
2012                                                        dc.init();
2013                                                } else {
2014                                                        CarInstance ci = ((SimulatedCarInfo) cars.get(poz))
2015                                                                        .getRealPos();
2016                                                        ci.deleteCarToPointMapping();
2017                                                        ci.setSpeed((byte) speed);
2018                                                        ci.setRoadIdx((short) rdIdx);
2019                                                        ci.setPointIdx((short) ptIdx);
2020                                                        ci.setLane(lane);
2021                                                        ci.setDirection((byte) dir);
2022                                                        ci.setOffset(offset);
2023                                                        ci.setTimestamp(crtTime);
2024                                                        ci.updateCarToPointMapping();
2025                                                }
2026                                        }
2027                                }
2028                        }
2029                } catch (Exception e) {
2030                        System.err.println("Error reading scenario file");
2031                        e.printStackTrace();
2032                }
2033        }
2034
2035        public static boolean outputToFile = false;
2036
2037        public void generateScenarioPhase() {
2038               
2039                long t1sem = System.currentTimeMillis();
2040                if (crtTime % Globals.SECOND == 0){
2041                        for (int j = 0; j < Globals.map.lightsIndices.size(); j++) {
2042                                IntersectionWithTrafficLights iwtl = (IntersectionWithTrafficLights) Globals.map.allIntersections
2043                                .get(Globals.map.lightsIndices.get(j));
2044                                iwtl.step(crtTime);
2045                        }
2046                }
2047                long t2sem = System.currentTimeMillis();
2048                semTime += (t2sem - t1sem);
2049
2050                int NCARS = 0;
2051
2052                for (int j = 0; j < Globals.map.roads.size(); j++) {
2053
2054                        //Petroaca - random car on road to send emergency message
2055                        Random r;
2056                        int randId=0;
2057                        if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
2058                        {
2059                                r=new Random();
2060                                randId=r.nextInt(Globals.map.roads.get(j).carsOnThisRoad.size()+1);
2061                               
2062                        }
2063                       
2064                        SortedCarVector newVector = new SortedCarVector();
2065                        for (int k = Globals.map.roads.get(j).carsOnThisRoad.size() - 1; k >= 0; k--) {
2066                                CarInstance car = Globals.map.roads.get(j).carsOnThisRoad
2067                                                .get(k);
2068                                if (car.finished) {
2069                                       
2070                                        totalControlDelay += car.totalControlDelay;
2071                                        fincars ++;
2072                                        if (maxControlDelay < car.totalControlDelay)
2073                                                maxControlDelay = car.totalControlDelay;
2074
2075                                        synchronized (cars) {
2076                                                if (car.startMonitor) {
2077                                                        crossedCars++;
2078                                                        totalEM.addEmissionsResults(car.em, 1);
2079                                                        totalkm += car.totalDistance - car.startMonitorDistance;
2080                                                        totalTime += (crtTime - car.startTime)/Globals.SECOND;
2081                                                }
2082                                                Globals.monitoredCars.remove(car.getSimulatedCarInfo());
2083                                                car.finish();
2084                                                car.deleteCarToPointMapping();
2085                                                cars.remove(car.getSimulatedCarInfo());
2086                                        }
2087                                        continue;
2088                                }
2089                                try {
2090                                        long t1 = System.currentTimeMillis();
2091
2092                                        synchronized (cars) {
2093                                                car.deleteCarToPointMapping();
2094                                                car.move();
2095
2096                                                if (Engine.simulationType == RoutingConstants.DYNAMIC_SELF_ROUTE) {
2097                                                        QueryGeneration.generateQueryForCar(car);
2098                                                }
2099
2100                                                if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
2101                                                        GuidanceRequest.generateRequestToInfrastructure(car);
2102                                                }
2103                                               
2104                                                if (Engine.simulationType == RoutingConstants.DYNAMIC_CITY_ROUTE) {
2105                                                        CarToIntersectionComm.updateMetrics(car);
2106                                                }
2107                                               
2108//                                              Petroaca - emergency messages schedule
2109                                               
2110                                                if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC && car.ID==randId && crtTime%50==0)
2111                                                {
2112                                                        EmergencyRequest.generateEmergencyMessage(car);
2113                                                }
2114                                               
2115                                                car.setTimestamp(crtTime);
2116                                       
2117                                               
2118                                               
2119                                                if (car.endMonitor){
2120                                                        crossedCars ++;
2121                                                        totalEM.addEmissionsResults(car.em, 1);
2122                                                        totalkm += car.totalDistance - car.startMonitorDistance;
2123        //                                              System.out.println("Fuel: " + car.em.fc / 1000 +" "+ car.totalDistance + " "+car.em.fc * 100.0/ (10000 * car.totalDistance) + " "+(car.totalDistance * 3600.0)  / (double)(car.travelTime / Globals.SECOND));
2124                                                        car.endMonitor = false;
2125                                                        car.startMonitor = false;
2126                                                }
2127
2128                                                car.updateCarToPointMapping();
2129                                                 
2130                                        }
2131
2132                                        long t2 = System.currentTimeMillis();
2133                                        moveTime += t2 - t1;
2134                                } catch (Exception ex) {
2135                                        ex.printStackTrace();
2136                                }
2137                                // if it has changed road, place it in the vector of its new
2138                                // road
2139                                if (car.getRoadIdx() != j) {
2140                                        if (car.getRoadIdx() > j)
2141                                                NCARS--; // it will be moved again when that road
2142                                                                        // will be processed
2143                                        Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad
2144                                                        .addCarInstance(car);
2145                                } else {
2146                                        // it's still on the same road
2147                                        newVector.addCarInstance(Globals.map.roads.get(j).carsOnThisRoad.get(k));
2148                                }
2149                                NCARS++;
2150                        }
2151
2152                        // loop through the new vector and set the indices
2153                        for (int k = 0; k < newVector.size(); k++) {
2154                                newVector.get(k).index = k;
2155                        }
2156                        Globals.map.roads.get(j).carsOnThisRoad = newVector;
2157                }
2158       
2159               
2160                if (!outputToFile)
2161                        return;
2162                // output text
2163                try {
2164                        pwText.print(NCARS + " ");
2165                        outBin.writeInt(NCARS);
2166                        for (int j = 0; j < Globals.map.roads.size(); j++) {
2167                                for (int k = 0; k < Globals.map.roads.get(j).carsOnThisRoad
2168                                                .size(); k++) {
2169                                        CarInstance ci = Globals.map.roads.get(j).carsOnThisRoad
2170                                                        .get(k);
2171                                        pwText.print(ci.ID + " " + ci.getRoadIdx() + " "
2172                                                        + ci.getPointIdx() + " " + ci.getOffset() + " "
2173                                                        + ci.getDirection() + " " + ci.getLane() + "   ");
2174                                        outBin.writeInt(ci.ID);
2175                                        outBin.writeInt(ci.getRoadIdx());
2176                                        outBin.writeInt(ci.getPointIdx());
2177                                        outBin.writeDouble(ci.getOffset());
2178                                        outBin.writeInt(ci.getDirection());
2179                                        outBin.writeInt(ci.getLane());
2180                                        outBin.writeDouble(ci.getSpeed());
2181                                }
2182                        }
2183                        pwText.println();
2184                } catch (IOException e) {
2185                        System.err.println("Error writing traces");
2186                        e.printStackTrace();
2187                        System.exit(0);
2188                }
2189        }
2190       
2191        public int getCrtTime(){
2192                return crtTime;
2193        }
2194       
2195       
2196       
2197       
2198        public SimulatedCarInfo getCarIdx(int rdIdx, int ptIdx) 
2199        {
2200                synchronized (cars) 
2201                {
2202                        Iterator<SimulatedCarInfo> it = cars.iterator();
2203                        while (it.hasNext()) {
2204                                SimulatedCarInfo r = it.next();
2205                                if (r.getRoadIdx() == rdIdx && r.getPointIdx() == ptIdx)
2206                                        return r;
2207                        }
2208                }
2209                return null;
2210        }
2211
2212        public SimulatedCarInfo getCarIdx(int idx) 
2213        {
2214                synchronized (cars) 
2215                {
2216                        Iterator<SimulatedCarInfo> it = cars.iterator();
2217                        while (it.hasNext()) {
2218                                SimulatedCarInfo r = it.next();
2219                                if (r.vehicleId == idx)
2220                                        return r;
2221                        }
2222                }
2223                return null;
2224        }
2225
2226        public static void main(String args[]) {
2227               
2228                // Globals.map = new Map("Intersectie.RT1","Intersectie.RT2");
2229
2230                int tests = 1;
2231                for (int i = 0; i < tests; i++){
2232                        try{
2233                                switch (i){
2234                                        case 0: Globals.pw.println("Adaptive xc  = 1, variations2");
2235                                                break;
2236                                        case 1:Globals.pw.println("Adaptive xc  = 0.95, variations2");
2237                                                break;
2238                                        case 2:break;
2239                                }
2240                               
2241//                              ObjectInputStream ois=new ObjectInputStream(new FileInputStream(".\\maps\\fsc\\Apaca.fsc"));
2242//                              Scenario sc=(Scenario)ois.readObject();
2243//                              Mobility.loadScenario(sc);
2244                       
2245                                Engine e = Globals.engine = new Engine(false, true);
2246                                e.init();
2247//                                              public void run(){
2248//                                                      Globals.demo = new Display();
2249//                                                      Globals.demo.setVisible(true);
2250//                                              }
2251//                                      });
2252//                              t.start();
2253//                              e.play();
2254                                switch (i){
2255                                        case 0:
2256                                                Globals.Xc = 0.95;
2257                                                break;
2258                                        case 1:break;
2259                                        case 2:break;
2260                                }
2261                               
2262                                if (i != tests - 1){
2263                                        Globals.pw.close();
2264                                        String pwname = "rezultate"+System.currentTimeMillis()+".txt";
2265                                        Globals.pw = new PrintWriter(new FileWriter(pwname));
2266                                }
2267                        } catch (Exception ex) {
2268                                ex.printStackTrace();
2269                                System.exit(0);
2270                        }               
2271               
2272                       
2273                }
2274               
2275/*              long t1 = System.currentTimeMillis();
2276                e.play(60);
2277                long t2 = System.currentTimeMillis();
2278
2279                System.out.println("SimTime: " + (t2 - t1));
2280                System.out.println("events: " + (double) (100 * e.eventsTime)
2281                                / (t2 - t1));
2282                System.out.println("mobility: " + (double) (100 * e.mobilityTime)
2283                                / (t2 - t1));
2284                System.out.println("move: " + (double) (100 * e.moveTime) / (t2 - t1));
2285                System.out.println("code: " + (double) (100 * e.codeTime) / (t2 - t1));
2286                System.out.println("net: " + (double) (100 * e.netTime) / (t2 - t1));
2287                System.out.println("cleanup: " + (double) (100 * e.cleanupTime)
2288                                / (t2 - t1));
2289                System.out
2290                                .println("sched: " + (double) (100 * e.schedTime) / (t2 - t1));
2291
2292//              System.out.println("pkavg " + pkavg + "\npkmax" + pkmax
2293//                              + "\ncomp time " + avgTime);
2294                //              e.play();
2295                //              e.step();
2296                //              e.step();
2297                //              e.step();
2298                //              e.step();
2299                //              e.step();
2300                System.exit(0);*/
2301        }
2302
2303       
2304/*      public void createDummyCars() {
2305                Road r = Globals.map.roads.get(1);
2306               
2307                //Stopping a car on a road
2308                int ID = lastCarID;
2309                lastCarID++;
2310                CarInstance car = Mobility.createNewCar(1, 46, 0, 1, 0.0,
2311                                new NotMovingPersonality(), 0.0, ID, 2, 64, null, 1);
2312                if (car == null) {
2313                        lastCarID--;
2314                        System.out.println("Could not create the first stopped car");
2315                } else {
2316                        System.out.println("Jammed car id=" + ID);
2317                        jammed = ID;
2318                }
2319
2320                this.addCar(car);
2321        }
2322*/
2323       
2324
2325}
Note: See TracBrowser for help on using the repository browser.