UNPKG

@geogirafe/lib-geoportal

Version:

GeoGirafe is a flexible application to build online geoportals.

419 lines (418 loc) 26 kB
import { html as uHtml } from 'uhtml'; import GirafeResizableElement from '../../../base/GirafeResizableElement'; import ConfigManager from '../../../tools/configuration/configmanager'; import { Scatterplot } from '../scatterplot'; import { PytreeManager } from '../pytreemanager'; import { computeColors } from '../utils'; import { download } from '../../../tools/export/download'; class CrossSectionViewComponent extends GirafeResizableElement { constructor() { super('cross-section-view'); Object.defineProperty(this, "template", { enumerable: true, configurable: true, writable: true, value: () => { return uHtml `<style> #panel,:host{position:absolute;top:0;left:0;right:0;bottom:0;overflow:hidden;height:100%;width:100%;min-height:10rem;background:var(--bkg-color)}#profile-panel{position:relative;width:100%;height:100%;margin:auto;background-color:none;overflow:hidden}#gutter{border:none;height:6px;width:100%;background:var(--bkg-color);position:absolute;top:0;left:0;cursor:row-resize}#glcanvas{position:absolute}#svg-outer{position:absolute;z-index:1}.svg-axis{font-size:12;font-family:inherit,sans-serif;user-select:none}.ruler-text{text-anchor:middle}.point:hover{stroke:blue;fill:chartreuse}#spinner{visibility:hidden;background-color:#f7f7f7;border-radius:50%}.spinner{z-index:99;position:absolute;top:15px;right:10px;width:30px;height:30px;-webkit-animation:spin 2s linear infinite;-moz-animation:spin 2s linear infinite;animation:spin 2s linear infinite}@-moz-keyframes spin{100%{-moz-transform:rotate(360deg)}}@-webkit-keyframes spin{100%{-webkit-transform:rotate(360deg)}}@keyframes spin{100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}} </style><style> *{font-family:Arial,sans-serif}.hidden{display:none!important}.gg-rotate90{transform:rotate(90deg)}.gg-rotate180{transform:rotate(180deg)}.gg-rotate270{transform:rotate(270deg)}img{filter:var(--svg-filter)}img.legend-image{filter:var(--svg-map-filter);background:var(--svg-legend-bkg)}div{scrollbar-width:thin}a{color:var(--link-color)}a:visited{color:var(--link-color)}@keyframes spin{from{transform:rotate(0)}to{transform:rotate(360deg)}}@keyframes spin-wait{0%{transform:rotate(0)}7%{transform:rotate(360deg)}100%{transform:rotate(360deg)}}.gg-spin{animation-name:spin;animation-duration:2s;animation-iteration-count:infinite;animation-timing-function:linear}.gg-spin-wait{animation-name:spin-wait;animation-duration:10s;animation-iteration-count:infinite;animation-timing-function:linear}::-webkit-scrollbar{width:5px}::-webkit-scrollbar-thumb{background:#999}.gg-button,.gg-input,.gg-select,.gg-textarea{background-color:var(--bkg-color);color:var(--text-color);outline:0;border-radius:3px;border:var(--app-standard-border);display:inline-block;box-sizing:border-box;padding:0 0 0 .5rem;margin:0;cursor:pointer}.gg-label{background-color:var(--bkg-color);color:var(--text-color);border:none;display:flex;align-items:center;padding:0;margin:0}.gg-button,.gg-input,.gg-label,.gg-select{min-height:calc(var(--app-standard-height)/ 1.5)}.gg-textarea{max-height:initial;padding:.5rem;height:6rem;resize:vertical;line-height:1.3rem}.gg-input{cursor:text}.gg-checkbox{accent-color:var(--text-color);width:1.2rem}.gg-range{accent-color:var(--text-color)}.gg-button{padding:0 .5rem}.gg-button.active{border:solid 1px var(--text-color-grad2);background-color:var(--text-color-grad2);color:var(--bkg-color)}.gg-button:disabled{background-color:#d3d3d3;color:grey;border:none;cursor:not-allowed}.gg-input:disabled,.gg-select:disabled,.gg-textarea:disabled{background-color:#d3d3d3;color:grey;cursor:not-allowed}.gg-button>img{vertical-align:middle}.gg-icon-button{border:none;background-color:transparent;display:flex;flex-direction:column;color:var(--text-color);padding:0;align-items:center;justify-content:center;cursor:pointer}.gg-big,.gg-big-withtext{min-width:var(--app-standard-height);min-height:var(--app-standard-height);max-height:var(--app-standard-height)}.gg-big img,.gg-big-withtext img{margin:0;width:calc(var(--app-standard-height) - 1.5rem)}.gg-big-withtext span{font-size:.9rem;font-variant:small-caps;padding:0 1rem}.gg-medium,.gg-medium-withtext{flex-direction:row;min-width:calc(var(--app-standard-height)/ 1.2);min-height:calc(var(--app-standard-height)/ 1.2);max-height:calc(var(--app-standard-height)/ 1.2)}.gg-medium img{margin:0;width:calc(var(--app-standard-height)/ 2.4)}.gg-medium-withtext img{margin-left:.5rem;width:calc(var(--app-standard-height)/ 2.4)}.gg-medium-withtext span{font-size:.9rem;padding:0 1rem;padding-left:.5rem}.gg-small,.gg-small-withtext{flex-direction:row;min-width:calc(var(--app-standard-height)/ 2);min-height:calc(var(--app-standard-height)/ 2);max-height:calc(var(--app-standard-height)/ 2)}.gg-small img{margin:0;width:calc(var(--app-standard-height)/ 3)}.gg-small-withtext img{margin-left:.5rem;width:calc(var(--app-standard-height)/ 3)}.gg-small-withtext span{font-size:.9rem;padding:0 .5rem;padding-left:.3rem}.gg-button:hover,.gg-icon-button:hover,.gg-input:hover,.gg-select:hover,.gg-textarea:hover{background-color:var(--bkg-color-grad1)}.gg-opacity{opacity:.5}.gg-opacity:hover{background-color:transparent;opacity:1}.gg-tabs{display:flex;justify-content:left;margin:.5rem auto 0;border-bottom:1px solid grey;cursor:pointer;height:2rem;align-items:end;gap:1rem;margin-bottom:1rem}.gg-tab{border:none;background:0 0;cursor:pointer;padding:.5rem;color:var(--text-color)}.gg-tab.active{border-bottom:solid 2px var(--text-color-grad2);font-weight:600}.girafe-button-big,.girafe-button-large,.girafe-button-small,.girafe-button-tiny{border:none;background-color:transparent;display:flex;flex-direction:column;color:var(--text-color)}.girafe-button-big:hover,.girafe-button-large:hover,.girafe-button-small:hover,.girafe-button-tiny:hover{background-color:var(--bkg-color-grad1);cursor:pointer}.girafe-button-big.dark,.girafe-button-large.dark,.girafe-button-small.dark,.girafe-button-tiny.dark{background-color:var(--bkg-color);filter:invert(1)}.girafe-button-big{width:var(--app-standard-height);height:var(--app-standard-height);align-items:center;padding:1rem}.girafe-button-big img{overflow:hidden}.girafe-button-large{flex-direction:row}.girafe-button-large img{margin:.3rem;height:2rem}.girafe-button-large span{line-height:2rem;height:2rem;margin:.3rem}.girafe-button-small{min-width:calc(var(--app-standard-height)/ 2);height:calc(var(--app-standard-height)/ 2);align-items:center;padding:.5rem}.girafe-button-small img{overflow:hidden}.girafe-button-small span{width:100%;text-align:left;overflow:hidden;text-overflow:ellipsis}.girafe-button-tiny{width:1rem;height:1rem;align-items:center;padding:0}.girafe-button-tiny img{overflow:hidden} </style> <div id="panel"> <div id="profile-panel"></div> <div id="gutter"></div> </div> `; } }); Object.defineProperty(this, "crossSectionState", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "eventsCallbacks", { enumerable: true, configurable: true, writable: true, value: [] }); Object.defineProperty(this, "darkFrontendMode", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "visible", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "scatterplot", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "abortController", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "uv", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "rgb", { enumerable: true, configurable: true, writable: true, value: void 0 }); // 1 byte * 3 values Object.defineProperty(this, "intensity", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "classification", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "currentRefreshId", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "panel", { enumerable: true, configurable: true, writable: true, value: null }); Object.defineProperty(this, "pytreeManager", { enumerable: true, configurable: true, writable: true, value: null }); this.crossSectionState = this.state.extendedState.crossSection; this.abortController = new AbortController(); // Initialize point data attributes this.uv = new Float32Array(this.crossSectionState.maxNumberOfPoints * 2); // 4 bytes * 2 values this.rgb = new Uint8Array(this.crossSectionState.maxNumberOfPoints * 3); // 1 byte * 3 values this.intensity = new Uint16Array(this.crossSectionState.maxNumberOfPoints); // 2 bytes * 1 value this.classification = new Uint8Array(this.crossSectionState.maxNumberOfPoints); // 1 bytes * 1 value } async initPytreeManager() { const baseURL = ConfigManager.getInstance().Config.lidar?.url.replace(/\/?$/, '/') ?? ''; this.pytreeManager = new PytreeManager(baseURL); await this.pytreeManager.getConfig(); } async refreshData(lineWidth, lineCoordinates) { if (!this.pytreeManager) { try { await this.initPytreeManager(); } catch (error) { console.error('Cross-section-viewer: Unavble to initialize Pytree manager', error); throw error; } } this.scatterplot.clearGLPoints(); this.validateRequestArgs(lineWidth, lineCoordinates); this.abortOngoingRequest(); this.abortController = new AbortController(); const signal = this.abortController.signal; // Activate loading status this.crossSectionState.loading = true; this.state.loading = true; // document.getElementById('spinner').style.visibility = 'visible'; // Uncomment to enable spinner const coordinateString = lineCoordinates.map((x) => `{${x}}`).join(); this.crossSectionState.numberOfPoints = 0; // Initialize point data arrays this.uv = new Float32Array(this.crossSectionState.maxNumberOfPoints * 2); // 4 bytes * 2 values this.rgb = new Uint8Array(this.crossSectionState.maxNumberOfPoints * 3); // 1 byte * 3 values this.intensity = new Uint16Array(this.crossSectionState.maxNumberOfPoints); // 2 bytes * 1 value this.classification = new Uint8Array(this.crossSectionState.maxNumberOfPoints); // 1 bytes * 1 value // Create a unique identifier for this refresh operation const refreshId = Symbol('refreshId'); this.currentRefreshId = refreshId; let LOD = 1; while (this.crossSectionState.numberOfPoints < this.crossSectionState.maxNumberOfPoints && LOD <= 14) { try { this.crossSectionState.loading = true; this.state.loading = true; // Asynchronous request to retrieve cross-section data at given level of detail (LOD) const response = await this.pytreeManager.getData(this.pytreeManager.config.default_point_cloud, LOD, LOD, lineWidth, coordinateString, this.abortController.signal); if (!response || signal.aborted || this.currentRefreshId !== refreshId) { break; } const remainder = Math.max(0, this.crossSectionState.maxNumberOfPoints - this.crossSectionState.numberOfPoints); // Update data arrays if (response.metadata.points > 0 && remainder > 0 && !signal.aborted) { for (const key in response.data) { switch (key) { case 'POSITION_PROJECTED_PROFILE': this.uv.set( // @ts-expect-error: D3 typing issue response.data['POSITION_PROJECTED_PROFILE'].slice(0, remainder * 2), this.crossSectionState.numberOfPoints * 2); break; case 'RGB': // @ts-expect-error: D3 typing issue this.rgb.set(response.data['RGB'].slice(0, remainder * 3), this.crossSectionState.numberOfPoints * 3); break; case 'INTENSITY': this.intensity.set( // @ts-expect-error: D3 typing issue response.data['INTENSITY'].slice(0, remainder), this.crossSectionState.numberOfPoints); break; case 'CLASSIFICATION': this.classification.set( // @ts-expect-error: D3 typing issue response.data['CLASSIFICATION'].slice(0, remainder), this.crossSectionState.numberOfPoints); break; } } this.crossSectionState.numberOfPoints = Math.min(this.crossSectionState.maxNumberOfPoints, this.crossSectionState.numberOfPoints + response.metadata.points); this.updateScatterplot(refreshId); } if (remainder === 0) { return; } LOD++; } catch (error) { console.error('Cross-section-viewer: Fetch failed due to unexpected error:', error); throw error; } } // document.getElementById('spinner').style.visibility = 'hidden'; Uncomment to enable spinner // Deactivate loading state when data fetch is complete this.crossSectionState.loading = false; this.state.loading = false; } validateRequestArgs(lineWidth, lineCoordinates) { if (lineWidth <= 0.0) { throw new Error('lineWidth must be larger than 0'); } if (lineCoordinates.length < 2) { throw new Error('At least two line coordinates are required'); } } abortOngoingRequest() { if (this.crossSectionState.loading) { this.abortController.abort('New linestring requested before previous data finished loading'); this.scatterplot.clearGLPoints(); this.crossSectionState.loading = false; this.state.loading = false; } this.abortController = new AbortController(); } updateScatterplot(refreshId) { if (this.scatterplot && this.currentRefreshId === refreshId) { this.scatterplot.updatePoints(this.uv.slice(0, this.crossSectionState.numberOfPoints * 2)); this.changeColormap(this.crossSectionState.colorVariable, this.crossSectionState.colorPalette); this.scatterplot.updatePlot(); } } changeColormap(variable, colormap = 'spectral') { let colors; switch (variable) { case 'intensity': colors = computeColors(this.intensity.slice(0, this.crossSectionState.numberOfPoints), colormap, [15000, 65000]); break; case 'natural': colors = this.rgb.slice(0, this.crossSectionState.numberOfPoints * 3); break; case 'classification': // colors = computeColors(this.classification.slice(0, this.crossSectionState.numberOfPoints), 'custom', [1, 41]); colors = this.pytreeManager.getClassificationColor(this.classification.slice(0, this.crossSectionState.numberOfPoints), this.pytreeManager.config.classification_colors); break; case 'uniform': colors = computeColors(this.classification.slice(0, this.crossSectionState.numberOfPoints), this.crossSectionState.colorUniform, []); break; } // Update scatterplot if (this.scatterplot) { this.scatterplot.updateColors(colors); this.scatterplot.initializeGL(); this.scatterplot.updateTransform(); } } printCanvas() { this.scatterplot?.updateTransform(); const canvas = this.scatterplot?.canvas.node(); if (canvas) { const scaleFactor = 1.0; const printWidth = scaleFactor * canvas.width; const printHeight = scaleFactor * canvas.height; // Get SVG elements const svg = this.scatterplot?.containerSVG.node().cloneNode(true); // Adjust SVG dimensions for print svg.setAttribute('width', printWidth.toString()); svg.setAttribute('height', printHeight.toString()); // Serialise SVG const svgString = new XMLSerializer().serializeToString(svg); const printString = `<svg width="${printWidth}" height="${printHeight}" xmlns="http://www.w3.org/2000/svg"><image href="${canvas.toDataURL('image/png')}" x="0" y="0" width="${printWidth}" height="${printHeight}" />${svgString}</svg>`; download(printString, 'profile.svg', 'image/svg+xml;charset=utf-8'); } } render() { this.visible ? this.renderComponent() : this.renderEmpty(); } renderComponent() { super.render(); super.girafeTranslate(); this.panel = this.shadowRoot.getElementById('profile-panel'); this.scatterplot = new Scatterplot(this.panel, this.crossSectionState.margins, new Float32Array(0), new Uint8Array(0)); this.scatterplot.setZoom(this.crossSectionState.zoom); this.registerEvents(); } registerEvents() { this.eventsCallbacks.push(this.subscribe('interface.darkFrontendMode', (_oldValue, _newValue) => { this.darkFrontendMode = _newValue; }), this.subscribe('extendedState.crossSection.verticalExaggerationSettings.value', (_oldVal, _newVal) => { this.scatterplot?.updateVerticalExaggeration(_newVal); }), this.subscribe('extendedState.crossSection.pointSizeSettings.value', (_oldVal, _newVal, _parent) => { this.scatterplot?.updatePointSize(_newVal); }), this.subscribe('extendedState.crossSection.backgroundColor', (_oldVal, _newVal, _parent) => { this.scatterplot?.setBackgroundColor(_newVal); }), this.subscribe('extendedState.crossSection.colorVariable', (_oldVal, _newVal, _parent) => { this.changeColormap(this.crossSectionState.colorVariable, this.crossSectionState.colorPalette); }), this.subscribe('extendedState.crossSection.colorUniform', (_oldVal, _newVal, _parent) => { if (this.crossSectionState.colorVariable === 'uniform') { this.changeColormap(this.crossSectionState.colorVariable, this.crossSectionState.colorPalette); } }), this.subscribe('extendedState.crossSection.colorPalette', (_oldVal, _newVal, _parent) => { this.changeColormap(this.crossSectionState.colorVariable, this.crossSectionState.colorPalette); }), this.subscribe('extendedState.crossSection.zoom', (_oldVal, _newVal, _parent) => { if (this.crossSectionState.zoomUpdate) { this.scatterplot?.setZoom(_newVal); } }), this.subscribe('extendedState.crossSection.sectionWidthSettings.value', (_oldVal, _newVal) => { if (_newVal > 0 && this.crossSectionState.linestringCoordinates.length >= 2) { this.refreshData(_newVal, this.crossSectionState.linestringCoordinates); } }), this.subscribe('extendedState.crossSection.linestringCoordinates', (_oldVal, _newVal, _parent) => { this.scatterplot?.deleteAllMeasurements(); if (_newVal.length === 0) { this.abortController.abort('Cross-section-viewer: current data fetch was aborted by new request'); this.scatterplot.resetPlot(); return; } if (this.crossSectionState.sectionWidthSettings.value > 0 && this.crossSectionState.linestringCoordinates.length >= 2) { this.refreshData(this.crossSectionState.sectionWidthSettings.value, this.crossSectionState.linestringCoordinates); } }), // Measurement mode this.subscribe('extendedState.crossSection.drawMeasurement', (_oldVal, _newVal, _parent) => { if (_newVal) { // Disable annotation mode to avoid conflict with measurement mode this.crossSectionState.drawMarker = false; } this.scatterplot?.toggleMeasurement(_newVal); }), // Annotation (marker drawing) mode this.subscribe('extendedState.crossSection.drawMarker', (_oldVal, _newVal, _parent) => { if (_newVal) { // Disable measurement mode to avoid conflict with annotation mode this.crossSectionState.drawMeasurement = false; } this.scatterplot?.toggleAnnotation(_newVal); }), // Markers array this.subscribe('extendedState.crossSection.markers', (_oldVal, _newVal, _parent) => { this.scatterplot.markers = _newVal; this.scatterplot?.updateMarkers(); this.scatterplot?.updateMeasurements(); this.scatterplot?.updateLabels(); })); // Delete all annotations (markers) document.addEventListener('delete-markers', () => { this.scatterplot?.deleteAllMarkers(); }); // Listen to 'delete-measurements' event emitted by the cross-section settings component (CrossSectionSettingsComponent). Delete all measurements when event fires. document.addEventListener('delete-measurements', () => { this.scatterplot?.deleteAllMeasurements(); }); // Listen to 'print-canvas' event emitted by the cross-section settings component (CrossSectionSettingsComponent). Print profile canvas when event fires. document.addEventListener('print-canvas', () => { this.printCanvas(); }); // Listen to 'cursormove' event emitted by the scatterplot. Update cursordomain coordinates in the state manager when event fires. this.panel?.addEventListener('cursormove', ((e) => { this.crossSectionState.cursorDomainCoordinates = e.detail.domainCoords; })); // Changed profile domain (X-Y extent) this.panel?.addEventListener('changedomain', ((e) => { console.debug('Cross-section viewer: changedomain event fired'); this.crossSectionState.domain = { xmin: e.detail.xDomain[0], xmax: e.detail.xDomain[1], ymin: e.detail.yDomain[0], ymax: e.detail.yDomain[1] }; this.crossSectionState.zoomUpdate = false; this.crossSectionState.zoom = { k: this.scatterplot.zoomTransform.k, tx: this.scatterplot.zoomTransform.x, ty: this.scatterplot.zoomTransform.y }; })); // Listen to changes in Markers array this.panel?.addEventListener('changemarkers', ((e) => { console.debug('Cross-section viewer: changemarkers event fired'); const newMarkers = e.detail.markers; const current = this.crossSectionState.markers; const newIdSet = new Set(newMarkers.map((m) => m.id)); // Update/add markers for (const nm of newMarkers) { const existing = current.find((cm) => cm.id === nm.id); if (existing) { Object.assign(existing, nm); } else { current.push(nm); } } // Remove deleted markers for (let i = current.length - 1; i >= 0; i--) { if (!newIdSet.has(current[i].id)) { current.splice(i, 1); } } })); // Listen to 'changemeasurements' event emitted by the scatterplot. Update measurements array in the state manager when event fires. this.panel?.addEventListener('changemeasurements', ((e) => { console.debug('Cross-section viewer: changemeasurements event fired'); this.crossSectionState.measurements = e.detail.measurements; })); } unregisterEvents() { this.unsubscribe(this.eventsCallbacks); this.eventsCallbacks.length = 0; } registerVisibilityEvents() { this.subscribe('interface.crossSectionPanelVisible', (_oldValue, _newValue) => { this.togglePanel(_newValue); }); } togglePanel(visible) { this.visible = visible; this.render(); } connectedCallback() { this.render(); this.registerVisibilityEvents(); } } export default CrossSectionViewComponent;