// https://stackoverflow.com/questions/21646738/convert-hex-to-rgba // [ function hexToRGB(hex) { return [ parseInt(hex.slice(1, 3), 16), parseInt(hex.slice(3, 5), 16), parseInt(hex.slice(5, 7), 16), ]; } // https://stackoverflow.com/questions/4492385/convert-simple-array-into-two-dimensional-array-matrix // convert a 1D array into a 2D matrix export function toMatrix(array, width) { return array.reduce( (rows, key, index) => (index % width == 0 ? rows.push([key]) : rows[rows.length - 1].push(key)) && rows, [] ); } // convert an image into a black and white image export function picToBlackAndWhite(pixels, width, height) { return pixels.reduce((acc, pixel, index) => { if (index % 4 == 0) { const count = pixels[index] + pixels[index + 1] + pixels[index + 2]; const colour = count >= 255 ? 255 : 1; acc.data[index] = colour; acc.data[index + 1] = colour; acc.data[index + 2] = colour; acc.data[index + 3] = 255; } return acc; }, new ImageData(width, height)); } // convert an ImageData into a 2D array of boolean (0, 1) values export function picToBoard(pixels, width, height) { const flat = pixels.reduce((acc, pixel, index) => { const i = index * 4; const count = pixels[i] + pixels[i + 1] + pixels[i + 2]; const value = count >= 255 ? 1 : 0; acc[index] = value; return acc; }, []); return toMatrix(flat, width, height); } // convert board to ImageData // TODO : different cell to color functions // (binary, intermediate states, camaieux, etc) export function boardToPic(board, width, height, cellProperties) { const live = cellProperties.liveColor; const dead = cellProperties.deadColor; const img = new ImageData(width, height); const colors = [hexToRGB(live), hexToRGB(dead)]; board.flat().reduce((acc, cell, index) => { const color = cell === 1 ? colors[0] : colors[1]; const i = index * 4; acc[i] = color[0]; acc[i + 1] = color[1]; acc[i + 2] = color[2]; acc[i + 3] = 255; return acc; }, img.data); return img; }