-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.ts
3471 lines (3267 loc) · 144 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import './simscript/simscript.css';
import './style.css';
import {
startSampleGroup, endSampleGroup,
showSimulation, setText, getLineChart,
createX3Queue, createX3Car, createX3Person
} from './util';
import { SimulationState } from './simscript/simulation';
import { Animation, IAnimatedQueue } from './simscript/animation';
import { Entity } from './simscript/entity';
import { Queue } from './simscript/queue';
import { Exponential } from './simscript/random';
import { format, bind } from './simscript/util';
import { SimpleTest, SimplestSimulation, Interrupt, Preempt, MM1 } from './simulations/simpletest';
import { PromiseAll } from './simulations/promise-all';
import { Generator } from './simulations/simpletest';
import { RandomVarTest } from './simulations/randomvartest';
import { BarberShop } from './simulations/barbershop';
import { MMC } from './simulations/mmc';
import { Crosswalk, Pedestrian } from './simulations/crosswalk';
import { AnimationOptions, RoamEntity } from './simulations/animation-options';
import { MultiServer } from './simulations/multiserver';
import { NetworkIntro, ServiceVehicle, renderNetworkSVG, renderNetworkX3D } from './simulations/network-intro';
import { CarFollow } from './simulations/car-follow';
import { CarFollowNetwork } from './simulations/car-follow-network';
import { Asteroids, Ship, Missile, Asteroid } from './simulations/asteroids';
import {
Telephone, Inventory, TVRepairShop, QualityControl, OrderPoint, Manufacturing,
Textile, OilDepot, PumpAssembly, RobotFMS, BicycleFactory, StockControl, QTheory,
Traffic, Supermarket, Port
} from './simulations/gpss';
import {
SteeringBehaviors,
SteeringWander, SteeringSeek, SteeringChase, SteeringAvoid, SteeringFollow,
SteeringLinearObstacles, SteeringLinearObstaclesSeek
} from './simulations/steering';
import {
NetworkSteering
} from './simulations/network-steering';
//----------------------------------------------------------
// SimScript sample Group
startSampleGroup(
'SimScript Samples',
`<p>
These samples show SimScript features, ranging from simple simulations
to animations and network-based samples.</p>`
);
if (true) {
//----------------------------------------------------------
// PromiseAll
showSimulation(
new PromiseAll(),
'PromiseAll',
`<p>
Shows how an Entity may span multiple sub-entities and
execute them all using a <b>Promise.all</b> call.
</p>`
);
//----------------------------------------------------------
// Generator
if (false)
showSimulation(
new Generator(),
'Generator',
`<p>
Simple test for the Simulation.generateEntities method.
</p>`
);
//----------------------------------------------------------
// SimplestSimulation
if (false)
showSimulation(
new SimplestSimulation(),
'SimplestSimulation',
`<p>
Simple test with some asserts.
</p>`
);
//----------------------------------------------------------
// SimpleTest
if (false)
showSimulation(
new SimpleTest({
stateChanged: (sim) => {
if (sim.state == SimulationState.Finished) {
console.log('** SimpleTest done in', sim.timeElapsed, 'ms');
}
}
}),
'SimpleTest Simulation',
`<p>
Simple test with some asserts.
</p>
<p>
Run the simulation and look at the console.
There should be no errors.
</p>`,
(sim: SimpleTest, log: HTMLElement) => {
log.innerHTML = sim.getStatsTable(true);
}
);
//----------------------------------------------------------
// Interruptible Delays
if (false)
showSimulation(
new Interrupt(),
'Interrupt',
`<p>
Test Interruptible delays.
The queue's average dwell time should be less than 10.
</p>`,
(sim: Interrupt, log: HTMLElement) => {
log.innerHTML = `
<p>
<b>${sim.elapsed}</b> entities finished their delays.<br/>
<b>${sim.interrupted}</b> entities were interrupted.<br/>
</p>` +
sim.getStatsTable();
}
)
//----------------------------------------------------------
// Preempt on seize
showSimulation(
new Preempt(),
'Preempt',
`<p>
Shows how to use interruptible delays to simulate pre-empting
resources.</p>
<p>
The sample has three entity types, each with a different
priority, all competing for a single resource.</p>`
);
//----------------------------------------------------------
// RandomVarTest
showSimulation(
new RandomVarTest(),
'RandomVarTest',
`<p>
Shows how to create and use
<a href='https://en.wikipedia.org/wiki/Random_variable'>random variable</a>
objects.</p>
<p>
Random variables are used to obtain values for inter-arrival times,
service times, and other non-deterministic values.</p>
<p>
Random variables may specify seed values, which cause the variable to
produce repeatable streams of random values. If a seed value is not
specified, then each run produces a different stream of random values.</p>`,
(sim: RandomVarTest, log: HTMLElement) => {
function getRandomVarOptions() {
let options = '';
sim.randomVars.forEach((rnd, index) => {
options += `<option ${index == sim.randomVarIndex ? 'selected' : ''}>
${rnd.name}
</option>`
});
return options;
}
log.innerHTML = `
<label>
Type:
<select id='rand-type'>${getRandomVarOptions()}</select>
</label>
<label>
Sample size:
<input id='rand-size' type='range' min='10' max='100000'>
</label>
<label>
Seeded:
<input id='rand-seeded' type='checkbox'>
</label>
<ul>
<li>Count:
<b>${format(sim.tally.cnt, 0)}</b>
</li>
<li>Average:
<b>${format(sim.tally.avg)}</b>
</li>
<li>Standard Deviation:
<b>${format(sim.tally.stdev)}</b>
</li>
<li>Variance:
<b>${format(sim.tally.var)}</b>
</li>
<li>Min:
<b>${format(sim.tally.min)}</b>
</li>
<li>Max:
<b>${format(sim.tally.max)}</b>
</li>
</ul>` +
sim.tally.getHistogramChart(sim.randomVar.name);
// parameters
bind('rand-type', sim.randomVarIndex, v => sim.randomVarIndex = v);
bind('rand-size', sim.sampleSize, v => sim.sampleSize = v, ' samples');
bind('rand-seeded', sim.seeded, v => sim.seeded = v);
}
);
//----------------------------------------------------------
// MultiServer
showSimulation(
new MultiServer({
timeEnd: 1e5
}),
'MultiServer',
`<p>
Single resource with multiple servers versus
multiple resources with a single server.</p>`,
(sim: MultiServer, log: HTMLElement) => {
let utzQSingle = 0;
sim.qSingle.forEach((q: Queue) => {
utzQSingle += q.grossPop.avg / q.capacity;
});
utzQSingle /= sim.qSingle.length;
let utzQSingleNC = 0;
sim.qSingleNC.forEach((q: Queue) => {
utzQSingleNC += q.grossPop.avg / q.capacity;
});
utzQSingleNC /= sim.qSingleNC.length;
const report = (utz: number, q: Queue) => {
return `
<ul>
<li>Utilization:
<b>${format(utz * 100)}%</b>
</li>
<li>Count:
<b>${format(q.totalCount, 0)}</b> customers
</li>
<li>Average Wait:
<b>${format(q.averageDwell)}</b> minutes
</li>
<li>Longest Wait:
<b>${format(q.maxDwell)}</b> minutes
</li>
<li>Average Queue:
<b>${format(q.averageLength)}</b> customers
</li>
<li>Longest Queue (95%):
<b>${format(q.grossPop.avg + q.grossPop.stdev * 2)}</b> customers
</li>
<li>Longest Queue:
<b>${format(q.maxLength)}</b> customers
</li>
</ul>
`;
}
log.innerHTML = `
<h3>
Single Multi-Server Resource
</h3>
<p>
One queue (resource) with multiple servers.
</p>
${report(sim.qMulti.utilization, sim.qMultiWait)}
<h3>
Multiple Single-Server Resources (Available Server, single-line)
</h3>
<p>
Multiple queues (resources) with a single server each.</p>
<p>
Customers look for available servers as they arrive.
The results are the same as those for a single queue
with multiple servers.</p>
${report(utzQSingle, sim.qSingleWait)}
<h3>
Multiple Single-Server Resources (Random Server, multi-line)
</h3>
<p>
Multiple queues (resources) with a single server each.</p>
<p>
Customers choose a server randomly when they arrive.
Even though the number of servers and service times
are the same, the load is not evenly distributed among
the servers, so queues and waits are longer.</p>
${report(utzQSingleNC, sim.qSingleWaitNC)}
<h3>
Stats
</h3>
${sim.getStatsTable(true)}
`;
}
);
//----------------------------------------------------------
// BarberShop
showSimulation(
new BarberShop(),
'BarberShop',
`<p>
This is a classic
<a
href='https://try-mts.com/gpss-introduction-and-barber-shop-simulation/'
>GPSS simulation example</a>:
customers arrive at a barbershop,
wait until the barber is available, get serviced, and leave.</p>`,
(sim: BarberShop, log: HTMLElement) => {
log.innerHTML = `<ul>
<li>Simulated time: <b>${format(sim.timeNow / 60, 0)}</b> hours</li>
<li>Elapsed time: <b>${format(sim.timeElapsed / 1000, 2)}</b> seconds</li>
<li>Barber Utilization: <b>${format(sim.qJoe.grossPop.avg * 100)}%</b></li>
<li>Average Wait: <b>${format(sim.qWait.grossDwell.avg)}</b> minutes</li>
<li>Longest Wait: <b>${format(sim.qWait.grossDwell.max)}</b> minutes</li>
<li>Waiting chairs needed: <b>${format(sim.qWait.grossPop.max, 0)}</b></li>
<li>Customers Served: <b>${format(sim.qJoe.grossDwell.cnt, 0)}</b></li>
</ul>` +
// show stats table
sim.getStatsTable(true) +
// show waiting queue's gross dwell histogram
sim.qWait.grossDwell.getHistogramChart('Waiting Times (min)');
}
);
//----------------------------------------------------------
// M/M/1
// https://en.wikipedia.org/wiki/M/M/1_queue
showSimulation(
new MM1(),
'M/M/1',
`<p>
The utilization is
<b><span id='mm1-utz'>?</span>%</b></p>
<p>
The mean number of customers in the system is
<b><span id='mm1-pop'>?</span></b> customers.</p>
<p>
The mean dwell time is
<b><span id='mm1-dwell'>?</span></b> seconds.</p>`,
(sim: MM1, log: HTMLElement) => {
const interArr = sim.interArrival.mean;
const service = sim.serviceTime.mean;
const utz = service / interArr;
setText('#mm1-utz', format(utz * 100, 0));
setText('#mm1-pop', format(utz / (1 - utz)));
setText('#mm1-dwell', format(1 / (1/service - 1/interArr)));
log.innerHTML = sim.getStatsTable();
}
);
//----------------------------------------------------------
// MMC
showSimulation(
new MMC(),
'M/M/C',
`<p>
This is a classic
<a href='https://en.wikipedia.org/wiki/M/M/c_queue'>M/M/C queueing system</a>.
Entities arrive, are served by one of C servers, and leave.</p>
<p>
This system is simple enough that there are formulas to calculate the
average queue length and waits (calculated values are shown in italics).</p>`,
(sim: MMC, log: HTMLElement) => {
const
lambda = 1 / sim.interArrival.mean, // arrival rate
mu = 1 / sim.service.mean, // service rate
c = sim.qService.capacity, // server count
rho1 = lambda / mu, // utilization
rho = rho1 / c; // actual utilization
const
p0 = 1 / (sum(rho1, c) + 1 / factorial(c) * Math.pow(rho1, c) * c * mu / (c * mu - lambda)),
ws = Math.pow(rho1, c) * mu * p0 / (factorial(c - 1) * Math.pow(c * mu - lambda, 2)) + 1 / mu,
ls = ws * lambda,
lq = ls - rho1, // average queue length
wq = lq / lambda; // average wait
log.innerHTML = `
<label>
Number of Servers:
<input id='mmc-capy' type='range' min='2' max='10'>
</label>
<label>
Mean inter-arrival time:
<input id='mmc-inter-arr' type='range' min='10' max='200'>
</label>
<label>
Mean service time:
<input id='mmc-service' type='range' min='10' max='200'>
</label>
<ul>
<li>Simulated time:
<b>${format(sim.timeNow / 60, 0)}</b> hours
</li>
<li>Elapsed time:
<b>${format(sim.timeElapsed / 1000, 2)}</b> seconds
</li>
<li>Number of Servers:
<b>${format(sim.qService.capacity, 0)}</b>
</li>
<li>Mean Inter-Arrival Time:
<b>${format(sim.interArrival.mean, 0)}</b> minutes
</li>
<li>Mean Service Time:
<b>${format(sim.service.mean, 0)}</b> minutes
</li>
<li>Server Utilization:
<b>${format(sim.qService.grossPop.avg / sim.qService.capacity * 100)}%</b>
(<i>${format(rho * 100)}%</i>)
</li>
<li>Average Wait:
<b>${format(sim.qWait.grossDwell.avg)}</b>
(<i>${format(wq)})</i> minutes
</li>
<li>Average Queue:
<b>${format(sim.qWait.grossPop.avg)}</b>
(<i>${format(lq)}</i>) customers
</li>
<li>Longest Wait:
<b>${format(sim.qWait.grossDwell.max)}</b> minutes
</li>
<li>Longest Queue:
<b>${format(sim.qWait.grossPop.max, 0)}</b> customers
</li>
<li>
Customers Served: <b>${format(sim.qService.grossDwell.cnt, 0)}</b>
</li>
</ul>`;
if (rho > 1) {
log.innerHTML += `<p class='error'>
** The server utilization exceeds 100%; the system will not reach a steady-state **
</p>`;
}
log.innerHTML += `
${sim.qWait.grossPop.getHistogramChart('Queue lengths')}
${sim.qWait.grossDwell.getHistogramChart('Wait times (minutes)')}`;
// parameters
bind('mmc-capy', sim.qService.capacity, v => sim.qService.capacity = v, ' servers');
bind('mmc-inter-arr', sim.interArrival.mean, v => sim.interArrival = new Exponential(v), ' seconds');
bind('mmc-service', sim.service.mean, v => sim.service = new Exponential(v), ' seconds');
// helpers
function sum(rho1: number, c: number): number {
let sum = 0;
for (let i = 0; i < c; i++) {
sum += 1 / factorial(i) * Math.pow(rho1, i);
}
return sum;
}
function factorial(n: number): number {
let f = 1;
for (let i = 2; i <= n; i++) f *= i;
return f;
}
}
);
//----------------------------------------------------------
// Crosswalk
showSimulation(
new Crosswalk(),
'Crosswalk',
`<p>
Simulates a crosswalk with a traffic light.</p>
<p>
Shows how to use the <b>waitsignal</b> and <b>sendSignal</b> methods.</p>`,
(sim: Crosswalk, log: HTMLElement) => {
const c = sim.cycle;
const wPavg = (c.yellow + c.red) / (c.yellow + c.red + c.green) * (c.yellow + c.red) / 2;
const wCavg = (c.yellow + c.green) / (c.yellow + c.red + c.green) * (c.yellow + c.green) / 2;
const wPmax = c.yellow + c.red;
const wCmax = c.yellow + c.green;
log.innerHTML = `
<p>
Pedestrian light cycle times (seconds):
</p>
<label>
<span class='light red'></span>Red:
<input id='xwalk-red' type='range' min='0' max='120' >
</label>
<label>
<span class='light yellow'></span>Yellow:
<input id='xwalk-yellow' type='range' min='0' max='120' >
</label>
<label>
<span class='light green'></span>Green:
<input id='xwalk-green' type='range' min='0' max='120' >
</label>
<ul>
<li>Simulated time: <b>${format(sim.timeNow / 60 / 60)}</b> hours</li>
<li>Elapsed time: <b>${format(sim.timeElapsed / 1000)}</b> seconds</li>
<li>
Average Pedestrian Wait: <b>${format(sim.qPedXing.grossDwell.avg)}</b>
<i>(${format(wPavg)})</i> seconds
</li>
<li>
Longest Pedestrian Wait: <b>${format(sim.qPedXing.grossDwell.max)}</b>
<i>(${format(wPmax)})</i> seconds
</li>
<li>
Average Car Wait: <b>${format(sim.qCarXing.grossDwell.avg)}</b>
<i>(${format(wCavg)})</i> seconds
</li>
<li>
Longest Car Wait: <b>${format(sim.qCarXing.grossDwell.max)}</b>
<i>(${format(wCmax)})</i> seconds
</li>
<li>Pedestrian Count: <b>${format(sim.qPedXing.grossDwell.cnt, 0)}</b></li>
<li>Car Count: <b>${format(sim.qCarXing.grossDwell.cnt, 0)}</b></li>
</ul>` +
// show pedestrian queue's population histogram
sim.qPedXing.grossPop.getHistogramChart('Pedestrians waiting to cross') +
// show car queue's population histogram
sim.qCarXing.grossPop.getHistogramChart('Cars waiting to cross');
// parameters
bind('xwalk-red', sim.cycle.red, v => sim.cycle.red = v, ' seconds');
bind('xwalk-yellow', sim.cycle.yellow, v => sim.cycle.yellow = v, ' seconds');
bind('xwalk-green', sim.cycle.green, v => sim.cycle.green = v, ' seconds');
}
);
//----------------------------------------------------------
// Animated Crosswalk (div)
showSimulation(
new Crosswalk({
frameDelay: 20
}),
'Animated Crosswalk',
`<p>
This sample uses the same Crosswalk <b>Simulation</b> class
as shown earlier, with an added <b>Animation</b> object that
adds an animated pane to show the flow of entities through
the simulation.</p>
<p>
The animation pane is a regular <code><div></code> element.
Queue positions are defined by elements in the animation element.
Entities in each queue and in transit between queues are shown
using <code><img></code> elements.</p>
<p>
Animations are great for presenting simulations and can be useful
for debugging purposes.
Keeping them decoupled from the simulations keeps <b>SimScript</b>
simple and flexible.</p>
<div class='ss-anim'>
<div class='time-now'>
Time: <span>0.00</span> hours
</div>
<div class='light'>
<div class='red'></div>
<div class='yellow'></div>
<div class='green'></div>
</div>
<div class='street'></div>
<div class='crosswalk'></div>
<div class='ss-queue car-arr'></div>
<div class='ss-queue car-xing'></div>
<div class='ss-queue car-xed'></div>
<div class='ss-queue ped-arr'></div>
<div class='ss-queue ped-xing'></div>
<div class='ss-queue ped-xed'></div>
<div class='ss-queue ped-leave'></div>
</div>`,
(sim: Crosswalk, animationHost: HTMLElement) => {
new Animation(sim, animationHost, {
getEntityHtml: e => {
// use explicit image sizes to measuring errors while loading images
return e instanceof Pedestrian
? `<img class='ped' src='resources/blueped.png' width='15' height='19'>`
: `<img class='car' src='resources/redcar.png' width='55' height='19'>`;
},
queues: [
{ queue: sim.qPedArr, element: '.ss-queue.ped-arr' },
{ queue: sim.qPedXing, element: '.ss-queue.ped-xing', angle: -45, max: 8 },
{ queue: sim.qPedXed, element: '.ss-queue.ped-xed' },
{ queue: sim.qPedLeave, element: '.ss-queue.ped-leave' },
{ queue: sim.qCarArr, element: '.ss-queue.car-arr' },
{ queue: sim.qCarXing, element: '.ss-queue.car-xing', angle: 0, max: 16 },
{ queue: sim.qCarXed, element: '.ss-queue.car-xed' },
]
});
// update display when the time or state change
const lights = animationHost.querySelectorAll('.light div');
const timeNow = animationHost.querySelector('.time-now span');
const updateStats = () => {
timeNow.textContent = format(sim.timeNow / 3600);
for (let i = 0; i < lights.length; i++) {
(lights[i] as HTMLElement).style.opacity = i == sim.light ? '1' : '';
}
}
sim.timeNowChanged.addEventListener(updateStats);
sim.stateChanged.addEventListener(updateStats);
}
);
//----------------------------------------------------------
// Animated Crosswalk (SVG)
showSimulation(
new Crosswalk({
frameDelay: 20
}),
'Animated Crosswalk (SVG)',
`<p>
This sample uses the same Crosswalk <b>Simulation</b> class
as shown earlier, this time using an SVG-based animation.</p>
<div class='svg ss-time-now'>
Time: <b><span>0.00</span></b> hours
</div>
<svg class='ss-anim' viewBox='0 0 1000 500'>
<g class='light'>
<rect class='light' x='47.5%' y='0%' width='5%' height='25%' rx='2%'/>
<circle class='red' cx='50%' cy='5%' r='2%'/>
<circle class='yellow' cx='50%' cy='12.5%' r='2%'/>
<circle class='green' cx='50%' cy='20%' r='2%'/>
</g>
<rect class='street' x='10%' y='50%' width='80%' height='20%'/>
<rect class='crosswalk' x='45%' y='50%' width='10%' height='20%'/>
<circle class='ss-queue car-arr' cx='10%' cy='60%' r='10'/>
<circle class='ss-queue car-xing' cx='40%' cy='60%' r='10'/>
<circle class='ss-queue car-xed' cx='90%' cy='60%' r='10'/>
<circle class='ss-queue ped-arr' cx='10%' cy='85%' r='10'/>
<circle class='ss-queue ped-xing' cx='50%' cy='75%' r='10'/>
<circle class='ss-queue ped-xed' cx='50%' cy='45%' r='10'/>
<circle class='ss-queue ped-leave' cx='90%' cy='35%' r='10'/>
</svg>`,
(sim: Crosswalk, animationHost: HTMLElement) => {
new Animation(sim, animationHost, {
getEntityHtml: e => {
if (e instanceof Pedestrian) {
return `<g class='ped' fill='black' stroke='black' opacity='0.8' transform='scale(1,0.8)'>
<circle cx='1%' cy='1%' r='0.5%' fill='orange'/>
<rect x='.4%' y='2%' width='1.3%' height='4%' fill='green' rx='0.7%'/>
<rect x='.66%' y='4%' width='.8%' height='3%' fill='blue'/>
<rect x='.4%' y='7%' width='1.3%' height='.75%' rx='0.5%'/>
</g>`;
} else {
return `<g class='car' fill='black' stroke='black'>
<rect x='1%' y='0' width='5%' height='4%' rx='1%'/>
<rect x='0' y='1.5%' width='9%' height='3%' fill='red' rx='0.5%'/>
<circle cx='1.5%' cy='4%' r='.9%' opacity='0.8'/>
<circle cx='7.5%' cy='4%' r='.9%' opacity='0.8'/>
<rect x='0' y='0' width='10%' height='1%' opacity='0'/>
</g>`;
}
},
queues: [
{ queue: sim.qPedArr, element: 'svg .ss-queue.ped-arr' },
{ queue: sim.qPedXing, element: 'svg .ss-queue.ped-xing', angle: -45, max: 8 },
{ queue: sim.qPedXed, element: 'svg .ss-queue.ped-xed' },
{ queue: sim.qPedLeave, element: 'svg .ss-queue.ped-leave' },
{ queue: sim.qCarArr, element: 'svg .ss-queue.car-arr' },
{ queue: sim.qCarXing, element: 'svg .ss-queue.car-xing', angle: 0, max: 16 },
{ queue: sim.qCarXed, element: 'svg .ss-queue.car-xed' },
]
});
// update display when the time or state change
const lights = animationHost.querySelectorAll('.light circle');
const timeNow = document.querySelector('.svg.ss-time-now span');
const updateStats = () => {
timeNow.textContent = format(sim.timeNow / 3600);
for (let i = 0; i < lights.length; i++) {
(lights[i] as HTMLElement).style.opacity = i == sim.light ? '1' : '';
}
}
sim.timeNowChanged.addEventListener(updateStats);
sim.stateChanged.addEventListener(updateStats);
}
);
//----------------------------------------------------------
// Animated Crosswalk (X3DOM)
showSimulation(
new Crosswalk({
frameDelay: 20
}),
'Animated Crosswalk (X3DOM)',
`<p>
This sample uses the same Crosswalk <b>Simulation</b> class
as shown earlier, this time using an X3DOM-based animation.</p>
<div class='x3d ss-time-now'>
Time: <b><span>0.00</span></b> hours
</div>
<x3d class='ss-anim'>
<scene>
<!-- default viewpoint -->
<viewpoint
position='0 -320 320'
orientation='1 0 0 .8'
centerOfRotation='0 0 -20'>
</viewpoint>
<!-- ground -->
<transform scale='300 150 .1' translation='0 0 -0.5'>
<shape>
<appearance>
<material diffuseColor='0.1 0.3 0.1' transparency='0.2'></material>
</appearance>
<box/>
</shape>
</transform>
<!-- street -->
<transform scale='250 50 .1'>
<shape>
<appearance>
<material diffuseColor='.95 .95 .95'></material>
</appearance>
<box/>
</shape>
</transform>
<!-- crosswalk -->
<transform scale='50 50 .1' translation='0 0 .1'>
<shape>
<appearance>
<material diffuseColor='.6 .6 .6'></material>
</appearance>
<box/>
</shape>
</transform>
<!-- light -->
<transform class='light'>
<transform translation='0 120 25' rotation='1 0 0 1.57'>
<shape> <!-- post -->
<appearance>
<material diffuseColor='.5 .5 .0'></material>
</appearance>
<cylinder height='50' radius='3'></cylinder>
</shape>
<transform translation='0 -21 0'>
<shape> <!-- bottom rim -->
<appearance>
<material diffuseColor='.5 .5 .0'></material>
</appearance>
<cylinder height='5' radius='15'></cylinder>
</shape>
</transform>
<transform translation='0 55 0'>
<shape> <!-- box -->
<appearance>
<material diffuseColor='.5 .5 .0'></material>
</appearance>
<box size='22 65 20'/>
</shape>
</transform>
<transform translation='0 75 5'>
<shape>
<appearance>
<material class='light red' diffuseColor='1 0 0'></material>
</appearance>
<sphere radius='10'/>
</shape>
</transform>
<transform translation='0 55 5'>
<shape>
<appearance>
<material class='light yellow' diffuseColor='1 1 0'></material>
</appearance>
<sphere radius='10'/>
</shape>
</transform>
<transform translation='0 35 5'>
<shape>
<appearance>
<material class='light green' diffuseColor='0 1 0'></material>
</appearance>
<sphere radius='10'/>
</shape>
</transform>
</transform>
</transform>
<!-- queues -->
${createX3Queue('car-arr', -250, 0)}
${createX3Queue('car-xing', -50, 0)}
${createX3Queue('car-xed', +250, 0)}
${createX3Queue('ped-arr', -125, -100)}
${createX3Queue('ped-xing', 0, -75, 5)}
${createX3Queue('ped-xed', 0, 75, 5)}
${createX3Queue('ped-leave', +250, 100)}
</scene>
</x3d>`,
(sim: Crosswalk, animationHost: HTMLElement) => {
new Animation(sim, animationHost, {
rotateEntities: true,
getEntityHtml: (e: Entity) => {
if (e instanceof Pedestrian) {
return createX3Person('pedestrian');
} else {
return e.serial % 2
? createX3Car('car red', 30, 14, 8, [1, 0, 0])
: createX3Car('car green', 25, 12, 8, [1, 1, 0]);
}
},
queues: [
{ queue: sim.qPedArr, element: 'x3d .ss-queue.ped-arr' },
{ queue: sim.qPedXing, element: 'x3d .ss-queue.ped-xing', angle: -45, max: 8 },
{ queue: sim.qPedXed, element: 'x3d .ss-queue.ped-xed' },
{ queue: sim.qPedLeave, element: 'x3d .ss-queue.ped-leave' },
{ queue: sim.qCarArr, element: 'x3d .ss-queue.car-arr' },
{ queue: sim.qCarXing, element: 'x3d .ss-queue.car-xing', angle: 0, max: 16 },
{ queue: sim.qCarXed, element: 'x3d .ss-queue.car-xed' },
]
});
// update display when the time or state change
const lights = animationHost.querySelectorAll('material.light');
const timeNow = document.querySelector('.x3d.ss-time-now span');
const updateStats = () => {
timeNow.textContent = format(sim.timeNow / 3600);
for (let i = 0; i < lights.length; i++) {
const e = lights[i] as HTMLElement;
e.setAttribute('transparency', i == sim.light ? '0' : '0.7');
e.closest('transform').setAttribute('scale', i == sim.light ? '1.1 1.1 1.1' : '.9 .9 .9');
}
}
sim.timeNowChanged.addEventListener(updateStats);
sim.stateChanged.addEventListener(updateStats);
}
);
//----------------------------------------------------------
// AnimationOptions (SVG)
showSimulation(
new AnimationOptions({
maxTimeStep: 0.1
}),
'Animation Options (SVG)',
`<p>
Change the animation parameters to see their effect:</p>
<label>
Queue Angle
<input id='q-angle' type='range' min='0' max='360' step='15'>
</label>
<label>
Rotate Entities
<input id='rotate-ents' type='checkbox'>
</label>
<label>
Spline Tension
<input id='tension' type='range' min='0' max='1' step='.1'>
</label>
<label>
Max Time Step
<input id='max-step' type='range' min='0' max='1' step='.1'>
</label>
<label>
Frame Delay
<input id='frame-delay' type='range' min='0' max='250' step='10'>
</label>
<svg class='ss-anim' viewBox='0 0 1000 500'>
<!-- one rotating queue -->
<rect class='ss-queue rotate' x='98%' y='23%' width='4%' height='4%'/>
<line x1='100%' y1='15%' x2='100%' y2='35%' stroke='black'/>
<line x1='90%' y1='25%' x2='110%' y2='25%' stroke='black'/>
<!-- one queue at the center -->
<rect class='ss-queue center' x='38%' y='48%' width='4%' height='4%'/>
<!-- twelve queues around it -->
<rect class='ss-queue q1' x='58%' y='83%' width='4%' height='4%'/>
<rect class='ss-queue q2' x='73%' y='68%' width='4%' height='4%'/>
<rect class='ss-queue q3' x='78%' y='48%' width='4%' height='4%'/>
<rect class='ss-queue q4' x='73%' y='28%' width='4%' height='4%'/>
<rect class='ss-queue q5' x='58%' y='13%' width='4%' height='4%'/>
<rect class='ss-queue q6' x='38%' y='8%' width='4%' height='4%'/>
<rect class='ss-queue q7' x='18%' y='13%' width='4%' height='4%'/>
<rect class='ss-queue q8' x='3%' y='28%' width='4%' height='4%'/>
<rect class='ss-queue q9' x='-2%' y='48%' width='4%' height='4%'/>
<rect class='ss-queue q10' x='3%' y='68%' width='4%' height='4%'/>
<rect class='ss-queue q11' x='18%' y='83%' width='4%' height='4%'/>
<rect class='ss-queue q12' x='38%' y='88%' width='4%' height='4%'/>
</svg>`,
(sim: AnimationOptions, animationHost: HTMLElement) => {
const anim = new Animation(sim, animationHost, {
rotateEntities: true,
getEntityHtml: (e: Entity) => {
if (e instanceof RoamEntity) {
return e.fast
? `<polygon points='0 0, 40 0, 50 10, 40 20, 0 20' stroke='black' fill='yellow' opacity='0.5'/>`
: `<polygon points='0 0, 20 0, 30 20, 20 40, 0 40' stroke='black' fill='red' opacity='0.5'/>`;
} else { // EnterLeaveEntity
return e.serial % 2 // long/short images
? `<polygon points='0 0, 40 0, 50 10, 40 20, 0 20' stroke='black' fill='blue'/>`
: `<polygon points='0 0, 20 0, 30 20, 20 40, 0 40' stroke='black' fill='green'/>`;
}
},
queues: [
{ queue: sim.qRotate, element: 'svg .ss-queue.rotate', angle: sim.qAngle },
{ queue: sim.qCenter, element: 'svg .ss-queue.center' },
{ queue: sim.q1, element: 'svg .ss-queue.q1' },
{ queue: sim.q2, element: 'svg .ss-queue.q2' },
{ queue: sim.q3, element: 'svg .ss-queue.q3' },
{ queue: sim.q4, element: 'svg .ss-queue.q4' },
{ queue: sim.q5, element: 'svg .ss-queue.q5' },
{ queue: sim.q6, element: 'svg .ss-queue.q6' },
{ queue: sim.q7, element: 'svg .ss-queue.q7' },
{ queue: sim.q8, element: 'svg .ss-queue.q8' },
{ queue: sim.q9, element: 'svg .ss-queue.q9' },
{ queue: sim.q10, element: 'svg .ss-queue.q10' },
{ queue: sim.q11, element: 'svg .ss-queue.q11' },
{ queue: sim.q12, element: 'svg .ss-queue.q12' },
]
});
// parameters
bind('q-angle', sim.qAngle, v => {
sim.qAngle = v;
let q = anim.queues;
q[0].angle = v;
anim.queues = q;
});
bind('rotate-ents', anim.rotateEntities, v => anim.rotateEntities = v);
bind('tension', sim.splineTension, v => sim.splineTension = v);
bind('max-step', sim.maxTimeStep, v => sim.maxTimeStep = v, ' sim time units');
bind('frame-delay', sim.frameDelay, v => sim.frameDelay = v, ' ms');
}
);
//----------------------------------------------------------
// AnimationOptions (A-Frame)
showSimulation(
new AnimationOptions({
maxTimeStep: 0.1
}),
'Animation Options (A-Frame)',
`<p>
This sample uses the same Crosswalk Simulation class as shown earlier,
this time using an <a href="https://aframe.io">A-Frame-based</a> animation.</p>
<p>
Change the animation parameters to see their effect:</p>
<label>
Queue Angle
<input id='af-q-angle' type='range' min='0' max='360' step='15'>
</label>
<label>
Rotate Entities
<input id='af-rotate-ents' type='checkbox'>
</label>
<label>
Spline Tension
<input id='af-tension' type='range' min='0' max='1' step='.1'>
</label>
<label>
Max Time Step
<input id='af-max-step' type='range' min='0' max='1' step='.1'>
</label>
<label>
Frame Delay
<input id='af-frame-delay' type='range' min='0' max='250' step='10'>
</label>
<div class="anim-host">
<a-scene embedded class='ss-anim'>
<!-- mix-ins -->
<a-assets>
<a-mixin id='queue' geometry='radius:4' material='color:orange;opacity:0.3'></a-mixin>
<a-mixin id='transparent' opacity='0.6' transparent='true'></a-mixin>
</a-assets>
<!-- camera -->
<a-entity id='rig' position='0 -150 150' rotation='40 0 0'>
<a-camera id='camera' far='50000' fov='80'></a-camera>
</a-entity>
<!-- camera
<a-entity id='rig' position='0 -200 50' rotation='70 0 0'>
<a-camera id='camera' far='50000' fov='60' look-controls></a-camera>
</a-entity>
-->
<!-- add a light -->
<a-entity light='type:directional; castShadow:true;' position='5 5 15'></a-entity>
<!-- background -->