GLSL 中没有高阶函数,但可以模拟它们:
#define second_order 1
#define second_order1 2
#define another_function 3
//there are no function pointers in GLSL, so I use integers instead
int call(int f2,int param1){
//instead of a function, an integer is passed as a parameter
switch(f2){
case second_order:
return param1*2;
case second_order1:
return param1*3;
}
}
int call(int f2,int param1,int param2){
//this function can be overloaded to accept more parameters
switch(f2){
case another_function:
return param1 + param2;
}
}
int f(int f2, int i) {
return call(f2,i);
}
或者,这可以使用结构来完成:
struct function{
int x;
};
function Sin(){
return function(1);
}
function Cos(){
return function(2);
}
float call(function func,float x){
if(func == Sin()){
return sin(x);
}
else if(func == Cos()){
return cos(x);
}
}
vec4 map(function func,vec4 a1){
//this function can be overloaded for different array sizes
vec4 a2;
for(int i = 0; i < 4; i++){
a2[i] = call(func,a1[i]);
}
return a2;
}
也可以使用宏来模拟通用二阶函数:
#define map(function,input1,output1) \
for(int i = 0; i < input1.length(); i++){ \
output1[i] = function(input1[i]); \
}
此宏可用于任何类型的数组:
float[] arr1 = float[](1.,3.,4.);
float[arr1.length()] output1;
map(sin,arr1,output1)