All files / app/codeCharta/ui/codeMap/threeViewer threeSceneService.ts

85.26% Statements 191/224
52.85% Branches 37/70
83.33% Functions 35/42
85.71% Lines 186/217

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 44349x     49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x               49x                 185x       185x 185x 185x   185x 185x     185x 185x 185x 185x 185x 185x 152x 152x       185x 185x 185x 185x   185x 185x 185x 185x 185x 185x   185x   185x 185x 185x 185x 185x       183x       5x   5x 5x 3x     2x 2x 1x   1x 1x 1x   1x             1x   1x             2x       72x       6x 6x 6x     6x                                     2x   2x 2x 2x 2x                                               1x 1x 1x       3x                 74x 2x 2x 2x 2x               3x 3x     3x 3x 3x   3x 3x           5x 5x   5x 2x     5x 5x   5x 5x   5x 5x   5x 5x   5x   5x   5x   5x         3x 3x       11x 3x 3x   3x 3x     3x         7x   6x 6x         9x   9x 9x   9x   9x   9x         3x 3x 1x     2x       42x       9x 21x 21x 21x   21x   21x 2x   19x         5x 5x 5x 5x 5x   5x     11x 6x 6x 6x   6x   6x         6x               5x       2x 2x 2x 3x 3x 3x           2x 2x 2x 3x 3x 3x           25x 1x         24x           24x     24x 24x           185x 185x 185x   185x 185x   185x 185x 185x       5x   5x     5x   5x 5x 5x   5x   5x       87x       101x               29x       114x 3x        
import { AmbientLight, Box3, BufferGeometry, DirectionalLight, Group, Line, Material, Object3D, Raycaster, Scene, Vector3 } from "three"
import { CodeMapMesh } from "../rendering/codeMapMesh"
import { CodeMapBuilding } from "../rendering/codeMapBuilding"
import { CcState, CodeMapNode, LayoutAlgorithm, Node } from "../../../codeCharta.model"
import { hierarchy } from "d3-hierarchy"
import { ColorConverter } from "../../../util/color/colorConverter"
import { FloorLabelDrawer } from "./floorLabels/floorLabelDrawer"
import { setSelectedBuildingId } from "../../../state/store/appStatus/selectedBuildingId/selectedBuildingId.actions"
import { idToNodeSelector } from "../../../state/selectors/accumulatedData/idToNode.selector"
import { IdToBuildingService } from "../../../services/idToBuilding/idToBuilding.service"
import { mapColorsSelector } from "../../../state/store/appSettings/mapColors/mapColors.selector"
import { ThreeRendererService } from "./threeRenderer.service"
import { Injectable, OnDestroy } from "@angular/core"
import { defaultMapColors } from "../../../state/store/appSettings/mapColors/mapColors.reducer"
import { treeMapSize } from "../../../util/algorithm/treeMapLayout/treeMapHelper"
import { EventEmitter } from "../../../util/EventEmitter"
import { State, Store } from "@ngrx/store"
 
type BuildingSelectedEvents = {
    onBuildingSelected: (data: { building: CodeMapBuilding }) => void
    onBuildingDeselected: () => void
}
 
@Injectable({ providedIn: "root" })
export class ThreeSceneService implements OnDestroy {
    scene: Scene
    labels: Group
    floorLabelPlanes: Group
    edgeArrows: Group
    mapGeometry: Group
 
    private readonly lights: Group
    private mapMesh: CodeMapMesh
    private eventEmitter = new EventEmitter<BuildingSelectedEvents>()
 
    private floorLabelDrawer
 
    private selected: CodeMapBuilding = null
    private highlighted: CodeMapBuilding[] = []
    private constantHighlight: Map<number, CodeMapBuilding> = new Map()
 
    private folderLabelColorHighlighted = ColorConverter.convertHexToNumber("#FFFFFF")
    private folderLabelColorNotHighlighted = ColorConverter.convertHexToNumber("#7A7777")
    private folderLabelColorSelected: string
    private numberSelectionColor: number
    private rayPoint = new Vector3(0, 0, 0)
    private normedTransformVector = new Vector3(0, 0, 0)
    private highlightedLabel = null
    private highlightedLineIndex = -1
    private highlightedLine = null
    private subscription = this.store.select(mapColorsSelector).subscribe(mapColors => {
        this.folderLabelColorSelected = mapColors.selected
        this.numberSelectionColor = ColorConverter.convertHexToNumber(this.folderLabelColorSelected)
    })
 
    constructor(
        private store: Store<CcState>,
        private state: State<CcState>,
        private idToBuilding: IdToBuildingService,
        private threeRendererService: ThreeRendererService
    ) {
        this.scene = new Scene()
        this.mapGeometry = new Group()
        this.lights = new Group()
        this.labels = new Group()
        this.floorLabelPlanes = new Group()
        this.edgeArrows = new Group()
 
        this.initLights()
 
        this.scene.add(this.mapGeometry)
        this.scene.add(this.edgeArrows)
        this.scene.add(this.labels)
        this.scene.add(this.lights)
        this.scene.add(this.floorLabelPlanes)
    }
 
    ngOnDestroy(): void {
        this.subscription.unsubscribe()
    }
 
    private initFloorLabels(nodes: Node[]) {
        this.floorLabelPlanes.clear()
 
        const { layoutAlgorithm, enableFloorLabels } = this.state.getValue().appSettings
        if (layoutAlgorithm !== LayoutAlgorithm.SquarifiedTreeMap || !enableFloorLabels) {
            return
        }
 
        const rootNode = this.getRootNode(nodes)
        if (!rootNode) {
            return
        }
        const scaling = this.state.getValue().appSettings.scaling
        const experimentalFeaturesEnabled = this.state.getValue().appSettings.experimentalFeaturesEnabled
        const scalingVector = new Vector3(scaling.x, scaling.y, scaling.z)
 
        this.floorLabelDrawer = new FloorLabelDrawer(
            this.mapMesh.getNodes(),
            rootNode,
            treeMapSize,
            scalingVector,
            experimentalFeaturesEnabled
        )
        const floorLabels = this.floorLabelDrawer.draw(this.state.getValue())
 
        Iif (floorLabels.length > 0) {
            this.floorLabelPlanes.add(...floorLabels)
            this.scene.add(this.floorLabelPlanes)
        }
    }
 
    private getRootNode(nodes: Node[]) {
        return nodes.find(node => node.id === 0)
    }
 
    getConstantHighlight() {
        return this.constantHighlight
    }
 
    highlightBuildings() {
        const state = this.state.getValue() as CcState
        this.getMapMesh().highlightBuilding(this.highlighted, this.selected, state, this.constantHighlight)
        Iif (this.mapGeometry.children[0]) {
            this.highlightMaterial(this.mapGeometry.children[0]["material"])
        }
        this.threeRendererService.render()
    }
 
    private selectMaterial(materials: Material[]) {
        const selectedMaterial = materials.find(({ userData }) => userData.id === this.selected.node.id)
        selectedMaterial?.["color"].setHex(this.numberSelectionColor)
    }
 
    private resetMaterial(materials: Material[]) {
        const selectedID = this.selected ? this.selected.node.id : -1
        for (const material of materials) {
            const materialNodeId = material.userData.id
            Iif (materialNodeId !== selectedID) {
                material["color"]?.setHex(this.folderLabelColorHighlighted)
            }
        }
    }
 
    scaleHeight() {
        const scale = this.state.getValue().appSettings.scaling
 
        this.floorLabelDrawer?.translatePlaneCanvases(scale)
        this.mapGeometry.scale.set(scale.x, scale.y, scale.z)
        this.mapGeometry.position.set(-treeMapSize * scale.x, 0, -treeMapSize * scale.z)
        this.mapMesh.setScale(scale)
    }
 
    private highlightMaterial(materials: Material[]) {
        const highlightedNodeIds = new Set(this.highlighted.map(({ node }) => node.id))
        const constantHighlightedNodes = new Set<number>()
 
        for (const { node } of this.constantHighlight.values()) {
            constantHighlightedNodes.add(node.id)
        }
 
        for (const material of materials) {
            const materialNodeId = material.userData.id
            if (this.selected && materialNodeId === this.selected.node.id) {
                material["color"].setHex(this.numberSelectionColor)
            } else if (highlightedNodeIds.has(materialNodeId) || constantHighlightedNodes.has(materialNodeId)) {
                material["color"].setHex(this.folderLabelColorHighlighted)
            } else {
                material["color"]?.setHex(this.folderLabelColorNotHighlighted)
            }
        }
    }
 
    highlightSingleBuilding(building: CodeMapBuilding) {
        this.highlighted = []
        this.addBuildingToHighlightingList(building)
        this.highlightBuildings()
    }
 
    addBuildingToHighlightingList(building: CodeMapBuilding) {
        this.highlighted.push(building)
    }
 
    clearHoverHighlight() {
        this.highlighted = []
        this.highlightBuildings()
    }
 
    clearHighlight() {
        if (this.getMapMesh()) {
            this.getMapMesh().clearHighlight(this.selected)
            this.highlighted = []
            this.constantHighlight.clear()
            Iif (this.mapGeometry.children[0]) {
                this.resetMaterial(this.mapGeometry.children[0]["material"])
            }
        }
    }
 
    selectBuilding(building: CodeMapBuilding) {
        // TODO: This check shouldn't be necessary. When investing into model we should investigate why and remove the need.
        if (building.id !== this.selected?.id) {
            this.store.dispatch(setSelectedBuildingId({ value: building.node.id }))
        }
 
        this.getMapMesh().selectBuilding(building, this.folderLabelColorSelected)
        this.selected = building
        this.highlightBuildings()
 
        this.eventEmitter.emit("onBuildingSelected", { building: this.selected })
        Iif (this.mapGeometry.children[0]) {
            this.selectMaterial(this.mapGeometry.children[0]["material"])
        }
    }
 
    animateLabel(hoveredLabel: Object3D, raycaster: Raycaster, labels: Object3D[]) {
        if (hoveredLabel !== null && raycaster !== null) {
            this.resetLabel()
 
            if (hoveredLabel["material"]) {
                hoveredLabel["material"].opacity = 1
            }
 
            this.highlightedLineIndex = this.getHoveredLabelLineIndex(labels, hoveredLabel)
            this.highlightedLine = labels[this.highlightedLineIndex]
 
            this.rayPoint = new Vector3()
            this.rayPoint.subVectors(raycaster.ray.origin, hoveredLabel.position)
 
            const norm = Math.sqrt(this.rayPoint.x ** 2 + this.rayPoint.y ** 2 + this.rayPoint.z ** 2)
            this.normedTransformVector = new Vector3(this.rayPoint.x / norm, this.rayPoint.y / norm, this.rayPoint.z / norm)
 
            const cameraPoint = raycaster.ray.origin
            const maxDistance = this.calculateMaxDistance(hoveredLabel, labels, cameraPoint)
 
            this.normedTransformVector.multiplyScalar(maxDistance)
 
            hoveredLabel.position.add(this.normedTransformVector)
 
            this.toggleLineAnimation(hoveredLabel)
 
            this.highlightedLabel = hoveredLabel
        }
    }
 
    resetLineHighlight() {
        this.highlightedLineIndex = -1
        this.highlightedLine = null
    }
 
    resetLabel() {
        if (this.highlightedLabel !== null) {
            this.highlightedLabel.position.sub(this.normedTransformVector)
            this.highlightedLabel.material.opacity = defaultMapColors.labelColorAndAlpha.alpha
 
            if (this.highlightedLine) {
                this.toggleLineAnimation(this.highlightedLabel)
            }
 
            this.highlightedLabel = null
        }
    }
 
    getHoveredLabelLineIndex(labels: Object3D[], label: Object3D) {
        const index = labels.findIndex(({ uuid }) => uuid === label.uuid)
 
        if (index >= 0) {
            return index + 1
        }
    }
 
    toggleLineAnimation(hoveredLabel: Object3D) {
        const endPoint = new Vector3(hoveredLabel.position.x, hoveredLabel.position.y, hoveredLabel.position.z)
 
        const pointsBufferGeometry = this.highlightedLine.geometry as BufferGeometry
        const pointsArray = [...pointsBufferGeometry.attributes.position.array]
 
        const geometry = new BufferGeometry().setFromPoints([new Vector3(pointsArray[0], pointsArray[1], pointsArray[2]), endPoint])
 
        const newLineForHighlightedLabel = new Line(geometry, this.highlightedLine.material)
 
        this.labels.children.splice(this.highlightedLineIndex, 1, newLineForHighlightedLabel)
    }
 
    getLabelForHoveredNode(hoveredBuilding: CodeMapBuilding, labels: Object3D[]) {
        // 2-step: the labels array consists of alternating label and the corresponding label antennae
        for (let counter = 0; counter < labels?.length; counter += 2) {
            if (labels[counter].userData.node === hoveredBuilding.node) {
                return labels[counter]
            }
        }
        return null
    }
 
    private isOverlapping(a: Box3, b: Box3, dimension: string) {
        return Number(a.max[dimension] >= b.min[dimension] && b.max[dimension] >= a.min[dimension])
    }
 
    private getIntersectionDistanceFunction(bboxHoveredLabel: Box3, bboxObstructingLabel: Box3) {
        return (distance: number) => {
            const normedVector = this.normedTransformVector.clone()
            normedVector.multiplyScalar(distance)
            bboxHoveredLabel.translate(normedVector)
            const count =
                this.isOverlapping(bboxObstructingLabel, bboxHoveredLabel, "x") +
                this.isOverlapping(bboxObstructingLabel, bboxHoveredLabel, "y")
            if (count === 2 || (count === 1 && this.isOverlapping(bboxObstructingLabel, bboxHoveredLabel, "z"))) {
                return distance
            }
            return 0
        }
    }
 
    private calculateMaxDistance(hoveredLabel: Object3D, labels: Object3D[], cameraPoint: Vector3) {
        const bboxHoveredLabel = new Box3().setFromObject(hoveredLabel)
        const centerPoint = new Vector3()
        bboxHoveredLabel.getCenter(centerPoint)
        const distanceLabelCenterToCamera = cameraPoint.distanceTo(centerPoint)
        let maxDistance = distanceLabelCenterToCamera / 20
 
        for (let counter = 0; counter < labels.length; counter += 2) {
            // Creates a nice small highlighting for hovered, unobstructed
            // labels, empirically gathered value.
            if (labels[counter] !== hoveredLabel) {
                const bboxHoveredLabelWorkingCopy = bboxHoveredLabel.clone()
                const bboxObstructingLabel = new Box3().setFromObject(labels[counter])
                const centerPoint2 = new Vector3()
 
                bboxObstructingLabel.getCenter(centerPoint2)
 
                const calculateIntersectionDistance = this.getIntersectionDistanceFunction(
                    bboxHoveredLabelWorkingCopy,
                    bboxObstructingLabel
                )
 
                maxDistance = Math.max(
                    calculateIntersectionDistance(distanceLabelCenterToCamera - cameraPoint.distanceTo(centerPoint2)),
                    calculateIntersectionDistance(distanceLabelCenterToCamera - cameraPoint.distanceTo(bboxObstructingLabel.max)),
                    calculateIntersectionDistance(distanceLabelCenterToCamera - cameraPoint.distanceTo(bboxObstructingLabel.min)),
                    maxDistance
                )
            }
        }
        return maxDistance
    }
 
    addNodeAndChildrenToConstantHighlight(codeMapNode: Pick<CodeMapNode, "id">) {
        const idToNode = idToNodeSelector(this.state.getValue())
        const codeMapBuilding = idToNode.get(codeMapNode.id)
        for (const { data } of hierarchy(codeMapBuilding)) {
            const building = this.idToBuilding.get(data.id)
            if (building) {
                this.constantHighlight.set(building.id, building)
            }
        }
    }
 
    removeNodeAndChildrenFromConstantHighlight(codeMapNode: Pick<CodeMapNode, "id">) {
        const idToNode = idToNodeSelector(this.state.getValue())
        const codeMapBuilding = idToNode.get(codeMapNode.id)
        for (const { data } of hierarchy(codeMapBuilding)) {
            const building = this.idToBuilding.get(data.id)
            if (building) {
                this.constantHighlight.delete(building.id)
            }
        }
    }
 
    clearConstantHighlight() {
        if (this.constantHighlight.size > 0) {
            this.clearHighlight()
        }
    }
 
    clearSelection() {
        Iif (this.selected) {
            this.getMapMesh().clearSelection(this.selected)
            this.store.dispatch(setSelectedBuildingId({ value: null }))
            this.eventEmitter.emit("onBuildingDeselected")
        }
 
        Iif (this.highlighted.length > 0) {
            this.highlightBuildings()
        }
        this.selected = null
        Iif (this.mapGeometry.children[0]) {
            this.resetMaterial(this.mapGeometry.children[0]["material"])
        }
    }
 
    initLights() {
        const ambilight = new AmbientLight(0x70_70_70) // soft white light
        const light1 = new DirectionalLight(0xe0_e0_e0, 1.5)
        light1.position.set(50, 10, 8).normalize()
 
        const light2 = new DirectionalLight(0xe0_e0_e0, 1.5)
        light2.position.set(-50, 10, -8).normalize()
 
        this.lights.add(ambilight)
        this.lights.add(light1)
        this.lights.add(light2)
    }
 
    setMapMesh(nodes: Node[], mesh: CodeMapMesh) {
        this.mapMesh = mesh
 
        this.initFloorLabels(nodes)
 
        // Reset children
        this.mapGeometry.children.length = 0
 
        this.mapGeometry.position.x = -treeMapSize
        this.mapGeometry.position.y = 0
        this.mapGeometry.position.z = -treeMapSize
 
        this.mapGeometry.add(this.mapMesh.getThreeMesh())
 
        this.idToBuilding.setIdToBuilding(this.mapMesh.getMeshDescription().buildings)
    }
 
    getMapMesh() {
        return this.mapMesh
    }
 
    getSelectedBuilding() {
        return this.selected
    }
 
    getHighlightedBuilding() {
        return this.highlighted[0]
    }
 
    dispose() {
        this.mapMesh?.dispose()
    }
 
    subscribe<Key extends keyof BuildingSelectedEvents>(key: Key, callback: BuildingSelectedEvents[Key]) {
        this.eventEmitter.on(key, (data?) => {
            callback(data)
        })
    }
}