class Node {
constructor(level, parent) {
this._color = new Color(0, 0, 0);
this.pixelCount = 0;
this.paletteIndex = 0;
this.children = [];
this._debugColor;
if (level < MAX_DEPTH - 1) parent.addLevelNode(level, this);
}
get isLeaf() {
return this.pixelCount > 0;
}
get leafNodes() {
let leafNodes = [];
for (let node of this.children) {
if (!node) continue;
if (node.isLeaf) {
leafNodes.push(node);
} else {
leafNodes.push(...node.leafNodes);
}
}
return leafNodes;
}
addColor(color, level, parent) {
if (level >= MAX_DEPTH) {
this._color.add(color);
this.pixelCount++;
return;
}
let index = getColorIndex(color, level);
if (!this.children[index]) {
this.children[index] = new Node(level, parent);
}
this.children[index].addColor(color, level + 1, parent);
}
getPaletteIndex(color, level) {
if (this.isLeaf) {
return this.paletteIndex;
}
let index = getColorIndex(color, level);
if (this.children[index]) {
return this.children[index].getPaletteIndex(color, level + 1);
} else {
for (let node of this.children) {
return node.getPaletteIndex(color, level + 1);
}
}
}
removeLeaves() {
let result = 0;
for (let node of this.children) {
if (!node) continue;
this._color.add(node._color);
this.pixelCount += node.pixelCount;
result++;
}
this.children = [];
return result - 1;
}
get debugColor() {
if (this._debugColor) return this._debugColor;
if (this.isLeaf) return this.color;
let c = new Color();
let count = 0;
function traverse(node) {
for (let child of node.children) {
if (child.isLeaf) {
c.add(child._color);
count++;
} else {
traverse(child);
}
}
}
traverse(this);
return c.normalized(count);
}
get color() {
return this._color.normalized(this.pixelCount);
}
}