-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbrassmapeditor.html
executable file
·984 lines (845 loc) · 30.6 KB
/
brassmapeditor.html
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
<!--
=============================================================================
BRASS Map editor
Authors: Javier Camara and Bradley Schmerl
Please report bugs and other issues to jcmoreno@cs.cmu.edu
Running the editor:
1. Put on a web server, or create a local one running "python -m SimpleHTTPServer"
from the folder where the editor is.
2. Load on web browser (tested in Chrome Version 59.0.3071.115 (64-bit) OSX.
(e.g., "http://localhost:8000/brassmapeditor.html")
Using the editor:
Detailed instructions can be found in "instructions.html", or by clicking on
the "Help" link on the top-right corner of the editor's UI.
=============================================================================
-->
<table cellpadding="0" cellspacing="0" width="800" border="1" bordercolor="#dddddd">
<tr>
<td>
<label><font size="2">Background:</font> </label>
<input type="file" id="imageLoader" name="imageLoader"/>
<input type="text" label="m/px" id="mpr" size='6' value='18.5'/>
<label for='mpr'><font size="2">cm/px</font></label>
</td>
<td>
<label><font size="2">Map:</font> </label>
<input type="file" id="mapLoader" name="mapLoader"/>
</td>
<td>
<center>
<font size="2">
<a id="exportMap" onclick="exportMap(this);" class="btn"><i class="icon-download"></i> [Export Map]</a>
</font>
</center>
</td>
<td>
<center>
<font size="2">
<a href="instructions.html" target="_blank">Help</a>
</font>
</center>
</td>
</tr>
</table>
<font size="2">
Tools:
<button type="button" title="Set origin of coordinates" id="setOriginTool" name="setOriginTool" onclick="setToolOrigin(this)"><img src="icons/origin.png" width=15 /></button>
<button type="button" title="Create waypoint (+alt key eliminates waypoint)" id="createTool" name="createTool" onclick="setToolCreate(this)"><img src="icons/location.png" width=15 /></button>
<!-- <button type="button" title="Remove waypoint" id="removeTool" name="removeTool" onclick="setToolRemove(this)"><img src="icons/removelocation.png" width=15 /></button> -->
<button type="button" title="Connect waypoints" id="connectTool" name="connectTool" onclick="setToolConnect(this)"><img src="icons/connect.png" width=15 /></button>
<!-- <button type="button" title="Disconnect waypoints" id="disconnectTool" name="disconnectTool" onclick="setToolDisconnect(this)"><img src="icons/removeconnect.png" width=15 /></button>-->
<button type="button" title="Move waypoint" id="moveTool" name="moveTool" onclick="setToolMove(this)"><img src="icons/move.png" width=15 /></button>
<button type="button" title="Draw walls (+alt key eliminates wall)" id="wallTool" name="wallTool" onclick="setToolWall(this)"><img src="icons/wall.png" width=15 /></button>
<!--<button type="button" title="Remove walls" id="removeWallTool" name="removeWallTool" onclick="setToolRemoveWall(this)"><img src="icons/removewall.png" width=15 /></button>-->
<button type="button" title="Place obstacle (+alt key eliminates obstacle)" id="obstacleTool" name="obstacleTool" onclick="setToolObstacle(this)"><img src="icons/obstacle.png" width=15 /></button>
<button type="button" title="Place light" id="placeLightTool" name="placeLightTool" onclick="setToolPlaceLight(this)"><img src="icons/lightbulb.png" width=15 /></button>
<button type="button" title="Toggle charging station" id="toggleChargingTool" name="toggleChargingTool" onclick="setToolToggleCharging(this)"><img src="icons/battery.png" width=15 /></button>
<button type="button" title="Place obstacle info" id="obstacleInfoTool" name="obstacleInfoTool" onclick="setToolInfoObstacle(this)"><img src="icons/attribute.png" width=15 /></button>
<button type="button" title="Remove obstacle info" id="removeObstacleTool" name="removeObstacleTool" onclick="setToolRemoveObstacle(this)"><img src="icons/removeattribute.png" width=15 /></button>
<select id="attEdit" name="attEdit">
<option value="easy"> Easy</option>
<option value="medium"> Medium</option>
<option value="difficult"> Difficult</option>
</select>
Display:
<input type="checkbox" title="Display background" id="displaybackgroundcheck"> Background
<input type="checkbox" title="Display lights" id="displaylightscheck" checked> Lights
<!-- <input type="checkbox" title="Display initial points" id="displayinitialpointscheck" checked> Initial points -->
</font>
<canvas id="imageCanvas"></canvas>
<script>
// =============================================================================
// User interface vars
// =============================================================================
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', importImage, false);
var mapLoader = document.getElementById('mapLoader');
mapLoader.addEventListener('change', importMap, false);
var canvas = document.getElementById('imageCanvas');
var saveButton = document.getElementById("saveMap");
var ctx = canvas.getContext('2d');
var img =null;
var obstacleicon = new Image();
obstacleicon.src = "/icons/obstacle.png";
var lighticon = new Image();
lighticon.src = "/icons/lightbulb.png";
var batteryicon = new Image();
batteryicon.src = "/icons/battery.png";
rx=ry=0; // current cursor position
v=3;
grid_granularity=5; // Snap grid cell size
// =============================================================================
// Map vars
// =============================================================================
var MPR = 22; // Meter to pixel ratio
var origin=[];
var locationsx=[], locationsy=[], locationsl=[]; // location coordinates and labels (nodes)
var connections=[]; // trajectories (arcs)
var walllocationsx=[], walllocationsy=[]; // wall location coordinates
var obstacles=[], obstaclelabels=[]; // obstacles associated with arcs
var lightsx=[], lightsy=[], lightids=[]; // Lights
var ipointsx=[], ipointsy=[]; // Initial points grid
var IPS = 2 * grid_granularity; // Separation between initial points in grid
var OBSTACLE_SIZE = 10 // 50/MPR; Size of obstacles
var stations=[]; // charging stations
var worldobstaclesx=[], worldobstaclesy=[]; // x,y obstacles 0.5x05m in world
// =============================================================================
// Map querying (checking locations at x,y position, etc.)
// =============================================================================
function getLocationAt(x, y){
for (var i = 0; i < locationsx.length; i ++) {
if (Math.abs(locationsx[i]-x)<=grid_granularity && Math.abs(locationsy[i]-y)<=grid_granularity)
return locationsl[i];
}
return "";
}
function getWorldObstacleAt(x, y){
for (var i = 0; i < worldobstaclesx.length; i ++) {
if (Math.abs(worldobstaclesx[i]-x)<=OBSTACLE_SIZE && Math.abs(worldobstaclesy[i]-y)<=OBSTACLE_SIZE)
return [i];
}
return -1;
}
function getLocationIndex(label){
for (var i = 0; i < locationsl.length; i ++) {
if (locationsl[i]==label)
return i;
}
return -1;
}
function getCoords(label){
for (var i = 0; i < locationsl.length; i ++) {
if (locationsl[i]==label)
return ({x:locationsx[i],y:locationsy[i]});
}
}
function getConnections(label){
var result=[];
for (var i=0; i < connections.length; i++){
if (connections[i].from==label)
result.push(connections[i].to);
}
return result;
}
function locationsConnected(l1,l2){
return (getConnections(l1).indexOf(l2)>=0);
}
function pixelsToMeters(coords){
var result = ([parseFloat(((coords[0]-origin[0])/MPR).toFixed(3)), parseFloat(((origin[1]-coords[1])/MPR).toFixed(3))]);
return result;
}
function metersToPixels(coords){
var result = [];
return ([Math.floor(origin[0]+coords[0]*MPR), Math.floor(origin[1]-coords[1]*MPR)]);
}
function originPixelsToMeters() {
return [parseFloat((origin[0]/MPR).toFixed(3)), parseFloat((origin[1]/MPR).toFixed(3))]
}
function originMetersToPixels(o) {
return [Math.floor(o[0]*MPR), Math.floor(o[1]*MPR)]
}
function coordsWithinWalls (x, y){
/* var wlx=[], wly = [];
var i=1;
wlx.push(walllocationsx[0]);
wly.push(walllocationsy[0]);
while (((walllocationsx[i]!=walllocationsx[0]) && (walllocationsy[i]!=walllocationsy[0])) || (i<walllocationsx.length)){
wlx.push(walllocationsx[0]);
wly.push(walllocationsy[0]);
i=i+1;
}
if (wlx.length>0)
console.log(wlx.length);*/
return coordsWithinPolygon (x, y, walllocationsx, walllocationsy);
}
function coordsWithinPolygon (x, y, cornersX, cornersY) {
var i, j=cornersX.length-1 ;
var oddNodes=false;
var polyX = cornersX;
var polyY = cornersY;
for (i=0; i<cornersX.length; i++) {
if ((polyY[i]< y && polyY[j]>=y || polyY[j]< y && polyY[i]>=y) && (polyX[i]<=x || polyX[j]<=x)) {
oddNodes^=(polyX[i]+(y-polyY[i])/(polyY[j]-polyY[i])*(polyX[j]-polyX[i])<x);
}
j=i;
}
return oddNodes;
}
function coordsOnLine(x, y, sx, sy, ex, ey) {
tolerance = 3
var L2 = ( ((ex-sx) * (ex-sx)) + ((ey-sy) * (ey-sy)));
if (L2 == 0) return false;
var r = (((x - sx) * (ex - sx)) + ((y - sy) * (ey - sy)))/L2;
if (r < 0) {
return (Math.sqrt(((sx - x) * (sx - x)) + ((sy - y) * (sy -y))) <= tolerance)
}
else if ((0 <= r) && (r <= 1)) {
var s = (((sy - y) * (ex - sx)) - ((sx - x) * (ey - sy))) / L2;
return (Math.abs(s) * Math.sqrt(L2) < tolerance);
}
else {
return (Math.sqrt(((ex - x) * (ex-x)) + ((ey -y) * (ey-y))) <= tolerance);
}
}
function removeWallAt(px, py) {
var wlx = [], wly = [];
var i = 1;
while (i < walllocationsx.length) {
if (!coordsOnLine(px,py, walllocationsx[i-1], walllocationsy[i-1], walllocationsx[i], walllocationsy[i])) {
wlx.push(walllocationsx[i-1])
wlx.push(walllocationsx[i])
wly.push(walllocationsy[i-1])
wly.push(walllocationsy[i])
}
i = i + 2;
}
walllocationsx = wlx;
walllocationsy = wly;
}
function removeConnectionAt(px, py) {
var newconns=[]
console.log("removeconnat "+px.toString()+" "+py.toString())
for (var i=0; i<connections.length; i++){
if (!coordsOnLine(px, py, getCoords(connections[i].from).x,
getCoords(connections[i].from).y,
getCoords(connections[i].to).x,
getCoords(connections[i].to).y )){
newconns.push(connections[i]);
}
}
connections = newconns;
}
function removeObstaclesBetweenLocations (l1, l2){
var auxobstacles=[];
var auxobstaclelabels=[];
for (var i = 0; i < obstacles.length; i += 1) {
if (!((obstacles[i].from==l1 && obstacles[i].to==l2) || (obstacles[i].from==l2 && obstacles[i].to==l1))){
auxobstaclelabels.push(obstaclelabels[i]);
auxobstacles.push(obstacles[i]);
}
}
obstacles = auxobstacles;
obstaclelabels = auxobstaclelabels;
}
function createLightsOnWaypoints(){
for (var i=0; i<locationsx.length;i+=1){
lightsx.push(locationsx[i]);
lightsy.push(locationsy[i]);
lightids.push("light"+lightids.length.toString());
}
}
function createInitialPoints(){
ipointsx=[];
ipointsy=[];
for (var i = grid_granularity; i < canvas.height; i += IPS)
for (var j = grid_granularity; j < canvas.width; j += IPS)
if (coordsWithinWalls(j,i)){
ipointsx.push(j);
ipointsy.push(i);
}
}
// =============================================================================
// Tool vars
// =============================================================================
var tool = 0; // tool= 0 create, 1 connect, 2 move, 3 setorigin,
// 4 Wall, 5 obstacle, 6 remove obstacle, 7 remove wall, 8 place light
// 9 toggle charging station, 10 disconnect waypoints, 11 remove waypoints,
// 12 place rewal world obstacle
var initStroke, endStroke; // Location aux vars for tools
var connecting=false, moving=false; // Aux var for connection and moving tool
// =============================================================================
// Tool manipulation and canvas event handling
// =============================================================================
function setToolConnect(){
connecting = false;
moving = false;
tool = 1;
}
function setToolCreate(){
connecting = false;
moving = false;
tool = 0;
}
function setToolMove(){
connecting = false;
moving = false;
tool = 2;
}
function setToolOrigin(){
connecting = false;
moving = false;
tool = 3;
}
function setToolWall(){
connecting = false;
moving = false;
tool = 4;
}
function setToolInfoObstacle(){
connecting = false;
moving = false;
tool = 5;
}
function setToolRemoveObstacle(){
connecting = false;
moving = false;
tool = 6;
}
function setToolRemoveWall(){
connecting = false;
moving = false;
tool = 7;
}
function setToolPlaceLight(){
connecting = false;
moving = false;
tool = 8;
}
function setToolToggleCharging(){
connecting = false;
moving = false;
tool = 9;
}
function setToolDisconnect(){
connecting = false;
moving = false;
tool = 10;
}
function setToolRemove(){
connecting = false;
moving = false;
tool = 11;
}
function setToolObstacle(){
connecting = false;
moving = false;
tool = 12;
}
// Handles mouse move events
function moveReporter(e){
var rect = imageCanvas.getBoundingClientRect();
ex = e.pageX-rect.left;
ey = e.pageY-rect.top;
rx=Math.floor(ex/grid_granularity)*grid_granularity;
ry=Math.floor(ey/grid_granularity)*grid_granularity;
if (tool==2 && moving==true){
mindex = getLocationIndex(initStroke);
locationsx[mindex] = rx;
locationsy[mindex] = ry;
}
}
// Handles mouse click events
function clickReporter(e){
if (tool==0){ // Creating waypoints
if (!e.altKey){
locationsx.push(rx);
locationsy.push(ry);
locationsl.push("l"+locationsx.length.toString());
console.log("l"+locationsx.length.toString()+" created.")
} else { // Eliminate waypoint
var sloc = getLocationAt(rx,ry)
slocidx=locationsl.indexOf(sloc)
if (slocidx>=0){
if (getConnections(sloc).length==0){ // Removed only if waypoint not connected to any other waypoint
locationsx.splice(slocidx,1);
locationsy.splice(slocidx,1);
locationsl.splice(slocidx,1);
}
}
}
}
if (tool==1){ // Creating connections between locations
if (connecting==false){ // If starting a connection (selecting start node)
initStroke = getLocationAt(rx,ry);
if (initStroke!=""){
connecting = true;
}
} else { // If finishing a connection (selecting end node)
endStroke = getLocationAt(rx,ry);
if (endStroke!="" && endStroke!=initStroke && !locationsConnected(initStroke,endStroke)){
connecting = false;
connections.push({from:initStroke,to:endStroke}); // Connections are bidirectional
connections.push({from:endStroke,to:initStroke});
}
}
}
if (tool==2){ // Moving node
if (moving == false) {
initStroke = getLocationAt(rx,ry);
if (initStroke!=""){
moving = true;
}
}
else
moving = false;
}
if (tool==3){ // Setting origin of coordinates
origin[0] = rx;
origin[1] = ry;
}
if (tool==4){ // adding wall vertex
if (!e.altKey){
walllocationsx.push(rx);
walllocationsy.push(ry);
} else { // Remove wall
removeWallAt(rx, ry);
}
}
if (tool==5){ // Creating obstacles between waypoints
if (connecting==false){ // If starting a connection (selecting start node)
initStroke = getLocationAt(rx,ry);
if (initStroke!=""){
connecting = true;
}
} else { // If finishing a connection (selecting end node)
endStroke = getLocationAt(rx,ry);
if (endStroke!=""){
connecting = false;
obstacles.push({from:initStroke,to:endStroke}); // associate obstacle with connecting arcs
obstacles.push({from:endStroke,to:initStroke});
obstaclelabels.push(attEdit.value);
obstaclelabels.push(attEdit.value);
}
}
}
if (tool==6){ // Removing obstacles between waypoints
if (connecting==false){ // If starting a connection (selecting start node)
initStroke = getLocationAt(rx,ry);
if (initStroke!=""){
connecting = true;
}
} else { // If finishing a connection (selecting end node)
endStroke = getLocationAt(rx,ry);
if (endStroke!=""){
connecting = false;
removeObstaclesBetweenLocations(initStroke, endStroke);
}
}
}
if (tool==8){ // Creating lights
lightsx.push(rx);
lightsy.push(ry);
lightids.push("light"+lightids.length.toString());
}
if (tool==9) { // Toggle charging station on location
var sloc = getLocationAt(rx,ry);
if (locationsl.indexOf(sloc) >= 0) { // If location at mouse pointer
if (stations.indexOf(sloc) >= 0){
stations.splice(stations.indexOf(sloc),1); // If it is a charging station, remove it from charging station list
} else {
stations.push(sloc); // Otherwise, add it to charging stations
}
} // If no location at mouse pointer, do nothing
}
if (tool==10){ // Remove connection between waypoints
removeConnectionAt(rx,ry);
}
if (tool==12){
if (!e.altKey){ // Place real world obstacle
worldobstaclesx.push(rx);
worldobstaclesy.push(ry);
} else{ // Delete obstacle if found in location
var wobs = getWorldObstacleAt(rx,ry);
if (wobs>=0){
worldobstaclesx.splice(wobs,1);
worldobstaclesy.splice(wobs,1);
}
}
}
}
// Keyboard handling
function KeyPress(e) {
var evtobj = window.event? event : e
if (evtobj.keyCode == 90 && evtobj.ctrlKey) { // undo (ctrl+z)
if (tool==4){ // undo last wall
walllocationsx.splice(-2,2);
walllocationsy.splice(-2,2);
}
if (tool==8){ // undo last light
lightsx.splice(-1,1);
lightsy.splice(-1,1);
lightids.splice(-1,1);
}
}
if (evtobj.keyCode == 66 && evtobj.ctrlKey) { // toggle background image display (ctrl+b)
displaybackgroundcheck.checked = !displaybackgroundcheck.checked;
}
if (evtobj.keyCode == 76 && evtobj.ctrlKey) { // toggle lights display (ctrl+l)
displaylightscheck.checked = !displaylightscheck.checked;
}
if (evtobj.keyCode == 81 /*&& evtobj.ctrlKey*/) { // Create lights on all waypoints (ctrl+q)
createLightsOnWaypoints();
}
if (evtobj.keyCode == 73 && evtobj.ctrlKey) { // Create initial points grid (ctrl+i)
createInitialPoints();
}
}
document.onkeydown = KeyPress;
// =============================================================================
// Import/Export of Map Data (JSON) and BG map image
// =============================================================================
function exportMap(el) {
var map = [];
MPR = parseFloat(document.getElementById('mpr').value)
for (var i = 0; i < locationsx.length; i ++) {
var mcoord = pixelsToMeters([locationsx[i], locationsy[i]]);
var coord = {x: mcoord[0] , y: mcoord[1]};
coord["x"]=parseFloat(coord["x"]);
coord["y"]=parseFloat(coord["y"]);
var obj = {"node-id": locationsl[i], coords:coord, "connected-to":getConnections(locationsl[i])};
map.push(obj);
}
var walls = [];
for (var i = 0; i < walllocationsx.length-1; i = i+2) { // export walls
var mcoord1 = pixelsToMeters([walllocationsx[i], walllocationsy[i]]);
var mcoord2 = pixelsToMeters([walllocationsx[i+1], walllocationsy[i+1]]);
var coord1 = {x: mcoord1[0] , y: mcoord1[1]};
var coord2 = {x: mcoord2[0] , y: mcoord2[1]};
coord1["x"]=parseFloat(coord1["x"]);
coord1["y"]=parseFloat(coord1["y"]);
coord2["x"]=parseFloat(coord2["x"]);
coord2["y"]=parseFloat(coord2["y"]);
var objw = {"p1": coord1, "p2": coord2 };
walls.push(objw);
}
var objobstacles=[];
for (var i = 0; i < obstacles.length; i ++) {
var obj = {"from": obstacles[i].from, "to": obstacles[i].to, "id":obstaclelabels[i]};
objobstacles.push(obj);
}
var objlights=[];
for (var i = 0; i < lightids.length; i ++) {
var lcoord = pixelsToMeters([lightsx[i].toFixed(3), lightsy[i].toFixed(3)]);
var obj = {"light-id": lightids[i], "coord": { "x": parseFloat(lcoord[0]), "y": parseFloat(lcoord[1])} };
objlights.push(obj);
}
ocoord = originPixelsToMeters()
var objipoints=[];
for (var i = 0; i < ipointsx.length; i ++) {
var lcoord = pixelsToMeters([ipointsx[i].toFixed(3), ipointsy[i].toFixed(3)]);
var obj = {"x": parseFloat(lcoord[0]), "y": parseFloat(lcoord[1])};
objipoints.push(obj);
}
var objwobstacles=[];
for (var i = 0; i < worldobstaclesx.length; i ++) {
var lcoord = pixelsToMeters([worldobstaclesx[i].toFixed(3), worldobstaclesy[i].toFixed(3)]);
var obj = {"x": parseFloat(lcoord[0]), "y": parseFloat(lcoord[1])};
objwobstacles.push(obj);
}
var jsonobj = {mpr : MPR, map: map, walls: walls, origin: {"x" : ocoord [0],"y" : ocoord[1]}, "unsafe-rects": [], obstacles: objobstacles, worldobstacles: objwobstacles,lights: objlights, "stations": stations, "initial-points": objipoints};
var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(jsonobj, null, 2));
el.setAttribute("href", "data:"+data);
el.setAttribute("download", "data.json");
}
function importMap(e){
var reader = new FileReader();
reader.onload = load(e.target.files[0]["name"]);
}
function getURLPath(urlStr){
var pathArray = urlStr.split( '/' );
var newPathname = "";
for (var i = 1; i < pathArray.length-1; i++) {
newPathname += "/";
newPathname += pathArray[i];
}
// console.log(newPathname);
return newPathname;
}
var actual_JSON;
function load(filename) {
console.log(filename);
var filename2 =getURLPath(window.location.href)+"/"+filename;
loadJSON(filename2, function(response) {
actual_JSON = JSON.parse(response);
// console.log(actual_JSON);
clearMap();
parseMap();
});
}
function loadJSON(file, callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', file, true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
function clearMap(){
origin = [];
locationsx = [];
locationsy = [];
locationsl = [];
walllocationsx=[];
walllocationsy=[];
connections = [];
lightsx = [];
lightsy = [];
lightids = [];
}
function parseMap (){
var JSONmap = actual_JSON;
if (!JSONmap["mpr"]) {
MPR = 18.5;
}
else {
MPR = parseFloat(JSONmap["mpr"]);
}
// load origin
if (JSONmap["origin"]["x"]) {
// new origin format
o = [JSONmap["origin"]["x"], JSONmap["origin"]["y"]];
origin = originMetersToPixels(o);
}
else {
origin.push(JSONmap["origin"]["x"]); // setting origin of coordinates
origin.push(JSONmap["origin"]["y"]);
}
// load graph map
for (var i=0; i<JSONmap["map"].length; i++){
pcoord = metersToPixels([JSONmap["map"][i]["coords"]["x"], JSONmap["map"][i]["coords"]["y"]]);
locationsx.push(pcoord[0]);
locationsy.push(pcoord[1]);
locationsl.push(JSONmap["map"][i]["node-id"]);
for (var j=0; j<JSONmap["map"][i]["connected-to"].length; j++){
connections.push({from:JSONmap["map"][i]["node-id"],to:JSONmap["map"][i]["connected-to"][j]});
}
}
// load walls
if (JSONmap["walls"]){
for (var i=0; i<JSONmap["walls"].length; i++){
pcoord1 = metersToPixels([JSONmap["walls"][i]["p1"]["x"], JSONmap["walls"][i]["p1"]["y"]]);
pcoord2 = metersToPixels([JSONmap["walls"][i]["p2"]["x"], JSONmap["walls"][i]["p2"]["y"]]);
walllocationsx.push(pcoord1[0]);
walllocationsy.push(pcoord1[1]);
walllocationsx.push(pcoord2[0]);
walllocationsy.push(pcoord2[1]);
}
}
// load obstacles
if (JSONmap["obstacles"]){
for (var i=0; i<JSONmap["obstacles"].length; i++){
obstacles.push({from:JSONmap["obstacles"][i]["from"], to:JSONmap["obstacles"][i]["to"]});
obstaclelabels.push(JSONmap["obstacles"][i]["id"]);
}
}
// load lights
if (JSONmap["lights"]){
for (var i=0; i<JSONmap["lights"].length; i++){
var lcoord=metersToPixels([JSONmap["lights"][i]["coord"]["x"], JSONmap["lights"][i]["coord"]["y"]]);
lightsx.push(lcoord[0]);
lightsy.push(lcoord[1]);
lightids.push(JSONmap["lights"][i]["light-id"]);
}
}
// load world obstacles
if (JSONmap["worldobstacles"]){
for (var i=0; i<JSONmap["worldobstacles"].length; i++){
var lcoord=metersToPixels([JSONmap["worldobstacles"][i]["x"], JSONmap["worldobstacles"][i]["y"]]);
worldobstaclesx.push(lcoord[0]);
worldobstaclesy.push(lcoord[1]);
}
}
// load stations
if (JSONmap["stations"]){
for (var i=0; i<JSONmap["stations"].length; i++){
stations.push(JSONmap["stations"][i]);
}
}
document.getElementById('mpr').value = MPR
}
function importImage(e){
var reader = new FileReader();
reader.onload = function(event){
img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
rx=canvas.width/2;
ry=canvas.height/2;
setInterval(update,1000/20);
canvas.addEventListener('mousemove', moveReporter, false);
canvas.addEventListener('click',clickReporter,false);
origin.push(0);
origin.push(img.height);
}
img.src = event.target.result;
document.getElementById("displaybackgroundcheck").checked = true;
}
reader.readAsDataURL(e.target.files[0]);
}
// =============================================================================
// Rendering
// =============================================================================
function update(){
if (displaybackgroundcheck.checked){
ctx.drawImage(img,0,0);
}
else {
ctx.fillStyle = "rgb(255, 255, 255)";
ctx.fillRect(0, 0, img.width , img.height);
}
render();
ctx.fillStyle = "rgb(200, 200, 200)";
ctx.fillRect(rx-grid_granularity/2, ry-grid_granularity/2, grid_granularity, grid_granularity);
}
function render(){
MPR = parseFloat(document.getElementById('mpr').value)
drawGrid();
drawCoordinates();
drawTool();
drawLocations();
drawConnections();
drawWorldObstacles();
drawObstacles();
drawOrigin();
drawWalls();
if (displaylightscheck.checked)
drawLights();
// if (displayinitialpointscheck.checked)
// drawInitialPoints();
}
function drawGrid(){
ctx.strokeStyle = '#cccccc';
ctx.strokeStyle = "rgba(200, 200, 200 ,0.3)";
ctx.lineWidth=1;
ctx.beginPath();
for (var i = grid_granularity; i < canvas.height; i += grid_granularity) {
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
}
for (var j = grid_granularity; j < canvas.width; j += grid_granularity) {
ctx.moveTo(j, 0);
ctx.lineTo(j, canvas.height);
}
ctx.stroke();
}
function drawCoordinates(){
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.font="20px Georgia";
var mrx = pixelsToMeters([rx,ry])[0].toString();
var mry = pixelsToMeters([rx,ry])[1].toString();
// ctx.fillText("X: "+rx.toString()+"["+mrx+"]"+" Y: "+ry.toString()+"["+mry+"]",10,30);
ctx.fillText("X: "+mrx+" Y: "+mry.toString(),10,30);
}
function drawTool(){
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.font="20px Georgia";
var strTool = "[create]";
if (tool==1){
strTool = "[connect]";
}
if (tool==2){
strTool= "[move]";
}
if (tool==3){
strTool= "[set origin]";
}
if (tool==4){
strTool= "[draw walls]";
}
if (tool==5){
strTool= "[place obstacles]";
}
if (tool==8){
strTool= "[place lights]";
}
if (tool==9){
strTool = "[toggle charging station]"
}
if (tool==10){
strTool = "[disconnect waypoints]"
}
if (tool==11){
strTool = "[remove waypoints]"
}
ctx.fillText("Tool:"+strTool,10,50);
}
function drawLocations(){
for (var i = 0; i < locationsx.length; i ++) {
ctx.fillStyle = "rgb(200, 0, 0)";
ctx.fillRect(locationsx[i]-grid_granularity/2, locationsy[i]-grid_granularity/2, grid_granularity, grid_granularity);
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.font="10px Georgia";
ctx.fillText(locationsl[i],locationsx[i]+grid_granularity,locationsy[i]+grid_granularity);
if (stations.indexOf(locationsl[i])>=0){
ctx.drawImage(batteryicon, locationsx[i]-batteryicon.width-Math.floor(grid_granularity/2) , locationsy[i]-Math.floor(grid_granularity/2));
}
}
}
function drawInitialPoints(){
ctx.fillStyle = "rgba(0, 0, 200 ,0.3)";
for (var i = 0; i < ipointsx.length; i ++) {
ctx.fillRect(ipointsx[i]-grid_granularity/2, ipointsy[i]-grid_granularity/2, grid_granularity, grid_granularity);
}
}
function drawOrigin(){
ctx.fillStyle = "rgb(0, 0, 127)";
ctx.fillRect(origin[0]-grid_granularity, origin[1]-grid_granularity, grid_granularity*2, grid_granularity*2);
ctx.fillStyle = "rgb(0, 0, 255)";
ctx.fillRect(origin[0]-grid_granularity/2, origin[1]-grid_granularity/2, grid_granularity, grid_granularity);
}
function drawConnections(){
ctx.strokeStyle = '#ff0000';
ctx.lineWidth=2;
ctx.beginPath();
for (var i = 0; i < connections.length; i += 1) {
ctx.moveTo(getCoords(connections[i].from).x , getCoords(connections[i].from).y);
ctx.lineTo(getCoords(connections[i].to).x, getCoords(connections[i].to).y);
}
ctx.stroke();
}
function drawObstacles(){
for (var i = 0; i < obstacles.length; i += 1) {
ctx.drawImage(obstacleicon, Math.floor((getCoords(obstacles[i].from).x+getCoords(obstacles[i].to).x)/2)-Math.floor(grid_granularity/2) , Math.floor((getCoords(obstacles[i].from).y+getCoords(obstacles[i].to).y)/2)-Math.floor(grid_granularity/2));
}
}
function drawLights(){
for (var i = 0; i < lightids.length; i += 1) {
ctx.drawImage(lighticon, lightsx[i]-Math.floor(grid_granularity/2) , lightsy[i]-Math.floor(grid_granularity/2));
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.font="10px Georgia";
ctx.fillText(lightids[i],lightsx[i]+grid_granularity/2+lighticon.width,lightsy[i]+grid_granularity);
}
}
function drawWalls(){
ctx.strokeStyle = '#00ff00';
ctx.lineWidth=2;
ctx.beginPath();
for (var i = 0; i < Math.max(0,walllocationsx.length-1); i += 2) {
ctx.moveTo(walllocationsx[i] , walllocationsy[i]);
ctx.lineTo(walllocationsx[i+1] , walllocationsy[i+1]);
}
ctx.stroke();
}
function drawWorldObstacles(){
for (var i = 0; i < worldobstaclesx.length; i ++) {
ctx.fillStyle = "rgb(200, 0, 200)";
ctx.fillRect(worldobstaclesx[i]-OBSTACLE_SIZE/2, worldobstaclesy[i]-OBSTACLE_SIZE/2, OBSTACLE_SIZE, OBSTACLE_SIZE);
}
}
</script>