Skip to content

Commit c885028

Browse files
author
Martin Schuhfuss
committed
Merge pull request beyondscreen#9 from usefulthink/gamma-correct
Gamma correct
2 parents 3e8b3e6 + 402e36d commit c885028

File tree

1 file changed

+37
-12
lines changed

1 file changed

+37
-12
lines changed

lib/ws281x-native.js

Lines changed: 37 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -40,23 +40,46 @@ if(!ws281xNative) {
4040
}
4141

4242

43+
var gammaCorrect = (function() {
44+
var _gamma = 1/0.45;
45+
var _gammaTable = new Uint8Array(256);
4346

44-
var _numLeds = 0,
45-
_indexMapping = null;
47+
// equation from http://rgb-123.com/ws2812-color-output/
48+
for(var i=0; i<256; i++) {
49+
_gammaTable[i] = Math.floor(Math.pow(i / 255, _gamma) * 255 + 0.5);
50+
}
4651

52+
return function gammaCorrect(color) {
53+
return (
54+
_gammaTable[color & 0xff]
55+
| (_gammaTable[(color >> 8) & 0xff] << 8)
56+
| (_gammaTable[(color >> 16) & 0xff] << 16)
57+
);
58+
};
59+
} ());
4760

48-
function remap(src, indexMapping) {
49-
var dest = new Uint32Array(src.length);
5061

51-
for(var i=0; i<src.length; i++) {
52-
dest[i] = src[indexMapping[i]];
53-
}
62+
var remap = (function() {
63+
var _tmpData = null;
5464

55-
return dest;
56-
}
65+
return function remap(data, indexMapping) {
66+
if(!_tmpData) {
67+
_tmpData = new Uint32Array(data.length);
68+
}
69+
70+
_tmpData.set(data);
71+
72+
for(var i=0; i<data.length; i++) {
73+
data[i] = gammaCorrect(_tmpData[indexMapping[i]]);
74+
}
75+
76+
return data;
77+
};
78+
} ());
5779

5880

5981
var ws281x = new EventEmitter();
82+
var _indexMapping = null;
6083

6184
/**
6285
* configures PWM and DMA for sending data to the LEDs
@@ -67,16 +90,14 @@ var ws281x = new EventEmitter();
6790
* (PWM frequency, DMA channel, GPIO, Brightness)
6891
*/
6992
ws281x.init = function(numLeds, options) {
70-
_numLeds = numLeds;
71-
7293
ws281xNative.init(numLeds, options);
7394
};
7495

7596
/**
7697
* register a mapping to manipulate array-indices within the
7798
* data-array before rendering.
7899
*
79-
* @param {Array.<Number>} map the mapping, indexed by destination.
100+
* @param {Array.<Number>} mapping the mapping, indexed by destination.
80101
*/
81102
ws281x.setIndexMapping = function(mapping) {
82103
_indexMapping = mapping;
@@ -96,6 +117,10 @@ ws281x.render = function(data) {
96117
data = remap(data, _indexMapping);
97118
}
98119

120+
for(var i=0; i<data.length; i++) {
121+
data[i] = gammaCorrect(data[i]);
122+
}
123+
99124
ws281xNative.render(data);
100125
this.emit('render', data);
101126

0 commit comments

Comments
 (0)