Skip to content

RLabs-Inc/color-generator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@rlabs-inc/color-generator

Mathematical color generation in 3D OKLCH perceptual space using sacred geometry, physics, and nature.

Instead of picking colors by eye or following color theory rules, this library maps real mathematical structures into perceptual color space. Golden ratios, Platonic solids, fractals, chaos attractors, quantum mechanics, and ancient geometric patterns become color palettes that are mathematically harmonious by construction.

Install

npm install @rlabs-inc/color-generator
# or
bun add @rlabs-inc/color-generator

Quick Start

import { generate, toHex, getPattern, getAllPatterns } from '@rlabs-inc/color-generator';

// Define a seed color in OKLCH
const seed = { l: 0.6, c: 0.15, h: 270 };

// Generate a palette from a sacred geometry pattern
const result = generate('Flower of Life', seed);
console.log(result.colors.map(toHex));
// => ['#8b5cf6', '#a78bfa', '#6d28d9', ...]

// Generate with options
const palette = generate('Merkaba', seed, { count: 12, randomSeed: 42 });

// List all 256 available patterns
console.log(getAllPatterns().map(p => p.name));

Core Concepts

OKLCH Color Space

All operations happen in OKLCH — a perceptually uniform color space where equal numeric distances correspond to equal visual differences. Every color is defined by three dimensions:

  • L (Lightness): 0 = black, 1 = white
  • C (Chroma): 0 = gray, ~0.4 = maximum saturation
  • H (Hue): 0-360 degrees

3D Point Clouds

Unlike traditional color generators that only vary hue angles, every pattern here generates true 3D point clouds — varying lightness, chroma, AND hue simultaneously. A Platonic Tetrahedron maps its 4 vertices across all three OKLCH dimensions, not just 4 hues at fixed lightness.

Mathematical Fidelity

Each pattern maps a real mathematical structure into color space. The Lorenz Attractor traces its actual chaotic trajectory. The Fibonacci Sequence uses actual Fibonacci-derived spacing. The Sri Yantra maps its 9 interlocking triangles with geometric precision.

256 Patterns in 7 Categories

Classical (8 patterns)

Traditional color harmony with mathematical precision.

Pattern Default Colors Description
Monochromatic 7 Single hue, full L/C variation
Analogous 7 Neighboring hues (30 degrees) with gentle modulation
Complementary 8 Opposing hues (180 degrees) with mirrored lightness
Split Complementary 9 Base hue + two flanking complements
Triadic 9 Three equidistant hues (120 degree spacing)
Tetradic 8 Four equidistant hues (90 degree spacing)
Golden Ratio 12 Phi-based evolution in all three OKLCH dimensions
Fibonacci Sequence 12 Fibonacci-derived spacing in all three dimensions

Sacred Geometry (43 patterns)

Ancient geometric structures mapped into color space.

Includes: Flower of Life, Seed of Life, Egg of Life, Fruit of Life, Metatron's Cube, Sri Yantra, Merkaba, Vesica Piscis, Tree of Life, 64 Tetrahedron Grid, Torus, Vector Equilibrium, all 5 Platonic Solids (Tetrahedron, Cube, Octahedron, Dodecahedron, Icosahedron), Star of David, Enneagram, Labyrinth, Yin Yang, Ouroboros, Celtic Knot, Sacred Spiral, Gordian Knot, Lotus Unfolding, and more.

Mathematical (78 patterns)

Pure mathematics as color. Fractals, curves, sequences, surfaces.

Includes: Mandelbrot Set, Julia Set, Sierpinski Triangle, Koch Snowflake, Lissajous Curve, Rose Curve, Spirograph, Euler Spiral, Fermat Spiral, Lorenz Attractor, Rossler Attractor, Henon Map, Logistic Bifurcation, Cantor Dust, Barnsley Fern, Apollonian Gasket, Menger Sponge, and many more.

Physics (45 patterns)

Physical phenomena as color. Quantum mechanics, wave functions, relativity.

Includes: Quantum Superposition, Lindblad Equation, Schrödinger Well, Schwarzschild, Hawking Radiation, Cosmic Microwave Background, Gravitational Lensing, Pulsar Lighthouse, Supernova Remnant, Solar Flare, Galaxy Spiral Arms, Cosmic Web, and more.

Topology (25 patterns)

Topological surfaces and knots in color space.

Includes: Möbius Strip, Klein Bottle, Torus Knot, Trefoil Knot, Hopf Fibration, Calabi-Yau, Projective Plane, Borromean Rings, Seifert Surface, Hyperbolic Tiling, and more.

Natural (45 patterns)

Patterns found in nature.

Includes: Reaction-Diffusion, Lightning Fractal, River Delta, Snowflake Crystal, Nautilus Shell, Leaf Venation, Coral Branch, Crystal Lattice, Sand Dune, Aurora, Bioluminescence, Root System, Murmuration, Soap Film, Mycelium, Bismuth Crystal, Geode Cavity, Opal Iridescence, Amethyst Cluster, and more.

Harmonic (12 patterns)

Music theory and acoustics as color.

Pattern Default Colors Description
Overtone Series 12 Natural harmonic series
Solfeggio Frequencies 9 174-963 Hz healing frequencies as colors
Circle of Fifths 12 Musical fifths mapped to hue rotation
Cymatics 12 Standing wave patterns
Pentatonic Scale 5 Five-note scale
Chromatic Scale 12 All 12 semitones
Pythagorean Tuning 7 Ratio-based intervals
Schumann Resonance 7 Earth's electromagnetic frequencies
Binaural Beats 8 Frequency difference patterns
Harmonic Convergence 10 Multiple harmonic series converging
Acoustic Resonance 8 Room mode frequencies
Shepard Tone 10 Infinite rising/falling pitch illusion

API Reference

Generation

generate(pattern, seed, options?)

Generate a 3D OKLCH point cloud from a pattern and seed color.

import { generate } from '@rlabs-inc/color-generator';

const seed = { l: 0.5, c: 0.15, h: 180 };

// By pattern name (case-insensitive, separator-agnostic)
const result = generate('flower of life', seed);
// "Flower-of-Life", "flower_of_life", "FLOWER OF LIFE" all work

// With options
const result2 = generate('Merkaba', seed, {
  count: 16,        // Override default color count
  randomSeed: 42,   // Deterministic randomization
});

// result.colors   → OklchColor[]
// result.pattern  → 'Flower of Life'
// result.seed     → { l: 0.5, c: 0.15, h: 180 }

Pattern Registry

import {
  getAllPatterns,
  getPattern,
  getPatternsByCategory,
  getRandomPattern,
  definePattern,
  registerPattern,
} from '@rlabs-inc/color-generator';

// Browse patterns
const all = getAllPatterns();                    // All 256 patterns
const sacred = getPatternsByCategory('sacred'); // 43 sacred geometry patterns
const random = getRandomPattern('physics');     // Random physics pattern

// Lookup by name
const pattern = getPattern('Sri Yantra');
console.log(pattern.description);   // "9 interlocking triangles..."
console.log(pattern.defaultCount);  // 14
console.log(pattern.category);      // 'sacred'

// Register custom patterns
const myPattern = definePattern({
  name: 'My Pattern',
  category: 'mathematical',
  description: 'Custom 3D mapping',
  defaultCount: 8,
  generate: (seed, options) => {
    const count = options?.count ?? 8;
    // Return OklchColor[] array
    return Array.from({ length: count }, (_, i) => ({
      l: seed.l + (i * 0.05),
      c: seed.c,
      h: seed.h + (i * 45),
    }));
  },
});
registerPattern(myPattern);

Color Conversion

import {
  toHex, fromHex, toRgb, toHsl, toP3, toCss,
  toColorOutput, toColorOutputs,
} from '@rlabs-inc/color-generator';

const color = { l: 0.6, c: 0.15, h: 270 };

toHex(color);       // '#8b5cf6'
toRgb(color);       // { r: 139, g: 92, b: 246 }
toHsl(color);        // { h: 258, s: 89, l: 66 }
toP3(color);        // { r: 0.49, g: 0.35, b: 0.94 } (Display P3)
toCss(color);       // { oklch: 'oklch(0.6 0.15 270)', rgb: 'rgb(139, 92, 246)', ... }

// Full multi-format output
const output = toColorOutput(color);
output.hex;          // '#8b5cf6'
output.oklch;        // { l: 0.6, c: 0.15, h: 270 }
output.css.p3;       // 'color(display-p3 0.49 0.35 0.94)'

// Parse hex
const parsed = fromHex('#ff6b35');
// => { l: 0.68, c: 0.17, h: 46.2 }

Color Manipulation

import {
  blend, withAlpha, adjustLightness, adjustChroma, variations,
} from '@rlabs-inc/color-generator';

const a = { l: 0.6, c: 0.15, h: 270 };
const b = { l: 0.8, c: 0.10, h: 90 };

// Blend in OKLCH space (handles hue wrapping)
blend(a, b, 0.5);           // Midpoint between a and b

// Adjustments
adjustLightness(a, 0.1);    // 10% brighter
adjustLightness(a, -0.1);   // 10% darker
adjustChroma(a, 0.05);      // More vivid
adjustChroma(a, -0.05);     // More muted

// Alpha
withAlpha(a, 0.5);          // 50% opacity

// Generate variations
variations(a, 5, {
  lightnessSpread: 0.15,
  chromaSpread: 0.05,
  hueSpread: 10,
});

Contrast & Accessibility

import { contrast, ensureContrast, clampContrast, isDark } from '@rlabs-inc/color-generator';

const fg = { l: 0.9, c: 0.02, h: 0 };
const bg = { l: 0.15, c: 0.02, h: 0 };

// WCAG 2.x contrast ratio (1-21)
contrast(fg, bg);            // ~15.3

// Adjust lightness to meet minimum contrast (binary search, ~20 iterations)
const accessible = ensureContrast(fg, bg, 7.0);   // WCAG AAA

// Clamp to maximum contrast (for muted elements like comments)
const muted = clampContrast(fg, bg, 4.0);

// Perceptual darkness check
isDark(bg);                  // true (L < 0.5)
isDark(fg);                  // false

Color Analysis

import {
  distance, nearestByHue, filterByRange, sortColors, uniqueColors,
} from '@rlabs-inc/color-generator';

const colors = generate('Flower of Life', seed).colors;

// Perceptual distance (Euclidean in OKLab)
distance(colors[0], colors[1]);

// Find nearest color to a target hue
nearestByHue(colors, 120);  // Nearest to green

// Filter by OKLCH ranges (handles hue wrapping)
filterByRange(colors, {
  l: [0.3, 0.7],    // Mid-lightness only
  h: [200, 300],    // Blues and purples
});

// Sort by dimension
sortColors(colors, 'h');     // By hue
sortColors(colors, 'l');     // By lightness

// Deduplicate (default min distance: 0.02)
uniqueColors(colors, 0.05); // Remove perceptually similar colors

Gamut Management

import { clampToGamut, isInGamut } from '@rlabs-inc/color-generator';

const vivid = { l: 0.7, c: 0.35, h: 150 };

isInGamut(vivid);          // false (too saturated for sRGB)
clampToGamut(vivid);       // Reduces chroma, preserves L and H

Randomization

import { randomColor, createRng } from '@rlabs-inc/color-generator';

// Random color (clamped to sRGB gamut)
randomColor();
randomColor({ l: [0.3, 0.7], h: [200, 300] }); // Constrained ranges

// Seeded PRNG for deterministic generation
const rng = createRng(42);
rng(); // Always the same sequence

Picker Primitives

Building a color picker UI? These functions provide the low-level primitives.

import {
  lightnessGradient, chromaGradient, hueGradient, alphaGradient,
  generate2DMap, colorAtPosition, positionOfColor,
  pickerIsInGamut, mapToGamut,
} from '@rlabs-inc/color-generator';

const base = { l: 0.6, c: 0.15, h: 270 };

// 1D gradients for sliders
lightnessGradient(base, 21);  // L sweeps 0 to 1, C/H fixed
chromaGradient(base, 22);     // C sweeps 0 to 0.4, L/H fixed
hueGradient(base, 23);        // H sweeps 0 to 360, L/C fixed
alphaGradient(base, 10);      // Alpha sweeps 0 to 1

// 2D maps for pickers
const map = generate2DMap('lightness-chroma', base, 200, 200);
// map[y][x] → OklchColor (200x200 grid)

// Interactive: click position → color
colorAtPosition('hue-lightness', 50, 30, 200, 200, base);

// Reverse: color → position
positionOfColor('hue-lightness', someColor, 200, 200);

// Gamut checking (supports sRGB, Display P3, Rec. 2020)
pickerIsInGamut(color, 'p3');
mapToGamut(outOfGamutColor, 'srgb');

Mathematical Constants

import {
  PHI, GOLDEN_ANGLE, TAU, FIBONACCI, SOLFEGGIO, METALLIC_RATIOS,
  clamp01, clamp04, wrapHue, hueInRange,
} from '@rlabs-inc/color-generator';

PHI;              // 1.618033988749895 (Golden Ratio)
GOLDEN_ANGLE;     // 137.508 degrees
TAU;              // 2 * PI
FIBONACCI;        // [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
SOLFEGGIO;        // [174, 285, 396, 417, 528, 639, 741, 852, 963]
METALLIC_RATIOS;  // { silver: 2.414, bronze: 3.302, copper: 4.236 }

clamp01(1.5);     // 1.0
clamp04(0.5);     // 0.4
wrapHue(400);     // 40
hueInRange(350, 330, 30);  // true (handles wrapping)

Types

interface OklchColor {
  l: number;      // Lightness 0-1
  c: number;      // Chroma 0-~0.4
  h: number;      // Hue 0-360
  alpha?: number; // Opacity 0-1
}

interface Pattern {
  name: string;
  category: PatternCategory;
  description: string;
  defaultCount: number;
  generate: (seed: OklchColor, options?: PatternOptions) => OklchColor[];
}

interface GeneratedPalette {
  colors: OklchColor[];
  pattern: string;
  seed: OklchColor;
  options?: PatternOptions;
}

type PatternCategory =
  | 'classical' | 'sacred' | 'mathematical' | 'physics'
  | 'topology' | 'natural' | 'harmonic';

How It Works

  1. Seed: You provide a single OKLCH color as the origin point
  2. Pattern: A mathematical structure (e.g., Flower of Life's 19 intersection points) is mapped into 3D OKLCH space relative to the seed
  3. Generation: The pattern function produces an array of OKLCH colors — a true 3D point cloud
  4. Clamping: All output colors are automatically clamped to valid OKLCH ranges and sRGB gamut

The result is a set of colors that are harmonious not because someone picked them by eye, but because they follow the same mathematical relationships that create harmony in geometry, music, and nature.

License

MIT

About

Generate matching colors using sacred geometry

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors