Vuo 2.4.4
Loading...
Searching...
No Matches
VuoImageMapColors.c
Go to the documentation of this file.
1
10#include "VuoImageRenderer.h"
11#include <OpenGL/CGLMacro.h>
12
14#ifdef VUO_COMPILER
16 "title" : "VuoImageMapColors",
17 "dependencies" : [
18 "VuoImageRenderer"
19 ]
20 });
21#endif
23
28{
29 if (!image)
30 return NULL;
31
32 if (!colors)
33 return image;
34
35 static const char * fragmentShaderSource = VUOSHADER_GLSL_SOURCE(120,
36
37 uniform float gradientCount;
38 uniform sampler2D image; // the unfiltered image
39 uniform sampler2D gradientStrip;// the gradient strip to map against
40 uniform float amount; // the amount to mix gradient and image
41 varying vec2 fragmentTextureCoordinate;
42
43 // https://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
44 float brightness(vec3 col)
45 {
46 // Digital CCIR601 (gives more weight to the green and red components):
47 return 0.299*col.r + 0.587*col.g + 0.114*col.b;
48 }
49
50 void main(void)
51 {
52 vec4 orig = texture2D(image, fragmentTextureCoordinate);
53
54 float lum = brightness(orig.rgb/orig.a);
55
56 float gradientWidth = (1./gradientCount)/2.;
57 lum = lum * (1-gradientWidth*2) + gradientWidth;
58
59 vec4 color = texture2D(gradientStrip, vec2(clamp(lum, gradientWidth, 1-gradientWidth), .5));
60
61 vec4 mixed = mix(orig, color, amount);
62 mixed *= orig.a;
63
64 gl_FragColor = mixed;
65 }
66 );
67
68 int len = VuoListGetCount_VuoColor(colors);
69
70 unsigned char* pixels = (unsigned char*)malloc(sizeof(unsigned char)*len*4);
71 int n = 0;
72 for(int i = 1; i <= len; i++)
73 {
74 VuoColor col = VuoListGetValue_VuoColor(colors, i);
75 // VuoColor is non-premultiplied, but VuoImage_makeFromBuffer() expects premultiplied colors, so premultiply them.
76 pixels[n++] = (unsigned int)(col.a*col.b*255);
77 pixels[n++] = (unsigned int)(col.a*col.g*255);
78 pixels[n++] = (unsigned int)(col.a*col.r*255);
79 pixels[n++] = (unsigned int)(col.a*255);
80 }
81
82 VuoImage gradientStrip = VuoImage_makeFromBuffer(pixels, GL_BGRA, len, 1, VuoImageColorDepth_8, ^(void *buffer){ free(buffer); });
83
84 VuoShader shader = VuoShader_make("Map Image Brightness to Gradient Shader");
85 VuoShader_addSource(shader, VuoMesh_IndividualTriangles, NULL, NULL, fragmentShaderSource);
86 VuoRetain(shader);
87
88 // Set `image` before `gradientStrip`, so that `image`'s scaleFactor is used for the output image.
89 VuoShader_setUniform_VuoImage(shader, "image", image);
90 VuoShader_setUniform_VuoImage(shader, "gradientStrip", gradientStrip);
91 VuoShader_setUniform_VuoReal (shader, "gradientCount", (float)len);
92 VuoShader_setUniform_VuoReal (shader, "amount", filterOpacity);
93
94 // Render.
95 VuoImage mappedImage = VuoImageRenderer_render(shader, image->pixelsWide, image->pixelsHigh, VuoImage_getColorDepth(image));
96
97 VuoRelease(shader);
98
99 return mappedImage;
100}