Constellations/js/Share/Decoder/Protocol.js
2022-08-11 09:58:57 +02:00

79 lines
1.8 KiB
JavaScript

import * as CellSet from Geometry.CellSet;
import * as Decoder from Share.Decoder.Class;
import {diagonal, plus, zero} from Geometry.Vector;
import * as Vector from Geometry.Vector;
import * as Protocol from Share.Protocol;
return {
grid: decodeGrid
};
function decodeGrid(size, input) {
if(input != undefined) {
return decoderLoop(
Decoder.make(input),
square(size),
CellSet.make({type: 'rectangle', origin: zero(), offset: diagonal(size)})
);
}
}
function decoderLoop(decoder, grid, missing) {
var queue = [];
var nextBit = decoder.pop();
var cell = zero();
var danglingCells = [];
while(nextBit != null) {
if(nextBit == 1) {
fillBlock(grid, decodeBlock(decoder), missing);
} else {
handleCell(grid, cell, decodeDirection(decoder), danglingCells);
}
moveToNext(cell, grid, missing);
nextBit = decoder.pop();
}
resolve(grid, danglingCells);
return grid;
}
function moveToNext(cell, grid, missing) {
cell.column++;
while(!missing.contains(cell)) {
if(cell.column >= grid[cell.row].length) {
cell.row++;
cell.column = 0;
} else {
cell.column++;
}
}
}
function fillBlock(grid, block, missing, cell) {
var offset = Vector[block.direction](1);
var newCell = Vector.make(cell.row, cell.column);
for(var delta = 0; delta < block.size; delta++) {
set(grid, newCell, block.color);
missing.remove(newCell);
newCell = plus(newCell, offset);
}
}
function decodeBlock(decoder) {
return {
direction: decoder.pop() == 1 ? 'vertical' : 'horizontal',
size: decoder.variableLength6() + Protocol.MIN_BLOCK_SIZE,
color: decoder.int(3)
};
}
function handleCell(grid, cell, direction, danglingCells) {
}
function resolve(grid, danglingCells) {
}
function decodeDirection(decoder) {
return Protocol.directions[decoder.int(2)];
}