appCesium.js 16.6 KB
Newer Older
Pithon Kabiro's avatar
Pithon Kabiro committed
1
2
"use strict";

3

4
5
6
// Functions
import {
    aggregateResponse,
7
8
    switchDayMonth_inDate,
    whereIsDateInArray,
9
10
11
} from "./aggregation.js";


12
13
// Functions
import {
14
15
16
17
18
19
20
21
    getDatastreamIdFromBuildingNumber,
    getObservationsUrl,
    createTemporalFilterString,
    formatSTAResponseForHeatMap,
    drawHeatMapHC,
    formatSTAResponseForLineChart,
    drawLineChartHC,
    followNextLink,
22
23
24
25
} from "./appChart.js";

// Constants
import {
26
27
28
29
    BASE_URL,
    PARAM_RESULT_FORMAT,
    PARAM_ORDER_BY,
    PARAM_SELECT,
30
31
} from "./appChart.js";

32
var ALLDATA = [];
33
var bld = 0;
34

Pithon Kabiro's avatar
Pithon Kabiro committed
35
Cesium.Ion.defaultAccessToken =
36
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIyODgxYzJlNi1kNDZiLTQ3ZmQtYmUxYy0yMWI0OGM3NDA5MzAiLCJpZCI6NDczOSwic2NvcGVzIjpbImFzciIsImdjIl0sImlhdCI6MTU0MTUyMzU0MX0.shj2hM3pvsvcmE_wMb2aBDuk_cKWmFmbolltInGImwU";
Pithon Kabiro's avatar
Pithon Kabiro committed
37
38
39
40
41
42

// Flag to determine models that will be loaded
// Set to `true` or `false`
const LOAD_DETAILED_BLDG225 = false;

// Global variable
43
const viewer = new Cesium.Viewer("cesiumGlobeContainer", {
44
45
46
47
    scene3DOnly: true,
    imageryProvider: Cesium.createOpenStreetMapImageryProvider({
        url: "https://a.tile.openstreetmap.org/",
    }),
Pithon Kabiro's avatar
Pithon Kabiro committed
48
49
});

50
51
52
53
54
/**
 * Load and zoom to the extents of 3DTiles
 * @param {String} urlTiles URL to the 3DTiles to be loaded
 * @returns {undefined} undefined
 */
55
const loadTiles = function(urlTiles) {
56
57
58
59
60
    const tileset = new Cesium.Cesium3DTileset({
        url: urlTiles,
    });
    viewer.scene.primitives.add(tileset);

61
    tileset.readyPromise.then(function() {
62
63
64
65
66
67
68
69
        viewer
            .zoomTo(
                tileset,
                new Cesium.HeadingPitchRange(
                    0.0, -0.5,
                    tileset.boundingSphere.radius / 0.5
                )
            )
70
            .otherwise(function(err) {
71
72
73
                throw err;
            });
    });
Pithon Kabiro's avatar
Pithon Kabiro committed
74
75
};

76
77
78
79
80
/**
 * Load 3DTiles for all the buildings; ignore any glTF models
 * @param{*}
 * @returns {undefined} undefined
 */
81
const loadNonDetailed = function() {
82
83
    // Paths to data sources
    const URL_3DTILES = "data_3d/3dtiles/1_full/tileset.json";
Pithon Kabiro's avatar
Pithon Kabiro committed
84

85
86
    // Tileset with all buildings
    loadTiles(URL_3DTILES);
Pithon Kabiro's avatar
Pithon Kabiro committed
87
88
};

89
90
91
92
93
94
/**
 * Load glTF models
 * @param {String} gltfUrl Path to the folder containing the glTF models
 * @param {String} gltfId Name of the glTF model file without the extension i.e. exclude the `.gltf` suffix
 * @returns {undefined} undefined
 */
95
const gltfLoad = function(gltfUrl, gltfId) {
96
97
98
99
100
101
102
103
104
105
106
107
    const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
        Cesium.Cartesian3.fromDegrees(9.083385, 48.881342, 0)
    );

    viewer.scene.primitives.add(
        Cesium.Model.fromGltf({
            url: `${gltfUrl}/${gltfId}.gltf`,
            modelMatrix: modelMatrix,
            scale: 0.0254,
            allowPicking: true,
        })
    );
108
109
};

110
111
112
113
114
/**
 * Load detailed glTF models for Building 225 and 3DTiles for the rest of the buildings
 * @param{*}
 * @returns {undefined} undefined
 */
115
const loadDetailed = function() {
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
    // Paths to data sources
    const URL_3DTILES = "data_3d/3dtiles/2_partial/tileset.json";
    const URL_GLTF = "data_3d/gltf";

    // Tileset without building 225
    loadTiles(URL_3DTILES);

    // Load Building 225
    gltfLoad(URL_GLTF, "bosch_si225_3");

    // Load sensors in Building 225
    const gltfArray = [
        "sensor_013",
        "sensor_023",
        "sensor_033",
        "sensor_053",
        "sensor_063",
        "sensor_073",
        "sensor_083",
        "sensor_093",
        "sensor_103",
        "sensor_113",
        "sensor_123",
        "sensor_133",
        "sensor_143",
        "sensor_153",
        "sensor_163",
        "sensor_173",
        "sensor_183",
        "sensor_213",
        "sensor_223",
        "sensor_233",
        "sensor_253",
        "sensor_263",
        "sensor_273",
        "sensor_283",
        "sensor_293",
        "sensor_303",
        "sensor_313",
        "sensor_323",
        "sensor_333",
        "sensor_343",
        "sensor_353",
        "sensor_363",
        "sensor_373",
        "sensor_383_v2",
    ];

    gltfArray.forEach((sensor) => gltfLoad(URL_GLTF, sensor));
Pithon Kabiro's avatar
Pithon Kabiro committed
165
166
167
};

if (!LOAD_DETAILED_BLDG225) {
168
169
    // Default case: load only 3dTiles
    loadNonDetailed();
Pithon Kabiro's avatar
Pithon Kabiro committed
170
} else {
171
172
    // Alternative case: load 3dTiles + glTF
    loadDetailed();
Pithon Kabiro's avatar
Pithon Kabiro committed
173
}
174
175
176
177

/**
 * Activate feature picking for the displayed 3DTiles
 * @param {*}
178
 * @returns {undefined}
179
 */
180
const activate3DTileFeaturePicking = function() {
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
    // HTML overlay for showing feature name on mouseover
    const 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 = "black";
    nameOverlay.style.color = "white";
    nameOverlay.style.fontFamily = "Fira Sans, sans-serif";
    nameOverlay.style.fontSize = "0.75em";

    // Information about the currently selected feature
    const selected = {
        feature: undefined,
        originalColor: new Cesium.Color(),
    };

    // An entity object which will hold info about the currently selected feature for infobox display
    const selectedEntity = new Cesium.Entity();

    // Get default left click handler for when a feature is not picked on left click
    const clickHandler = viewer.screenSpaceEventHandler.getInputAction(
        Cesium.ScreenSpaceEventType.LEFT_CLICK
    );

    // Change the feature color on mouse over

    // Information about the currently highlighted feature
    const highlighted = {
        feature: undefined,
        originalColor: new Cesium.Color(),
    };

    // Color a feature on hover.
    viewer.screenSpaceEventHandler.setInputAction(function onMouseMove(movement) {
        // If a feature was previously highlighted, undo the highlight
        if (Cesium.defined(highlighted.feature)) {
            highlighted.feature.color = highlighted.originalColor;
            highlighted.feature = undefined;
        }
        // Pick a new feature
        const pickedFeature = viewer.scene.pick(movement.endPosition);
        if (!Cesium.defined(pickedFeature)) {
            nameOverlay.style.display = "none";
            return;
        }
        // A feature was picked, so show it's overlay content
        nameOverlay.style.display = "block";
        nameOverlay.style.bottom =
            viewer.canvas.clientHeight - movement.endPosition.y + "px";
        nameOverlay.style.left = movement.endPosition.x + "px";
        let name = pickedFeature.getProperty("_gebaeude");
        if (!Cesium.defined(name)) {
            name = pickedFeature.getProperty("id");
        }
        nameOverlay.textContent = name;
        // Highlight the feature if it's not already selected.
        if (pickedFeature !== selected.feature) {
            highlighted.feature = pickedFeature;
            Cesium.Color.clone(pickedFeature.color, highlighted.originalColor);
            pickedFeature.color = Cesium.Color.GREY;
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    // Color a feature on selection and show metadata in the InfoBox.
    viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(movement) {
        // If a feature was previously selected, undo the highlight
        if (Cesium.defined(selected.feature)) {
            selected.feature.color = selected.originalColor;
            selected.feature = undefined;
        }
256
257
        ALLDATA = [];
        cnt = 0;
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
        // Pick a new feature
        const pickedFeature = viewer.scene.pick(movement.position);
        if (!Cesium.defined(pickedFeature)) {
            clickHandler(movement);
            return;
        }
        // Select the feature if it's not already selected
        if (selected.feature === pickedFeature) {
            return;
        }
        selected.feature = pickedFeature;
        // Save the selected feature's original color
        if (pickedFeature === highlighted.feature) {
            Cesium.Color.clone(highlighted.originalColor, selected.originalColor);
            highlighted.feature = undefined;
        } else {
            Cesium.Color.clone(pickedFeature.color, selected.originalColor);
        }
        // Highlight newly selected feature
        pickedFeature.color = Cesium.Color.LIME;
        // Set feature infobox description
        const featureName = pickedFeature.getProperty("name");
        selectedEntity.name = featureName;
        selectedEntity.description =
            'Loading <div class="cesium-infoBox-loading"></div>';
        viewer.selectedEntity = selectedEntity;
        selectedEntity.description = `
285
286
287
    <table class="cesium-infoBox-defaultTable">
      <tbody> 
        <tr><th>Bau</th><td>
288
        ${pickedFeature.getProperty("_gebaeude")} 
289
290
        </td></tr> 
        <tr><th>Nutzung</th><td>
291
        ${pickedFeature.getProperty("_nutzung")}
292
293
        </td></tr>
        <tr><th>Baujahr</th><td>
294
        ${pickedFeature.getProperty("_baujahr")}
295
296
        </td></tr>
        <tr><th>Geschosse</th><td>
297
        ${pickedFeature.getProperty("_geschosse")} 
298
        </td></tr>
299
300
        <tr><th>Gebäudefläche (m<sup>2</sup>)</th><td>
        ${pickedFeature.getProperty("_gebaeudeflaeche")} 
301
302
303
304
        </td></tr>
      </tbody>
    </table>
    `;
305

306
307
308
309
310
311
312
313
314
315
316
317
318
        const clickedBuilding = pickedFeature.getProperty("_gebaeude");
        const clickedBuildingDatastreamId = getDatastreamIdFromBuildingNumber(
            clickedBuilding,
            "vl",
            "60min"
        );

        const BASE_URL_OBSERVATIONS = getObservationsUrl(
            BASE_URL,
            clickedBuildingDatastreamId
        );
        const PARAM_FILTER = createTemporalFilterString("2020-01-01", "2021-01-01");

319
320
321
322
323
324
325
326
327
        // const axiosGetRequest = axios.get(BASE_URL_OBSERVATIONS, {
        //     params: {
        //         "$resultFormat": PARAM_RESULT_FORMAT,
        //         "$orderBy": PARAM_ORDER_BY,
        //         "$filter": PARAM_FILTER,
        //         "$select": PARAM_SELECT,
        //     },
        // });

328
329
330
        const BUILDING_STREAM_ID = [75, 76, 77, 78, 79, 80];
        const BUILDING_ID = ["101", "102", "107", "112, 118", "125", "225"];
        // ALLDATA = [];
331
332
        var cnt = 0;

333

334
        for (bld = 0; bld < BUILDING_STREAM_ID.length; bld++) {
335

336
            var baseUrlBld = getObservationsUrl(BASE_URL, BUILDING_STREAM_ID[bld]);
337
338
339
340
341
342
343
344
            const axiosGetRequest = axios.get(baseUrlBld, {
                params: {
                    "$resultFormat": PARAM_RESULT_FORMAT,
                    "$orderBy": PARAM_ORDER_BY,
                    "$filter": PARAM_FILTER,
                    "$select": PARAM_SELECT,
                },
            });
345

346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
            // Get "ALL" the Observations that satisfy our query
            followNextLink(axiosGetRequest)
                .then((success) => {
                    const successValue = success.data.value;

                    // Array that will hold the combined observations
                    const combinedObservations = [];

                    successValue.forEach((dataObj) => {
                        // Each page of results will have a dataArray that holds the observations
                        const dataArrays = dataObj.dataArray;

                        combinedObservations.push(...dataArrays);
                    });
                    // DEBUG: Check total number of observations
361
                    // console.log(combinedObservations.length);
362
                    // DEBUG: Print the array of observations
363
                    // console.log(combinedObservations);
364
365
366
367
368
369
370
371
372

                    return combinedObservations;
                })
                .catch((err) => {
                    console.log("ERROR: ")
                    console.log(err);
                })
                .then((observationArr) => {
                    var agg = aggregateResponse(observationArr, 0, 'mean');
373
                    var tmpObj = {
374
375
                        BldID: BUILDING_ID[cnt],
                        streamID: BUILDING_STREAM_ID[cnt],
376
377
378
379
                        timestamp: agg.aggDates,
                        data: agg.aggVals,
                    };
                    ALLDATA.push(tmpObj);
380
                    // console.log(agg);
381

382
383
                    drawHeatMapHC(formatSTAResponseForHeatMap(agg.originalFormat));
                    drawLineChartHC(formatSTAResponseForLineChart(agg.originalFormat));
384

385
386
                    if (ALLDATA.length == 6) {
                        var selectedDate = document.getElementById("DateSelected").innerHTML;
387

388
389
390
391
392
                        var date = new Date(
                            Date.parse(
                                switchDayMonth_inDate(selectedDate)
                            )
                        );
393

394
395
396
397
398
399
400
401
                        var p = whereIsDateInArray(ALLDATA[0].timestamp, date);
                        const DATA = getDataForAllBuildingsPerDate(p);
                        colorBlds(DATA);
                        console.log(date);
                    }

                    console.log(ALLDATA.length);
                    cnt++
402

403
404
                    // alert('waiting...');
                });
405
406


407

408
        }
409

410

411
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
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
activate3DTileFeaturePicking();

function goon(ALLDATA) {

    if (ALLDATA.length > 0) {
        var selectedDate = document.getElementById("DateSelected").innerHTML;

        var date = new Date(
            Date.parse(
                switchDayMonth_inDate(selectedDate)
            )
        );

        var p = whereIsDateInArray(ALLDATA[0].timestamp, date);
        const DATA = getDataForAllBuildingsPerDate(p);
        colorBlds(DATA);
        console.log(date);
    }
}



// /**
//  * 
//  * @param {Number} datePos 
//  */

export const getDataForAllBuildingsPerDate = function(datePos) {

    var dataObjPerBld = [];
    var dataArray = [];
    for (var i = 0; i < ALLDATA.length; i++) {

        var tmp = {
            BldId: ALLDATA[i].BldID,
            dateVal: ALLDATA[i].timestamp[datePos],
            dataVal: ALLDATA[i].data[datePos]
        };
        dataArray.push(tmp.dataVal);
        dataObjPerBld.push(tmp);
    }


    return {
        dataPerBld: dataObjPerBld,
        dataArray: dataArray
    };
}

export const colorBlds = function(bldInfo) {


    // see: https://github.com/PimpTrizkit/PJs/wiki/12.-Shade,-Blend-and-Convert-a-Web-Color-(pSBC.js)
    const RGB_Linear_Blend = (p, c0, c1) => {
        var i = parseInt,
            r = Math.round,
            P = 1 - p,
            [a, b, c, d] = c0.split(","),
            [e, f, g, h] = c1.split(","),
            x = d || h,
            j = x ? "," + (!d ? h : !h ? d : r((parseFloat(d) * P + parseFloat(h) * p) * 1000) / 1000 + ")") : ")";
        return "rgb" + (x ? "a(" : "(") + r(i(a[3] == "a" ? a.slice(5) : a.slice(4)) * P + i(e[3] == "a" ? e.slice(5) : e.slice(4)) * p) + "," + r(i(b) * P + i(f) * p) + "," + r(i(c) * P + i(g) * p) + d;
    }

    // get the gradient colors between the two defined colors;
    const c1 = "rgb(255,64,0)";
    const c2 = "rgb(63,131,163)";
    var L = bldInfo.dataArray.length;
    var offset = 1 / (L - 1);
    var colorsForBld = [];
    var p = 0;
    for (var i = 0; i < L; i++) {
        var cnew = RGB_Linear_Blend(p, c1, c2);
        cnew = cnew.replace('undefined', ')');
        colorsForBld.push(cnew);
        p += offset;
        console.log(p);
    }

    var numbers = bldInfo.dataArray,
        ma = numbers.reduce(function(a, b) { return Math.max(a, b); }),
        mi = numbers.reduce(function(a, b) { return Math.min(a, b); }),
        dif = ma - mi,
        l = numbers.length,
        i;

    for (i = 0; i < l; i++) {
        numbers[i] = (numbers[i] - mi) / dif;
    }

    function sortWithIndeces(toSort) {
        for (var i = 0; i < toSort.length; i++) {
            toSort[i] = [toSort[i], i];
        }
        toSort.sort(function(left, right) {
            return left[0] < right[0] ? -1 : 1;
        });
        toSort.sortIndices = [];
        for (var j = 0; j < toSort.length; j++) {
            toSort.sortIndices.push(toSort[j][1]);
            toSort[j] = toSort[j][0];
        }
        return toSort;
    }


    sortWithIndeces(numbers);
    // alert(numbers.sortIndices.join(","));
    var sortedIndices = numbers.sortIndices;
    // convert object to array
    var i = 0,
        arr = [];
    for (var ob in inputObj)
        arr[i++] = ob;


    // numbers = (6)[0.37684400819550146, 0, 0.5862015830883935, 1, 0.444816858861194, 0.9179110359561272],

    console.log(numbers);
    // assign the color to the buildings based on their id
    // var sortedValues = bldInfo.dataArray.sort

    // if (!Cesium.defined(name)) {
    //     name = pickedFeature.getProperty("id");
    // }

}