Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 48 additions & 14 deletions src/color/creating_reading.js
Original file line number Diff line number Diff line change
Expand Up @@ -291,11 +291,14 @@ function creatingReading(p5, fn) {
* p5.strands is an experimental mode for writing shader code with p5.js-like
* syntax instead of GLSL. In p5.strands shader callbacks, `color()` accepts
* the same input formats but returns a `vec4` instead of a `p5.Color`
* object, with RGBA components normalized to the 0–1 range. All colors in
* strands are RGB-based; `colorMode()` has no effect inside shader
* callbacks. Color utility functions such as `red()`, `green()`, `blue()`,
* `alpha()`, `hue()`, `saturation()`, `brightness()`, and `lightness()`
* also return values in the 0–1 range when used in strands.
* object, with RGBA components normalized to the 0–1 range. It follows
* `colorMode()`, and calling `colorMode()` inside a shader callback only
* affects that shader. `color()` also accepts shader values, such as
* `hue(c)` or a uniform, in the `RGB`, `HSB` and `HSL` color modes. Color
* utility functions such as `red()`, `green()`, `blue()`, `alpha()`,
* `hue()`, `saturation()`, `brightness()`, and `lightness()` return values
* in the 0–1 range when used in strands, so `colorMode(HSB, 1)` lets you
* pass them back into `color()`.
*
* ```js example
* let myShader;
Expand All @@ -322,6 +325,35 @@ function creatingReading(p5, fn) {
* }
* ```
*
* ```js example
* let myShader;
* function setup() {
* createCanvas(100, 100, WEBGL);
* myShader = buildMaterialShader(myShaderBuilder);
* }
*
* function myShaderBuilder() {
* // Use HSB values from 0 to 1, like hue() returns.
* colorMode(HSB, 1);
* finalColor.begin();
* let c = finalColor.color;
* // Shift the hue over time. Hues wrap around past 1.
* let h = hue(c) + millis() * 0.0002;
* finalColor.set(color(h, saturation(c), brightness(c), alpha(c)));
* finalColor.end();
* }
*
* function draw() {
* background(200);
* shader(myShader);
* noStroke();
* fill(255, 0, 0);
* sphere(40);
*
* describe('A sphere slowly changing through the colors of the rainbow.');
* }
* ```
*
* @method color
* @param {Number} gray number specifying value between white and black.
* @param {Number} [alpha] alpha value relative to current color range
Expand Down Expand Up @@ -491,7 +523,7 @@ function creatingReading(p5, fn) {
*
* In p5.strands shader callbacks, `red()` operates on `vec4` values and
* returns the red channel as a normalized value in the 0–1 range.
* `colorMode()` has no effect inside shader callbacks.
* The range doesn't change with `colorMode()`.
*
* ```js example
* let myShader;
Expand Down Expand Up @@ -644,7 +676,7 @@ function creatingReading(p5, fn) {
*
* In p5.strands shader callbacks, `green()` operates on `vec4` values and
* returns the green channel as a normalized value in the 0–1 range.
* `colorMode()` has no effect inside shader callbacks.
* The range doesn't change with `colorMode()`.
*
* ```js example
* let myShader;
Expand Down Expand Up @@ -797,7 +829,7 @@ function creatingReading(p5, fn) {
*
* In p5.strands shader callbacks, `blue()` operates on `vec4` values and
* returns the blue channel as a normalized value in the 0–1 range.
* `colorMode()` has no effect inside shader callbacks.
* The range doesn't change with `colorMode()`.
*
* ```js example
* let myShader;
Expand Down Expand Up @@ -918,7 +950,7 @@ function creatingReading(p5, fn) {
*
* In p5.strands shader callbacks, `alpha()` operates on `vec4` values and
* returns the alpha channel as a normalized value in the 0–1 range.
* `colorMode()` has no effect inside shader callbacks.
* The range doesn't change with `colorMode()`.
*
* ```js example
* let myShader;
Expand Down Expand Up @@ -1059,7 +1091,7 @@ function creatingReading(p5, fn) {
*
* In p5.strands shader callbacks, `hue()` operates on `vec4` values and
* returns the hue as a normalized value in the 0–1 range.
* `colorMode()` has no effect inside shader callbacks.
* The range doesn't change with `colorMode()`.
*
* ```js example
* let myShader;
Expand Down Expand Up @@ -1266,7 +1298,8 @@ function creatingReading(p5, fn) {
*
* In p5.strands shader callbacks, `saturation()` operates on `vec4` values
* and returns the saturation as a normalized value in the 0–1 range.
* `colorMode()` has no effect inside shader callbacks.
* It returns HSB saturation in `HSB` mode and HSL saturation otherwise.
* The range doesn't change with `colorMode()`.
*
* ```js example
* let myShader;
Expand Down Expand Up @@ -1429,7 +1462,7 @@ function creatingReading(p5, fn) {
*
* In p5.strands shader callbacks, `brightness()` operates on `vec4` values
* and returns the brightness as a normalized value in the 0–1 range.
* `colorMode()` has no effect inside shader callbacks.
* The range doesn't change with `colorMode()`.
*
* ```js example
* let myShader;
Expand Down Expand Up @@ -1591,7 +1624,7 @@ function creatingReading(p5, fn) {
*
* In p5.strands shader callbacks, `lightness()` operates on `vec4` values
* and returns the lightness as a normalized value in the 0–1 range.
* `colorMode()` has no effect inside shader callbacks.
* The range doesn't change with `colorMode()`.
*
* ```js example
* let myShader;
Expand Down Expand Up @@ -1735,7 +1768,8 @@ function creatingReading(p5, fn) {
*
* In p5.strands shader callbacks, `lerpColor()` interpolates between
* `vec4` colors and returns a normalized `vec4` with RGBA components in
* the 0–1 range. `colorMode()` has no effect inside shader callbacks.
* the 0–1 range. Colors are always mixed in RGB, whatever the
* `colorMode()`.
*
* ```js example
* let myShader;
Expand Down
5 changes: 5 additions & 0 deletions src/color/setting.js
Original file line number Diff line number Diff line change
Expand Up @@ -729,6 +729,11 @@ function setting(p5, fn) {
* is mapped using (50 + 100) / 2 = 75 as its effective maximum. More complex or negative
* ranges are currently not handled, so results in those cases may be ambiguous.
*
* In p5.strands shader callbacks, calling `colorMode()` only affects that
* shader and doesn't change the sketch's color mode. If it isn't called,
* the sketch's color mode is used. When <a href="#/p5/color">color()</a> is
* given shader values, it supports the `RGB`, `HSB` and `HSL` color modes.
*
* @method colorMode
* @param {RGB|HSB|HSL|RGBP3|HWB|LAB|LCH|OKLAB|OKLCH} mode either RGB, HSB, HSL,
* or one of the extended modes described above.
Expand Down
6 changes: 6 additions & 0 deletions src/strands/p5.strands.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ function strands(p5, fn) {
* @property {Array} tempProps Temporary property descriptors, restored newest first.
* @property {Number} _noiseOctaves Noise octave override captured by `noiseDetail()`.
* @property {Number} _noiseAmpFalloff Noise falloff override captured by `noiseDetail()`.
* @property {String} _colorMode Color mode override captured by `colorMode()`.
* @property {Object} _colorMaxes Color range overrides captured by `colorMode()`.
* @property {Number} _randomSeed Random seed override captured by `randomSeed()`.
* @property {Object} _builtinGlobals Cache of builtin-global uniform nodes for the current DAG.
* @property {Map} sharedVariables Shared variable metadata that tracks vertex/fragment usage to decide whether each variable becomes a local declaration or a varying.
Expand Down Expand Up @@ -131,6 +133,8 @@ function strands(p5, fn) {
ctx.tempProps = [];
ctx._noiseOctaves = null;
ctx._noiseAmpFalloff = null;
ctx._colorMode = null;
ctx._colorMaxes = null;
ctx._randomSeed = null;
ctx._builtinGlobals = createBuiltinGlobalsCache(ctx.dag);
ctx.sharedVariables = new Map();
Expand Down Expand Up @@ -174,6 +178,8 @@ function strands(p5, fn) {
ctx.tempProps = [];
ctx._noiseOctaves = null;
ctx._noiseAmpFalloff = null;
ctx._colorMode = null;
ctx._colorMaxes = null;
ctx._randomSeed = null;
ctx._builtinGlobals = createBuiltinGlobalsCache(ctx.dag);
ctx.sharedVariables = new Map();
Expand Down
145 changes: 143 additions & 2 deletions src/strands/strands_api.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,18 @@ import {
isReservedStrandsName,
STRANDS_INTERNAL_NAME_PREFIX
} from './strands_names';
import { Color } from '../color/p5.Color';
import {
RGB,
RGBP3,
HSB,
HSL,
HWB,
LAB,
LCH,
OKLAB,
OKLCH
} from '../color/color_constants';

const BUILTIN_GLOBAL_SPECS = {
width: { typeInfo: DataType.float1, get: p => p.width },
Expand Down Expand Up @@ -956,13 +968,137 @@ export function initGlobalStrandsAPI(p5, fn, strandsContext) {
return result;
});

// Like noiseDetail(), colorMode() in strands only applies to this shader
const getStrandsColorMode = instance => ({
mode: strandsContext._colorMode ?? instance._renderer.states.colorMode,
maxes: strandsContext._colorMaxes ?? instance._renderer.states.colorMaxes
});

const originalColorMode = fn.colorMode;
augmentFn(fn, p5, 'colorMode', function (mode, max1, max2, max3, maxA) {
if (!strandsContext.active) {
return originalColorMode.apply(this, arguments);
}
if ([RGB, RGBP3, HSB, HSL, HWB, LAB, LCH, OKLAB, OKLCH].includes(mode)) {
if ([max1, max2, max3, maxA].some(max => max?.isStrandsNode)) {
FES.userError(
'type error',
'colorMode() in p5.strands needs plain numbers for its ranges, not shader values.'
);
}
// Same as core colorMode(), but saved on the strands context
const colorMaxes = getStrandsColorMode(this).maxes.clone();
const maxes = colorMaxes[mode];
if (arguments.length === 2) {
maxes[0] = max1;
maxes[1] = max1;
maxes[2] = max1;
maxes[3] = max1;
} else if (arguments.length === 4) {
maxes[0] = max1;
maxes[1] = max2;
maxes[2] = max3;
} else if (arguments.length === 5) {
maxes[0] = max1;
maxes[1] = max2;
maxes[2] = max3;
maxes[3] = maxA;
}
strandsContext._colorMode = mode;
strandsContext._colorMaxes = colorMaxes;
}
return getStrandsColorMode(this).mode;
});

// Hue to RGB at full saturation and brightness, based on:
// http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl
// Uses fract() to wrap the hue, since mod() differs on WebGPU
const _hue2rgb = (instance, h) => {
const K = instance.vec3(1, 2 / 3, 1 / 3);
const p = instance.abs(
instance.fract(instance.vec3(h, h, h).add(K)).mult(6).sub(3)
);
return instance.clamp(p.sub(1), 0, 1);
};

// HSB to RGB conversion based on:
// https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_RGB
const _hsb2rgb = (instance, h, s, b) =>
instance.mix(instance.vec3(1, 1, 1), _hue2rgb(instance, h), s).mult(b);

// HSL to RGB conversion based on:
// https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB
const _hsl2rgb = (instance, h, s, l) => {
const chroma = p5.strandsNode(1).sub(instance.abs(l.mult(2).sub(1))).mult(s);
return _hue2rgb(instance, h).sub(0.5).mult(chroma).add(l);
};

// Converts shader values to a vec4, reading them in the strands colorMode
const _colorFromShaderValues = (instance, values) => {
const { mode, maxes } = getStrandsColorMode(instance);
if (![RGB, HSB, HSL].includes(mode)) {
FES.userError(
'unsupported color mode',
`color() with shader values works in RGB, HSB and HSL color modes for now, not ${mode}. Numbers and color strings still work in every color mode.`
);
}
// Split vectors into channels, e.g. color(vec3(h, s, b))
const channels = values.flatMap(value =>
value?.isStrandsNode && value.dimension > 1
? ['x', 'y', 'z', 'w'].slice(0, value.dimension).map(c => value[c])
: [value]
);
if (channels.length > 4) {
FES.userError(
'parameter validation error',
`color() with shader values expects 1 to 4 values, but ${channels.length} were provided.`
);
}
// From the colorMode range to 0-1
const scale = (value, max) => p5.strandsNode(value).div(max);
const clamp01 = node => instance.clamp(node, 0, 1);
const ranges = maxes[mode];

let rgb;
let alpha = p5.strandsNode(1);
if (channels.length <= 2) {
// Grayscale uses the third channel's range, like p5.Color does
const gray = clamp01(scale(channels[0], ranges[2]));
rgb = instance.vec3(gray, gray, gray);
if (channels.length === 2) {
alpha = scale(channels[1], ranges[3]);
}
} else {
const [c1, c2, c3] = [0, 1, 2].map(i => scale(channels[i], ranges[i]));
if (mode === HSB) {
rgb = _hsb2rgb(instance, c1, clamp01(c2), clamp01(c3));
} else if (mode === HSL) {
rgb = _hsl2rgb(instance, c1, clamp01(c2), clamp01(c3));
} else {
rgb = instance.vec3(c1, c2, c3);
}
if (channels.length === 4) {
alpha = scale(channels[3], ranges[3]);
}
}
return instance.vec4(clamp01(rgb), clamp01(alpha));
};

const originalColor = fn.color;
augmentFn(fn, p5, 'color', function (...args) {
if (!strandsContext.active) {
return originalColor.apply(this, args);
}
const values = Array.isArray(args[0]) ? args[0] : args;
// Shader values can't go through the CPU parser below
if (values.some(value => value?.isStrandsNode)) {
return _colorFromShaderValues(this, values);
}
// Reuse p5's parser - handles hex strings, rgb(), CSS named colors, numerics
const c = originalColor.apply(this, args);
const { mode, maxes } = getStrandsColorMode(this);
const c = args[0] instanceof Color
? args[0]
: new Color(values, mode, maxes[mode], { clamp: true });
// _getRGBA() returns [r, g, b, a] normalized to 0-1
const rgba = c._getRGBA();
const { id, dimension } = build.primitiveConstructorNode(
Expand Down Expand Up @@ -1076,7 +1212,12 @@ export function initGlobalStrandsAPI(p5, fn, strandsContext) {
augmentFn(fn, p5, 'saturation', function (...args) {
if (!strandsContext.active) return originalSaturation.apply(this, args);
const colorNode = p5.strandsNode(args[0]);
return _rgb2hsl(this, this.vec3(colorNode.x, colorNode.y, colorNode.z)).y;
const rgb = this.vec3(colorNode.x, colorNode.y, colorNode.z);
// HSB saturation in HSB mode so it pairs with brightness(), else HSL
if (getStrandsColorMode(this).mode === HSB) {
return _rgb2hsb(this, rgb).y;
}
return _rgb2hsl(this, rgb).y;
});

const originalBrightness = fn.brightness;
Expand Down
Loading