All files / app/codeCharta/ui/codeMap/arrow codeMap.arrow.service.ts

82.85% Statements 116/140
61.11% Branches 33/54
88.46% Functions 23/26
82.73% Lines 115/139

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 26615x 15x 15x 15x 15x   15x 15x 15x 15x 15x 15x     15x   49x 49x 49x 49x 3x     49x       49x       49x             49x 49x 49x 49x   49x 49x       29x     49x 2x 2x 2x   2x     49x 5x 4x 4x   5x     49x 1x 1x       3x       51x   51x 50x 50x   27x       55x   55x       2x 2x   2x 2x 2x 2x 2x         53x   29x 9x 9x 9x                       4x       30x 30x 4x 4x 4x         7x       53x 53x   53x 4x 4x   53x 1x 1x   53x 4x   49x         4x   4x 6x       6x 2x   4x 4x     4x 2x 2x       2x               4x 4x 4x 4x 4x 4x       3x 3x       3x 3x 3x 3x 3x                                   4x 4x 6x   4x                                           3x 3x   3x 3x       3x   3x 3x 3x   3x      
import { Injectable, OnDestroy } from "@angular/core"
import { ThreeSceneService } from "../threeViewer/threeSceneService"
import { Node, EdgeVisibility, CcState } from "../../../codeCharta.model"
import { ArrowHelper, BufferGeometry, CubicBezierCurve3, Line, LineBasicMaterial, Object3D, Vector3 } from "three"
import { ColorConverter } from "../../../util/color/colorConverter"
import { CodeMapBuilding } from "../rendering/codeMapBuilding"
import { IdToBuildingService } from "../../../services/idToBuilding/idToBuilding.service"
import { tap } from "rxjs"
import { hoveredNodeIdSelector } from "../../../state/store/appStatus/hoveredNodeId/hoveredNodeId.selector"
import { debounce } from "../../../util/debounce"
import { Store, State } from "@ngrx/store"
import { edgeVisibilitySelector } from "./utils/edgeVisibility.selector"
 
@Injectable({ providedIn: "root" })
export class CodeMapArrowService implements OnDestroy {
    private map: Map<string, Node>
    private VERTICES_PER_LINE = 5
    private arrows: Object3D[] = new Array<Object3D>()
    private HIGHLIGHT_BUILDING_DELAY = 1
    private debounceCalculation: (hoveredBuilding: CodeMapBuilding) => void = debounce(
        (hoveredBuilding: CodeMapBuilding) => this.resetEdgesOfBuildings(hoveredBuilding),
        this.HIGHLIGHT_BUILDING_DELAY
    )
    private subscription = this.store
        .select(hoveredNodeIdSelector)
        .pipe(
            tap(hoveredNodeId => {
                Iif (hoveredNodeId !== null) {
                    const hoveredBuilding = this.idToBuildingService.get(hoveredNodeId)
                    this.onBuildingHovered(hoveredBuilding)
                } else {
                    this.onBuildingUnhovered()
                }
            })
        )
        .subscribe()
 
    constructor(
        private store: Store<CcState>,
        private state: State<CcState>,
        private threeSceneService: ThreeSceneService,
        private idToBuildingService: IdToBuildingService
    ) {
        this.threeSceneService.subscribe("onBuildingSelected", this.onBuildingSelected)
        this.threeSceneService.subscribe("onBuildingDeselected", this.onBuildingDeselected)
    }
 
    ngOnDestroy(): void {
        this.subscription.unsubscribe()
    }
 
    private resetEdgesOfBuildings = (hoveredBuilding: CodeMapBuilding) => {
        if (this.isEdgeApplicableForBuilding(hoveredBuilding)) {
            this.clearArrows()
            this.showEdgesOfBuildings(hoveredBuilding)
        }
        this.scale()
    }
 
    onBuildingSelected = (data: { building: CodeMapBuilding }) => {
        if (this.isEdgeApplicableForBuilding(data.building)) {
            this.clearArrows()
            this.showEdgesOfBuildings()
        }
        this.scale()
    }
 
    onBuildingDeselected = () => {
        this.clearArrows()
        this.addEdgePreview()
    }
 
    onBuildingHovered(hoveredBuilding: CodeMapBuilding) {
        this.debounceCalculation(hoveredBuilding)
    }
 
    onBuildingUnhovered() {
        const { isEdgeMetricVisible } = this.state.getValue().appSettings
 
        if (isEdgeMetricVisible) {
            this.clearArrows()
            this.showEdgesOfBuildings()
        }
        this.scale()
    }
 
    clearArrows() {
        this.arrows = []
        // Remove all children
        this.threeSceneService.edgeArrows.children.length = 0
    }
 
    addArrow(arrowTargetNode: Node, arrowOriginNode: Node, buildingIsOriginNode: boolean) {
        const { appSettings, dynamicSettings } = this.state.getValue()
        const curveScale = 100 * appSettings.edgeHeight
 
        if (arrowTargetNode.attributes?.[dynamicSettings.heightMetric] && arrowOriginNode.attributes?.[dynamicSettings.heightMetric]) {
            const curve = this.createCurve(arrowOriginNode, arrowTargetNode, curveScale)
            const color = ColorConverter.getNumber(appSettings.mapColors[buildingIsOriginNode ? "outgoingEdge" : "incomingEdge"])
            this.highlightBuilding(buildingIsOriginNode ? arrowTargetNode : arrowOriginNode)
            this.setCurveColor(curve, color)
        }
    }
 
    addEdgePreview() {
        const edges = edgeVisibilitySelector(this.state.getValue())
 
        for (const edge of edges) {
            const originNode = this.map.get(edge.fromNodeName)
            const targetNode = this.map.get(edge.toNodeName)
            Iif (originNode && targetNode && edge.visible !== EdgeVisibility.none && edge.visible) {
                //TODO It seems originNode or targetNode might be undefined here,
                // I think it results from the method being called multiple times when it might not be available yet
                // I changed that back to avoid console errors and re-enable the edge-metric, however we should investigate why this is happening
                const curveScale = 100 * this.state.getValue().appSettings.edgeHeight
                const curve = this.createCurve(originNode, targetNode, curveScale)
                this.previewMode(curve, edge.visible)
            }
        }
    }
 
    addEdgeMapBasedOnNodes(nodes: Node[]) {
        this.map = this.getNodesAsMap(nodes)
    }
 
    scale() {
        const { scaling } = this.state.getValue().appSettings
        for (const arrow of this.arrows) {
            arrow.scale.x = scaling.x
            arrow.scale.y = scaling.y
            arrow.scale.z = scaling.z
        }
    }
 
    private isEdgeApplicableForBuilding(codeMapBuilding: CodeMapBuilding) {
        return this.state.getValue().appSettings.isEdgeMetricVisible && codeMapBuilding && !codeMapBuilding.node.flat
    }
 
    private showEdgesOfBuildings(hoveredbuilding?: CodeMapBuilding) {
        const buildings: Map<string, Node> = new Map()
        const selectedBuilding = this.threeSceneService.getSelectedBuilding()
 
        if (selectedBuilding) {
            const { node } = selectedBuilding
            buildings.set(node.path, node)
        }
        if (hoveredbuilding) {
            const { node } = hoveredbuilding
            buildings.set(node.path, node)
        }
        if (buildings.size > 0) {
            this.buildPairingEdges(buildings)
        } else {
            this.addEdgePreview()
        }
    }
 
    private buildPairingEdges(node: Map<string, Node>) {
        const { edges } = this.state.getValue().fileSettings
 
        for (const edge of edges) {
            const originNode = this.map.get(edge.fromNodeName)
            // TODO: Maps should only have valid edges. If that's not the case, the
            // internal decoration is likely faulty. Check if only test data is not
            // correct or what the root cause of these checks actually is.
            if (originNode === undefined) {
                continue
            }
            const targetNode = this.map.get(edge.toNodeName)
            Iif (targetNode === undefined) {
                continue
            }
            if (node.has(originNode.path)) {
                this.addArrow(targetNode, originNode, true)
                this.threeSceneService.highlightBuildings()
                // TODO: Check if the second if case is actually necessary. Edges should
                // always have valid origin and target paths. The test data is likely
                // faulty and should be improved.
            } else Iif (node.has(targetNode.path)) {
                this.addArrow(targetNode, originNode, false)
                this.threeSceneService.highlightBuildings()
            }
        }
    }
 
    private createCurve(arrowOriginNode: Node, arrowTargetNode: Node, curveScale) {
        const bezierPoint2 = arrowOriginNode.outgoingEdgePoint.clone()
        const bezierPoint3 = arrowTargetNode.incomingEdgePoint.clone()
        const arrowHeight = Math.max(bezierPoint2.y + arrowTargetNode.height, bezierPoint3.y + 1) + curveScale
        bezierPoint2.setY(arrowHeight)
        bezierPoint3.setY(arrowHeight)
        return new CubicBezierCurve3(arrowOriginNode.outgoingEdgePoint, bezierPoint2, bezierPoint3, arrowTargetNode.incomingEdgePoint)
    }
 
    private highlightBuilding(node: Node) {
        const building = this.threeSceneService.getMapMesh().getMeshDescription().getBuildingByPath(node.path)
        this.threeSceneService.addBuildingToHighlightingList(building)
    }
 
    private setCurveColor(bezier: CubicBezierCurve3, color: number, bezierPoints = 50) {
        const points = bezier.getPoints(bezierPoints)
        const curveObject = this.buildLine(points, color)
        curveObject.add(this.buildArrow(points))
        this.threeSceneService.edgeArrows.add(curveObject)
        this.arrows.push(curveObject)
    }
 
    private previewMode(curve, edgeVisibility: EdgeVisibility) {
        Iif (edgeVisibility === EdgeVisibility.both || edgeVisibility === EdgeVisibility.from) {
            const outgoingArrow: Object3D = this.makeArrowFromBezier(curve, false)
            this.threeSceneService.edgeArrows.add(outgoingArrow)
            this.arrows.push(outgoingArrow)
        }
 
        Iif (edgeVisibility === EdgeVisibility.both || edgeVisibility === EdgeVisibility.to) {
            const incomingArrow: Object3D = this.makeArrowFromBezier(curve, true)
            this.threeSceneService.edgeArrows.add(incomingArrow)
            this.arrows.push(incomingArrow)
        }
    }
 
    private getNodesAsMap(nodes: Node[]) {
        const map: Map<string, Node> = new Map()
        for (const node of nodes) {
            map.set(node.path, node)
        }
        return map
    }
 
    private makeArrowFromBezier(bezier: CubicBezierCurve3, incoming: boolean, bezierPoints = 50) {
        const points = bezier.getPoints(bezierPoints)
        const { incomingEdge, outgoingEdge } = this.state.getValue().appSettings.mapColors
        const arrowColor = incoming ? incomingEdge : outgoingEdge
        const pointsPreviews = incoming
            ? points.slice(bezierPoints + 1 - this.VERTICES_PER_LINE)
            : points.slice(0, points.length - (bezierPoints + 1 - this.VERTICES_PER_LINE))
 
        return this.buildEdge(pointsPreviews, ColorConverter.getNumber(arrowColor))
    }
 
    private buildEdge(points: Vector3[], color: number): Object3D {
        const curveObject = this.buildLine(points, color)
        curveObject.add(this.buildArrow(points))
 
        return curveObject
    }
 
    private buildLine(points: Vector3[], color = 0) {
        const geometry = new BufferGeometry()
        geometry.setFromPoints(points)
 
        const material = new LineBasicMaterial({ color, linewidth: 1 })
        return new Line(geometry, material)
    }
 
    private buildArrow(points: Vector3[], ARROW_COLOR = 0, headLength = 10, headWidth = 10) {
        const direction = points.at(-1).clone().sub(points.at(-2).clone()).normalize()
 
        const origin = points.at(-1).clone()
        if (direction.y < 0) {
            origin.y += headLength + 1
        }
        return new ArrowHelper(direction, origin, headLength + 1, ARROW_COLOR, headLength, headWidth)
    }
}