{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "opal-loop",
  "title": "Opal Loop",
  "author": "HorizonX <https://horizonx.so>",
  "description": "A twisted, iridescent glass loop rendered with three.js on a transparent background.",
  "dependencies": [
    "three"
  ],
  "devDependencies": [
    "@types/three"
  ],
  "files": [
    {
      "path": "registry/drops/opal-loop/opal-loop.tsx",
      "content": "'use client';\n\nimport { useEffect, useRef, type CSSProperties } from 'react';\nimport { buildOpalLoop, type OpalLoopConfig, type OpalLoopHandle } from './opal-loop.engine.js';\n\nexport interface OpalLoopProps {\n  /** Sphere size, 0.5 to 1.5. */\n  scale?: number;\n  /** Glass tint. */\n  color?: string;\n  /** 0.04 to 0.5. */\n  roughness?: number;\n  /** 0 to 1. */\n  transmission?: number;\n  /** 0 to 1. */\n  iridescence?: number;\n  /** 0.5 to 2. */\n  exposure?: number;\n  /** Tilt in radians, -1.2 to 1.2. */\n  tilt?: number;\n  /** 0 to 2. */\n  speed?: number;\n  paused?: boolean;\n  className?: string;\n  style?: CSSProperties;\n}\n\nconst DEFAULTS = { scale: 1, color: '#f6f5ff', roughness: 0.075, transmission: 0.9, iridescence: 1, exposure: 1.05, tilt: 0.38, speed: 1 };\n\nconst clamp = (value: number | undefined, min: number, max: number, fallback: number) =>\n  typeof value === 'number' && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback;\n\nfunction toConfig(props: OpalLoopProps): OpalLoopConfig {\n  return {\n    scale: clamp(props.scale, 0.5, 1.5, DEFAULTS.scale),\n    color: props.color ?? DEFAULTS.color,\n    roughness: clamp(props.roughness, 0.04, 0.5, DEFAULTS.roughness),\n    transmission: clamp(props.transmission, 0, 1, DEFAULTS.transmission),\n    iridescence: clamp(props.iridescence, 0, 1, DEFAULTS.iridescence),\n    exposure: clamp(props.exposure, 0.5, 2, DEFAULTS.exposure),\n    tilt: clamp(props.tilt, -1.2, 1.2, DEFAULTS.tilt),\n    speed: clamp(props.speed, 0, 2, DEFAULTS.speed),\n    animate: !props.paused\n  };\n}\n\nconst CSS = `\n.opal-viewport{position:relative;box-sizing:border-box;width:100%;height:100%;background:transparent;isolation:isolate}\n.opal-canvas{display:block;width:100%;height:100%;background:transparent}\n.opal-status{position:absolute;inset:0;display:grid;place-items:center;padding:24px;color:inherit;font:14px/1.5 system-ui,sans-serif;text-align:center;pointer-events:none}\n.opal-status:empty{display:none}\n`;\n\n/** A twisted, iridescent glass loop rendered with three.js. Transparent background; fills its parent. */\nexport function OpalLoop({ className, style, ...props }: OpalLoopProps) {\n  const root = useRef<HTMLDivElement>(null);\n  const engine = useRef<OpalLoopHandle | null>(null);\n  const config = toConfig(props);\n  const latest = useRef(config);\n  const key = JSON.stringify(config);\n\n  // Declared before the mount effect so a remount always starts from the newest props.\n  useEffect(() => {\n    latest.current = config;\n    engine.current?.update(config);\n  }, [key]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  useEffect(() => {\n    // The engine force-loses its WebGL context on destroy, so every mount gets a fresh canvas.\n    const node = root.current!;\n    const canvas = document.createElement('canvas');\n    canvas.className = 'opal-canvas';\n    canvas.setAttribute('role', 'img');\n    canvas.setAttribute('aria-label', 'Animated opalescent glass loop');\n    node.prepend(canvas);\n    const handle = buildOpalLoop(node, latest.current);\n    engine.current = handle;\n    return () => { handle.destroy(); engine.current = null; canvas.remove(); };\n  }, []);\n\n  return (\n    <>\n      <style href=\"hx-drops-opal-loop\" precedence=\"default\">{CSS}</style>\n      <div ref={root} className={className ? `opal-viewport ${className}` : 'opal-viewport'} style={style}>\n        <span className=\"opal-status\" role=\"status\" />\n      </div>\n    </>\n  );\n}\n\nexport default OpalLoop;\n",
      "type": "registry:component"
    },
    {
      "path": "registry/drops/opal-loop/opal-loop.engine.js",
      "content": "// HorizonX Drops: this engine is copied unchanged from the HorizonX editor\n// (horizonx-frontend src/lib/tools/opalLoop.engine.js at 00b7cec).\n// Licensed under the HorizonX Drops License in this repository's LICENSE file.\n// Do not edit here: change it in horizonx-frontend and run scripts/sync-from-horizonx.mjs.\n// --- end of HorizonX Drops banner ---\n// Opal Loop: original procedural glass sphere. No background, external model or texture.\nexport function buildOpalLoop(root, initial) {\n  let dead=false, scene=null, config=initial;\n  const canvas=root.querySelector('.opal-canvas');\n  const status=root.querySelector('.opal-status');\n  const ready=import('three').then(THREE=>{\n    if(dead)return;\n\n\nconst CONFIG = {\n  geometry: { radius: 1.04, height: 1.04, twist: 6.8, segments: 128, rings: 96 },\n  material: { color: '#f6f5ff', metalness: .7, roughness: .075, transmission: .9, ior: 1.46, thickness: 1.6, iridescence: 1, iridescenceIOR: 1.8, iridescenceThicknessRange: [180, 520], dispersion: .28, clearcoat: 1, clearcoatRoughness: .035, envMapIntensity: 1.5 },\n  // Two-start symmetry produces a visual recurrence twice per full revolution.\n  animation: { duration: 4, tilt: .38 },\n};\n\nfunction geometry() {\n  const { radius, height, twist, segments: nu, rings: nv } = CONFIG.geometry;\n  const positions = [], uvs = [], indices = [];\n  for (let j = 0; j <= nv; j++) {\n    const v = j / nv, phi = v * Math.PI, y = Math.cos(phi);\n    for (let i = 0; i <= nu; i++) {\n      const u = i / nu, theta = u * Math.PI * 2;\n      const envelope = Math.max(0, Math.sin(phi));\n      const wave = 2 * theta + twist * y;\n      const lip = Math.pow(.5 + .5 * Math.cos(wave), 9);\n      const groove = Math.pow(.5 + .5 * Math.cos(wave + .55), 12);\n      // Fade the shallow spiral relief toward the poles to retain a round envelope.\n      const r = radius * envelope * (1 + envelope ** 2 * (.015*Math.cos(wave) + .065 * lip - .015 * groove));\n      positions.push(r * Math.cos(theta), height * y, r * Math.sin(theta));\n      uvs.push(u, v);\n      if (j < nv && i < nu) {\n        const a = j * (nu + 1) + i, b = a + nu + 1;\n        indices.push(a, a + 1, b, a + 1, b + 1, b);\n      }\n    }\n  }\n  const g = new THREE.BufferGeometry();\n  g.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));\n  g.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2));\n  g.setIndex(indices); g.computeVertexNormals();\n  const normals = g.attributes.normal, n = new THREE.Vector3();\n  for (let j = 0; j <= nv; j++) {\n    const a = j * (nu + 1), b = a + nu;\n    n.set(normals.getX(a)+normals.getX(b), normals.getY(a)+normals.getY(b), normals.getZ(a)+normals.getZ(b)).normalize();\n    normals.setXYZ(a,n.x,n.y,n.z); normals.setXYZ(b,n.x,n.y,n.z);\n  }\n  // Every longitude meets at each pole: unify their normals, not just the seam.\n  for(let i=0;i<=nu;i++){normals.setXYZ(i,0,1,0);normals.setXYZ(nv*(nu+1)+i,0,-1,0);}\n  return g;\n}\n\nfunction studio(renderer) {\n  const scene = new THREE.Scene();\n  scene.background = new THREE.Color('#898592');\n  function panel(x,y,z,w,h,color,intensity) {\n    const p = new THREE.Mesh(new THREE.PlaneGeometry(w,h), new THREE.MeshBasicMaterial({color:new THREE.Color(color).multiplyScalar(intensity),side:THREE.DoubleSide}));\n    p.position.set(x,y,z); p.lookAt(0,0,0); scene.add(p);\n  }\n  panel(-3,4,4,2,5,'#ffffff',4);\n  panel(3,1,3,.5,5,'#e7eeff',3);\n  panel(-4,-1,1,1,4,'#d1ffff',2);\n  panel(0,4,-2,4,2,'#ffffff',3);\n  panel(1,-3,2,3,.65,'#fff0ff',2);\n  panel(3,0,-3,2,4,'#bdb1e8',1.5);\n  panel(-1,1,-4,2,3,'#282335',.5);\n  panel(0,-2,4,.4,3,'#393344',.6);\n  const pmrem = new THREE.PMREMGenerator(renderer);\n  const target = pmrem.fromScene(scene,.035,.1,100);\n  scene.traverse(o => { o.geometry?.dispose(); o.material?.dispose(); });\n  pmrem.dispose();\n  return target;\n}\n\nfunction maps() {\n  const size=256, optics=new Uint8Array(size*size*4), film=new Uint8Array(size*size*4);\n  for (let y=0;y<size;y++) for (let x=0;x<size;x++) {\n    const u=x/(size-1)*Math.PI*2, h=Math.cos(y/(size-1)*Math.PI);\n    const ridge=Math.pow(.5+.5*Math.cos(2*u+CONFIG.geometry.twist*h),5);\n    const polish=Math.max(ridge,Math.pow(Math.abs(h),5)*.9), i=(y*size+x)*4;\n    optics[i]=255*(1-.50*polish); optics[i+1]=255*(.85-.55*polish); optics[i+2]=255*(.04+.75*polish); optics[i+3]=255;\n    const t=150+(1-Math.pow(Math.abs(h),8))*(65*Math.sin(u*2+h*3)+35*Math.sin(h*5-u));\n    film[i]=film[i+1]=film[i+2]=t;film[i+3]=255;\n  }\n  return [optics,film].map(data=>{\n    const texture=new THREE.DataTexture(data,size,size);\n    texture.wrapS=THREE.RepeatWrapping;texture.magFilter=texture.minFilter=THREE.LinearFilter;texture.needsUpdate=true;return texture;\n  });\n}\n\nfunction createOpal(canvas, initial) {\n  let config = initial;\n  const renderer=new THREE.WebGLRenderer({canvas,antialias:true,alpha:true,powerPreference:'high-performance'});\n  renderer.setPixelRatio(Math.min(devicePixelRatio,1.25));\n  // The refracted body is intentionally cloudy; a half-resolution transmission\n  // pass preserves its look without shading a full-size second scene each frame.\n  renderer.transmissionResolutionScale=0.5;\n  renderer.outputColorSpace=THREE.SRGBColorSpace;\n  renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.toneMappingExposure=1.05;\n  const scene=new THREE.Scene();\n  // Keep alpha outside the sphere; the rear surface provides the refracted body.\n  renderer.setClearColor('#e3e2e8',0);\n  const camera=new THREE.PerspectiveCamera(28,1,.1,100);\n  const environment=studio(renderer);scene.environment=environment.texture;\n  const [optics,film]=maps();\n  const spectral = { value: config.iridescence };\n  const material=new THREE.MeshPhysicalMaterial({...CONFIG.material,metalnessMap:optics,roughnessMap:optics,transmissionMap:optics,iridescenceThicknessMap:film});\n  // Reinforce thin-film optics in reflected directions, not painted UV stripes.\n  material.onBeforeCompile=shader=>{\n    shader.uniforms.opalIridescence=spectral;\n    shader.vertexShader='varying vec3 opalPosition;\\n'+shader.vertexShader;\n    shader.vertexShader=shader.vertexShader.replace('#include <begin_vertex>','#include <begin_vertex>\\nopalPosition=position;');\n    shader.fragmentShader='uniform float opalIridescence;\\nvarying vec3 opalPosition;\\n'+shader.fragmentShader;\n    shader.fragmentShader=shader.fragmentShader.replace('#include <opaque_fragment>',`\n      vec3 V = normalize(vViewPosition);\n      vec3 R = reflect(-V,normal);\n      float F = pow(1.0-abs(dot(normal,V)),0.7);\n      float polish = smoothstep(0.05,0.43,metalnessFactor);\n      float cloud = sin(opalPosition.y*8.0+sin(opalPosition.x*9.0))*sin(opalPosition.z*7.0+opalPosition.y*4.0);\n      float phase = dot(R,vec3(0.62,0.48,0.33))*1.5+F*0.35+cloud*0.06;\n      vec3 spectrum = 0.5+0.5*cos(6.283185*(phase+vec3(0.0,0.33,0.67)));\n      float streak = pow(0.5+0.5*sin(R.x*6.0+R.y*4.0),4.0);\n      vec3 pearl = mix(vec3(0.13,0.055,0.55),vec3(0.12,0.92,1.0),smoothstep(0.1,0.82,spectrum.b));\n      pearl = mix(pearl,vec3(1.0,0.91,0.38),pow(spectrum.r,4.0)*0.7);\n      pearl = mix(pearl,vec3(1.0,0.45,0.75),pow(spectrum.g,9.0)*.25);\n      pearl = mix(vec3(dot(pearl,vec3(0.2126,0.7152,0.0722))),pearl,opalIridescence);\n      vec3 reflection = mix(vec3(0.08,0.055,0.24),pearl*1.55,0.6+streak*0.4);\n      float glint = pow(max(0.0,1.0-abs(R.x*.75+R.y*.65-.12)),65.0);\n      reflection += vec3(glint*3.8);\n      vec3 milk = mix(vec3(0.69,0.71,0.79),spectrum,(0.07+F*0.1)*opalIridescence)+cloud*0.018;\n      outgoingLight = mix(outgoingLight,milk,0.18*(1.0-polish));\n      outgoingLight = mix(outgoingLight,reflection,polish*.87);\n      #include <opaque_fragment>\n    `);\n  };\n  const mesh=new THREE.Mesh(geometry(),material), tilt=new THREE.Group();\n  // Approximate the exit surface: the front glass refracts these rear folds.\n  // This gives the milky center optical depth instead of a flat background.\n  const interiorMaterial=new THREE.MeshPhysicalMaterial({color:'#d1dbea',metalness:.38,roughness:.16,iridescence:1,iridescenceIOR:1.8,iridescenceThicknessRange:[180,420],iridescenceThicknessMap:film,envMapIntensity:1.1,side:THREE.BackSide});\n  const interior=new THREE.Mesh(mesh.geometry,interiorMaterial);interior.scale.setScalar(.96);mesh.add(interior);\n  tilt.rotation.set(.15,0,CONFIG.animation.tilt);tilt.add(mesh);scene.add(tilt);\n  const light=new THREE.DirectionalLight('#ffffff',1.1);light.position.set(-3,4,5);scene.add(light);\n  const reduced=matchMedia('(prefers-reduced-motion: reduce)');\n  let elapsed=0, previous=performance.now(), frame=0, disposed=false, visible=true, contextLost=false;\n  const paused=()=>!config.animate || config.speed===0 || reduced.matches;\n  function draw(){if(disposed||contextLost)return;mesh.rotation.y=elapsed/CONFIG.animation.duration*Math.PI*2+.7;renderer.render(scene,camera);}\n  function tick(now){frame=0;if(disposed||contextLost||document.hidden||!visible)return;if(!paused())elapsed+=Math.min((now-previous)/1000,.1)*config.speed;previous=now;draw();if(!paused())frame=requestAnimationFrame(tick);}\n  function resume(){cancelAnimationFrame(frame);frame=0;previous=performance.now();if(!disposed&&!contextLost&&!document.hidden&&visible){draw();if(!paused())frame=requestAnimationFrame(tick);}}\n  function resize(){const {width,height}=canvas.getBoundingClientRect();if(!width||!height)return;renderer.setSize(width,height,false);camera.aspect=width/height;const span=5.05*Math.max(1,.8/camera.aspect);camera.position.set(0,0,span/(2*Math.tan(THREE.MathUtils.degToRad(camera.fov/2))));camera.updateProjectionMatrix();draw();}\n  function apply(next){config=next;material.color.set(config.color);material.roughness=config.roughness;if((material.transmission===0)!==(config.transmission===0))material.needsUpdate=true;material.transmission=config.transmission;material.iridescence=config.iridescence;interiorMaterial.iridescence=config.iridescence;spectral.value=config.iridescence;renderer.toneMappingExposure=config.exposure;tilt.rotation.z=config.tilt;tilt.scale.setScalar(config.scale);resume();}\n  function visibility(){resume();}\n  function motion(){resume();}\n  function lost(event){event.preventDefault();contextLost=true;cancelAnimationFrame(frame);}\n  function restored(){contextLost=false;resize();resume();}\n  const observer=new ResizeObserver(resize);observer.observe(canvas);\n  const intersection=new IntersectionObserver(entries=>{visible=entries[0].isIntersecting;resume();});intersection.observe(canvas);\n  document.addEventListener('visibilitychange',visibility);reduced.addEventListener('change',motion);\n  canvas.addEventListener('webglcontextlost',lost);canvas.addEventListener('webglcontextrestored',restored);\n  resize();apply(config);\n  return {\n    update:apply,\n    setTime(seconds){elapsed=seconds;draw();},\n    getState(){return{elapsed,paused:paused(),drawCalls:renderer.info.render.calls,triangles:renderer.info.render.triangles};},\n    destroy(){if(disposed)return;disposed=true;cancelAnimationFrame(frame);observer.disconnect();intersection.disconnect();document.removeEventListener('visibilitychange',visibility);reduced.removeEventListener('change',motion);canvas.removeEventListener('webglcontextlost',lost);canvas.removeEventListener('webglcontextrestored',restored);mesh.geometry.dispose();material.dispose();interiorMaterial.dispose();optics.dispose();film.dispose();environment.dispose();renderer.dispose();renderer.forceContextLoss();},\n  };\n}\n\n    scene=createOpal(canvas,config);\n    root.dataset.opalReady='true';\n  }).catch(()=>{if(!dead){status.textContent='WebGL 2 is required to display Opal Loop.';root.dataset.opalReady='error';}});\n  return {\n    ready,\n    update(next){if(dead)return;config=next;scene?.update(config);},\n    setTime(seconds){scene?.setTime(seconds);},\n    getState(){return scene?.getState();},\n    destroy(){if(dead)return;dead=true;scene?.destroy();scene=null;delete root.dataset.opalReady;}\n  };\n}\n",
      "type": "registry:component"
    },
    {
      "path": "registry/drops/opal-loop/opal-loop.engine.d.ts",
      "content": "// Types for opal-loop.engine.js (the engine itself is plain JavaScript).\nexport interface OpalLoopConfig {\n  scale: number;\n  color: string;\n  roughness: number;\n  transmission: number;\n  iridescence: number;\n  exposure: number;\n  tilt: number;\n  speed: number;\n  animate: boolean;\n}\n\nexport interface OpalLoopHandle {\n  ready: Promise<void>;\n  update(next: OpalLoopConfig): void;\n  setTime(seconds: number): void;\n  getState(): { elapsed: number; paused: boolean; drawCalls: number; triangles: number } | undefined;\n  destroy(): void;\n}\n\nexport function buildOpalLoop(root: HTMLElement, initial: OpalLoopConfig): OpalLoopHandle;\n",
      "type": "registry:component"
    }
  ],
  "meta": {
    "license": "HorizonX Drops License 1.0",
    "page": "https://horizonx.so/tools/opal-loop",
    "source": "https://horizonx.so"
  },
  "docs": "Opal Loop fills its parent, so give the parent a width and height. The full editor, presets and exports are at https://horizonx.so/tools/opal-loop",
  "categories": [
    "webgl",
    "3d"
  ],
  "type": "registry:component"
}