summaryrefslogtreecommitdiff
path: root/rushs/eplace/src/rooms/canvas/utils.js
blob: 5737dbbf874ce141e618674425d87425b4ade3f8 (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
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
// This file handles the room canvas DOM manipulation
// Functions includes:
// - initCanvas (initialize the canvas)
// - renderCanvasUpdate (render a canvas update)
// - getPlacementData (get the necessary data to place a pixel)
// - toggleTooltip (toggle the tooltip and display the pixel's information)

import $ from "jquery";
import { getPixelInfo } from ".";
import { getStudent } from "../../students";

const canvasContainer = $("#canvas-container")?.[0];
const canvas = $("#canvas")?.[0];
const canvasCtx = canvas.getContext("2d");
const selector = $("#selector")?.[0];

const positionTooltip = $("#position-tooltip")?.[0];
const tooltip = $("#tooltip")?.[0];
const colorPicker = $("#color-picker")?.[0];
const colorWheelContainer = $("#color-wheel-container")?.[0];
const colorWheel = $("#color-wheel")?.[0];

/**
 * Global variables
 */
let board, palette, selectedColorIdx;
let animation;

const zoomSpeed = 1 / 25;
let zoom = 2.5;

let x, y;
let cx = 0;
let cy = 0;
let target = { x: 0, y: 0 };
let isDrag = false;

/**
 * Returns the necessary data to place a pixel
 * @returns {{color: number, posX: number, posX: number}} the data
 */
export const getPlacementData = () => ({
    color: selectedColorIdx,
    posX: target.x,
    posY: target.y,
});

/**
 * Toggle the tooltip and display the pixel's information
 * @param {boolean} state
 */
export const toggleTooltip = async (state = false) => {
    tooltip.style.display = state ? "flex" : "none";

    if (state) {
        const pixelInfo = await getPixelInfo();
        const uid = pixelInfo.placedByUid;
        const placeDate = new Date(pixelInfo.timestamp);

        if (!pixelInfo) {
            throw new Error(
                'An error occured while hitting the "/rooms/epi-place/canvas/pixels" endpoint',
            );
        }

        const studentInfo = await getStudent(uid);

        if (!studentInfo) {
            throw new Error(
                'An error occured while hitting the "/students/:id" endpoint',
            );
        }

        document.getElementById("tooltip-time").innerHTML =
            placeDate.toLocaleTimeString();
        document.getElementById("tooltip-date").innerHTML =
            placeDate.toLocaleDateString();
        document
            .getElementById("tooltip-info-avatar")
            .setAttribute(
                "src",
                studentInfo.avatarURL ?? "/default-avatar.png",
            );
        document.getElementById("tooltip-info-quote").innerHTML =
            studentInfo.quote;
        document.getElementById("tooltip-info-login").innerHTML =
            studentInfo.login;
        // FIXME: You should implement or call a function to get the pixel's information
        // and display it. Make use of target.x and target.y to get the pixel's position.
    }
};

/**
 * Calculate the target position according to the top left corner of the canvas
 * @param {*} event
 * @returns {x: number, y: number} the target position
 */
const calculateTarget = (event) => {
    const rect = canvas.getBoundingClientRect();
    const scaleX = canvas.width / rect.width;
    const scaleY = canvas.height / rect.height;
    const canvasLeft = rect.left + window.pageXOffset;
    const canvasTop = rect.top + window.pageYOffset;

    return {
        x: Math.floor(
            ((event?.pageX ?? window.innerWidth / 2) - canvasLeft) * scaleX,
        ),
        y: Math.floor(
            ((event?.pageY ?? window.innerHeight / 2) - canvasTop) * scaleY,
        ),
    };
};

/**
 * Update the position tooltip
 * @param {*} event
 */
const positionUpdate = (event) => positionDisplay(calculateTarget(event));

/**
 * Update the position tooltip
 * @param {{x: number, y: number}} target
 */
const positionDisplay = ({ x, y }) => {
    positionTooltip.innerText = `X=${x} Y=${y}`;
    canvas.style.transform = `translate(${cx}px, ${cy}px) scale(${zoom})`;

    // We add the canvas.width * zoom to make cx and cy positive
    let selectorX = cx + canvas.width * zoom;
    let selectorY = cy + canvas.height * zoom;

    // Make odd canvas align
    if (canvas.width % 2 !== 0) {
        selectorX += zoom / 2;
        selectorY += zoom / 2;
    }

    // Find the translate
    selectorX %= zoom;
    selectorY %= zoom;

    // Center selector on the pixel
    selectorX -= zoom / 2;
    selectorY -= zoom / 2;

    selector.style.transform = `translate(${selectorX}px, ${selectorY}px) scale(${zoom})`;
};

// Toggle the color wheel on click on the color picker
colorPicker.addEventListener("click", () => {
    const state = colorWheelContainer.style.display;

    colorWheelContainer.style.display =
        !state || state === "none" ? "block" : "none";
});

/**
 * Transform #RRGGBB to 0xBBGGRRAA
 * @param {string} hex
 * @returns {number} the 32 bits color
 */
const transformHexTo32Bits = (hex) => {
    const reverse = hex.substring(1).match(/.{2}/g).reverse().join("");

    return parseInt(`0xFF${reverse}`, 16);
};

/**
 * Render the canvas
 * @param {number[]} pixels
 * @param {string[]} colors
 */
const renderCanvas = (pixels, colors) => {
    const img = new ImageData(canvas.width, canvas.height);
    const data = new Uint32Array(img.data.buffer);

    board = pixels;
    palette = colors;
    for (let i = 0; i < pixels.length; i++) {
        data[i] = transformHexTo32Bits(colors[pixels[i]]);
    }

    canvasCtx.putImageData(img, 0, 0);
    canvasCtx.imageSmoothingEnabled = false;
    canvas.style.imageRendering = "pixelated";

    // Remove all the colors from the color wheel
    while (colorWheel.firstChild) {
        colorWheel.removeChild(colorWheel.firstChild);
    }

    // Add the colors to the color wheel
    for (let i = 0; i < colors.length; i++) {
        const btn = document.createElement("button");

        colorWheel.appendChild(btn);

        btn.addEventListener("click", () => {
            selectedColorIdx = i;
            colorPicker.style.color = colors[i];
            colorPicker.style.border = `${colors[i]} 0.1rem solid`;
        });

        btn.style.backgroundColor = colors[i];
    }
};

/**
 * Initialize the canvas
 * @param {*} roomConfig
 * @param {number[]} pixels
 */
export const initCanvas = (roomConfig, pixels) => {
    const canvasDimensions = roomConfig.metadata.canvasDimensions;

    canvas.width = canvasDimensions;
    canvas.height = canvasDimensions;

    positionDisplay({ x: canvasDimensions / 2, y: canvasDimensions / 2 });
    selectedColorIdx = 0;

    const roomColors = roomConfig.settings.roomColors.split(",");

    colorPicker.style.color = roomColors[0];
    colorPicker.style.border = `${roomColors[0]} 0.1rem solid`;

    renderCanvas(pixels, roomColors);
};

/**
 * Update the canvas
 * @param {string} color
 * @param {number} x
 * @param {number} y
 */
export const renderCanvasUpdate = (color, x, y) => {
    const img = new ImageData(canvas.width, canvas.height);
    const data = new Uint32Array(img.data.buffer);

    board[y * canvas.width + x] = color;
    for (let i = 0; i < board.length; i++) {
        data[i] = transformHexTo32Bits(palette[board[i]]);
    }

    canvasCtx.putImageData(img, 0, 0);
};

/**
 * Reset the canvas values
 */
export const resetValues = () => {
    zoom = 2.5;
    x = 0;
    y = 0;
    cx = 0;
    cy = 0;
    isDrag = false;

    positionDisplay({ x, y });
    colorWheelContainer.style.display = "none";
    toggleTooltip(false);
};

// Handle scroll on canvas
document.addEventListener("wheel", (e) => {
    // Make sure we're scrolling on the canvas or the body and not the UI
    if (e.target !== canvas && e.target !== canvasContainer) {
        return;
    }

    clearInterval(animation);
    toggleTooltip(false);

    const delta = Math.sign(e.deltaY) * zoomSpeed;
    const zoomFactor = 1 + delta;
    const oldZoom = zoom;
    const newZoom = Math.max(2.5, Math.min(40, oldZoom * zoomFactor));

    // Get the position of the mouse relative to the canvas
    const mouseX = e.clientX - window.innerWidth / 2;
    const mouseY = e.clientY - window.innerHeight / 2;

    // Calculate the new center point based on the mouse position
    const newCx = mouseX - (mouseX - cx) * (newZoom / oldZoom);
    const newCy = mouseY - (mouseY - cy) * (newZoom / oldZoom);

    if (newZoom !== oldZoom) {
        zoom = newZoom;
        cx = newCx;
        cy = newCy;
        positionUpdate();
    }
});

// Handle click and drag on canvas
document.addEventListener("mousedown", (e) => {
    // Make sure we're clicking on the canvas or the body and not the UI
    if (e.target !== canvas && e.target !== canvasContainer) {
        return;
    }

    e.preventDefault();

    // Ignore if right click
    if (e.button === 2) {
        return;
    }

    clearInterval(animation);

    isDrag = false;
    x = e.clientX;
    y = e.clientY;

    document.addEventListener("mousemove", mouseMove);
});

// Smooth animation
function easeOutQuart(t, b, c, d) {
    t /= d;
    t--;
    return -c * (t * t * t * t - 1) + b;
}

// Handle when the user releases the mouse
document.addEventListener("mouseup", (e) => {
    document.removeEventListener("mousemove", mouseMove);

    // Make sure we're clicking on the canvas or the body and not the UI
    if (e.target !== canvas && e.target !== canvasContainer) {
        return;
    }

    e.preventDefault();

    // Get the tile position
    target = calculateTarget(e);

    // Make sure we're clicking on the canvas
    if (
        target.x >= 0 &&
        target.x < canvas.width &&
        target.y >= 0 &&
        target.y < canvas.height
    ) {
        // We want to differentiate between a click and a drag
        // If it is a click, we want to move the camera to the clicked tile

        // We wait to see if the position changed
        // If it did not, we consider it a click
        if (!isDrag) {
            const duration = 1000;
            const startZoom = zoom;
            const endZoom = Math.max(15, Math.min(40, zoom));

            // Get the position of the click in relation to the center of the screen
            const clickX = e.clientX - window.innerWidth / 2;
            const clickY = e.clientY - window.innerHeight / 2;
            const canvaswidthzoom = canvas.width * startZoom;
            const canvasheightzoom = canvas.height * startZoom;
            const startx = (cx + canvaswidthzoom / 2) / startZoom;
            const starty = (cy + canvasheightzoom / 2) / startZoom;
            const endx = startx - clickX / startZoom;
            const endy = starty - clickY / startZoom;
            const endCx = endx * endZoom - (canvas.width / 2) * endZoom;
            const endCy = endy * endZoom - (canvas.height / 2) * endZoom;
            const startCx = cx;
            const startCy = cy;
            const startTime = Date.now();

            // If the distance is small enough, we just warp to it
            if (
                Math.abs(endCx - startCx) < 10 &&
                Math.abs(endCy - startCy) < 10
            ) {
                cx = endCx;
                cy = endCy;
                zoom = endZoom;
                canvas.style.transform = `translate(${cx}px, ${cy}px) scale(${zoom})`;
            } else {
                clearInterval(animation);

                animation = setInterval(() => {
                    const elapsed = Date.now() - startTime;

                    if (elapsed >= duration) {
                        clearInterval(animation);
                        return;
                    }

                    const t = elapsed / duration;

                    zoom = easeOutQuart(t, startZoom, endZoom - startZoom, 1);
                    cx = easeOutQuart(t, startCx, endCx - startCx, 1);
                    cy = easeOutQuart(t, startCy, endCy - startCy, 1);

                    positionUpdate();
                }, 10);
            }
        }

        // Toggle the tooltip if it is a click
        toggleTooltip(!isDrag);

        // Update the position of the tooltip
        positionDisplay(target);
    }
});

// Handle mouse move
const mouseMove = (e) => {
    e.preventDefault();

    toggleTooltip(false);
    positionUpdate();

    const dx = e.clientX - x;
    const dy = e.clientY - y;

    // For a big enough delta, we consider it a drag
    if (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5) {
        isDrag = true;
    }

    x = e.clientX;
    y = e.clientY;
    cx += dx;
    cy += dy;

    canvas.style.transform = `translate(${cx}px, ${cy}px) scale(${zoom})`;
};