From 812c5e45e0f6dcb389d864e7c5f118867ba17bb6 Mon Sep 17 00:00:00 2001 From: cha0s Date: Wed, 30 Mar 2022 06:47:12 -0500 Subject: [PATCH] opt: colors --- packages/color/src/traits/colorized.js | 79 ++++++++++++++------------ 1 file changed, 42 insertions(+), 37 deletions(-) diff --git a/packages/color/src/traits/colorized.js b/packages/color/src/traits/colorized.js index a8fe8cc..00a6187 100644 --- a/packages/color/src/traits/colorized.js +++ b/packages/color/src/traits/colorized.js @@ -20,14 +20,20 @@ export default (flecks) => { return class Colorized extends decorate(Trait) { + constructor(...args) { + super(...args); + this.$$rgbChanged = false; + this.$$hsvChanged = false; + this.$$hsv = [0, 0, 0]; + } + get blue() { return this.state.blue; } set blue(blue) { - this.wrapRgbSet(() => { - super.blue = blue; - }); + super.blue = blue; + this.$$rgbChanged = true; } static defaultState() { @@ -43,17 +49,22 @@ export default (flecks) => { } set green(green) { - this.wrapRgbSet(() => { - super.green = green; - }); + super.green = green; + this.$$rgbChanged = true; } get hue() { - return rgb2hsv([this.red, this.green, this.blue])[0]; + return this.$$hsv[0]; } set hue(hue) { - this.wrapHsvSet(0, hue); + this.$$hsv[0] = hue; + this.$$hsvChanged = true; + } + + async load(json) { + await super.load(json); + this.$$hsv = rgb2hsv([this.state.red, this.state.green, this.state.blue]); } get red() { @@ -61,47 +72,41 @@ export default (flecks) => { } set red(red) { - this.wrapRgbSet(() => { - super.red = red; - }); + super.red = red; + this.$$rgbChanged = true; } get saturation() { - return rgb2hsv([this.red, this.green, this.blue])[1]; + return this.$$hsv[1]; } set saturation(saturation) { - this.wrapHsvSet(1, saturation); + this.$$hsv[1] = saturation; + this.$$hsvChanged = true; + } + + tick() { + // RGB takes priority... + if (this.$$rgbChanged) { + this.$$hsv = rgb2hsv([this.state.red, this.state.green, this.state.blue]); + } + else if (this.$$hsvChanged) { + [this.red, this.green, this.blue] = hsv2rgb(this.$$hsv); + } + else { + return; + } + this.$$hsvChanged = false; + this.$$rgbChanged = false; } get value() { - return rgb2hsv([this.red, this.green, this.blue])[2]; + return this.$$hsv[2]; } set value(value) { - this.wrapHsvSet(2, value); - } - - wrapHsvSet(i, nv) { - const hsv = rgb2hsv([this.red, this.green, this.blue]); - const keys = ['hue', 'saturation', 'value']; - if (nv !== hsv[i]) { - hsv[i] = nv; - [this.red, this.green, this.blue] = hsv2rgb(hsv); - this.entity.emit(`${keys[i]}Changed`); - } - } - - wrapRgbSet(fn) { - const o = rgb2hsv([this.red, this.green, this.blue]); - fn(); - const n = rgb2hsv([this.red, this.green, this.blue]); - ['hue', 'saturation', 'value'].forEach((key, i) => { - if (n[i] !== o[i]) { - this.entity.emit(`${key}Changed`); - } - }); - + this.$$hsv[2] = value; + this.$$hsvChanged = true; } };