All files / tools/ReFlex.TrackingServer/ClientApp/src/app/calibration calibration.component.ts

97.52% Statements 197/202
94.5% Branches 86/91
96.92% Functions 63/65
97.96% Lines 193/197

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 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 6531x                                                     1x             1x 1x 1x 1x 1x                                       25x   1x           23x   23x   23x           23x           23x               23x             23x   23x   23x   23x 23x   23x 23x 23x 23x 23x 23x 23x 23x   23x 23x             23x             11x 2x       9x       11x   11x 1x       9x                 3x     6x       21x 21x   21x   134x   2x 2x   2x       21x       21x   20x     20x         21x   21x     134x   1x 1x       21x         15x 15x     3x 3x       21x         16x     3x 3x       21x         15x     3x 3x       21x   21x       23x 23x 23x 23x       2x     2x       2x 1x         1x               2x 1x 1x 1x         11x       4x 2x         1x       22x       7x       3x   3x     4x   4x       58x 58x       8x             2x     6x           6x     6x         5x     1x 1x           14x 2x 2x   2x     12x 1x     11x       20x         20x 20x 20x 20x       20x 20x       2x         1x 1x     1x 1x     2x 2x       2x             2x         1x 1x     1x       1x 1x           840x                 840x                   222x   222x   222x           280x                 2x         1x     1x 1x           59x               257x                             134x 12x     122x       122x 122x   122x   122x       134x 10x       122x   366x   72x 122x   72x     76x   76x   76x           46x 34x   35x         46x 33x 33x   13x 13x       46x         3x       1x         17x                 38x         32x     2x 2x           21x         16x     2x 2x           17x 17x           5x 5x 5x 5x 4x 4x     1x 1x               15x       60x      
import { markViewForCheck } from 'src/shared/util/mark-view-for-check';
/* eslint-disable max-lines */
import { CommonModule } from '@angular/common';
import { HttpResponse } from '@angular/common/http';
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ElementRef,
  HostListener,
  OnDestroy,
  OnInit,
  Renderer2,
  ViewChild,
  inject
} from '@angular/core';
import { PanelHeaderComponent } from '@reflex/angular-components/dist';
import {
  Calibration,
  CalibrationPoint,
  CalibrationTransform,
  CompleteInteractionData,
  FrameSizeDefinition,
  Interaction,
  InteractionType,
  Point3
} from '@reflex/shared-types';
import { NEVER, Observable, Subscription } from 'rxjs';
import {
  catchError,
  concatMap,
  startWith,
  switchMap,
  tap
} from 'rxjs/operators';
import { CalibrationService } from 'src/shared/services/calibration.service';
import { ProcessingService } from 'src/shared/services/processing.service';
import { SettingsService } from 'src/shared/services/settingsService';
import { LogService } from '../log/log.service';
 
export interface TransformString {
  transform: string;
}
 
export interface BorderString {
  top: string;
  left: string;
  width: string;
  height: string;
}
 
@Component({
  selector: 'app-calibration',
  templateUrl: './calibration.component.html',
  styleUrls: ['./calibration.component.scss'],
  changeDetection: ChangeDetectionStrategy.Eager,
  imports: [CommonModule, PanelHeaderComponent]
})
export class CalibrationComponent implements OnInit, OnDestroy {
 
  private static readonly fullScreenClassName = 'fullScreen';
 
  @ViewChild('calibrationView')
  private readonly view?: ElementRef<HTMLDivElement>;
 
  // TODO: toggle between Calbration / Borders and display of current calibration values
  public isInteractiveCalibrationVisible = false;
 
  public borderOffset: Array<number> = [0, 0, 0, 0];
 
  public calibrationSource: Array<CalibrationPoint> = [
    { positionX: 100, positionY: 200, touchId: -1 },
    { positionX: 600, positionY: 200, touchId: -1 },
    { positionX: 600, positionY: 700, touchId: -1 }
  ];
 
  public calibratedTargets: Array<CalibrationPoint> = [
    { positionX: 100, positionY: 200, touchId: -1 },
    { positionX: 600, positionY: 200, touchId: -1 },
    { positionX: 600, positionY: 700, touchId: -1 }
  ];
 
  public currentCalibration: Calibration = {
    lastUpdated: [],
    sourceValues: [],
    targetValues: [],
    lowerThreshold: 0,
    upperThreshold: 0
  };
 
  public calibrationMatrix: Array<Array<number>> = [
    [1, 0, 0, 0],
    [0, 1, 0, 0],
    [0, 0, 1, 0],
    [0, 0, 0, 1]
  ];
 
  public interactions: Array<Interaction> = [];
 
  public calibratedInteractions: Array<Interaction> = [];
 
  public isProcessingActive = false;
 
  public selectedValue: Array<Interaction> = [];
  public selectedIdx = 0;
 
  public update = false;
  public displayCalibratedInteractions = false;
  private readonly changeDetector = inject(ChangeDetectorRef);
  private readonly renderer = inject(Renderer2);
  private readonly processingService = inject(ProcessingService);
  private readonly calibrationService = inject(CalibrationService);
  private readonly settingsService = inject(SettingsService);
  private readonly logService = inject(LogService);
 
  private currentlyActiveStage = -1;
  private selectedBorderIndex = -1;
 
  private interactionsSubscription?: Subscription;
  private calibrationSubscription?: Subscription;
  private readonly calibratedInteractionsSubscription?: Subscription;
  private settingsSubscription?: Subscription;
  private matrixSubscription?: Subscription;
  private maxConfidence = 30;
 
  private completeInteractions$?: Observable<CompleteInteractionData>;
  private isProcessing$?: Observable<string>;
 
  @HostListener('mousemove', ['$event'])
  public onmouseMove(evt: MouseEvent): void {
    if (this.selectedBorderIndex < 0 || this.selectedBorderIndex > 3) {
      return;
    }
 
    const offset
      = this.selectedBorderIndex === 0 || this.selectedBorderIndex === 2
        ? evt.movementY
        : evt.movementX;
 
    let newOffset = this.borderOffset[this.selectedBorderIndex] + offset;
 
    if (newOffset < 0) {
      newOffset = 0;
    }
 
    // check if borders collide / are too close
    if (
      (this.selectedBorderIndex === 0
        && this.borderOffset[2] - newOffset < 70)
      || (this.selectedBorderIndex === 1
        && this.borderOffset[3] - newOffset < 70)
      || (this.selectedBorderIndex === 2
        && newOffset - this.borderOffset[0] < 70)
      || (this.selectedBorderIndex === 3 && newOffset - this.borderOffset[1] < 70)
    ) {
      return;
    }
 
    this.borderOffset[this.selectedBorderIndex] = newOffset;
  }
 
  public ngOnInit(): void {
    this.resetBorders();
    this.resetSelectedInteraction();
 
    const interactions$ = this.processingService.getInteractions().pipe(
      concatMap((result: Array<Interaction>) =>
        this.calibrationService.computeCalibratedAbsolutePosition(result)),
      catchError((error: unknown) => {
        console.error(error);
        this.logService.sendErrorLog(`${error}`);
 
        return [];
      })
    );
 
    this.isProcessing$ = this.processingService
      .getStatus()
      .pipe(markViewForCheck(this.changeDetector));
 
    this.completeInteractions$ = this.isProcessing$.pipe(
      tap((processing) => {
        this.isProcessingActive = processing === 'Active';
      }),
      switchMap((processing) =>
        processing
          ? interactions$
          : NEVER.pipe(startWith({ raw: [], normalized: [], absolute: [] })))
    );
 
    this.settingsService.update();
 
    this.interactionsSubscription = this.completeInteractions$
      .pipe(markViewForCheck(this.changeDetector))
      .subscribe(
        (result) => this.updateInteractions(result),
        (error: unknown) => {
          this.logService.sendErrorLog(`${error}`);
          console.error(error);
        }
      );
 
    this.settingsSubscription = this.settingsService
      .getSettings()
      .pipe(markViewForCheck(this.changeDetector))
      .subscribe(
        (result) => {
          this.updateCalibrationValues(result.calibrationValues);
          this.maxConfidence = result.filterSettingValues.confidence.max;
        },
        (error: unknown) => {
          this.logService.sendErrorLog(`${error}`);
          console.error(error);
        }
      );
 
    this.calibrationSubscription = this.calibrationService
      .getFrameSize()
      .pipe(markViewForCheck(this.changeDetector))
      .subscribe(
        (result) => {
          this.updateBorders(result);
        },
        (error: unknown) => {
          this.logService.sendErrorLog(`${error}`);
          console.error(error);
        }
      );
 
    this.matrixSubscription = this.calibrationService
      .getCalibrationMatrix()
      .pipe(markViewForCheck(this.changeDetector))
      .subscribe(
        (result) => {
          this.calibrationMatrix = result.transformation;
        },
        (error: unknown) => {
          this.logService.sendErrorLog(`${error}`);
          console.error(error);
        }
      );
 
    this.updateSourceValues();
 
    this.updateTargetPoints();
  }
 
  public ngOnDestroy(): void {
    this.interactionsSubscription?.unsubscribe();
    this.settingsSubscription?.unsubscribe();
    this.calibrationSubscription?.unsubscribe();
    this.matrixSubscription?.unsubscribe();
  }
 
  public toggleCalibrationMode(): void {
    this.isInteractiveCalibrationVisible
      = !this.isInteractiveCalibrationVisible;
 
    Iif (this.view === undefined) {
      return;
    }
 
    if (this.isInteractiveCalibrationVisible) {
      this.renderer.addClass(
        this.view.nativeElement,
        CalibrationComponent.fullScreenClassName
      );
    } else {
      this.renderer.removeClass(
        this.view.nativeElement,
        CalibrationComponent.fullScreenClassName
      );
    }
  }
 
  public updateCalibrationToggle(): void {
    if (!this.update) {
      this.displayCalibratedInteractions = false;
      this.interactions = [];
      this.calibratedInteractions = [];
    }
  }
 
  public focusBorder(index: number): void {
    this.selectedBorderIndex = index;
  }
 
  public releaseBorder(index: number): void {
    if (this.selectedBorderIndex === index) {
      this.selectedBorderIndex = -1;
    }
  }
 
  public releaseAllBorders(): void {
    this.selectedBorderIndex = -1;
  }
 
  public resetBorders(): void {
    this.borderOffset = [100, 100, 500, 500];
  }
 
  public select(interactionIdx: number): void {
    if (
      interactionIdx === this.selectedIdx
      || interactionIdx >= this.interactions.length
    ) {
      this.resetSelectedInteraction();
 
      return;
    }
 
    this.selectedValue[this.currentlyActiveStage]
      = this.interactions[interactionIdx];
    this.selectedIdx = interactionIdx;
  }
 
  public resetSelectedInteraction(): void {
    this.selectedValue = this.getDefaultSelectedValues();
    this.selectedIdx = -1;
  }
 
  public submit(): void {
    if (
      this.selectedIdx < 0
      || this.currentlyActiveStage < 0
      || this.currentlyActiveStage > 2
      || this.selectedValue.length < this.currentlyActiveStage + 1
      || this.selectedValue[this.currentlyActiveStage].touchId < 0
    ) {
      return;
    }
 
    const pos: CalibrationPoint = {
      positionX: this.selectedValue[this.currentlyActiveStage].position.x,
      positionY: this.selectedValue[this.currentlyActiveStage].position.y,
      touchId: this.selectedValue[this.currentlyActiveStage].touchId
    };
 
    this.calibratedTargets[this.currentlyActiveStage] = pos;
 
    // todo: never returns ???
    this.calibrationSubscription = this.calibrationService
      .updateCalibrationPoint(this.currentlyActiveStage, pos)
      .pipe(markViewForCheck(this.changeDetector))
      .subscribe(
        (result: HttpResponse<CalibrationTransform>) => {
          this.handleUpdatedCalibration(result);
        },
        (error: unknown) => {
          this.logService.sendErrorLog(`${error}`);
          console.error(error);
        }
      );
  }
 
  public display(idx: number): void {
    if (idx < 0) {
      this.currentlyActiveStage = -1;
      this.resetSelectedInteraction();
 
      return;
    }
 
    if (idx > 2) {
      return;
    }
 
    this.currentlyActiveStage = idx;
  }
 
  public resetCalibration(): void {
    this.calibrationService
      .restartCalibration()
      .pipe(markViewForCheck(this.changeDetector))
      .subscribe(
        (result) => {
          this.calibrationMatrix = result.transformation;
          this.resetTarget(0);
          this.resetTarget(1);
          this.resetTarget(2);
        },
        (error) => console.error(error)
      );
    this.currentlyActiveStage = -1;
    this.resetSelectedInteraction();
  }
 
  public applyCalibration(): void {
    this.calibrationService
      .applyCalibration()
      .pipe(markViewForCheck(this.changeDetector))
      .subscribe(
        (result) => {
          this.calibrationMatrix = result.transformation;
          console.log(`${result.transformation}`);
        },
        (error: unknown) => {
          this.logService.sendErrorLog(`${error}`);
          console.error(error);
        }
      );
    this.currentlyActiveStage = -1;
    this.resetSelectedInteraction();
  }
 
  public updateFrameSize(): void {
    const frame: FrameSizeDefinition = {
      width: this.borderOffset[3] - this.borderOffset[1],
      height: this.borderOffset[2] - this.borderOffset[0],
      left: this.borderOffset[1],
      top: this.borderOffset[0]
    };
 
    this.calibrationService
      .updateFrameSize(frame)
      .pipe(markViewForCheck(this.changeDetector))
      .subscribe(
        (result) => {
          Eif (result.body) {
            console.log(
              `received updated frame size - result:  ${result.status} - [${result.body.top} | ${result.body.left} | ${result.body.height} | ${result.body.width}]`
            );
            this.updateBorders(result.body);
          }
        },
        (error: unknown) => {
          this.logService.sendErrorLog(`${error}`);
          console.error(error);
        }
      );
  }
 
  public getCalibrationSourcePointStyle(index: number): object {
    return {
      transform: `translate(${this.calibrationSource[index].positionX}px, ${this.calibrationSource[index].positionY}px)`,
      visibility: `${
        this.currentlyActiveStage === index ? 'visible' : 'collapse'
      }`
    };
  }
 
  public getCalibrationTargetPointStyle(index: number): object {
    return {
      transform: `translate(${this.calibratedTargets[index].positionX}px, ${this.calibratedTargets[index].positionY}px)`,
      visibility: `${this.currentlyActiveStage >= 0 ? 'visible' : 'collapse'}`
    };
  }
 
  public getCalibratedInteractionPointStyle(
    type: InteractionType,
    position: Point3
  ): TransformString {
    const resultingPosition = position;
 
    const scale = ((resultingPosition.z * resultingPosition.z) + 0.5) * 2;
 
    return {
      transform: `translate(${resultingPosition.x}px, ${resultingPosition.y}px) scale(${scale}, ${scale})`
    };
  }
 
  public getBorderFill(): BorderString {
    return {
      top: `${this.borderOffset[0]}px`,
      left: `${this.borderOffset[1]}px`,
      height: `${this.borderOffset[2] - this.borderOffset[0]}px`,
      width: `${this.borderOffset[3] - this.borderOffset[1]}px`
    };
  }
 
  public saveCalibration(): void {
    this.calibrationService
      .saveCalibration()
      .pipe(markViewForCheck(this.changeDetector))
      .subscribe(
        (result) => {
          console.log(result);
        },
        (error: unknown) => {
          this.logService.sendErrorLog(`${error}`);
          console.error(error);
        }
      );
  }
 
  private getDefaultSelectedValues(): Array<Interaction> {
    return [
      this.getDefaultInteraction(),
      this.getDefaultInteraction(),
      this.getDefaultInteraction()
    ];
  }
 
  private getDefaultInteraction(): Interaction {
    return {
      touchId: -1,
      confidence: 0,
      position: { x: 0, y: 0, z: 0, isFiltered: true, isValid: false },
      type: 0,
      extremumDescription: {
        numFittingPoints: 0,
        percentageFittingPoints: 0,
        type: 0
      },
      time: 0
    };
  }
 
  private updateInteractions(interactions: CompleteInteractionData): void {
    if (!this.update) {
      return;
    }
 
    Iif (this.calibratedInteractionsSubscription !== undefined) {
      this.calibratedInteractionsSubscription.unsubscribe();
    }
 
    const maxItems = Math.min(interactions.raw.length, 3);
    const filtered = interactions.raw.slice(0, maxItems);
 
    this.interactions = filtered;
 
    this.calibratedInteractions = this.displayCalibratedInteractions
      ? interactions.absolute
      : filtered;
 
    if (this.currentlyActiveStage < 0 || this.currentlyActiveStage > 2) {
      this.resetSelectedInteraction();
    }
 
    // check if touch with current id has been set as target in another stage...
    const alreadySelectedIds = this.selectedValue
      .filter(
        (elem, idx) => elem.touchId >= 0 && idx !== this.currentlyActiveStage
      )
      .map((i) => i.touchId);
    if (
      this.interactions.length <= 0
      || alreadySelectedIds.find((id) => id === this.interactions[0].touchId)
        !== undefined
    ) {
      this.selectedValue[this.currentlyActiveStage]
        = this.getDefaultInteraction();
      this.selectedIdx = -1;
 
      return;
    }
 
    let restore: Interaction | undefined;
 
    // restore index of selected touch id
    if (this.selectedValue[this.currentlyActiveStage]?.touchId >= 0) {
      restore = this.interactions.find(
        (touch) =>
          touch.touchId
          === this.selectedValue[this.currentlyActiveStage]?.touchId
      );
    }
 
    if (restore !== undefined) {
      this.selectedIdx = this.interactions.indexOf(restore);
      this.selectedValue[this.currentlyActiveStage] = restore;
    } else {
      [this.selectedValue[this.currentlyActiveStage]] = this.interactions;
      this.selectedIdx = 0;
    }
 
    // auto save point with highest confidence if point with this touch id is not already used for calibration
    if (
      this.selectedValue[this.currentlyActiveStage].confidence
        >= this.maxConfidence
      && this.calibratedTargets.filter(
        (elem) =>
          elem.touchId
          === this.selectedValue[this.currentlyActiveStage]?.touchId
      ).length === 0
    ) {
      this.submit();
    }
  }
 
  private setBorders(borderValues: FrameSizeDefinition): void {
    this.borderOffset = [
      borderValues.top,
      borderValues.left,
      borderValues.top + borderValues.height,
      borderValues.left + borderValues.width
    ];
  }
 
  private updateSourceValues(): void {
    this.calibrationService
      .getCalibrationSourcePoints()
      .pipe(markViewForCheck(this.changeDetector))
      .subscribe(
        (result) => {
          this.calibrationSource = result;
        },
        (error: unknown) => {
          this.logService.sendErrorLog(`${error}`);
          console.error(error);
        }
      );
  }
 
  private updateTargetPoints(): void {
    this.calibrationService
      .getCurrentCalibrationTargetPoints()
      .pipe(markViewForCheck(this.changeDetector))
      .subscribe(
        (result) => {
          this.calibratedTargets = result;
        },
        (error: unknown) => {
          this.logService.sendErrorLog(`${error}`);
          console.error(error);
        }
      );
  }
 
  private updateBorders(borderValues: FrameSizeDefinition): void {
    this.setBorders(borderValues);
    this.updateSourceValues();
  }
 
  private handleUpdatedCalibration(
    result: HttpResponse<CalibrationTransform>
  ): void {
    const trans = result.body as CalibrationTransform;
    if (trans !== undefined) {
      this.calibrationMatrix = trans.transformation;
      if (this.currentlyActiveStage < 2 && this.currentlyActiveStage >= 0) {
        this.currentlyActiveStage += 1;
        this.selectedValue[this.currentlyActiveStage]
          = this.getDefaultInteraction();
      } else {
        this.currentlyActiveStage = -1;
        this.selectedValue = this.getDefaultSelectedValues();
      }
    } else E{
      this.resetTarget(this.currentlyActiveStage);
    }
  }
 
  private updateCalibrationValues(calibration: Calibration): void {
    this.currentCalibration = calibration;
  }
 
  private resetTarget(idx: number): void {
    this.calibratedTargets[idx] = { positionX: 0, positionY: 0, touchId: -1 };
  }
}