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

Last change on this file since 87 was 87, checked in by (none), 14 years ago

commit la varianta cu executor

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