All files TraceMatrix.ts

97.15% Statements 171/176
94% Branches 47/50
100% Functions 29/29
96.81% Lines 152/157

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 26511x 11x 11x 11x   11x 11x 11x         11x         178874x 9653x   169221x     11x 16240x     16240x 16240x     11x   7x       7x 7x 9840x 9840x 2460x   7380x   7x 7x 238x 8844x 1180x 1180x 1180x 1180x 1180x 1180x 1180x 1180x 1180x             7x 11x 7x 11x 11x 6x   7x 11x 11x 5x   11x               11x   16240x       7x 17x 17x 17x 17x 25840x 17x 17x 5360x 5360x 16080x 48240x 48240x       5343x 5343x       5360x     17x       1405x 1405x 1405x 1549x 7377x 1388x 1388x 1388x 1388x   5989x 1405x               28x 28x 28x 1080x 42080x 9648x       28x     7x 12x 12x     12x 12x 12x 12x 12x 12x 12x 5x 5x 1388x   5x 5x 5x 5x 5x   17x     7x 17x                     6194x 2549x   17x       17x 17x 17x   17x   17x   1215x 3764x 3764x 3764x 1215x   2549x   1215x 155x 155x   1215x 1215x     17x 16x   1x     7x 11x             11x 11x 16240x 11x 11x 420x 420x   11x 412x 412x   11x 12544x 12544x 50176x 50176x 50176x 10880x 10880x         11x 11x     9840x 53x 78000x      
import {DPoint} from './DPoint';
import {DPolygon, MIN_POINTS_IN_VALID_POLYGON} from './DPolygon';
import {FastSearch} from './FastSearch';
import {createArray} from './utils';
 
export enum TraceMatrixValues {
  f = 0,
  t = 1
}
 
export type SimpleMatrix = TraceMatrixValues[][];
 
const getByPosition = (
  m: SimpleMatrix,
  p: DPoint,
  defaultValue: TraceMatrixValues = TraceMatrixValues.f
): TraceMatrixValues => {
  if (m[p.y] === undefined || m[p.y][p.x] === undefined) {
    return defaultValue;
  }
  return m[p.y][p.x];
};
 
const setByPosition = (m: SimpleMatrix, p: DPoint, value: TraceMatrixValues): TraceMatrixValues => {
  Iif (m[p.y] === undefined || m[p.y][p.x] === undefined) {
    return value;
  }
  m[p.y][p.x] = value;
  return m[p.y][p.x];
};
 
export class TraceMatrix {
  private readonly m: SimpleMatrix;
  public approximation: boolean = true;
  private readonly size: DPoint;
 
  constructor(s: DPoint, f: (p: DPoint) => TraceMatrixValues) {
    this.size = s.clone().scale(4);
    const t = TraceMatrix.createMatrix(this.size, (p) => {
      const {x, y} = p.clone().mod(4);
      if ([1, 2].includes(x) && [1, 2].includes(y)) {
        return f(p.clone().div(4));
      }
      return TraceMatrixValues.f;
    });
    this.m = TraceMatrix.createMatrix(this.size);
    for (let i = 1; i < this.size.y - 1; i++) {
      for (let j = 1; j < this.size.x - 1; j++) {
        if (t[i][j] === TraceMatrixValues.t) {
          this.m[i - 1][j - 1] = TraceMatrixValues.t;
          this.m[i - 1][j] = TraceMatrixValues.t;
          this.m[i - 1][j + 1] = TraceMatrixValues.t;
          this.m[i][j - 1] = TraceMatrixValues.t;
          this.m[i][j] = TraceMatrixValues.t;
          this.m[i][j + 1] = TraceMatrixValues.t;
          this.m[i + 1][j - 1] = TraceMatrixValues.t;
          this.m[i + 1][j] = TraceMatrixValues.t;
          this.m[i + 1][j + 1] = TraceMatrixValues.t;
        }
      }
    }
  }
 
  fullMatrixTrace(): DPolygon[] {
    const groups = this.findAllGroupsInMatrix(this.m);
    const paths = groups.map((g: DPolygon) => this.traceGroup(this.m, g));
    const holeMatrixs = groups.map(this.createHoleMatrix);
    const holesGroups = holeMatrixs.map((m: SimpleMatrix | null) => m && this.findAllGroupsInMatrix(m));
    const holesPaths = holesGroups.map((hg: DPolygon[] | null, index: number) => hg && hg.map((g: DPolygon) => this
      .traceGroup(holeMatrixs[index]!, g)).filter((r: DPolygon) => r.length > MIN_POINTS_IN_VALID_POLYGON));
 
    return groups.map((g: DPolygon, index: number) => {
      const res = paths[index];
      if (holesGroups[index] && holesGroups[index]!.length) {
        res.holes = holesPaths[index]!;
      }
      return res.loop()
        .divide(4)
        .round()
        .run();
    });
  }
 
  private reverseMatrix(m: SimpleMatrix): SimpleMatrix {
    return TraceMatrix.createMatrix(
      this.size,
      (p: DPoint) => getByPosition(m, p) === TraceMatrixValues.f ? TraceMatrixValues.t : TraceMatrixValues.f
    );
  }
 
  private findGroupByIndex = (m: SimpleMatrix, s: DPoint): DPolygon => {
    const res: DPolygon = new DPolygon();
    if (s && getByPosition(m, s) === TraceMatrixValues.t) {
      res.push(s);
      let startIndex = 0;
      const marked = TraceMatrix.createMatrix(this.size, () => TraceMatrixValues.f);
      setByPosition(marked, s, TraceMatrixValues.t);
      while (startIndex < res.length) {
        const r = res.at(startIndex);
        for (let i = -1; i < 2; i++) {
          for (let j = -1; j < 2; j++) {
            const t = new DPoint(r.x + i, r.y + j);
            if (
              getByPosition(marked, t, TraceMatrixValues.t) === TraceMatrixValues.f &&
              getByPosition(m, t, TraceMatrixValues.f) === TraceMatrixValues.t
            ) {
              res.push(t);
              setByPosition(marked, t, TraceMatrixValues.t);
            }
          }
        }
        startIndex++;
      }
    }
    return res;
  };
 
  private findMarked(m: SimpleMatrix, init?: DPoint): DPoint | null {
    const s = this.size;
    let ini = false;
    for (let i = 0; i < s.w; i++) {
      for (let j = 0; j < s.h; j++) {
        if (!ini && init) {
          i = init.x;
          j = init.y;
          ini = true;
          continue;
        }
        if (getByPosition(m, new DPoint(i, j)) === TraceMatrixValues.t) {
          return new DPoint(i, j);
        }
      }
    }
    return null;
  }
 
  private totalCountInMatrix(m: SimpleMatrix) {
    let res = 0;
    const s = this.size;
    for (let i = 0; i < s.w; i++) {
      for (let j = 0; j < s.h; j++) {
        if (getByPosition(m, new DPoint(i, j))) {
          res++;
        }
      }
    }
    return res;
  }
 
  private findAllGroupsInMatrix = (m: SimpleMatrix): DPolygon[] => {
    const firstMark = this.findMarked(m);
    Iif (!firstMark) {
      return [];
    }
    const group = this.findGroupByIndex(m, firstMark);
    const groups = [group];
    let groupSum = group.length;
    let allGroups = [...group.points];
    const fs = new FastSearch();
    fs.add(allGroups);
    while (groupSum < this.totalCountInMatrix(m)) {
      let mark = this.findMarked(m);
      while (mark && fs.find(mark)) {
        mark = this.findMarked(m, mark);
      }
      const nextGroup = this.findGroupByIndex(m, mark!);
      groupSum += nextGroup.length;
      allGroups = [...allGroups, ...nextGroup.points];
      fs.add(nextGroup.points);
      groups.push(nextGroup);
    }
    return groups.filter((g: DPolygon) => g.length > 2);
  };
 
  private traceGroup = (m: SimpleMatrix, group: DPolygon): DPolygon => {
    const traceDirections = [
      new DPoint(-1, -1),
      new DPoint(-1, 0),
      new DPoint(-1, 1),
      new DPoint(0, 1),
      new DPoint(1, 1),
      new DPoint(1, 0),
      new DPoint(1, -1),
      new DPoint(0, -1)
    ];
 
    const left = (d: number) => (d + traceDirections.length + 1) % traceDirections.length;
    const right = (d: number) => (d + traceDirections.length - 1) % traceDirections.length;
 
    Iif (group.length < 2) {
      const t = group.at(0).clone();
      return new DPolygon([t, t, t]);
    }
    const points: DPolygon = new DPolygon();
    let direction = 0;
    let prevDirection = Infinity;
 
    let p = group.at(0);
 
    while (!p.equal(group.at(0)) || points.length < 2) {
      // eslint-disable-next-line no-constant-condition
      while (true) {
        const nextValue = getByPosition(m, p.clone().move(traceDirections[direction]));
        const nextNeighbourValue = getByPosition(m, p.clone().move(traceDirections[left(direction)]));
        if (nextValue === TraceMatrixValues.t && nextNeighbourValue === TraceMatrixValues.f) {
          break;
        }
        direction = right(direction);
      }
      if (prevDirection !== direction) {
        points.push(p);
        prevDirection = direction;
      }
      p = p.clone().move(traceDirections[direction]);
      direction = left(left(direction));
    }
 
    if (this.approximation) {
      return points.approximation().close();
    }
    return points.clone().close();
  };
 
  private createHoleMatrix = (group: DPolygon): SimpleMatrix | null => {
    const fullTraceDirections = [
      new DPoint(-1, 0),
      new DPoint(0, 1),
      new DPoint(1, 0),
      new DPoint(0, -1)
    ];
 
    group.prepareToFastSearch();
    const tmpMatrix = TraceMatrix
      .createMatrix(this.size, (p: DPoint) => group.fastHas(p) ? TraceMatrixValues.t : TraceMatrixValues.f);
    const startCoords: DPolygon = new DPolygon();
    for (let i = 0; i < this.size.w; i++) {
      startCoords.push(new DPoint(i, -1));
      startCoords.push(new DPoint(i, this.size.h));
    }
    for (let i = 0; i < this.size.h; i++) {
      startCoords.push(new DPoint(-1, i));
      startCoords.push(new DPoint(this.size.w, i));
    }
    while (startCoords.length) {
      const point = startCoords.pop();
      for (const direction of fullTraceDirections) {
        const tmpPoint = point.clone().move(direction);
        const value = getByPosition(tmpMatrix, tmpPoint, TraceMatrixValues.t);
        if (value === TraceMatrixValues.f) {
          setByPosition(tmpMatrix, tmpPoint, TraceMatrixValues.t);
          startCoords.push(tmpPoint);
        }
      }
    }
 
    const t = this.reverseMatrix(tmpMatrix);
    return this.totalCountInMatrix(t) ? t : null;
  };
 
  static createMatrix(size: DPoint, f: (pos: DPoint) => TraceMatrixValues = () => TraceMatrixValues.f): SimpleMatrix {
    return createArray(size.h)
      .map((v: number, i: number) => createArray(size.w).map((v2: number, j: number) => f(new DPoint(j, i))));
  }
}