-
Notifications
You must be signed in to change notification settings - Fork 1
/
mapper.js
130 lines (111 loc) · 4.15 KB
/
mapper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
module.exports = function(RED) {
function Mapper(config) {
RED.nodes.createNode(this,config);
var node = this;
node.property = config.property||"payload";
node.keyframes = config.keyframes;
node.inputFrom = Number(config.inputFrom)
node.inputTo = Number(config.inputTo)
node.outputFrom = Number(config.outputFrom)
node.outputTo = Number(config.outputTo)
node.rounding = Number(config.rounding)
node.inputOutOfRangeStrategy = config.inputOutOfRangeStrategy
node.on('input', function(msg, send, done)
{
send = send || function() { node.send.apply(node, arguments) }
let x = RED.util.getMessageProperty(msg, node.property);
if( x !== undefined )
{
x = Number(x)
if(isNaN(x))
{
node.error(`Property is not a number: ${x}`)
if(done)
done()
return
}
let y = x;
if( inInputRange(x) )
{
y = computeOutput(x)
}
else
{
switch(node.inputOutOfRangeStrategy)
{
case 'leave':
if(done)
done()
node.send(msg);
return
case 'block':
if(done)
done()
return
case 'limitKeyframe':
if(x < node.inputFrom )
y = computeOutput(node.inputFrom)
else
y = computeOutput(node.inputTo)
break
case 'limitRange':
if(x < node.inputFrom )
y = node.outputFrom
else
y = node.outputTo
break
default:
node.error('unknown input out of range strategy option (node.inputOutOfRangeStrategy)', msg)
return
}
}
if(node.rounding>=0)
y = Number(y.toFixed(node.rounding))
RED.util.setMessageProperty(msg, node.property, y)
node.send(msg);
}
if(done)
done()
});
function computeOutput(x)
{
let y = x
let normalizedX = normalize(x, node.inputFrom, node.inputTo);
for(var i = 1; i < node.keyframes.length; i++)
{
if( (normalizedX < node.keyframes[i].x) || (( i === node.keyframes.length-1) && normalizedX === node.keyframes[i].x) )
{
var startKeyframe = node.keyframes[i-1];
var endKeyframe = node.keyframes[i];
y = interpolateLinear(startKeyframe.y, endKeyframe.y, normalize(normalizedX, startKeyframe.x, endKeyframe.x) );
break;
}
}
return node.outputFrom + (node.outputTo-node.outputFrom) * y;
}
function inInputRange(x)
{
return ( x>= node.inputFrom && x <= node.inputTo);
}
function getXFromMessage(msg)
{
return msg.payload;
}
function normalize(x, min, max){
if( max == min )
return 0;
return (x-min)/(max-min);
}
function interpolateLinear(a, b, x) {
return ((b * x)+(a * (1-x)));
}
}
RED.nodes.registerType("mapper",Mapper);
RED.httpAdmin.get('/mapper/js/*', function(req, res){
var options = {
root: __dirname + '/static/',
dotfiles: 'deny'
};
res.sendFile(req.params[0], options);
});
}