polylines_with_particles.js 17.2 KB
Newer Older
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
$(function () {
  Cesium.Ion.defaultAccessToken =
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5ODI4ZTYyZS1mMTg2LTQ5NGEtYjdiOS02ODg2NzVhNjc0MTAiLCJpZCI6MjkwNCwiaWF0IjoxNTM1MTA5OTAzfQ.kyDX_0ScvJBkYnvXI0DW5NfZbiaRL5ezwtAUhxYnk1Y";
  var imageryViewModels = [];
  imageryViewModels.push(
    new Cesium.ProviderViewModel({
      name: "Sentinel-2",
      iconUrl: Cesium.buildModuleUrl(
        "Widgets/Images/ImageryProviders/sentinel-2.png"
      ),
      tooltip: "Sentinel-2 cloudless.",
      creationFunction: function () {
        return new Cesium.IonImageryProvider({ assetId: 3954 });
      },
    })
  );

  imageryViewModels.push(
    new Cesium.ProviderViewModel({
      name: "Blue Marble",
      iconUrl: Cesium.buildModuleUrl(
        "Widgets/Images/ImageryProviders/blueMarble.png"
      ),
      tooltip: "Blue Marble Next Generation July, 2004 imagery from NASA.",
      creationFunction: function () {
        return new Cesium.IonImageryProvider({ assetId: 3845 });
      },
    })
  );

  var viewer = new Cesium.Viewer("cesiumContainer", {
    imageryProvider: new Cesium.IonImageryProvider({ assetId: 3954 }),

    terrainProvider: new Cesium.CesiumTerrainProvider({
      url: Cesium.IonResource.fromAssetId(1),
    }),
    scene3DOnly: false,
    shouldAnimate: true,
    animation: true,
    infoBox: true,
    baseLayerPicker: true,
42
43
    fullscreenButton: false,
    timeline: false,
44
45
    navigationHelpButton: true,
    navigationInstructionsInitiallyVisible: false,
46
    homeButton: false,
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
    selectionIndicator: true,
    geocoder: true,
    // imageryProviderViewModels: imageryViewModels
  });

  // var layer = viewer.imageryLayers.addImageryProvider(
  // 	new Cesium.IonImageryProvider({ assetId: 3 })
  // );

  var imageryLayer = viewer.imageryLayers.addImageryProvider(
    new Cesium.IonImageryProvider({ assetId: 3954 })
  );

  var canvas = viewer.canvas;
  canvas.setAttribute("tabindex", "0"); // needed to put focus on the canvas
  canvas.addEventListener("click", function () {
    canvas.focus();
  });
  canvas.focus();
  var scene = viewer.scene;

  var tileset = viewer.scene.primitives.add(
    new Cesium.Cesium3DTileset({
      url: "buildingTiles/StoeckachLOD1/tileset.json",
      show: true,
    })
  );

  tileset.readyPromise.then(function (tileset) {
    return zoomAll(tileset);
  });

  tileset.readyPromise.then(function (tileset) {
    var R = 0; // roll
    var P = 0; // pitch
    var Yaw = 0; // yaw
    var height = 53;
    var cartographic = Cesium.Cartographic.fromCartesian(
      tileset.boundingSphere.center
    );
    var surface = Cesium.Cartesian3.fromRadians(
      cartographic.longitude,
      cartographic.latitude,
      0.0
    );
    var offset = Cesium.Cartesian3.fromRadians(
      cartographic.longitude,
      cartographic.latitude,
      height
    );
    var translation = Cesium.Cartesian3.subtract(
      offset,
      surface,
      new Cesium.Cartesian3()
    );

    //var rotMat = new Cesium.Matrix3();
    var rotation = new Cesium.Matrix3.fromHeadingPitchRoll(
      new Cesium.HeadingPitchRoll(Yaw, P, R)
    );

    tileset.modelMatrix = Cesium.Matrix4.fromRotationTranslation(
      rotation,
      translation
    );

    return zoomAll(tileset);
  });

  viewer.scene.globe.enableLighting = true; // set lighting to true

  var zoomAll = function (tileset) {
    return new Promise(function (resolve, reject) {
      if (!tileset) {
        reject("Tileset is undifined");
      }
      viewer.camera.viewBoundingSphere(
        tileset.boundingSphere,
        new Cesium.HeadingPitchRange(0, -0.5, 1500)
      );
      viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
      resolve();
    });
  };

  //////////////////////////////////////////
  // load streamline data from text file and parse it to polyline with multiple colors.

  var pos = [];
  var cols = [];
  var streamID = [];
  var Velocity = [];
  var pt_to_pt_dist = [];
  var avgVelocity = [];
141
  var czmlArray = [];
142
143
144
145
146
147
148
149
150
151
152

  function get_date_time_dt(deltaTime) {
    // deltaTime should be given in SECONDS and is then converted to milliseconds
    // set deltaTime to 0 if you want to get current date and time
    // set to +60000 to get date and time of 60 seconds = 60000 milliseconds in the future

    return (currentdate = new Date(
      new Date().getTime() + deltaTime * 1000
    ).toISOString());
  }

153
  var divisor = 15
154
  d3.dsv(",", "results/polylines_with_velocity.csv").then(function (text) {
155
    const particleDuration = 170; // units in seconds the particle / point should take to move from start to finish
156
157
158
159
160
161
    //define the czml structure
    var particle_czml = [
      {
        id: "document",
        name: "CZML Point - Time Dynamic",
        version: "1.0",
162
163
164
165
166
167
168
        clock: {
          interval: get_date_time_dt(0) + "/" + get_date_time_dt(particleDuration),         // This is the time range of our simulation
          currentTime: '',    // This is the time associated with the start view
          currentTime: get_date_time_dt(0),
          multiplier: 5,
          // range: 'LOOP_STOP',
        }
169
170
171
      },
      {
        id: "point",
172
173
        availability:
          get_date_time_dt(0) + "/" + get_date_time_dt(particleDuration),
174
175
176
177
178
        position: {
          epoch: get_date_time_dt(0),
          cartographicDegrees: [
            // use 4 coordinates / values : (t,x,y,z) or rather (t,lon,lat,alt)
          ],
179
180
          "interpolationAlgorithm": "LINEAR",
          "interpolationDegree": 5
181
182
183
        },
        point: {
          color: {
184
            rgba: [0, 0, 0, 250],
185
186
187
188
          },
          outlineColor: {
            rgba: [255, 0, 0, 128],
          },
189
190
          outlineWidth: 1,
          pixelSize: 6,
191
192
193
194
        },
      },
    ];

195
196
197
198
199
200
201
202
203
204
205
    //////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////
    let package_time_faktor = 2.0;

    // create an array of deep copies of the original czml data structure, to be modified below.
    let czmlArr = [];
    for (c=0; c < package_time_faktor; c++){
      czmlArr.push(JSON.parse(JSON.stringify(particle_czml)));    
      czmlArr[c][1].id = "point_arr_" + String(c);  
    }

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
    var temp = text;
    for (var i = 0; i < temp.length; i++) {
      // use i+=7 when parsed as d3.text(...)
      pos.push([
        parseFloat(text[i].Lon),
        parseFloat(text[i].Lat),
        parseFloat(text[i].z),
      ]);
      cols.push([
        parseInt(text[i].R),
        parseInt(text[i].G),
        parseInt(text[i].B),
      ]);
      streamID.push(parseInt(text[i].ID));
      Velocity.push(parseFloat(text[i].velocity));
      avgVelocity.push(parseFloat(text[i].AverageVelocity));
      pt_to_pt_dist.push(parseFloat(text[i].pt_to_pt_dist));
      // use these lines if parsed as text. i.e. using d3.text(...)
      //pos.push([parseFloat(temp[i+0]), parseFloat(temp[i+1]), parseFloat(temp[i+2])]);
      //colors.push([parseFloat(temp[i+3]),parseFloat(temp[i+4]),parseFloat(temp[i+5])])
      //streamID.push([parseFloat(temp[i+6])]);
    }

    const maxID = streamID.reduce(function (a, b) {
      return Math.max(a, b);
    });

    //find out the unique ids within the streamID array
    const uniqueStreamID = Array.from(new Set(streamID)); // const uniqueStreamID = [...new Set(streamID)]; // same can be done with spread operator

    //get index of each unique id, first element of those
    let sIDidx = [];
    for (var i = 0; i <= maxID; i++) {
      var tmpIdx = streamID.indexOf(i);
      if (tmpIdx !== -1) sIDidx.push(tmpIdx);
    }

    /////////////////////////////////////////////////
    // Create and draw a polyline with per vertex colors
    /////////////////////////////////////////////////
    const heightOffset = 120;
247
    for (var line = 0; line < uniqueStreamID.length; line++) {
248
249
250
251
252
253
254
      let positions = [];
      let positionsInDegrees = [];
      let colors = [];
      let individual_particle_velo = [];
      let individual_particle_pt_distance = [];
      let individual_particle_avg_velo = [];

255
256
257
      for (i = sIDidx[line - 1]; i < sIDidx[line] - 1; ++i) {
        positions.push(
          Cesium.Cartesian3.fromDegrees(
258
259
            pos[i][0],
            pos[i][1],
260
261
262
263
264
265
266
267
268
269
270
271
272
273
            pos[i][2] + heightOffset
          )
        );
        positionsInDegrees.push([
          pos[i][0],
          pos[i][1],
          pos[i][2] + heightOffset,
        ]);
        colors.push(
          Cesium.Color.fromBytes(cols[i][0], cols[i][1], cols[i][2], 180)
        );
        individual_particle_avg_velo.push(avgVelocity[i]);
        individual_particle_pt_distance.push(pt_to_pt_dist[i]);
        individual_particle_velo.push(Velocity[i]);
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
      }
      // For per segment coloring, supply the colors option with
      // an array of colors for each vertex.  Also set the
      // colorsPerVertex option to true.
      viewer.scene.primitives.add(
        new Cesium.Primitive({
          geometryInstances: new Cesium.GeometryInstance({
            geometry: new Cesium.PolylineGeometry({
              positions: positions,
              width: 5.0,
              vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
              colors: colors,
              colorsPerVertex: true,
            }),
          }),
          appearance: new Cesium.PolylineColorAppearance(),
        })
      );

      ////////////////////////////////////////////////
      // Create and prepare particles for movement
      /////////////////////////////////////////////////
      let streamDist = individual_particle_pt_distance.reduce(function (a, b) {
        return a + b;
298
299
	  }, 0);
	//   console.log(streamDist);
300
301

      let t = 0;
302
303
      let dt = (individual_particle_pt_distance[1] / individual_particle_avg_velo[0])/ divisor;
      // let dt = streamDist / individual_particle_avg_velo[0] / divisor;
304
305
      let temp_pos = [];

306
307
308
309
310
311
312
      for (i = 0; i < positionsInDegrees.length; i++) {
        if (i === 0) {
          temp_pos.push(
            0,
            positionsInDegrees[i][0],
            positionsInDegrees[i][1],
            positionsInDegrees[i][2]
313
          );
314
315
316
317
318
319
        } else {
          temp_pos.push(
            t,
            positionsInDegrees[i][0],
            positionsInDegrees[i][1],
            positionsInDegrees[i][2]
320
          );
321
          dt = individual_particle_pt_distance[i] /individual_particle_avg_velo[0] / divisor;
322
323
324
          // console.log(individual_particle_pt_distance[i] + "/" + individual_particle_avg_velo[i] );
          // console.log(dt);
        }
325

326
327
328
        t += dt;
      }
      particle_czml[1].id = "point" + String(line);
329
330
331
	  particle_czml[1].position.cartographicDegrees = temp_pos; 
	  
	//   czmlArray.push(particle_czml);
332
      viewer.dataSources.add(Cesium.CzmlDataSource.load(particle_czml));
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
        ////////////////////////////////////////////////      
        dt = (individual_particle_pt_distance[1] / individual_particle_avg_velo[0]) / divisor;
        for (c=0; c < czmlArr.length ; c++){

          temp_pos = [];
          for (i = 0; i < positionsInDegrees.length; i++) {
            if (i === 0) {
              temp_pos.push(
                t,
                positionsInDegrees[i][0],
                positionsInDegrees[i][1],
                positionsInDegrees[i][2]
              );          
            } else {
              temp_pos.push(
                t,
                positionsInDegrees[i][0],
                positionsInDegrees[i][1],
                positionsInDegrees[i][2]
              );          
              dt = individual_particle_pt_distance[i] /individual_particle_avg_velo[0] / divisor;
              // console.log(individual_particle_pt_distance[i] + "/" + individual_particle_avg_velo[i] );
              // console.log(dt);
            }

            t += dt;
          }
          czmlArr[c][1].position.cartographicDegrees = temp_pos;       
          czmlArr[c][1].id = "point_set_" + String(c) + "_" + String(line);  
          czmlArr[c][1].position.epoch = get_date_time_dt(0);
          viewer.dataSources.add(Cesium.CzmlDataSource.load(czmlArr[c])); 
        }
     
      
	  }   // end bracket for:  for (var line = 0; line < uniqueStreamID.length; line++) {
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

  

  // This adds a large arrow to the viewer. Works fine. for testing

  // var purpleArrow = viewer.entities.add({
  // 	name: "Purple straight arrow at height",
  // 	polyline: {
  // 	  positions: Cesium.Cartesian3.fromDegreesArrayHeights([
  // 		9.187290, 48.784567, 400,
  // 		9.195991, 48.790575, 400
  // 	  ]),
  // 	  width: 50,
  // 	  arcType: Cesium.ArcType.NONE,
  // 	  material: new Cesium.PolylineArrowMaterialProperty(
  // 		Cesium.Color.PURPLE
  // 	  ),
  // 	},
  //   });

  // var f = new File([""], "results/singlePolyline.csv", {type: "text/plain", lastModified: Date()})

  // var temp = text.split(',');
  //   for(var i = 0; i < temp.length; i+=6) {
  //     pos.push([parseFloat(temp[i+1]), parseFloat(temp[i+2]), parseFloat(temp[i+3])]);
  //     colors.push([parseInt(temp[i+4]),parseInt(temp[i+5]),parseInt(temp[i+6])])
  //   }

  console.log("Position data imported.");

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

  // HTML overlay for showing feature name on mouseover
  var nameOverlay = document.createElement("div");
  viewer.container.appendChild(nameOverlay);
  nameOverlay.className = "backdrop";
  nameOverlay.style.display = "none";
  nameOverlay.style.position = "absolute";
  nameOverlay.style.bottom = "0";
  nameOverlay.style.left = "0";
  nameOverlay.style["pointer-events"] = "none";
  nameOverlay.style.padding = "4px";
  nameOverlay.style.backgroundColor = "green";

  var scene = viewer.scene;
  var longitude;
  var latitude;
  var fid;
  var featuretype;
  var gmlid;
  var selID = new Array();
  var cnt = 0;
  var lastPickedObject;

  var viewModel = {
    rightClickAction: "properties",
    middleClickAction: "hide",
  };

  Cesium.knockout.track(viewModel);

  var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);

  handler.setInputAction(function (movement) {
    // makes camera go to a certain position given by the coordinates below

    var feature = viewer.scene.pick(movement.position);
    if (!Cesium.defined(feature)) {
      console.log("no feature defined");
      return;
    }
    var propertyNames = feature.getPropertyNames();
    var lat = feature.getProperty("Latitude");
    var lon = feature.getProperty("Longitude");
    var tmp = feature.getProperty("YearOfConstruction");

    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(lon, lat, 900),
      maximumHeight: 1500.0,
      orientation: {
        heading: Cesium.Math.toRadians(0.0),
        pitch: Cesium.Math.toRadians(-90.0),
        roll: Cesium.Math.toRadians(45.0),
      },
      duration: 2,
    });
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

  handler.setInputAction(function (movement) {
    var feature = viewer.scene.pick(movement.position);
    if (!Cesium.defined(feature)) {
      return;
    }
    var action = viewModel.rightClickAction;
    action === "properties";
    printProperties(movement, feature);
  }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

  function printProperties(movement, feature) {
    console.log("Properties:");
    var propertyNames = feature.getPropertyNames();
    var length = propertyNames.length;
    for (var i = 0; i < length; ++i) {
      var propertyName = propertyNames[i];
      if (
        propertyName == "gmlIdALKISLageBezeichnung_1" ||
        propertyName == "gmlIdALKISLageBezeichnung_2" ||
        propertyName == "gmlIdALKISLageBezeichnung_3" ||
        propertyName == "gmlIdALKISLageBezeichnung_4" ||
        propertyName == "gmlIdALKISLageBezeichnung_5" ||
        propertyName == "gmlIdALKISLageBezeichnung_6"
      )
        console.log("  " + propertyName + ": " + "zensiert");
      else
        console.log(
          "  " + propertyName + ": " + feature.getProperty(propertyName)
        );
    }

    // Evaluate feature description
    //console.log('Description : ' + tileset.style.meta.description.evaluate(scene.frameState, feature));
  }

  handler.setInputAction(function (movement) {
    var feature = viewer.scene.pick(movement.position);
    if (!Cesium.defined(feature)) {
      return;
    }

    var action = viewModel.middleClickAction;
    if (action === "hide") {
      feature.show = false;
    } else {
      feature.show = true;
    }
  }, Cesium.ScreenSpaceEventType.MIDDLE_CLICK);

  function showLegend() {
    $("#legend").css("display", "block");
  }
  function hideLegend() {
    $("#legend").css("display", "none");
  }

  // Legend - Colour Table
  function emptyColourTable() {
    $(".inner").empty();
  }

  function setHeightTable() {
    $(".inner").append(
      "<table>" +
        "<tr><td class='outlined' bgcolor='red'>&nbsp;&nbsp;&nbsp;&nbsp;</td><td> > 3.5 </td></tr>" +
        "<tr><td class='outlined' bgcolor='#ff6b21'></td><td> 3 </td></tr>" +
        "<tr><td class='outlined' bgcolor='#ffb400'></td><td> 2.5 </td></tr>" +
        "<tr><td class='outlined' bgcolor='yellow'></td><td> 2</td></tr>" +
        "<tr><td class='outlined' bgcolor='#89FF8F'></td><td> 1.5 </td></tr>" +
        "<tr><td class='outlined' bgcolor='cyan'></td><td> 1 </td></tr>" +
        "<tr><td class='outlined' bgcolor='blue'></td><td> 0.5 </td></tr>" +
        "</table>"
    );
  }

  return Cesium.when(tileset.readyPromise).then(function (tileset) {
    tileset.style = new Cesium.Cesium3DTileStyle({
      color: "color('white',1)",
    });
    showLegend();
    setHeightTable();
  });
});