Label.tstypescript
import {
  SpriteAlignment,
  Texture,
  SpriteMaterial,
  Sprite,
  Material,
} from "./WebGL";
import { Gradient } from "./Gradient";
import type { GradientSpec, GradientType } from "./Gradient";
import { Color, CC, ColorSpec } from "./colors";
import {XYZ} from "./WebGL/math"

// Adapted from the text sprite example from http://stemkoski.github.io/Three.js/index.html

export let LabelCount = 0;

// Function for drawing rounded rectangles - for Label drawing
function roundRect(ctx: CanvasRenderingContext2D, x: any, y: any, w: number, h: number, r: number, drawBorder: boolean) {
  ctx.beginPath();
  ctx.moveTo(x + r, y);
  ctx.lineTo(x + w - r, y);
  ctx.quadraticCurveTo(x + w, y, x + w, y + r);
  ctx.lineTo(x + w, y + h - r);
  ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
  ctx.lineTo(x + r, y + h);
  ctx.quadraticCurveTo(x, y + h, x, y + h - r);
  ctx.lineTo(x, y + r);
  ctx.quadraticCurveTo(x, y, x + r, y);
  ctx.closePath();
  ctx.fill();
  if (drawBorder) ctx.stroke();
}

//do all the checks to figure out what color is desired
function getColor(style: any, stylealpha?: any, init?: any) {
  var ret = init;
  if (typeof style != "undefined") {
    //convet regular colors
    if (style instanceof Color) ret = style.scaled();
    else {
      //hex or name
      ret = CC.color(style);
      if (typeof ret.scaled != "undefined") {
        ret = ret.scaled(); //not already scaled to 255
      }
    }
  }
  if (typeof stylealpha != "undefined") {
    ret.a = parseFloat(stylealpha);
  }
  return ret;
}

/** Text label appearance and placement. Pixel sizes are logical display pixels;
 * resolution increases texture detail without changing the displayed size.
 * Create labels with GLViewer.addLabel and update them with GLViewer.setLabelStyle.
 * @example <caption>Screen and world anchors with different texture resolutions</caption>
 * viewer.addModel().addAtoms([
 *   {elem: "C", x: -2, y: 0, z: 0}, {elem: "O", x: 2, y: 0, z: 0}
 * ]);
 * viewer.setStyle({}, {sphere: {radius: 0.7}});
 * // The two world labels follow the model when the view rotates.
 * [1, 3].forEach(function(resolution, i) {
 *   viewer.addLabel("world: " + resolution + "x", {
 *     position: {x: -2 + i * 4, y: -1.1, z: 0}, alignment: "topCenter",
 *     fontSize: 16, resolution: resolution, backgroundColor: "navy"
 *   });
 *   // Higher texture resolution sharpens text without enlarging the label.
 *   viewer.addLabel("screen: " + resolution + "x", {
 *     position: {x: 16, y: 16 + i * 34, z: 0}, useScreen: true,
 *     fontSize: 16, resolution: resolution, backgroundColor: "darkgreen"
 *   });
 * });
 * viewer.zoomTo();
 * viewer.rotate(25, "z");
 * viewer.render();
 */
export interface LabelSpec {
/** font name, default sans-serif */
  font?: string;
  /** font size in pixels, default 18 */
  fontSize?: number;
  /** Texture pixels per label pixel (default 2). Must be a finite number at least 1; invalid values use 2. Larger values increase texture memory. */
  resolution?: number;
  /** render text in bold, default false */
  bold?: boolean;
  /** padding around text in pixels; defaults to 4 when omitted or zero */
  padding?: number;
  /** font color, default white */
  fontColor?: ColorSpec;
  /** font opacity, default 1 */
  fontOpacity?: number;
  /** line width of border around label, default 0  */
  borderThickness?: number;
  /** color of border, default backgroundColor */
  borderColor?: ColorSpec;
  /** Border opacity; defaults to the background opacity. */
  borderOpacity?: number;
  /** color of background, default black */
  backgroundColor?: ColorSpec;
  /** left-to-right background gradient, used instead of backgroundColor */
  backgroundGradient?: GradientSpec | GradientType;
  /** opacity of background, default 1.0 */
  backgroundOpacity?: number;
  /** Label anchor in world coordinates (angstroms), or screen pixels when useScreen is true. GLViewer.addLabel can also position a label at the center of a selection. */
  position?: XYZ;
  /** x,y pixel offset of label from position */
  screenOffset?: { x: number; y: number };
  /** always put labels in front of model, default true */
  inFront?: boolean;
  /** show background rounded rectangle, default true */
  showBackground?: boolean;
  /** position uses screen coordinates: x and y are pixel offsets from the upper left corner; z is clamped to [0,1] */
  useScreen?: boolean;
  /** An image to draw into the label. Any CanvasImageSource is allowed. The label expands to fit the image. */
  backgroundImage?: any;
  /** minimum label width in pixels when backgroundImage is set; omitted or zero uses the image width */
  backgroundWidth?: number;
  /** minimum label height in pixels when backgroundImage is set; omitted or zero uses the image height */
  backgroundHeight?: number;
  /** how to orient the label w/respect to position: "topLeft" (default),
   * "topCenter", "topRight", "centerLeft", "center", "centerRight",
   * "bottomLeft", "bottomCenter", "bottomRight", or an arbitrary x,y alignment vector */
  alignment?: string | { x: number; y: number };
  /** If set, display only when the viewer is on this zero-based animation frame. */
  frame?: number;
}

/**
 * A text label and its rendering resources. Normally created with GLViewer.addLabel.
 * Remove it with GLViewer.removeLabel so the viewer also releases its resources.
 * @constructor $3Dmol.Label
 * @param {string} text - Label text
 * @param {LabelSpec} parameters Label style and font specifications
 */
export class Label {
  id: number;
  stylespec: any;
  canvas: HTMLCanvasElement;
  context: any;
  sprite: Sprite;
  text: any;
  frame: any;
  constructor(text: string, parameters: LabelSpec) {
    this.id = LabelCount++;
    this.stylespec = parameters || {};

    this.canvas = document.createElement("canvas");
    //todo: implement resizing canvas..
    this.canvas.width = 134;
    this.canvas.height = 35;
    this.context = this.canvas.getContext("2d");
    this.sprite = new Sprite();
    this.text = text;
    this.frame = this.stylespec.frame;
  }

  /** Return the current style object by reference. Use GLViewer.setLabelStyle to
   * apply changes and rebuild the label texture. */
  getStyle() {
    return this.stylespec;
  }

  /** Hide this label. Call viewer.render() to refresh the displayed scene. */
  public hide() {
    if(this.sprite) {
      this.sprite.visible = false;
    }
  }

  /** Show a hidden label. Call viewer.render() to refresh the displayed scene. */
  public show() {
    if(this.sprite) {
      this.sprite.visible = true;
    }
  }

  setContext() {
    var style = this.stylespec;
    const resolution = Number.isFinite(style.resolution) && style.resolution >= 1
      ? style.resolution : 2;
    var useScreen =
      typeof style.useScreen == "undefined" ? false : style.useScreen;

    var showBackground = style.showBackground;
    if (showBackground === "0" || showBackground === "false")
      showBackground = false;
    if (typeof showBackground == "undefined") showBackground = true; //default
    var font = style.font ? style.font : "sans-serif";

    var fontSize = parseInt(style.fontSize) ? parseInt(style.fontSize) : 18;

    var fontColor = getColor(style.fontColor, style.fontOpacity, {
      r: 255,
      g: 255,
      b: 255,
      a: 1.0,
    });

    var padding = style.padding ? style.padding : 4;
    var borderThickness = style.borderThickness ? style.borderThickness : 0;

    var backgroundColor = getColor(
      style.backgroundColor,
      style.backgroundOpacity,
      {
        r: 0,
        g: 0,
        b: 0,
        a: 1.0,
      }
    );

    var borderColor = getColor(
      style.borderColor,
      style.borderOpacity,
      backgroundColor
    );

    var position = style.position
      ? style.position
      : {
        x: -10,
        y: 1,
        z: 1,
      };

    // Should labels always be in front of model?
    var inFront = style.inFront !== undefined ? style.inFront : true;
    if (inFront === "false" || inFront === "0") inFront = false;

    // clear canvas

    var spriteAlignment = style.alignment || SpriteAlignment.topLeft;
    if (
      typeof spriteAlignment == "string" &&
      spriteAlignment in SpriteAlignment
    ) {
      spriteAlignment = (SpriteAlignment as any)[spriteAlignment] ;
    }

    var bold = "";
    if (style.bold) bold = "bold ";
    this.context.font = bold + fontSize + "px  " + font;

    var metrics = this.context.measureText(this.text);
    var textWidth = metrics.width;

    if (!showBackground) borderThickness = 0;

    var width = textWidth + 2.5 * borderThickness + 2 * padding;
    var height = fontSize * 1.25 + 2 * borderThickness + 2 * padding; // 1.25 is extra height factor for text below baseline: g,j,p,q.

    if (style.backgroundImage) {
      //resize label to image
      var img = style.backgroundImage;
      var w = style.backgroundWidth ? style.backgroundWidth : img.width;
      var h = style.backgroundHeight ? style.backgroundHeight : img.height;
      if (w > width) width = w;
      if (h > height) height = h;
    }

    // Keep the existing integer display size while rasterizing more texture pixels.
    const logicalWidth = Math.floor(width);
    const logicalHeight = Math.floor(height);
    this.canvas.width = Math.ceil(logicalWidth * resolution);
    this.canvas.height = Math.ceil(logicalHeight * resolution);
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    this.context.setTransform(
      logicalWidth > 0 ? this.canvas.width / logicalWidth : 1, 0,
      0, logicalHeight > 0 ? this.canvas.height / logicalHeight : 1, 0, 0
    );

    bold = "";
    if (style.bold) bold = "bold ";
    this.context.font = bold + fontSize + "px  " + font;

    // background color
    this.context.fillStyle =
      "rgba(" +
      backgroundColor.r +
      "," +
      backgroundColor.g +
      "," +
      backgroundColor.b +
      "," +
      backgroundColor.a +
      ")";
    // border color
    this.context.strokeStyle =
      "rgba(" +
      borderColor.r +
      "," +
      borderColor.g +
      "," +
      borderColor.b +
      "," +
      borderColor.a +
      ")";

    if (style.backgroundGradient) {
      let gradient = this.context.createLinearGradient(
        0,
        height / 2,
        width,
        height / 2
      );
      let g = Gradient.getGradient(style.backgroundGradient);
      let minmax = g.range();
      let min = -1;
      let max = 1;
      if (minmax) {
        min = minmax[0];
        max = minmax[1];
      }
      let d = max - min;
      for (let i = 0; i < 1.01; i += 0.1) {
        let c = getColor(g.valueToHex(min + d * i));
        let cname = "rgba(" + c.r + "," + c.g + "," + c.b + "," + c.a + ")";
        gradient.addColorStop(i, cname);
      }
      this.context.fillStyle = gradient;
    }

    this.context.lineWidth = borderThickness;
    if (showBackground) {
      roundRect(
        this.context,
        borderThickness,
        borderThickness,
        width - 2 * borderThickness,
        height - 2 * borderThickness,
        6,
        borderThickness > 0
      );
    }

    if (style.backgroundImage) {
      this.context.drawImage(img, 0, 0, width, height);
    }

    // text color
    this.context.fillStyle =
      "rgba(" +
      fontColor.r +
      "," +
      fontColor.g +
      "," +
      fontColor.b +
      "," +
      fontColor.a +
      ")";

    this.context.fillText(
      this.text,
      borderThickness + padding,
      fontSize + borderThickness + padding,
      textWidth
    );

    // canvas contents will be used for a texture
    var texture = new Texture(this.canvas);
    texture.logicalWidth = logicalWidth;
    texture.logicalHeight = logicalHeight;
    texture.needsUpdate = true;
    this.sprite.material = new SpriteMaterial({
      map: texture,
      useScreenCoordinates: useScreen,
      alignment: spriteAlignment,
      depthTest: !inFront,
      screenOffset: style.screenOffset || null,
    }) as Material;

    this.sprite.scale.set(1, 1, 1);

    this.sprite.position.set(position.x, position.y, position.z);
  }

  // clean up material and texture
  dispose() {
    if (this.sprite.material.map !== undefined)
      this.sprite.material.map.dispose();
    if (this.sprite.material !== undefined) this.sprite.material.dispose();
  }
}