Raymarching with SDFs

初出 1996 · John C. Hart — Sphere tracing of signed distance fields — Hart (1996); popularized in real time by Íñigo Quílez (2008–). · 年表 ↗

コミュニティ・通称 名称 — 記述的命名。符号付き距離場の「レイマーチング」。原理的な形は John C. Hart の「sphere tracing」(1996)。「ray marching」はコミュニティ用語で人名エポニムではない。

ひとことで Signed Distance Function に沿ってレイをマーチさせ陰関数曲面を描画する技法。フラグメントシェーダーで広く使われる。

Raymarching with SDFs · Open in new tab ↗ · Motion begins only when you press Run.

コード

上のデモの実際のスケッチ(サンドボックスで再現可能)。これで全部です。

raymarching-sdf/index.html
// Minimal raymarching of a smin'd union of 3 spheres + a ground plane,
// rendered in a single WebGL2 fragment shader.
const SEED = Math.random();

const c = document.getElementById('c');
const dpr = Math.min(devicePixelRatio || 1, 2);
const size = Math.min(innerWidth, innerHeight);
c.width  = Math.floor(size * dpr);
c.height = Math.floor(size * dpr);
const gl = c.getContext('webgl2');
if (!gl) {
  c.outerHTML = '<p style="color:#fff;font-family:system-ui">WebGL2 unavailable</p>';
} else {
  const vs = `#version 300 es
    in vec2 a; void main(){ gl_Position = vec4(a, 0.0, 1.0); }`;
  const fs = `#version 300 es
    precision highp float;
    out vec4 fragColor;
    uniform vec2 u_resolution;
    uniform float u_seed;

    // SDFs
    float sdSphere(vec3 p, float r){ return length(p) - r; }
    float sdPlane (vec3 p, float y){ return p.y - y; }
    // polynomial smooth min by IQ
    float smin(float a, float b, float k){
      float h = clamp(0.5 + 0.5*(b-a)/k, 0.0, 1.0);
      return mix(b, a, h) - k*h*(1.0-h);
    }

    // simple hash → [0,1)
    float hash(float n){ return fract(sin(n)*43758.5453123); }

    vec3 spherePos(int i){
      float s = u_seed * 100.0;
      return vec3(
        (hash(float(i)*7.1 + s) - 0.5) * 1.6,
        -0.2 + hash(float(i)*11.3 + s) * 0.7,
        (hash(float(i)*13.7 + s) - 0.5) * 1.6
      );
    }
    float sphereR(int i){ return 0.45 + hash(float(i)*17.0 + u_seed*100.0)*0.45; }

    float map(vec3 p){
      float d = sdPlane(p, -0.9);
      for (int i = 0; i < 3; i++) {
        d = smin(d, sdSphere(p - spherePos(i), sphereR(i)), 0.35);
      }
      return d;
    }
    vec3 normal(vec3 p){
      vec2 e = vec2(0.0015, 0.0);
      return normalize(vec3(
        map(p + e.xyy) - map(p - e.xyy),
        map(p + e.yxy) - map(p - e.yxy),
        map(p + e.yyx) - map(p - e.yyx)
      ));
    }

    void main(){
      vec2 uv = (gl_FragCoord.xy - 0.5 * u_resolution) / u_resolution.y;
      // camera
      vec3 ro = vec3(0.0, 0.4, 3.5);
      vec3 rd = normalize(vec3(uv, -1.4));

      float t = 0.0;
      float d = 0.0;
      vec3 p;
      bool hit = false;
      for (int i = 0; i < 96; i++) {
        p = ro + rd * t;
        d = map(p);
        if (d < 0.001) { hit = true; break; }
        if (t > 16.0) break;
        t += d;
      }

      vec3 col;
      if (hit) {
        vec3 n = normal(p);
        vec3 lDir = normalize(vec3(0.7, 0.9, 0.4));
        float diff = clamp(dot(n, lDir), 0.0, 1.0);
        float ao = 0.5 + 0.5*n.y;
        vec3 base = 0.5 + 0.5*sin(vec3(0.0, 2.1, 4.2) + p.y*1.5 + u_seed*6.28);
        col = base * (0.25 + 0.85*diff) * ao;
        // sky-fog
        col = mix(col, vec3(0.07,0.08,0.11), 1.0 - exp(-0.06 * t));
      } else {
        // sky gradient
        col = mix(vec3(0.05,0.06,0.10), vec3(0.18,0.21,0.28), 0.5 + 0.5*rd.y);
      }
      // gamma
      col = pow(col, vec3(1.0/2.2));
      fragColor = vec4(col, 1.0);
    }`;

  function shader(type, src){
    const sh = gl.createShader(type);
    gl.shaderSource(sh, src);
    gl.compileShader(sh);
    if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
      console.error(gl.getShaderInfoLog(sh));
    }
    return sh;
  }
  const prog = gl.createProgram();
  gl.attachShader(prog, shader(gl.VERTEX_SHADER, vs));
  gl.attachShader(prog, shader(gl.FRAGMENT_SHADER, fs));
  gl.linkProgram(prog);
  gl.useProgram(prog);

  const buf = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, buf);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
    -1,-1, 1,-1, -1,1,  -1,1, 1,-1, 1,1
  ]), gl.STATIC_DRAW);
  const loc = gl.getAttribLocation(prog, 'a');
  gl.enableVertexAttribArray(loc);
  gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);

  gl.uniform2f(gl.getUniformLocation(prog, 'u_resolution'), c.width, c.height);
  gl.uniform1f(gl.getUniformLocation(prog, 'u_seed'), SEED);
  gl.viewport(0, 0, c.width, c.height);
  gl.drawArrays(gl.TRIANGLES, 0, 6);
}

デモのソースを開く ↗

仕組み

SDF は任意の点から最近接面までの距離(内部は負)を返す。各ピクセルでカメラからレイを飛ばし「スフィアトレース」する:(1) 現在点で SDF を評価(面を越えない最大安全ステップ)、(2) その距離だけレイを進める、(3) 距離が微小 ε 未満(命中)か最大ステップ/距離超過(外れ)まで反復。命中点の法線は SDF の勾配(有限差分)から得て陰影を付ける。シーンはプリミティブ SDF を min/max(和/積)、smooth-min(融合)、座標の変換/反復で合成して構築する — すべてフラグメントシェーダー内で行う。

パラメータ

系譜

先行例
Iñigo Quílez
関連
Metaballs、Fragment Shader (GLSL)

よく組み合わされるアルゴリズム

このアルゴリズムを使う作品 (36)

Autoscope
erik-swahn
Bokeh (lamps)
mpkoz
Bokeh
mpkoz
celestial cyclones
hideo
chaos comes with the summer haze
cole-sternberg
Contractions
loie-hollowell
Cosmic Reef
leo-villareal
Cosmodesias
santiago
Cytographia
golan-levin
Divergence
loren-bednar
Elevated
inigo-quilez
Elysian
logicoma
Fabergé Fractals
tom-beddard
Fermi Paradox
mercury
Funktor
erik-swahn
Gaia Machina
approximate
Human Unreadable
operator
Immaterial
bj-rn-staal
Kai-Gen
takeshi-murata-christopher-rutledge-j-krispy
l.o
night-sea
Longing
phenomena
Melancholic Magical Maiden
emi-kusano
Meridian
matt-deslauriers
Observatory
cocoon
Ottocento
berubara
Petro National
john-gerrard
PRELUDES
trevor-paglen
Return
aaron-penne
Seedlings
ves3l
Solar Transits
robert-hodgin
Square
still
the spring begins with the first rainstorm
cole-sternberg
This Is Not A Rock
nicole-vella
Trichro-matic
mountvitruvius
Woman, Life, Freedom
armaghan-fatemi
World Flag
john-gerrard

最終更新 2026-07-16