All files / app/codeCharta/ui/export3DMapButton/export3DMapDialog export3DMapDialog.component.ts

79.37% Statements 127/160
65.62% Branches 21/32
56.25% Functions 18/32
79.24% Lines 126/159

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 3784x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x         4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x                                                                                       4x     4x         4x 4x     4x           4x             4x         4x                       4x 4x 4x 4x 4x 4x 4x     4x 4x     4x             4x 4x 4x 4x 4x   4x 4x   4x 4x 4x   4x 4x 4x 4x 16x         4x 4x                     15x                                                             1x 1x 1x 1x   1x 1x                 13x 13x 13x                   21x 21x 21x                   34x 2x 2x   32x 2x         4x 4x 4x   4x 4x 4x 4x   4x 4x 4x 4x   4x   4x 4x 4x 4x             4x       4x 4x 4x 4x 4x 4x 4x   4x   4x 131x 131x 131x     4x               5x                 1x             1x 1x   1x 1x                     4x 4x   4x 4x 4x   4x       4x   8x   12x                                                  
import { filesSelector } from "../../../state/store/files/files.selector"
import { accumulatedDataSelector } from "../../../state/selectors/accumulatedData/accumulatedData.selector"
import { FileNameHelper } from "../../../util/fileNameHelper"
import { getVisibleFileStates, isDeltaState } from "../../../model/files/files.helper"
import { FileDownloader } from "../../../util/fileDownloader"
import { Component, ElementRef, Input, ViewChild } from "@angular/core"
import { State } from "@ngrx/store"
import { CcState, NodeMetricData } from "../../../codeCharta.model"
import { ThreeSceneService } from "../../codeMap/threeViewer/threeSceneService"
import { Color, Mesh, PerspectiveCamera, Scene, ShaderMaterial, Vector2, Vector3, WebGLRenderer } from "three"
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"
import { STLExporter } from "three/examples/jsm/exporters/STLExporter"
import { metricTitles } from "../../../util/metric/metricTitles"
import { serialize3mf } from "../../../services/3DExports/serialize3mf.service"
import {
    calculateMaxPossibleWidthForPreview3DPrintMesh,
    GeometryOptions,
    Preview3DPrintMesh
} from "../../../services/3DExports/3DPreview/preview3DPrintMesh"
import { calculateNodeMetricData } from "../../../state/selectors/accumulatedData/metricData/nodeMetricData.calculator"
import { MatSlideToggleChange, MatSlideToggle } from "@angular/material/slide-toggle"
import { MatToolbar } from "@angular/material/toolbar"
import { CdkScrollable } from "@angular/cdk/scrolling"
import { MatDialogContent, MatDialogActions } from "@angular/material/dialog"
import { MatFormField, MatLabel } from "@angular/material/form-field"
import { MatSelect, MatSelectTrigger } from "@angular/material/select"
import { MatOption } from "@angular/material/core"
import { MatCard, MatCardHeader, MatCardContent } from "@angular/material/card"
import { MatSlider, MatSliderThumb } from "@angular/material/slider"
import { FormsModule } from "@angular/forms"
import { MatInput } from "@angular/material/input"
import { MatButton } from "@angular/material/button"
import { LabelledColorPickerComponent } from "../../labelledColorPicker/labelledColorPicker.component"
 
interface Printer {
    name: string
    x: number
    y: number
    z: number
    numberOfColors: number
}
 
interface ManualVisibilityItem {
    readonly defaultText: string
    readonly name: string
    isVisible: boolean
    currentText?: string
}
 
@Component({
    selector: "cc-export-3D-map-dialog",
    templateUrl: "./export3DMapDialog.component.html",
    styleUrls: ["./export3DMapDialog.component.scss"],
    standalone: true,
    imports: [
        MatToolbar,
        CdkScrollable,
        MatDialogContent,
        MatFormField,
        MatLabel,
        MatSelect,
        MatSelectTrigger,
        MatOption,
        MatCard,
        MatCardHeader,
        MatCardContent,
        MatSlider,
        MatSliderThumb,
        FormsModule,
        MatInput,
        MatSlideToggle,
        MatButton,
        LabelledColorPickerComponent,
        MatDialogActions
    ]
})
export class Export3DMapDialogComponent {
    @ViewChild("rendererContainer") rendererContainer: ElementRef
    @ViewChild("fileInput") fileInput: ElementRef
    @Input() logoColor = "#ffffff"
 
    private printPreviewScene: Scene
    currentSize: Vector3
 
    isFileSelected = false
    isPrintMeshLoaded = false
    frontText: string
 
    secondRow = {
        defaultText: new Date().toLocaleDateString(),
        name: "Second Row Text",
        isVisible: false,
        currentText: undefined
    }
    qrCode = {
        defaultText: "maibornwolff.de/service/it-sanierung",
        name: "QrCode",
        isVisible: false,
        currentText: undefined
    }
 
    printers: Printer[] = [
        { name: "Prusa MK3S (single color)", x: 245, y: 205, z: 205, numberOfColors: 1 },
        { name: "BambuLab A1 + AMS Lite", x: 251, y: 251, z: 251, numberOfColors: 4 },
        { name: "Prusa XL (5 colors)", x: 355, y: 335, z: 355, numberOfColors: 5 }
    ]
    selectedPrinter: Printer = this.printers[2]
    private currentNumberOfColors: number
 
    maxWidth: number
    wantedWidth: number
    private previewMesh: Preview3DPrintMesh
 
    private readonly areaMetric: string
    private readonly heightMetric: string
    private readonly colorMetric: string
    private nodeMetricData: NodeMetricData[]
 
    private readonly layerHeight = 0.2
    private readonly frontTextSize = 8
    private readonly secondRowTextSize = 6
    private readonly frontPrintDepth = 0.6
    private readonly mapSideOffset = 10
    private readonly baseplateHeight = 1 //should be a multiple of layerHeight
    private readonly logoSize = 10
 
    constructor(
        private state: State<CcState>,
        private threeSceneService: ThreeSceneService
    ) {
        //console.log(this.threeSceneService)
        this.maxWidth = calculateMaxPossibleWidthForPreview3DPrintMesh(
            new Vector3(this.selectedPrinter.x, this.selectedPrinter.y, this.selectedPrinter.z),
            this.threeSceneService.getMapMesh().getThreeMesh(),
            this.frontTextSize,
            this.baseplateHeight,
            this.mapSideOffset
        )
        this.currentSize = new Vector3()
        this.currentSize.x = this.maxWidth
        this.wantedWidth = this.maxWidth
        this.currentNumberOfColors = this.selectedPrinter.numberOfColors
        this.isPrintMeshLoaded = false
 
        this.secondRow.currentText = this.secondRow.defaultText
        this.qrCode.currentText = this.qrCode.defaultText
 
        this.areaMetric = this.state.getValue().dynamicSettings.areaMetric
        this.heightMetric = this.state.getValue().dynamicSettings.heightMetric
        this.colorMetric = this.state.getValue().dynamicSettings.colorMetric
 
        const visibleFileStates = getVisibleFileStates(this.state.getValue().files)
        const blacklist = this.state.getValue().fileSettings.blacklist
        const nodeMetricData = calculateNodeMetricData(visibleFileStates, blacklist)
        this.nodeMetricData = nodeMetricData.filter(
            metric => metric.name === this.areaMetric || metric.name === this.heightMetric || metric.name === this.colorMetric
        )
    }
 
    async ngAfterViewInit() {
        await this.createScene()
        this.isPrintMeshLoaded = true
    }
 
    onScaleChange() {
        this.previewMesh.updateSize(this.wantedWidth).then((qrCodeVisible: boolean) => {
            this.qrCode.isVisible = qrCodeVisible
        })
        this.currentSize = this.previewMesh.getSize()
    }
 
    onFrontTextChange() {
        this.previewMesh.updateFrontText(this.frontText)
    }
 
    onFileSelected(event) {
        const file: File = event.target.files[0]
        if (file) {
            this.isFileSelected = true // Set isFileSelected to true when a file is selected
            const reader = new FileReader()
            reader.readAsDataURL(file)
            reader.onload = () => {
                this.previewMesh.addCustomLogo(reader.result as string)
            }
        } else {
            this.isFileSelected = false
        }
    }
    onRotateLogo() {
        this.previewMesh.rotateCustomLogo()
    }
 
    onFlipLogo() {
        this.previewMesh.flipCustomLogo()
    }
 
    onRemoveLogo() {
        this.isFileSelected = false
        this.fileInput.nativeElement.value = ""
        this.previewMesh.removeCustomLogo()
    }
 
    onSelectedPrinterChange() {
        const wantedNumberOfColors = this.selectedPrinter.numberOfColors
        if (this.currentNumberOfColors !== wantedNumberOfColors) {
            this.previewMesh.updateNumberOfColors(wantedNumberOfColors)
            this.currentNumberOfColors = wantedNumberOfColors
        }
        this.makeMapMaxSize()
        this.updateCameraPosition(this.printPreviewScene.getObjectByName("camera") as PerspectiveCamera)
    }
 
    onLogoColorChange(newColor: string) {
        this.logoColor = newColor
        this.previewMesh.updateCustomLogoColor(this.logoColor)
    }
 
    onQrCodeTextChange() {
        this.onTextChange(this.qrCode)
        this.previewMesh.updateQrCodeText(this.qrCode.currentText)
        this.previewMesh.updateQrCodeVisibility(this.qrCode.isVisible)
    }
    onQrCodeVisibilityChange(event: MatSlideToggleChange) {
        Iif (this.qrCode.isVisible !== event.checked) {
            this.qrCode.isVisible = event.checked
            this.previewMesh.updateQrCodeVisibility(this.qrCode.isVisible)
        }
    }
 
    onSecondRowTextChange() {
        this.onTextChange(this.secondRow)
        this.previewMesh.updateSecondRowText(this.secondRow.currentText)
        this.previewMesh.updateSecondRowVisibility(this.secondRow.isVisible)
    }
    onSecondRowVisibilityChange(event: MatSlideToggleChange) {
        Iif (this.secondRow.isVisible !== event.checked) {
            this.secondRow.isVisible = event.checked
            this.previewMesh.updateSecondRowVisibility(this.secondRow.isVisible)
        }
    }
 
    private onTextChange(item: ManualVisibilityItem) {
        if (item.currentText === "") {
            item.isVisible = false
            return
        }
        if (!item.isVisible) {
            item.isVisible = true
        }
    }
 
    async createScene() {
        const printPreviewScene = new Scene()
        printPreviewScene.name = "printPreviewScene"
        this.printPreviewScene = printPreviewScene
 
        printPreviewScene.background = new Color(0xec_ed_dc) //TODO: can I somehow get the current background color from the store or something?
        const lights = this.threeSceneService.scene.clone().children[3]
        lights.name = "lights"
        printPreviewScene.add(lights)
 
        const camera = new PerspectiveCamera(45, 1.15, 50, 200_000)
        camera.name = "camera"
        camera.up = new Vector3(0, 0, 1)
        printPreviewScene.add(camera)
 
        this.initRenderer(printPreviewScene, camera)
 
        this.previewMesh = new Preview3DPrintMesh(this.initGeometryOptions())
        await this.previewMesh.initialize()
        this.currentSize = this.previewMesh.getSize()
        printPreviewScene.add(this.previewMesh.getThreeMesh())
 
        /*camera.position.set(
            0,
            0,
            -this.wantedWidth * 1.5
        ) //To directly see the backside of the map: uncomment this line and comment the next line*/
        this.updateCameraPosition(camera) //*/
    }
 
    private initRenderer(printPreviewScene, camera) {
        const renderer = this.getGL()
        const currentSize = new Vector2()
        renderer.getSize(currentSize)
        const containerWidth = this.rendererContainer.nativeElement.offsetWidth
        const containerHeight = currentSize.y * (containerWidth / currentSize.x)
        renderer.setSize(containerWidth, containerHeight, true)
        this.rendererContainer.nativeElement.appendChild(renderer.domElement)
 
        const controls = new OrbitControls(camera, renderer.domElement)
 
        const animate = function () {
            requestAnimationFrame(animate)
            controls.update()
            renderer.render(printPreviewScene, camera)
        }
 
        animate()
    }
 
    getGL() {
        return new WebGLRenderer()
    }
 
    private updateCameraPosition(camera: PerspectiveCamera) {
        camera.position.set(-this.currentSize.x * 0.2, -this.currentSize.y * 1.2, this.currentSize.z * 3)
    }
 
    async download3MFFile() {
        const compressed3mf = await serialize3mf(this.printPreviewScene.getObjectByName("PrintMesh") as Mesh)
        this.downloadFile(compressed3mf, "3mf")
    }
 
    private makeMapMaxSize() {
        this.wantedWidth = calculateMaxPossibleWidthForPreview3DPrintMesh(
            new Vector3(this.selectedPrinter.x, this.selectedPrinter.y, this.selectedPrinter.z),
            this.threeSceneService.getMapMesh().getThreeMesh(),
            this.frontTextSize,
            this.baseplateHeight,
            this.mapSideOffset
        )
        this.previewMesh.updateSize(this.wantedWidth).then((qrCodeVisible: boolean) => {
            this.qrCode.isVisible = qrCodeVisible
        })
        this.currentSize = this.previewMesh.getSize()
        this.maxWidth = this.currentSize.x
    }
 
    downloadStlFile() {
        const exportedBinaryFile = new STLExporter().parse(this.previewMesh.getMapMesh(), {
            binary: true
        }) as unknown as string
        this.downloadFile(exportedBinaryFile, "stl")
    }
 
    private initGeometryOptions(): GeometryOptions {
        const attributeDescriptors = this.state.getValue().fileSettings.attributeDescriptors
        const fallbackTitles: Map<string, string> = metricTitles
 
        const areaMetricTitle = attributeDescriptors[this.areaMetric]?.title || fallbackTitles.get(this.areaMetric)
        const heightMetricTitle = attributeDescriptors[this.heightMetric]?.title || fallbackTitles.get(this.heightMetric)
        const colorMetricTitle = attributeDescriptors[this.colorMetric]?.title || fallbackTitles.get(this.colorMetric)
 
        return {
            originalMapMesh: this.threeSceneService.getMapMesh().getThreeMesh(),
            width: this.wantedWidth,
            areaMetricTitle,
            areaMetricData: this.nodeMetricData.find(metric => metric.name === this.areaMetric),
            heightMetricTitle,
            heightMetricData: this.nodeMetricData.find(metric => metric.name === this.heightMetric),
            colorMetricTitle,
            colorMetricData: this.nodeMetricData.find(metric => metric.name === this.colorMetric),
            colorRange: this.state.getValue().dynamicSettings.colorRange,
            frontText: this.frontText,
            secondRowText: this.secondRow.currentText,
            secondRowVisible: this.secondRow.isVisible,
            qrCodeText: this.qrCode.currentText,
            defaultMaterial: this.threeSceneService.getMapMesh().getThreeMesh().material[0].clone() as ShaderMaterial,
            numberOfColors: this.currentNumberOfColors,
            layerHeight: this.layerHeight,
            frontTextSize: this.frontTextSize,
            secondRowTextSize: this.secondRowTextSize,
            printHeight: this.frontPrintDepth,
            mapSideOffset: this.mapSideOffset,
            baseplateHeight: this.baseplateHeight,
            logoSize: this.logoSize
        }
    }
 
    private downloadFile(data: string, fileExtension: string) {
        const files = filesSelector(this.state.getValue())
        const fileName = accumulatedDataSelector(this.state.getValue()).unifiedFileMeta?.fileName
        const downloadFileName = `${FileNameHelper.getNewFileName(fileName, isDeltaState(files))}.${fileExtension}`
        FileDownloader.downloadData(data, downloadFileName)
    }
}