You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
RnQ/Distro/Template/vibrant.tis

695 lines
18 KiB
Plaintext

// if (view.connectToInspector)
// view.connectToInspector();
function Array.max() {
if (this.length === 0) return null;
if (this.length === 1) return this[0];
var v = this[0];
for (var i = 1; i < this.length; i++)
v = Integer.max(this[i], v);
return v;
}
class pv {
function map(array, f = false) {
var o = {};
return f ? array.map(function(d, i) {
o.index = i;
return f.call(o, d);
}) : array.slice();
}
function naturalOrder(a, b) {
return (a < b) ? -1 : ((a > b) ? 1 : 0);
}
function sum(array, f = false) {
var o = {};
return array.reduce(f ? function(p, d, i) {
o.index = i;
return p + f.call(o, d);
} : function(p, d) {
return p + d;
}, 0);
}
function max(array, f = false) {
return f ? pv.map(array, f).max() : array.max();
}
}
function bnot(x) {
if (x < 0)
return Math.ceil(x).toInteger();
else
return Math.floor(x).toInteger();
}
class MMCQ {
var sigbits = 5,
rshift = 8 - sigbits,
maxIterations = 1000,
fractByPopulations = 0.75;
function getColorIndex(r, g, b) {
return (r << (2 * sigbits)) + (g << sigbits) + b;
}
function PQueue(comparator) {
var contents = [],
sorted = false;
function sort() {
contents.sort(comparator);
sorted = true;
}
return {
push: function(o) {
contents.push(o);
sorted = false;
},
peek: function(index) {
if (!sorted) sort();
if (index === undefined) index = contents.length - 1;
return contents[index];
},
pop: function() {
if (!sorted) sort();
return contents.pop();
},
size: function() {
return contents.length;
},
map: function(f) {
return contents.map(f);
},
debug: function() {
if (!sorted) sort();
return contents;
}
};
}
class VBox {
function this(r1, r2, g1, g2, b1, b2, histo) {
var vbox = this;
vbox.r1 = r1;
vbox.r2 = r2;
vbox.g1 = g1;
vbox.g2 = g2;
vbox.b1 = b1;
vbox.b2 = b2;
vbox.histo = histo;
}
function volume(force = false) {
var vbox = this;
if (!vbox._volume || force)
vbox._volume = ((vbox.r2 - vbox.r1 + 1) * (vbox.g2 - vbox.g1 + 1) * (vbox.b2 - vbox.b1 + 1));
return vbox._volume;
}
function count(force = false) {
var vbox = this,
histo = vbox.histo;
if (!vbox._count_set || force) {
var npix = 0, i, j, k;
for (i = vbox.r1; i <= vbox.r2; i++)
for (j = vbox.g1; j <= vbox.g2; j++)
for (k = vbox.b1; k <= vbox.b2; k++)
npix += (histo[getColorIndex(i, j, k)] || 0);
vbox._count = npix;
vbox._count_set = true;
}
return vbox._count;
}
function copy() {
var vbox = this;
return new VBox(vbox.r1, vbox.r2, vbox.g1, vbox.g2, vbox.b1, vbox.b2, vbox.histo);
}
function avg(force = false) {
var vbox = this,
histo = vbox.histo;
if (!vbox._avg || force) {
var ntot = 0,
mult = 1 << (8 - sigbits),
rsum = 0,
gsum = 0,
bsum = 0,
hval,
i, j, k;
for (i = vbox.r1; i <= vbox.r2; i++)
for (j = vbox.g1; j <= vbox.g2; j++)
for (k = vbox.b1; k <= vbox.b2; k++) {
hval = histo[getColorIndex(i, j, k)] || 0;
ntot += hval;
rsum += (hval * (i + 0.5) * mult);
gsum += (hval * (j + 0.5) * mult);
bsum += (hval * (k + 0.5) * mult);
}
if (ntot)
vbox._avg = [bnot(rsum / ntot), bnot(gsum / ntot), bnot(bsum / ntot)];
else
vbox._avg = [bnot(mult * (vbox.r1 + vbox.r2 + 1) / 2), bnot(mult * (vbox.g1 + vbox.g2 + 1) / 2), bnot(mult * (vbox.b1 + vbox.b2 + 1) / 2)];
}
return vbox._avg;
}
function contains(pixel) {
var vbox = this,
rval = pixel[0] >> rshift;
gval = pixel[1] >> rshift;
bval = pixel[2] >> rshift;
return (rval >= vbox.r1 && rval <= vbox.r2 &&
gval >= vbox.g1 && gval <= vbox.g2 &&
bval >= vbox.b1 && bval <= vbox.b2);
}
}
class CMap {
function this() {
this.vboxes = PQueue(function(a, b) {
return pv.naturalOrder(
a.vbox.count() * a.vbox.volume(),
b.vbox.count() * b.vbox.volume()
)
});
}
function push(vbox) {
this.vboxes.push({
vbox: vbox,
color: vbox.avg()
});
}
function palette() {
return this.vboxes.map(function(vb) {
return vb.color
});
}
function size() {
return this.vboxes.size();
}
function map(color) {
var vboxes = this.vboxes;
for (var i = 0; i < vboxes.size(); i++)
if (vboxes.peek(i).vbox.contains(color))
return vboxes.peek(i).color;
return this.nearest(color);
}
function nearest(color) {
var vboxes = this.vboxes,
d1, d2, pColor;
for (var i = 0; i < vboxes.size(); i++) {
d2 = Math.sqrt(
Math.pow(color[0] - vboxes.peek(i).color[0], 2) +
Math.pow(color[1] - vboxes.peek(i).color[1], 2) +
Math.pow(color[2] - vboxes.peek(i).color[2], 2)
);
if (d2 < d1 || d1 === undefined) {
d1 = d2;
pColor = vboxes.peek(i).color;
}
}
return pColor;
}
function forcebw() {
var vboxes = this.vboxes;
vboxes.sort(function(a, b) {
return pv.naturalOrder(pv.sum(a.color), pv.sum(b.color))
});
var lowest = vboxes[0].color;
if (lowest[0] < 5 && lowest[1] < 5 && lowest[2] < 5)
vboxes[0].color = [0, 0, 0];
var idx = vboxes.length - 1,
highest = vboxes[idx].color;
if (highest[0] > 251 && highest[1] > 251 && highest[2] > 251)
vboxes[idx].color = [255, 255, 255];
}
}
function getHisto(pixels) {
var histosize = 1 << (3 * sigbits),
histo = new Array(histosize),
index, rval, gval, bval;
for (var pixel in pixels) {
rval = pixel[0] >> rshift;
gval = pixel[1] >> rshift;
bval = pixel[2] >> rshift;
index = getColorIndex(rval, gval, bval);
histo[index] = (histo[index] || 0) + 1;
}
return histo;
}
function vboxFromPixels(pixels, histo) {
var rmin = 1000000,
rmax = 0,
gmin = 1000000,
gmax = 0,
bmin = 1000000,
bmax = 0,
rval, gval, bval;
for (var pixel in pixels) {
rval = pixel[0] >> rshift;
gval = pixel[1] >> rshift;
bval = pixel[2] >> rshift;
if (rval < rmin) rmin = rval;
else if (rval > rmax) rmax = rval;
if (gval < gmin) gmin = gval;
else if (gval > gmax) gmax = gval;
if (bval < bmin) bmin = bval;
else if (bval > bmax) bmax = bval;
}
return new VBox(rmin, rmax, gmin, gmax, bmin, bmax, histo);
}
function medianCutApply(histo, vbox) {
if (!vbox.count()) return;
var rw = vbox.r2 - vbox.r1 + 1,
gw = vbox.g2 - vbox.g1 + 1,
bw = vbox.b2 - vbox.b1 + 1,
maxw = pv.max([rw, gw, bw]);
if (vbox.count() == 1) return [vbox.copy()];
var total = 0,
partialsum = [],
lookaheadsum = [],
i, j, k, sum;
if (maxw == rw) {
for (i = vbox.r1; i <= vbox.r2; i++) {
sum = 0;
for (j = vbox.g1; j <= vbox.g2; j++)
for (k = vbox.b1; k <= vbox.b2; k++)
sum += (histo[getColorIndex(i, j, k)] || 0);
total += sum;
partialsum[i] = total;
}
} else if (maxw == gw) {
for (i = vbox.g1; i <= vbox.g2; i++) {
sum = 0;
for (j = vbox.r1; j <= vbox.r2; j++)
for (k = vbox.b1; k <= vbox.b2; k++)
sum += (histo[getColorIndex(j, i, k)] || 0);
total += sum;
partialsum[i] = total;
}
} else {
for (i = vbox.b1; i <= vbox.b2; i++) {
sum = 0;
for (j = vbox.r1; j <= vbox.r2; j++)
for (k = vbox.g1; k <= vbox.g2; k++)
sum += (histo[getColorIndex(j, k, i)] || 0);
total += sum;
partialsum[i] = total;
}
}
for (var (i, d) in partialsum)
if (d !== undefined && i !== undefined) lookaheadsum[i] = total - d;
function doCut(color) {
var dim1 = color + "1",
dim2 = color + "2",
left, right, vbox1, vbox2, d2, count2 = 0;
for (i = vbox[dim1]; i <= vbox[dim2]; i++) {
if (partialsum[i] > total / 2) {
vbox1 = vbox.copy();
vbox2 = vbox.copy();
left = i - vbox[dim1];
right = vbox[dim2] - i;
if (left <= right)
d2 = Integer.min(vbox[dim2] - 1, bnot(i + right / 2));
else
d2 = Integer.max(vbox[dim1], bnot(i - 1 - left / 2));
d2 = Integer.max(0, d2);
while (!partialsum[d2]) d2++;
count2 = lookaheadsum[d2];
while (!count2 && d2 >= 1 && partialsum[d2 - 1]) count2 = lookaheadsum[--d2];
vbox1[dim2] = d2;
vbox2[dim1] = vbox1[dim2] + 1;
return [vbox1, vbox2];
}
}
}
return maxw == rw ? doCut("r") : maxw == gw ? doCut("g") : doCut("b");
}
function quantize(pixels, maxcolors) {
if (!pixels.length || maxcolors < 2 || maxcolors > 256) return false;
var histo = getHisto(pixels),
histosize = 1 << (3 * sigbits);
var vbox = vboxFromPixels(pixels, histo),
pq = PQueue(function(a, b) {
return pv.naturalOrder(a.count(), b.count())
});
pq.push(vbox);
function iter(lh, target) {
var ncolors = 1,
niters = 0,
vbox;
while (niters < maxIterations) {
vbox = lh.pop();
if (!vbox.count()) {
lh.push(vbox);
niters++;
continue;
}
var vboxes = medianCutApply(histo, vbox);
if (!vboxes[0]) return;
lh.push(vboxes[0]);
if (vboxes.length > 1 && vboxes[1]) {
lh.push(vboxes[1]);
ncolors++;
}
if (ncolors >= target) return;
if (niters++ > maxIterations) return;
}
}
iter(pq, fractByPopulations * maxcolors);
var pq2 = PQueue(function(a, b) {
return pv.naturalOrder(a.count() * a.volume(), b.count() * b.volume())
});
while (pq.size()) pq2.push(pq.pop());
iter(pq2, maxcolors - pq2.size());
var cmap = new CMap();
while (pq2.size()) cmap.push(pq2.pop());
return cmap;
}
}
var bind = function(fn, me) {
return function(arguments..) {
return fn.apply(me, arguments);
};
},
slice = [].slice;
class Swatch {
var hsl = undefined;
var rgb = undefined;
var population = 1;
var yiq = 0;
function this(rgb, population) {
this.rgb = rgb;
this.population = population;
}
function getHsl() {
if (!this.hsl)
return this.hsl = Vibrant.rgbToHsl(this.rgb[0], this.rgb[1], this.rgb[2]);
else
return this.hsl;
}
function getPopulation() {
return this.population;
}
function getRgb() {
return this.rgb;
}
function getHex() {
return "#" + ((1 << 24) + (this.rgb[0].toInteger() << 16) + (this.rgb[1].toInteger() << 8) + this.rgb[2].toInteger()).toString(16).slice(1, 7);
}
function getTitleTextColor() {
this._ensureTextColors();
if (this.yiq < 200)
return "#fff";
else
return "#000";
}
function getBodyTextColor() {
this._ensureTextColors();
if (this.yiq < 150)
return "#fff";
else
return "#000";
}
function _ensureTextColors() {
if (!this.yiq)
return this.yiq = (this.rgb[0] * 299 + this.rgb[1] * 587 + this.rgb[2] * 114) / 1000;
}
}
class Vibrant {
var _swatches = [];
const TARGET_DARK_LUMA = 0.26;
const MAX_DARK_LUMA = 0.45;
const MIN_LIGHT_LUMA = 0.55;
const TARGET_LIGHT_LUMA = 0.74;
const MIN_NORMAL_LUMA = 0.3;
const TARGET_NORMAL_LUMA = 0.5;
const MAX_NORMAL_LUMA = 0.7;
const TARGET_MUTED_SATURATION = 0.3;
const MAX_MUTED_SATURATION = 0.4;
const TARGET_VIBRANT_SATURATION = 1;
const MIN_VIBRANT_SATURATION = 0.35;
const WEIGHT_SATURATION = 3;
const WEIGHT_LUMA = 6;
const WEIGHT_POPULATION = 1;
var VibrantSwatch = undefined;
var MutedSwatch = undefined;
var DarkVibrantSwatch = undefined;
var DarkMutedSwatch = undefined;
var LightVibrantSwatch = undefined;
var LightMutedSwatch = undefined;
var HighestPopulation = 0;
function this(image) {
this.swatches = bind(this.swatches, this);
var allPixels, cmap, x, y, offset, pixelCount, clr;
try {
pixelCount = image.width * image.height;
allPixels = [];
var quality = image.width / 64;
if (quality < 2) quality = 2;
//debug img: image.width, image.height, quality;
y = 0;
x = 0;
while (y < image.height) {
while (x < image.width) {
clr = image.colorAt(x, y);
if (clr && clr.a >= 125)
if (!(clr.r > 250 && clr.g > 250 && clr.b > 250))
allPixels.push([clr.r, clr.g, clr.b]);
x = x + quality;
if (x >= image.width) {
x = x - image.width;
break;
}
}
y++;
}
cmap = MMCQ.quantize(allPixels, 64);
if (cmap)
this._swatches = cmap.vboxes.map((function(_this) {
return function(vbox) {
return new Swatch(vbox.color, vbox.vbox.count());
};
})(this));
this.HighestPopulation = this.findMaxPopulation();
this.generateVarationColors();
this.generateEmptySwatches();
} finally {}
}
function generateVarationColors() {
this.VibrantSwatch = this.findColorVariation(this.TARGET_NORMAL_LUMA, this.MIN_NORMAL_LUMA, this.MAX_NORMAL_LUMA, this.TARGET_VIBRANT_SATURATION, this.MIN_VIBRANT_SATURATION, 1);
this.LightVibrantSwatch = this.findColorVariation(this.TARGET_LIGHT_LUMA, this.MIN_LIGHT_LUMA, 1, this.TARGET_VIBRANT_SATURATION, this.MIN_VIBRANT_SATURATION, 1);
this.DarkVibrantSwatch = this.findColorVariation(this.TARGET_DARK_LUMA, 0, this.MAX_DARK_LUMA, this.TARGET_VIBRANT_SATURATION, this.MIN_VIBRANT_SATURATION, 1);
this.MutedSwatch = this.findColorVariation(this.TARGET_NORMAL_LUMA, this.MIN_NORMAL_LUMA, this.MAX_NORMAL_LUMA, this.TARGET_MUTED_SATURATION, 0, this.MAX_MUTED_SATURATION);
this.LightMutedSwatch = this.findColorVariation(this.TARGET_LIGHT_LUMA, this.MIN_LIGHT_LUMA, 1, this.TARGET_MUTED_SATURATION, 0, this.MAX_MUTED_SATURATION);
return this.DarkMutedSwatch = this.findColorVariation(this.TARGET_DARK_LUMA, 0, this.MAX_DARK_LUMA, this.TARGET_MUTED_SATURATION, 0, this.MAX_MUTED_SATURATION);
}
function generateEmptySwatches() {
var hsl;
if (this.VibrantSwatch === undefined)
if (this.DarkVibrantSwatch !== undefined) {
hsl = this.DarkVibrantSwatch.getHsl();
hsl[2] = this.TARGET_NORMAL_LUMA;
this.VibrantSwatch = new Swatch(Vibrant.hslToRgb(hsl[0], hsl[1], hsl[2]), 0);
}
if (this.DarkVibrantSwatch === undefined)
if (this.VibrantSwatch !== undefined) {
hsl = this.VibrantSwatch.getHsl();
hsl[2] = this.TARGET_DARK_LUMA;
return this.DarkVibrantSwatch = new Swatch(Vibrant.hslToRgb(hsl[0], hsl[1], hsl[2]), 0);
}
}
function findMaxPopulation() {
var j, len, population, ref, swatch;
population = 0;
ref = this._swatches;
len = ref.length;
for (j = 0; j < len; j++) {
swatch = ref[j];
population = Integer.max(population, swatch.getPopulation());
}
return population;
}
function findColorVariation(targetLuma, minLuma, maxLuma, targetSaturation, minSaturation, maxSaturation) {
var j, len, luma, max, maxValue, ref, sat, swatch, value;
max = undefined;
maxValue = 0;
ref = this._swatches;
len = ref.length
for (j = 0; j < len; j++) {
swatch = ref[j];
sat = swatch.getHsl()[1];
luma = swatch.getHsl()[2];
if (sat >= minSaturation && sat <= maxSaturation && luma >= minLuma && luma <= maxLuma && !this.isAlreadySelected(swatch)) {
value = this.createComparisonValue(sat, targetSaturation, luma, targetLuma, swatch.getPopulation());
if (max === undefined || value > maxValue) {
max = swatch;
maxValue = value;
}
}
}
return max;
}
function createComparisonValue(saturation, targetSaturation, luma, targetLuma, population) {
return this.weightedMean(this.invertDiff(saturation, targetSaturation), this.WEIGHT_SATURATION, this.invertDiff(luma, targetLuma), this.WEIGHT_LUMA, population / this.HighestPopulation, this.WEIGHT_POPULATION);
}
function invertDiff(value, targetValue) {
return 1 - Math.abs(value - targetValue);
}
function weightedMean(arguments..) {
var i, sum, sumWeight, value, values, weight;
values = 1 <= arguments.length ? slice.call(arguments, 0) : [];
sum = 0;
sumWeight = 0;
i = 0;
while (i < values.length) {
value = values[i];
weight = values[i + 1];
sum += value * weight;
sumWeight += weight;
i += 2;
}
return sum / sumWeight;
}
function swatches() {
return {
Vibrant: this.VibrantSwatch,
Muted: this.MutedSwatch,
DarkVibrant: this.DarkVibrantSwatch,
DarkMuted: this.DarkMutedSwatch,
LightVibrant: this.LightVibrantSwatch,
LightMuted: this.LightMuted
};
}
function isAlreadySelected(swatch) {
return this.VibrantSwatch === swatch || this.DarkVibrantSwatch === swatch || this.LightVibrantSwatch === swatch || this.MutedSwatch === swatch || this.DarkMutedSwatch === swatch || this.LightMutedSwatch === swatch;
}
function rgbToHsl(r, g, b) {
var d, h, l, max, min, s;
r /= 255.0;
g /= 255.0;
b /= 255.0;
max = Float.max(r, g, b);
min = Float.min(r, g, b);
h = undefined;
s = undefined;
l = (max + min) / 2;
if (max === min) {
h = s = 0;
} else {
d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
}
h /= 6.0;
}
return [h, s, l];
}
function hslToRgb(h, s, l) {
var b, g, hue2rgb, p, q, r;
r = undefined;
g = undefined;
b = undefined;
hue2rgb = function(p, q, t) {
if (t < 0) {
t += 1;
}
if (t > 1) {
t -= 1;
}
if (t < 1 / 6) {
return p + (q - p) * 6 * t;
}
if (t < 1 / 2) {
return q;
}
if (t < 2 / 3) {
return p + (q - p) * (2 / 3 - t) * 6;
}
return p;
};
if (s === 0) {
r = g = b = l;
} else {
q = l < 0.5 ? l * (1 + s) : l + s - (l * s);
p = 2 * l - q;
r = hue2rgb(p, q, h + 1 / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - (1 / 3));
}
return [r * 255, g * 255, b * 255];
}
}
function getImageColors(image) {
var bts = new Bytes(image.length);
for (var (index, bt) in image) bts[index] = bt;
var img = Image.fromBytes(bts);
var vibrant = new Vibrant(img);
var swatches = vibrant.swatches();
// for (var swatch in swatches)
// if (swatches[swatch])
// stdout.println(swatch + ": " + swatches[swatch].getHex());
// else
// stdout.println(swatch + ": undefined");
var swt = null;
if (swatches.Muted)
swt = swatches.Muted;
else if (swatches.DarkMuted)
swt = swatches.DarkMuted;
else if (swatches.Vibrant)
swt = swatches.Vibrant;
else if (swatches.DarkVibrant)
swt = swatches.DarkVibrant;
if (swt !== null)
return [swt.getHex(), swt.getTitleTextColor()];
else
return [];
}