All files / src/components/VirtualWalkthrough TfAnnotationManager.ts

0% Statements 0/156
0% Branches 0/73
0% Functions 0/28
0% Lines 0/155

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
 
import { FILTER_LINEAR, PIXELFORMAT_RGBA8, Texture, Vec3 } from 'playcanvas';
import { AnnotationManager as PcAnnotationManager } from 'playcanvas/scripts/esm/annotations.mjs';
 
import Icon from '../Icon/Icon';
import { IconName } from '../Icon/icons';
import { AnnotationIconType } from './Annotation';
 
// Maps each annotation icon type to a @terraware/web-components icon.
const ANNOTATION_ICONS: Record<AnnotationIconType, IconName> = {
  text: 'iconComment',
  image: 'iconPhoto',
  video: 'iconVideo',
};
 
// Pixel dimensions of the (square) hotspot texture canvas at rest.
const HOTSPOT_TEXTURE_SIZE = 64;
 
// How much larger the hotspot appears while hovered.
const HOTSPOT_HOVER_SCALE = 1.3;
 
/**
 * Extended AnnotationManager that adds max size clamping for annotations
 * and fixes positioning when canvas is not at document origin.
 */
export class TfAnnotationManager extends PcAnnotationManager {
  static scriptName = 'tfAnnotationManager';
 
  private _maxWorldSize = 1.0;
  private _scratchScale = new Vec3();
  private _customParentDom: HTMLElement | null = null;
  private _clickHandlersAttached = new Set<any>();
  private _hotspotBackgroundColor = '#2C8658';
  private _iconImages = new Map<AnnotationIconType, HTMLImageElement>();
 
  /**
   * Maximum world-space size for annotations.
   * This prevents annotations from growing beyond this size regardless of camera distance.
   *
   * @attribute
   * @title Max World Size
   * @type {number}
   * @default 1.0
   */
  set maxWorldSize(value: number) {
    this._maxWorldSize = value;
  }
 
  get maxWorldSize() {
    return this._maxWorldSize;
  }
 
  /**
   * Background color for the hotspot texture canvas (the circle fill color).
   * This is a hex color string (e.g., '#2C8658') that's drawn on the texture canvas.
   * Note: This is different from hotspotColor and hoverColor, which are PlayCanvas Color objects
   * used for the material's emissive property.
   *
   * @attribute
   * @title Hotspot Background Color
   * @type {string}
   * @default '#2C8658'
   */
  set hotspotBackgroundColor(value: string) {
    this._hotspotBackgroundColor = value;
  }
 
  get hotspotBackgroundColor() {
    return this._hotspotBackgroundColor;
  }
 
  /**
   * Initialize with custom parent DOM if needed.
   */
  initialize() {
    // Find a container div with data-annotation-container attribute
    const canvas = this.app.graphicsDevice.canvas;
    const container = canvas.parentElement?.querySelector('[data-annotation-container]') as HTMLElement;
 
    if (container) {
      this._customParentDom = container;
      (this as any)._parentDom = container;
    }
 
    // Call parent initialize
    super.initialize();
 
    this._loadIconImages();
  }
 
  /**
   * Renders each web-components icon to an SVG image once. When an image finishes
   * loading, any annotations already using that icon are redrawn.
   * @private
   */
  _loadIconImages() {
    const fillColor = (this as any)._hotspotColor?.toString() ?? '#ffffff';
 
    (Object.keys(ANNOTATION_ICONS) as AnnotationIconType[]).forEach((iconType) => {
      const name = ANNOTATION_ICONS[iconType];
      const markup = renderToStaticMarkup(createElement(Icon, { name, fillColor })).replace(
        /^<svg/,
        '<svg width="128" height="128"'
      );
 
      const image = new Image();
      image.onload = () => this._refreshIcon(iconType);
      image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(markup)}`;
      this._iconImages.set(iconType, image);
    });
  }
 
  /**
   * Redraws the texture for all annotations using the given icon, once its image
   * has loaded.
   * @private
   */
  _refreshIcon(iconType: AnnotationIconType) {
    const annotationResources = (this as any)._annotationResources;
    if (!annotationResources) {
      return;
    }
 
    annotationResources.forEach((_resources: any, annotation: any) => {
      if ((annotation.icon ?? 'text') === iconType) {
        this._applyAnnotationIcon(annotation);
      }
    });
  }
 
  /**
   * Update loop to attach click handlers to annotations and manage visibility.
   */
  update() {
    const annotationResources = (this as any)._annotationResources;
    if (!annotationResources) {
      return;
    }
 
    // Attach click handlers and manage visibility for all annotations
    annotationResources.forEach((resources: any, annotation: any) => {
      if (resources && resources.hotspotDom) {
        // Attach click handler if not already attached
        if (!this._clickHandlersAttached.has(annotation)) {
          const callback = annotation.onClickCallback;
 
          if (callback) {
            this._clickHandlersAttached.add(annotation);
 
            resources.hotspotDom.addEventListener('pointerdown', (e: PointerEvent) => {
              callback(e.clientX, e.clientY);
            });
          }
        }
 
        // Disable/enable the entity itself based on visibility
        const isVisible = annotation.enabled !== undefined ? annotation.enabled : true;
 
        // Hide tooltip if the active annotation is hidden
        if ((this as any)._activeAnnotation === annotation && !isVisible) {
          (this as any)._tooltipDom.style.visibility = 'hidden';
          (this as any)._tooltipDom.style.opacity = '0';
          (this as any)._activeAnnotation = null;
        }
      }
    });
  }
 
  /**
   * Override annotation registration to draw the media icon onto the hotspot
   * texture once the annotation (and its icon) is available.
   * @private
   */
  _registerAnnotation(annotation: any) {
    super._registerAnnotation(annotation);
    this._applyAnnotationIcon(annotation);
 
    // Keep the hotspot mesh hidden until the first scale pass clamps it. The annotation entity
    // starts at unit local scale, so under a scaled content-root the plane would render many world
    // units across for the frames before _updateAnnotationRotationAndScale runs.
    const resources = (this as any)._annotationResources.get(annotation);
    if (resources) {
      resources.baseEntity.enabled = false;
      resources.overlayEntity.enabled = false;
    }
  }
 
  /**
   * Recreates the hotspot texture with the appropriate media icon drawn on it.
   * @private
   */
  _applyAnnotationIcon(annotation: any) {
    const resources = (this as any)._annotationResources.get(annotation);
    if (!resources) {
      return;
    }
 
    const icon: AnnotationIconType = annotation.icon ?? 'text';
 
    resources.texture.destroy();
    resources.texture = this._createHotspotTexture(annotation.label, HOTSPOT_TEXTURE_SIZE, 6, icon);
    resources.materials.forEach((material: any) => {
      material.emissiveMap = resources.texture;
      material.opacityMap = resources.texture;
      material.update();
    });
  }
 
  /**
   * Draws the icon image onto the hotspot texture canvas, scaled to fit the
   * circle. Does nothing if the image has not finished loading yet; the
   * annotation is redrawn once it has (see `_refreshIcon`).
   * @private
   */
  _drawIcon(ctx: CanvasRenderingContext2D, icon: AnnotationIconType, size: number) {
    const image = this._iconImages.get(icon);
    if (!image || !image.complete || image.naturalWidth === 0) {
      return;
    }
 
    const iconSize = size * 0.5;
    const offset = (size - iconSize) / 2;
    ctx.drawImage(image, offset, offset, iconSize, iconSize);
  }
 
  /**
   * Keep the media icon drawn on the hotspot texture. The label text itself
   * is not rendered on the hotspot, so we simply redraw with the icon.
   * @private
   */
  _onLabelChange(annotation: any) {
    this._applyAnnotationIcon(annotation);
  }
 
  /**
   * The hotspot colors are baked into the texture in `_createHotspotTexture`,
   * so the material emissive is kept white to let those colors render as drawn.
   * @private
   */
  _createHotspotMaterial(texture: any, options?: any) {
    const material = super._createHotspotMaterial(texture, options);
    material.emissive.set(1, 1, 1);
    material.update();
 
    return material;
  }
 
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  _setAnnotationHover(_annotation: any, _hover: boolean) {
    // No-op: the hover growth is handled in _updateAnnotationRotationAndScale
    // (via _hoverAnnotation); the texture is identical in both states.
  }
 
  _updateAllAnnotationColors() {
    // No-op: hotspot colors are baked into the texture (see _createHotspotMaterial).
  }
 
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  _showTooltip(_annotation: any) {
    // No-op: AnnotationPanel handles all annotation UI, this removes default behavior
  }
 
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  _onTextChange(_annotation: any, _text: string) {
    // No-op: AnnotationPanel handles all annotation UI, this removes default behavior
  }
 
  /**
   * Override position update to adjust for canvas offset and respect visibility.
   * @private
   */
  _updateAnnotationPositions(annotation: any, resources: any, screenPos: any) {
    const canvas = this.app.graphicsDevice.canvas;
    const rect = canvas.getBoundingClientRect();
 
    // If using a custom parent (positioned container), use raw screen coordinates
    // Otherwise, adjust for canvas position in document
    const offsetX = this._customParentDom ? 0 : rect.left + window.scrollX;
    const offsetY = this._customParentDom ? 0 : rect.top + window.scrollY;
 
    // Check if annotation is visible (defaults to true if not specified)
    const isVisible = annotation.enabled !== undefined ? annotation.enabled : true;
    resources.hotspotDom.style.display = isVisible ? 'block' : 'none';
    resources.hotspotDom.style.left = `${screenPos.x + offsetX}px`;
    resources.hotspotDom.style.top = `${screenPos.y + offsetY}px`;
 
    if ((this as any)._activeAnnotation === annotation) {
      (this as any)._tooltipDom.style.display = isVisible ? 'block' : 'none';
      (this as any)._tooltipDom.style.left = `${screenPos.x + offsetX}px`;
      (this as any)._tooltipDom.style.top = `${screenPos.y + offsetY}px`;
    }
 
    if (annotation.onScreenPositionUpdateCallback) {
      // Rendered hotspot diameter (px), set by _updateAnnotationRotationAndScale.
      // Parsed from the style rather than measured to avoid forcing a reflow.
      const hotspotSize = parseFloat(resources.hotspotDom.style.width) || undefined;
      annotation.onScreenPositionUpdateCallback(screenPos.x + offsetX, screenPos.y + offsetY, hotspotSize);
    }
  }
 
  /**
   * Override to also disable the hotspot mesh (not just the DOM) when the annotation is behind the
   * camera. The base implementation leaves the mesh enabled, so a not-yet-scaled plane under a
   * scaled content-root would stay huge in view until the camera moves the anchor in front.
   * @private
   */
  _hideAnnotationElements(annotation: any, resources: any) {
    super._hideAnnotationElements(annotation, resources);
    resources.baseEntity.enabled = false;
    resources.overlayEntity.enabled = false;
  }
 
  /**
   * Override the scale update to clamp the world size to a maximum value.
   * Also scales the hotspot DOM element to match.
   * @private
   */
  _updateAnnotationRotationAndScale(annotation: any) {
    const cameraRotation = (this as any)._camera.getRotation();
    annotation.entity.setRotation(cameraRotation);
    annotation.entity.rotateLocal(90, 0, 0);
 
    const cameraPos = (this as any)._camera.getPosition();
    const distance = annotation.entity.getPosition().distance(cameraPos);
    const canvas = (this as any).app.graphicsDevice.canvas;
    const screenHeight = canvas.clientHeight;
    const projMatrix = (this as any)._camera.camera.projectionMatrix;
 
    // The world size that projects to _hotspotSize screen pixels at this distance.
    const targetWorldSize = ((this as any)._hotspotSize / screenHeight) * ((2 * distance) / projMatrix.data[5]);
 
    // setLocalScale is applied on top of the parent's world scale (e.g. a scaled
    // content-root), so divide it out to keep the on-screen size independent of it.
    const parentScale = this._getParentWorldScale(annotation.entity);
    const unclampedScale = targetWorldSize / parentScale;
 
    // Clamp in the annotation's own (parent-local) space so maxWorldSize keeps the
    // same size relative to the model regardless of the content-root scale.
    const clampedScale = Math.min(unclampedScale, this._maxWorldSize);
 
    const hovered = (this as any)._hoverAnnotation === annotation;
    const hoverScale = hovered ? HOTSPOT_HOVER_SCALE : 1;
    const entityScale = clampedScale * hoverScale;
 
    annotation.entity.setLocalScale(entityScale, entityScale, entityScale);
 
    // Scale the hotspot DOM element proportionally when clamped, including the
    // hover growth so it tracks the visible circle. This is a pure screen-space
    // size, so it uses the true _hotspotSize and the clamp ratio only (never the
    // parent scale, which the DOM overlay does not inherit).
    const resources = (this as any)._annotationResources.get(annotation);
    if (resources) {
      // This branch only runs for annotations in front of the camera, and the scale above is now
      // clamped, so it is safe to reveal the mesh (hidden on register / when behind the camera).
      resources.baseEntity.enabled = true;
      resources.overlayEntity.enabled = true;
    }
    if (resources && resources.hotspotDom) {
      const clampRatio = clampedScale / unclampedScale;
      const baseSize = (this as any)._hotspotSize + 5; // Match the +5 from the stylesheet
      const scaledSize = baseSize * clampRatio * hoverScale;
      resources.hotspotDom.style.width = `${scaledSize}px`;
      resources.hotspotDom.style.height = `${scaledSize}px`;
    }
  }
 
  /**
   * World-space uniform scale of the annotation entity's parent (e.g. a scaled
   * content-root). Returns 1 when there is no parent or it has no scale.
   * @private
   */
  _getParentWorldScale(entity: any) {
    const parent = entity.parent;
    if (!parent) {
      return 1;
    }
    parent.getWorldTransform().getScale(this._scratchScale);
 
    return this._scratchScale.x || 1;
  }
 
  /**
   * Override to create hotspot texture with custom background color.
   * @private
   */
  _createHotspotTexture(label: string, size = HOTSPOT_TEXTURE_SIZE, borderWidth = 6, icon?: AnnotationIconType) {
    const canvas = document.createElement('canvas');
    canvas.width = size;
    canvas.height = size;
    const ctx = canvas.getContext('2d');
 
    if (!ctx) {
      throw new Error('Failed to get canvas 2d context');
    }
 
    // First clear with stroke color at zero alpha
    ctx.fillStyle = 'white';
    ctx.globalAlpha = 0;
    ctx.fillRect(0, 0, size, size);
    ctx.globalAlpha = 1.0;
 
    // Draw circle with custom background color
    const centerX = size / 2;
    const centerY = size / 2;
    const radius = size / 2 - 4;
 
    // The icon fill and border share the hotspot color
    const foregroundColor = (this as any)._hotspotColor?.toString() ?? '#ffffff';
 
    // Draw main circle
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
    ctx.fillStyle = this._hotspotBackgroundColor;
    ctx.fill();
 
    // Draw border
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
    ctx.lineWidth = borderWidth;
    ctx.strokeStyle = foregroundColor;
    ctx.stroke();
 
    // Draw the media icon inside the circle
    if (icon) {
      this._drawIcon(ctx, icon, size);
    }
 
    // Get pixel data
    const imageData = ctx.getImageData(0, 0, size, size);
    const data = imageData.data;
 
    // Create and return the texture
    return new Texture(this.app.graphicsDevice, {
      width: size,
      height: size,
      format: PIXELFORMAT_RGBA8,
      magFilter: FILTER_LINEAR,
      minFilter: FILTER_LINEAR,
      mipmaps: false,
      levels: [new Uint8Array(data.buffer)],
    });
  }
}