Skip to content

Instantly share code, notes, and snippets.

@MartinRGB
Forked from rc1/lut.frag
Last active November 30, 2017 06:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MartinRGB/aee922946fe4558a205c65ccc13ab8b6 to your computer and use it in GitHub Desktop.
Save MartinRGB/aee922946fe4558a205c65ccc13ab8b6 to your computer and use it in GitHub Desktop.
LUT Shader for Three.js for loading .cube files generate from Da Vinci resolve.
uniform sampler2D tDiffuse;
uniform sampler2D tLut;
uniform int lutSize;
uniform bool isEnabled;
varying vec2 vUv;
// Ref: http://www.khronos.org/webgl/wiki/WebGL_and_OpenGL_Differences#No_3D_Texture_support
vec4 sampleAs3DTexture( sampler2D tex, vec3 texCoord, float size ) {
float sliceSize = 1.0 / size; // space of 1 slice
float slicePixelSize = sliceSize / size; // space of 1 pixel
float sliceInnerSize = slicePixelSize * (size - 1.0); // space of size pixels
float zSlice0 = min(floor(texCoord.z * size), size - 1.0);
float zSlice1 = min(zSlice0 + 1.0, size - 1.0);
float xOffset = slicePixelSize * 0.5 + texCoord.x * sliceInnerSize;
float s0 = xOffset + (zSlice0 * sliceSize);
float s1 = xOffset + (zSlice1 * sliceSize);
vec4 slice0Color = texture2D(tex, vec2(s0, texCoord.y));
vec4 slice1Color = texture2D(tex, vec2(s1, texCoord.y));
float zOffset = mod(texCoord.z * size, 1.0);
return mix(slice0Color, slice1Color, zOffset);
}
void main() {
if ( !isEnabled ) {
gl_FragColor = texture2D( tDiffuse, vUv );
return;
}
vec4 color = texture2D( tDiffuse, vUv );
// Look it up in the LUT
color = sampleAs3DTexture( tLut, vec3( color.r, 1.0 - color.b , color.g ), float( lutSize ) );
gl_FragColor = color;
}
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
// First load `filename.cube` which can be generate from DaVinci resolve. The lut size will likely be 33. This function will create the texture.
function lutStringToTexture ( lutString, lutSize ) {
var totalNumberOfComponents = lutSize * lutSize * lutSize * 4;
var floatsIdx = 0;
var floatArray = lutString
.split( '\n' )
.map( function ( line ) {
return line.split( ' ' );
})
.filter( function ( components ) {
return components.length === 3;
})
.reduce( function ( floats, components, index ) {
components.forEach( function ( v, idx ) {
floats[ floatsIdx++ ] = v;
if ( idx===2 ) {
floats[ floatsIdx++ ] = 1.0;
}
});
return floats;
}, new Float32Array( totalNumberOfComponents ) );
var texture = new THREE.DataTexture( floatArray, lutSize * lutSize, lutSize );
texture.type = THREE.FloatType;
texture.format = THREE.RGBAFormat;
return texture;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment