Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
blob: d2f18a50fa745d88d5dec64c16cb8fc6ccd74067 (plain)
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
// https://www.redblobgames.com/grids/hexagons/

// Horizontal distance between hex centers is sqrt(3) * size. The vertical
// distance is 3 / 2 * size. When we calculate horzDist / vertDist, the size
// cancels out, leaving us with a unitless ratio of sqrt(3) / (3 / 2), or
// 2 * sqrt(3) / 3.

const svgns = "http://www.w3.org/2000/svg",
  horzToVertDistRatio = 2 * Math.sqrt(3) / 3,

  arcSize = {
    'small': Math.atan(horzToVertDistRatio / 6),
    'medium': Math.atan(horzToVertDistRatio / 2),
    'large': Math.atan(7 * horzToVertDistRatio / 2)
  },

  firingArcVisibility = {
    davion: false,
    liao: false
  };

let svg;

function calculateAngle(xDiff, yDiff) {
  yDiff = -yDiff;
  let angle = Math.abs(Math.atan(yDiff / xDiff));

  if (xDiff < 0 && yDiff > 0) {
    angle = Math.PI - angle;
  } else if (xDiff < 0 && yDiff < 0) {
    angle = Math.PI + angle;
  } else if (xDiff > 0 && yDiff < 0) {
    angle = 2 * Math.PI - angle;
  }

  return angle;
}

function edgePoint(x1, y1, x2, y2, maxX, maxY) {
  let pointCoords,
    xDiff = x2 - x1,
    yDiff = y2 - y1,
    xIntercept = y => (y - y1) * xDiff / yDiff + x1,
    yIntercept = x => (x - x1) * yDiff / xDiff + y1;

  if (xDiff > 0 && yDiff > 0) {
    let x = xIntercept(maxY);

    pointCoords = x <= maxX ? [x, maxY] : [maxX, yIntercept(maxX)];
  } else if (xDiff > 0 && yDiff < 0) {
    let y = yIntercept(maxX);

    pointCoords = y >= 0 ? [maxX, y] : [xIntercept(0), 0];
  } else if (xDiff < 0 && yDiff < 0) {
    let x = xIntercept(0);

    pointCoords = x >= 0 ? [x, 0] : [0, yIntercept(0)];
  } else {
    let y = yIntercept(0);

    pointCoords = y <= maxY ? [0, y] : [xIntercept(maxY), maxY];
  }

  return pointCoords;
}

function position(e) {
  let activeFiringArc = this.querySelector('polygon.firing-arc.active');

  // TODO: handle exactly horizontal and vertical lines

  if (activeFiringArc) {
    let activeFiringArcOutline = this.querySelector(`#lines polygon[data-number="${activeFiringArc.dataset.number}"][data-allegiance="${activeFiringArc.dataset.allegiance}"]`),
      board = this.querySelector('#image-maps'),
      { width, height } = board.getBBox(),
      pt = new DOMPoint(e.clientX, e.clientY),
      { x: pointerX, y: pointerY } = pt.matrixTransform(board.getScreenCTM().inverse()),
      [maxXpx, maxYpx] = [width, height],
      { x: x1px, y: y1px } = activeFiringArc.points[0];

    let [x2px, y2px] = [
      pointerX / width * maxXpx,
      pointerY / height * maxYpx
    ];

    let xDiff = x2px - x1px;
    let yDiff = y2px - y1px;
    let angle = calculateAngle(xDiff, yDiff);

    let arcAngle = arcSize[activeFiringArc.dataset.size];
    let distance = Math.sqrt((x2px - x1px) ** 2 + (y2px - y1px) ** 2);
    let yDelta = distance * Math.cos(angle) * Math.tan(arcAngle);
    let xDelta = distance * Math.sin(angle) * Math.tan(arcAngle);

    let [newY1, newX1] = [y2px + yDelta, x2px + xDelta];
    let [newY2, newX2] = [y2px - yDelta, x2px - xDelta];

    [newX1, newY1] = edgePoint(x1px, y1px, newX1, newY1, maxXpx, maxYpx);
    [newX2, newY2] = edgePoint(x1px, y1px, newX2, newY2, maxXpx, maxYpx);

    let oppositeEdgeConditions = [
      newX1 == 0 && newX2 == maxXpx,
      newX2 == 0 && newX1 == maxXpx,
      newY1 == 0 && newY2 == maxYpx,
      newY2 == 0 && newY1 == maxYpx
    ]

    let orthogonalEdgeConditions = [
      (newX1 == 0 || newX1 == maxXpx) && (newY2 == 0 || newY2 == maxYpx),
      (newX2 == 0 || newX2 == maxXpx) && (newY1 == 0 || newY1 == maxYpx),
    ]

    let points;

    if (oppositeEdgeConditions.some(e => e)) {
      let cornerPoints;

      if (xDiff > 0 && yDiff > 0) {
        if ((newY1 == 0 && newY2 == maxYpx) || (newY1 == maxYpx && newY2 == 0)) {
          cornerPoints = [[maxXpx, 0], [maxXpx, maxYpx]];
        } else {
          cornerPoints = [[maxXpx, maxYpx], [0, maxYpx]];
        }
      } else if (xDiff > 0 && yDiff < 0) {
        if ((newY1 == 0 && newY2 == maxYpx) || (newY1 == maxYpx && newY2 == 0)) {
          cornerPoints = [[maxXpx, 0], [maxXpx, maxYpx]];
        } else {
          cornerPoints = [[0, 0], [maxXpx, 0]];
        }

      } else if (xDiff < 0 && yDiff > 0) {
        if ((newY1 == 0 && newY2 == maxYpx) || (newY1 == maxYpx && newY2 == 0)) {
          cornerPoints = [[0, maxYpx], [0, 0]];
        } else {
          cornerPoints = [[maxXpx, maxYpx], [0, maxYpx]];
        }

      } else {
        if ((newY1 == 0 && newY2 == maxYpx) || (newY1 == maxYpx && newY2 == 0)) {
          cornerPoints = [[0, maxYpx], [0, 0]];
        } else {
          cornerPoints = [[0, 0], [maxXpx, 0]];
        }

      }
      points = `${x1px},${y1px} ${newX1},${newY1} ${cornerPoints[1]} ${cornerPoints[0]} ${newX2},${newY2}`;
    } else if (orthogonalEdgeConditions.some(e => e)) {
      let cornerPoints = [];
      let cp1, cp2;

      if (newX1 == 0 || newX1 == maxXpx) {
        cp1 = [newX1, yDiff > 0 ? maxYpx : 0];
      } else {
        cp1 = [xDiff > 0 ? maxXpx : 0, newY1];
      }

      if (newX2 == 0 || newX2 == maxXpx) {
        cp2 = [newX2, yDiff > 0 ? maxYpx : 0];
      } else {
        cp2 = [xDiff > 0 ? maxXpx : 0, newY2];
      }

      if (cp1[0] == cp2[0] && cp1[1] == cp2[1]) {
        cornerPoints.push(cp1);
      } else {
        cornerPoints.push(cp1);
        cornerPoints.push([xDiff > 0 ? maxXpx : 0, yDiff > 0 ? maxYpx : 0])
        cornerPoints.push(cp2);
      }

      points = `${x1px},${y1px} ${newX1},${newY1} ${cornerPoints.join(' ')} ${newX2},${newY2}`;
    } else {
      points = `${x1px},${y1px} ${newX1},${newY1} ${newX2},${newY2}`;
    }

    activeFiringArcOutline.setAttributeNS(null, 'points', points);
    activeFiringArc.setAttributeNS(null, 'points', points);
  }
}

function setDataAttrs({ dataset: { allegiance, number }}, el) {
  el.dataset.allegiance = allegiance;
  el.dataset.number = number;
}

function getClipPathId({ dataset: { allegiance, number }}) {
  return `clip-path-${allegiance}-${number}`;
}

function getUnclipped() {
  return svg.querySelectorAll('#firing-arcs polygon:not([clip-path])');
};

export default function (el) {
  svg = el;

  this.set = function (size, counter, { x, y }) {
    this.get(counter).forEach(fa => fa.remove());

    let arcLayer = svg.querySelector('#shapes');
    let outlineLayer = svg.querySelector('#lines');
    let arcContainer = svg.querySelector('#firing-arcs');

    let grid = svg.querySelector('.board');
    const transform = getComputedStyle(grid).transform.match(/-?\d+\.?\d*/g);
    const pt = new DOMPoint(x, y);
    const mtx = new DOMMatrix(transform);
    let tPt = pt.matrixTransform(mtx);

    let pivotPoint = [tPt.x, tPt.y];
    let firingArc = document.createElementNS(svgns, 'polygon');
    let firingArcOutline = document.createElementNS(svgns, 'polygon');

    setDataAttrs(counter, firingArc);
    firingArc.dataset.size = size;
    firingArc.classList.add('firing-arc', 'active');
    firingArc.setAttributeNS(null, 'points', `${pivotPoint} ${pivotPoint} ${pivotPoint}`);

    setDataAttrs(counter, firingArcOutline);
    firingArcOutline.setAttributeNS(null, 'points', `${pivotPoint} ${pivotPoint} ${pivotPoint}`);

    let clipShape = document.createElementNS(svgns, 'circle');
    clipShape.setAttributeNS(null, 'cx', tPt.x);
    clipShape.setAttributeNS(null, 'cy', tPt.y);
    clipShape.setAttributeNS(null, 'r', 100);

    let clipPath = document.createElementNS(svgns, 'clipPath');
    setDataAttrs(counter, clipPath);
    clipPath.setAttributeNS(null, 'id', getClipPathId(counter));
    clipPath.appendChild(clipShape);

    arcContainer.appendChild(clipPath);
    arcLayer.appendChild(firingArc);
    outlineLayer.appendChild(firingArcOutline);

    let firingArcPlacementListener = e => {
      svg.querySelectorAll('.firing-arc.active').forEach(el => el.classList.remove('active'));
      grid.removeAttribute('style');
      svg.removeEventListener('mousemove', position);
      firingArc.removeEventListener('click', firingArcPlacementListener);
      firingArc.removeEventListener('contextmenu', cancelFiringArcPlacement);
    };

    let cancelFiringArcPlacement = e => {
      e.preventDefault();

      firingArc.removeEventListener('click', firingArcPlacementListener);
      firingArc.removeEventListener('contextmenu', cancelFiringArcPlacement);

      this.get(counter).forEach(fa => fa.remove());

      grid.removeAttribute('style');
      svg.removeEventListener('mousemove', position);
    };

    grid.style.pointerEvents = 'none';
    svg.addEventListener('mousemove', position);
    firingArc.addEventListener('click', firingArcPlacementListener);
    firingArc.addEventListener('contextmenu', cancelFiringArcPlacement);
  };

  this.clear = function (allegiance) {
    const selector = `#firing-arcs [data-allegiance="${allegiance}"]`;
    svg.querySelectorAll(selector).forEach(el => el.remove());
  };

  this.get = function ({ dataset: { allegiance, number }}) {
    return svg.querySelectorAll(`#firing-arcs polygon[data-number="${number}"][data-allegiance="${allegiance}"]`);
  };

  this.toggleVisibility = function (allegiance) {
    const vis = firingArcVisibility[allegiance],
      clipPaths = svg.querySelectorAll(`clipPath[data-allegiance="${allegiance}"]`);

    clipPaths.forEach(cp => cp.style.display = !vis ? 'none' : '');
    firingArcVisibility[allegiance] = !vis;
  };

  this.toggleCounterVisibility = function ({ dataset: { number, allegiance }}, vis) {
    const cp = svg.querySelector(`#clip-path-${allegiance}-${number}`),
      display = vis ? 'none' : '';

    if (cp) {
      cp.style.display = firingArcVisibility[allegiance] ? 'none' : display;
    }
  };

  this.clipAll = function () {
    console.log('clipall')
    let unclipped = getUnclipped();

    unclipped.forEach(el => {
      const { number, allegiance } = el.dataset,
        clipPathId = `clip-path-${allegiance}-${number}`,
        isVisible = firingArcVisibility[allegiance];

      if (isVisible) {
        svg.querySelector(`#${clipPathId}`).style.display = 'none';
      }

      el.setAttributeNS(null, 'clip-path', `url(#${clipPathId})`);
    });
  };
}