GameCrew AIEarly access
Sign in
Three.jsmaterialsRevision 1 · Compile-verified pattern

Hexagonal Stochastic Anti-Tiling & Seamless Surface Detail in Three.js

Eliminate visible texture grid repetition on large floors, terrain, and cliffs in Three.js r183 by patching MeshStandardMaterial with 3-tap hexagonal barycentric stochastic UV sampling and variance-preserving blending.

  • tiling
  • hex-tiling
  • stochastic
  • texture
  • anti-tiling
  • terrain
  • materials
  • shader
  • onbeforecompile
  • webgl2

No demo.

When to Use & Field Best Practices

Repeating a single 1024 px stone, grass, sand, or cliff texture across a 100 m floor produces unmistakable checkerboard grids from elevated or overview cameras. Hexagonal Stochastic Tiling breaks repetition permanently using just 3 texture fetches per pixel on standard PBR materials — with zero extra geometry or megatextures:

  1. Hexagonal Lattice + Barycentric Weights: Partition UV space into an equilateral triangle/hex grid so every pixel sits inside one triangle of 3 hex centers. Compute smooth power-weighted barycentric weights (w^contrast) so hex blends remain crisp instead of blurry.
  2. Explicit textureGrad Derivatives (No Mipmap Seams!): Because each hex cell offsets (and optionally rotates) UVs discontinuously at triangle edges, naive texture2D causes finite-difference dFdx/dFdy spikes and ugly black/blurry seam lines. Always compute vec2 ddx = dFdx(uv); vec2 ddy = dFdy(uv); before offsetting and pass them into textureGrad(tex, uv + off, ddx, ddy).
  3. Variance-Preserving Color Restoration: Blending 3 random samples shrinks contrast toward the texture's mean color (sqrt(w1^2 + w2^2 + w3^2) < 1). Re-normalizing around a low-mip mean sample (or mix contrast boost) keeps stone grain and foliage crisp across blend zones.
  4. Stable customProgramCacheKey: Always set mat.customProgramCacheKey when using onBeforeCompile so Three.js shares compiled WebGL programs across materials using the same anti-tiling config.

Mathematical & Algorithmic Core

  • Skewed Triangular Lattice: Transform p = uv · s by the skew matrix M = beginpmatrix 1 & -frac1√3 \\ 0 & frac2√3 endpmatrix to locate triangle vertices v_1, v_2, v_3 and barycentric weights (w_1, w_2, w_3) with Σ w_i = 1.
  • Contrast-Preserving Blend with mean color c and sharpness k ∈ [1, 8]: $w_i = (w_i^k)/(Σ_j w_j^k), c = c + fracΣ_i w_i (s_i - c)√Σ_i w_i^2$

Engine Implementation (Assets/Game/hexTiling.ts)

Strict erasable TypeScript patching any THREE.MeshStandardMaterial (albedo + optional normal/roughness maps) plus a zero-dependency procedural tileable stone/ground DataTexture fallback:

import * as THREE from 'three';

export interface HexTilingOptions {
  /** World/UV tile scale multiplier inside the hex lattice (default 1.0). */
  patchScale?: number;
  /** Blend sharpness between neighboring hex patches (1 = soft, 6 = crisp, default 4.0). */
  blendSharpness?: number;
  /** Per-patch UV rotation in radians (0 keeps directional bricks aligned, default 0.35). */
  rotationJitter?: number;
  /** Restore micro-contrast across 3-tap blend zones (0..1, default 0.65). */
  contrastPreserve?: number;
}

export interface HexTilingUniforms {
  uHexScale: { value: number };
  uHexSharpness: { value: number };
  uHexRotate: { value: number };
  uHexContrast: { value: number };
}

const HEX_GLSL_HELPERS = /* glsl */ `
uniform float uHexScale;
uniform float uHexSharpness;
uniform float uHexRotate;
uniform float uHexContrast;

vec2 hexHash2(vec2 p) {
  vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973));
  p3 += dot(p3, p3.yzx + 33.33);
  return fract((p3.xx + p3.yz) * p3.zy);
}

mat2 hexRot2(float a) {
  float c = cos(a);
  float s = sin(a);
  return mat2(c, -s, s, c);
}

vec4 hexTileSample(sampler2D tex, vec2 uv) {
  vec2 ddx = dFdx(uv);
  vec2 ddy = dFdy(uv);

  vec2 p = uv * uHexScale;
  // Skew square grid into equilateral triangle lattice
  mat2 skew = mat2(1.0, 0.0, -0.57735027, 1.15470054);
  vec2 sp = skew * p;
  vec2 cell = floor(sp);
  vec2 f = fract(sp);

  vec2 v1 = cell;
  vec2 v2 = cell + vec2(1.0, 1.0);
  vec2 v3 = f.x > f.y ? (cell + vec2(1.0, 0.0)) : (cell + vec2(0.0, 1.0));

  float w1 = 1.0 - max(f.x, f.y);
  float w2 = min(f.x, f.y);
  float w3 = abs(f.x - f.y);

  float k = max(1.0, uHexSharpness);
  vec3 w = pow(max(vec3(w1, w2, w3), vec3(1e-4)), vec3(k));
  w /= (w.x + w.y + w.z);

  vec2 h1 = hexHash2(v1);
  vec2 h2 = hexHash2(v2);
  vec2 h3 = hexHash2(v3);

  mat2 r1 = hexRot2((h1.x - 0.5) * uHexRotate);
  mat2 r2 = hexRot2((h2.x - 0.5) * uHexRotate);
  mat2 r3 = hexRot2((h3.x - 0.5) * uHexRotate);

  vec4 s1 = textureGrad(tex, r1 * uv + h1, r1 * ddx, r1 * ddy);
  vec4 s2 = textureGrad(tex, r2 * uv + h2, r2 * ddx, r2 * ddy);
  vec4 s3 = textureGrad(tex, r3 * uv + h3, r3 * ddx, r3 * ddy);

  vec4 blended = s1 * w.x + s2 * w.y + s3 * w.z;
  if (uHexContrast > 0.001) {
    vec4 meanCol = textureLod(tex, uv, 6.0);
    float invNorm = inversesqrt(max(dot(w, w), 0.12));
    vec4 restored = meanCol + (blended - meanCol) * min(invNorm, 1.65);
    blended = mix(blended, clamp(restored, 0.0, 1.0), uHexContrast);
  }
  return blended;
}
`;

/**
 * Patches a Three.js MeshStandardMaterial in place so its albedo (map) and roughnessMap
 * sample via 3-tap hexagonal stochastic anti-tiling with derivative-safe textureGrad.
 */
export function applyHexAntiTiling(
  material: THREE.MeshStandardMaterial,
  opts: HexTilingOptions = {}
): HexTilingUniforms {
  const uniforms: HexTilingUniforms = {
    uHexScale: { value: opts.patchScale ?? 1.0 },
    uHexSharpness: { value: opts.blendSharpness ?? 4.0 },
    uHexRotate: { value: opts.rotationJitter ?? 0.35 },
    uHexContrast: { value: opts.contrastPreserve ?? 0.65 },
  };

  material.customProgramCacheKey = () => 'ccgd-hex-anti-tiling-v1';
  material.onBeforeCompile = (shader) => {
    shader.uniforms.uHexScale = uniforms.uHexScale;
    shader.uniforms.uHexSharpness = uniforms.uHexSharpness;
    shader.uniforms.uHexRotate = uniforms.uHexRotate;
    shader.uniforms.uHexContrast = uniforms.uHexContrast;

    shader.fragmentShader = shader.fragmentShader
      .replace('#include <common>', `#include <common>\n${HEX_GLSL_HELPERS}`)
      .replace(
        '#include <map_fragment>',
        /* glsl */ `
        #ifdef USE_MAP
          vec4 sampledDiffuseColor = hexTileSample( map, vMapUv );
          diffuseColor *= sampledDiffuseColor;
        #endif
        `
      )
      .replace(
        '#include <roughnessmap_fragment>',
        /* glsl */ `
        float roughnessFactor = roughness;
        #ifdef USE_ROUGHNESSMAP
          vec4 texelRoughness = hexTileSample( roughnessMap, vRoughnessMapUv );
          roughnessFactor *= texelRoughness.g;
        #endif
        `
      );
  };
  material.needsUpdate = true;
  return uniforms;
}

/**
 * Procedural seamless stone/earth DataTexture fallback (zero network/file dependency)
 * useful when building a terrain material before generated textures are loaded.
 */
export function createSeamlessGroundTexture(
  baseHex = 0x5c6354,
  accentHex = 0x454b3f,
  size = 128
): THREE.DataTexture {
  const data = new Uint8Array(size * size * 4);
  // Extract raw sRGB channels directly (new THREE.Color(hex) converts to linear, which would double-darken SRGBColorSpace DataTextures)
  const aR = (baseHex >> 16) & 255;
  const aG = (baseHex >> 8) & 255;
  const aB = baseHex & 255;
  const bR = (accentHex >> 16) & 255;
  const bG = (accentHex >> 8) & 255;
  const bB = accentHex & 255;

  const hash = (x: number, y: number): number => {
    const wx = ((x % size) + size) % size;
    const wy = ((y % size) + size) % size;
    const n = Math.sin(wx * 12.9898 + wy * 78.233) * 43758.5453;
    return n - Math.floor(n);
  };

  const smoothTileNoise = (u: number, v: number, freq: number): number => {
    const x = u * freq;
    const y = v * freq;
    const ix = Math.floor(x);
    const iy = Math.floor(y);
    const fx = x - ix;
    const fy = y - iy;
    const sx = fx * fx * (3 - 2 * fx);
    const sy = fy * fy * (3 - 2 * fy);
    const p = Math.max(1, Math.round(freq));
    const n00 = hash(ix % p, iy % p);
    const n10 = hash((ix + 1) % p, iy % p);
    const n01 = hash(ix % p, (iy + 1) % p);
    const n11 = hash((ix + 1) % p, (iy + 1) % p);
    return (n00 * (1 - sx) + n10 * sx) * (1 - sy) + (n01 * (1 - sx) + n11 * sx) * sy;
  };

  for (let y = 0; y < size; y++) {
    for (let x = 0; x < size; x++) {
      const u = x / size;
      const v = y / size;
      const fbm =
        smoothTileNoise(u, v, 8) * 0.55 +
        smoothTileNoise(u, v, 16) * 0.30 +
        smoothTileNoise(u, v, 32) * 0.15;
      const i = (y * size + x) * 4;
      data[i] = Math.round(bR + (aR - bR) * fbm);
      data[i + 1] = Math.round(bG + (aG - bG) * fbm);
      data[i + 2] = Math.round(bB + (aB - bB) * fbm);
      data[i + 3] = 255;
    }
  }

  const tex = new THREE.DataTexture(data, size, size, THREE.RGBAFormat);
  tex.wrapS = THREE.RepeatWrapping;
  tex.wrapT = THREE.RepeatWrapping;
  tex.generateMipmaps = true;
  tex.minFilter = THREE.LinearMipmapLinearFilter;
  tex.magFilter = THREE.LinearFilter;
  tex.colorSpace = THREE.SRGBColorSpace;
  tex.needsUpdate = true;
  return tex;
}

Browser, Mobile & Software-Renderer Budgets

  • Texture Cost: 3 textureGrad taps + 1 mip-6 mean lookup per mapped channel (~0.18 ms at 1080p on integrated/mobile GPUs). Keep rotationJitter = 0 on directional materials (brick, wood planks) and 0.35–1.2 on organic dirt, grass, sand, and stone.
  • Mipmaps Required: Ensure tex.generateMipmaps = true and tex.wrapS = tex.wrapT = THREE.RepeatWrapping on any texture passed to applyHexAntiTiling so textureLod(tex, uv, 6.0) returns a true average color.
  • VR Parity: Runs natively inside standard MeshStandardMaterial stereo draws with zero extra render passes — 100% WebXR safe.

Verification Checklist

  1. Run compile (threeCompile) to confirm the patched onBeforeCompile shader compiles cleanly in WebGL 2 with zero GLSL warnings.
  2. Tile a ground plane 12 × 12 times and inspect an overview capture: confirm zero checkerboard grid lines and zero black mipmap seams along hex patch boundaries.
  3. Verify contrastPreserve keeps terrain contrast readable rather than washing the ground into flat grey.

Official references

  • Ameobea — three-hex-tiling (MIT)
  • Morten S. Mikkelsen (2022 — Practical Real-Time Hex-Tiling)
  • Thomas Deliot & Eric Heitz (HPG 2018 — Procedural Stochastic Texturing by Tiling and Blending)
  • Inigo Quilez (2015 — Texture Repetition Elimination)

Open-source sources

Games built with this guide carry these credits, and the licence notices they ask for, in their third-party notices.

More Three.js games

Games made with GameCrew on the same engine. No game has been built with this guide yet: these show what Three.js games here look like.

More Three.js techniques

optimization

Instanced Wind Foliage, Object-Pooled Particles & Spring Feel in Three.js →

Single-draw-call THREE.InstancedMesh wind foliage with player bend, zero-GC pooled burst particles, and dt-invariant second-order springs that keep 60 Hz steps under 2 ms.

optimization

Octahedral Impostor Forests & Procedural Trees in Three.js →

Render thousands of 3D trees or distant props in a single Three.js r183 InstancedMesh draw call by baking an NxN hemisphere octahedral atlas at startup from a procedural ez-tree-style branching tree mesh.

rendering

Texel-Snapped 3D Pixel Art, Edge Highlights & PS1 Retro Rendering in Three.js →

Crisp low-resolution 3D pixel-art pipeline with depth silhouettes, normal-crease bevel highlights, Bayer 4x4 color quantization, texel-snapping helpers, and an optional PS1 clip-space vertex-snapping material patch in Three.js r183.

lighting

Fast Horizon AO, Contact Shadows & Planar Reflections in Three.js →

WebGL 2 scene-grounding lighting toolkit for Three.js r183 combining half-res rotated horizon AO with color-tinted bilateral denoise, VR/passthrough-safe soft contact shadows, and oblique-clipped planar mirror floors.

Use verified techniques inside a real game

Describe your game idea for free or connect an MCP assistant to search and contribute techniques.

Learn about collaboration