All files / app/codeCharta/ui/codeMap/rendering codeMapMesh.ts

71.27% Statements 67/94
39.02% Branches 16/41
69.56% Functions 16/23
70.96% Lines 66/93

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 23419x 19x       19x 19x             19x 19x 19x 19x 19x                 45x   45x 45x 45x   45x 45x 45x   45x       18x       1x       3x 3x 3x 3x                   7x       3x                 1x                 5x 5x 15x 10x     10x   10x     5x       2x 6x 6x             2x       10x       10x         45x 45x 128x 128x   45x               128x 128x   128x 2x 126x 126x   126x 12x     126x             21x                                     147x 147x   147x 147x   147x 3528x 3528x                             55x 55x                                   45x   45x   45x                                
import { CodeMapShaderStrings } from "./shaders/loaders/codeMapShaderStrings"
import { GeometryGenerator } from "./geometryGenerator"
import { CodeMapGeometricDescription } from "./codeMapGeometricDescription"
import { CodeMapBuilding } from "./codeMapBuilding"
import { Node, Scaling, CcState } from "../../../codeCharta.model"
import { BufferAttribute, Camera, Mesh, Ray, ShaderMaterial, UniformsLib, UniformsUtils, Vector3 } from "three"
import { TreeMapHelper, treeMapSize } from "../../../util/algorithm/treeMapLayout/treeMapHelper"
 
export interface MousePos {
    x: number
    y: number
}
 
export class CodeMapMesh {
    static readonly NUM_OF_COLOR_VECTOR_FIELDS = 3
    static readonly NUM_OF_VERTICES = 24
    static readonly LIGHTNESS_INCREASE = -10
    static readonly LIGHTNESS_DECREASE = 20
 
    private threeMesh: Mesh
    private material: ShaderMaterial
    private geomGen: GeometryGenerator
    private mapGeomDesc: CodeMapGeometricDescription
    private nodes: Node[]
 
    constructor(nodes: Node[], state: CcState, isDeltaState: boolean) {
        this.initMaterial()
 
        this.geomGen = new GeometryGenerator()
        this.material.precision = "lowp" // no need for high precision in our shaders
        const buildResult = this.geomGen.build(nodes, this.material, state, isDeltaState)
 
        this.threeMesh = buildResult.mesh
        this.mapGeomDesc = buildResult.desc
        this.nodes = nodes
 
        this.initDeltaColorsOnMesh(state)
    }
 
    getThreeMesh() {
        return this.threeMesh
    }
 
    getNodes() {
        return this.nodes
    }
 
    selectBuilding(building: CodeMapBuilding, color: string) {
        building.setColor(color)
        building.setDeltaColor(color)
        this.setVertexColor(building.id, building.getColorVector(), building.getDeltaColorVector())
        this.updateVertices()
    }
 
    clearSelection(selected: CodeMapBuilding) {
        selected.resetColor()
        this.setVertexColor(selected.id, selected.getDefaultColorVector(), selected.getDefaultDeltaColorVector())
        this.updateVertices()
    }
 
    getMeshDescription() {
        return this.mapGeomDesc
    }
 
    getBuildingByPath(path: string) {
        return this.mapGeomDesc.getBuildingByPath(path)
    }
 
    checkMouseRayMeshIntersection(mouse: MousePos, camera: Camera) {
        const ray = this.calculatePickingRay(mouse, camera)
        return this.getMeshDescription().intersect(ray)
    }
 
    setScale(scale: Scaling) {
        this.mapGeomDesc.setScales(scale)
    }
 
    highlightBuilding(
        highlightedBuildings: CodeMapBuilding[],
        selected: CodeMapBuilding,
        state: CcState,
        constantHighlight: Map<number, CodeMapBuilding>
    ) {
        const highlightBuildingMap = TreeMapHelper.buildingArrayToMap(highlightedBuildings)
        for (const building of this.mapGeomDesc.buildings) {
            if (!this.isBuildingSelected(selected, building)) {
                Iif (highlightBuildingMap.get(building.id) || constantHighlight.get(building.id)) {
                    building.decreaseLightness(CodeMapMesh.LIGHTNESS_INCREASE)
                } else {
                    this.adjustSurroundingBuildingColors(highlightedBuildings, building, state)
                }
                this.setVertexColor(building.id, building.getColorVector(), building.getDeltaColorVector())
            }
        }
        this.updateVertices()
    }
 
    clearHighlight(selected: CodeMapBuilding) {
        for (const currentBuilding of this.mapGeomDesc.buildings) {
            if (!this.isBuildingSelected(selected, currentBuilding)) {
                this.setVertexColor(
                    currentBuilding.id,
                    currentBuilding.getDefaultColorVector(),
                    currentBuilding.getDefaultDeltaColorVector()
                )
            }
        }
        this.updateVertices()
    }
 
    private adjustSurroundingBuildingColors(highlighted: CodeMapBuilding[], building: CodeMapBuilding, state: CcState) {
        Iif (state.appSettings.isPresentationMode) {
            const distance = highlighted[0].getCenterPoint(treeMapSize).distanceTo(building.getCenterPoint(treeMapSize))
            this.decreaseLightnessByDistance(building, distance)
        } else {
            building.decreaseLightness(CodeMapMesh.LIGHTNESS_DECREASE)
        }
    }
 
    private initDeltaColorsOnMesh(state: CcState) {
        if (this.mapGeomDesc.buildings[0]?.node.deltas) {
            for (const building of this.mapGeomDesc.buildings) {
                this.setNewDeltaColor(building, state)
                this.setVertexColor(building.id, building.getColorVector(), building.getDeltaColorVector())
            }
            this.updateVertices()
        }
    }
 
    private setNewDeltaColor(building: CodeMapBuilding, state: CcState) {
        const {
            appSettings: { mapColors },
            dynamicSettings: { heightMetric }
        } = state
        const { node } = building
 
        if (node.flat) {
            building.setInitialDeltaColor(mapColors.flat)
        } else if (node.deltas) {
            const deltaValue = node.deltas[heightMetric]
 
            if (deltaValue > 0) {
                building.setInitialDeltaColor(mapColors.positiveDelta)
            }
 
            Iif (deltaValue < 0) {
                building.setInitialDeltaColor(mapColors.negativeDelta)
            }
        }
    }
 
    private isBuildingSelected(selected: CodeMapBuilding, building: CodeMapBuilding) {
        return selected && building.equals(selected)
    }
 
    private decreaseLightnessByDistance(building: CodeMapBuilding, distance: number) {
        if (distance > 800) {
            building.decreaseLightness(40)
        } else if (distance > 400) {
            building.decreaseLightness(30)
        } else if (distance > 250) {
            building.decreaseLightness(20)
        } else if (distance > 100) {
            building.decreaseLightness(15)
        } else Iif (distance > 50) {
            building.decreaseLightness(10)
        }
    }
 
    private setVertexColor(id: number, newColorVector: Vector3, newDeltaColorVector) {
        //!Note  this function is called a lot of times see highlightBuilding , maybe bulk update the color and delta colors
        const numberOfColorFieldsPerBuilding = CodeMapMesh.NUM_OF_VERTICES
        const positionOfFirstColorEntry = id * numberOfColorFieldsPerBuilding
 
        const colorAttribute = this.threeMesh.geometry.getAttribute("color") as BufferAttribute
        const deltaAttribute = this.threeMesh.geometry.getAttribute("deltaColor") as BufferAttribute
 
        for (let index = positionOfFirstColorEntry; index < positionOfFirstColorEntry + numberOfColorFieldsPerBuilding; index += 1) {
            colorAttribute.setXYZ(index, newColorVector.x, newColorVector.y, newColorVector.z)
            deltaAttribute.setXYZ(index, newDeltaColorVector.x, newDeltaColorVector.y, newDeltaColorVector.z)
        }
 
        //!Note this can be used to update only the needed range => faster rendering
        //!     maybe return the offset and count, build the union of the result, and
        //!     use next lines inside updateVertices ?
 
        /*colorAttribute.updateRange.offset = positionOfFirstColorEntry
		colorAttribute.updateRange.count = numberOfColorFieldsPerBuilding
 
		deltaAttribute.updateRange.offset = positionOfFirstColorEntry
		deltaAttribute.updateRange.count = numberOfColorFieldsPerBuilding*/
    }
 
    private updateVertices() {
        this.threeMesh.geometry.getAttribute("color").needsUpdate = true
        this.threeMesh.geometry.getAttribute("deltaColor").needsUpdate = true
    }
 
    dispose() {
        // TODO more needs to be disposed (textures, render targets, passes , ...)
        this.disposeMesh()
        this.disposeMaterial()
    }
 
    private disposeMesh() {
        this.threeMesh?.geometry?.dispose()
    }
 
    private disposeMaterial() {
        this.material?.dispose()
    }
 
    private initMaterial() {
        const uniforms = UniformsUtils.merge([UniformsLib["lights"]])
 
        const shaderCode = new CodeMapShaderStrings()
 
        this.material = new ShaderMaterial({
            vertexShader: shaderCode.vertexShaderCode,
            fragmentShader: shaderCode.fragmentShaderCode,
            lights: true,
            uniforms
        })
    }
 
    private calculatePickingRay(mouse: MousePos, camera: Camera) {
        const ray = new Ray()
        ray.origin.setFromMatrixPosition(camera.matrixWorld)
        ray.direction.set(mouse.x, mouse.y, 0.5).unproject(camera).sub(ray.origin).normalize()
 
        return ray
    }
}