Codrops 원본

How to Create a Pixel-to-Voxel Video Drop Effect with Three.js and Rapier

섹션 · MIT

섹션 더 보기
ORIGINAL PREVIEW
How to Create a Pixel-to-Voxel Video Drop Effect with Three.js and Rapier 정적 미리보기

갤러리 안에서는 화면을 벗어나거나 움직임을 멈추면 예제도 닫힙니다. 다시 재생할 때는 처음부터 시작해요.

큰 화면으로 보기 새 탭

SOURCE FILES

원본 코드 읽기

21개 파일

수집한 원본 소스와 실행 안내를 함께 제공합니다.

src/css/base.css
파일 저장

*,
*::after,
*::before {
  box-sizing: border-box;
}

:root {
  font-size: 12px;
  --color-text: #fff;
  --color-bg: #000;
  --color-link: #fff;
  --color-link-hover: #fff;
  --page-padding: 1.5rem;
}

body {
  margin: 0;
  color: var(--color-text);
  background-color: var(--color-bg);
  font-family: ui-monospace, monospace;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

@media (scripting: enabled) {
  .loading {
    &::before,
    &::after {
      content: '';
      position: fixed;
      z-index: 10000;
    }

    &::before {
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: var(--color-bg);
    }

    &::after {
      top: 50%;
      left: 50%;
      width: 100px;
      height: 1px;
      margin: 0 0 0 -50px;
      background: var(--color-link);
      animation: loaderAnim 1.5s ease-in-out infinite alternate forwards;
    }
  }
}

@keyframes loaderAnim {
  0% {
    transform: scaleX(0);
    transform-origin: 0% 50%;
  }

  50% {
    transform: scaleX(1);
    transform-origin: 0% 50%;
  }

  50.1% {
    transform: scaleX(1);
    transform-origin: 100% 50%;
  }

  100% {
    transform: scaleX(0);
    transform-origin: 100% 50%;
  }
}

a {
  text-decoration: none;
  color: var(--color-link);
  outline: none;
  cursor: pointer;

  &:hover {
    text-decoration: underline;
    color: var(--color-link-hover);
  }

  &:focus {
    outline: none;
    background: lightgrey;

    &:not(:focus-visible) {
      background: transparent;
    }

    &:focus-visible {
      outline: 2px solid red;
      background: transparent;
    }
  }
}

.frame {
  padding: 3rem var(--page-padding) 0;
  display: grid;
  z-index: 1000;
  position: relative;
  grid-row-gap: 1rem;
  grid-column-gap: 2rem;
  pointer-events: none;
  justify-items: start;
  grid-template-columns: auto auto auto 1fr;
  grid-template-areas:
    'title title title title'
    'back archive github ...'
    'demos demos demos demos'
    'tags tags tags tags'
    'sponsor sponsor sponsor sponsor';

  #cdawrap {
    justify-self: start;
    grid-area: sponsor;
  }

  a,
  button {
    pointer-events: auto;
  }

  .frame__title {
    grid-area: title;
    font-size: inherit;
    margin: 0;
  }

  .frame__back {
    grid-area: back;
    justify-self: start;
  }

  .frame__archive {
    grid-area: archive;
    justify-self: start;
  }

  .frame__github {
    grid-area: github;
  }

  .frame__tags {
    grid-area: tags;
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
  }

  .frame__demos {
    grid-area: demos;
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
  }

  @media screen and (min-width: 53em) {
    padding: var(--page-padding);
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    grid-template-columns: auto auto auto auto 1fr;
    grid-template-rows: auto auto;
    align-content: space-between;
    grid-template-areas:
      'title back github archive demos'
      'tags tags tags sponsor sponsor';

    .frame__tags {
      align-self: end;
    }

    .frame__demos,
    #cdawrap {
      justify-self: end;
      text-align: right;
      max-width: 300px;
    }
  }
}

.content {
  padding: var(--page-padding);
  display: flex;
  flex-direction: column;
  width: 100vw;
  position: relative;

  @media screen and (min-width: 53em) {
    min-height: 100vh;
    justify-content: center;
    align-items: center;
  }
}
src/css/style.css
파일 저장

:root {
  --color-primary: #8bff38;
  --color-secondary: #fe4d29;
  --color-containerBg: #101010;
  --color-loadingBg: #242222;

  --color-pvd-text1: #b6b6b6;
  --color-pvd-text2: #111111;
}

/* -------------------------------------------------- */

body {
  background: var(--color-containerBg);
}

#loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: var(--color-loadingBg);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 2000;
  pointer-events: none;
}

.loader-word {
  color: var(--color-pvd-text);
  font-size: clamp(16px, 2.8vw, 32px);
  opacity: 0;
  animation-duration: 1.8s;
  animation-iteration-count: infinite;
}

#loading-overlay.loaded .loader-word {
  animation: none;
}


@keyframes anim-up-out {
  0% {
    opacity: 0;
    transform: translateY(10px);
  }

  15% {
    opacity: 1;
    transform: translateY(0);
    animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275);
  }

  75% {
    opacity: 1;
    transform: translateY(0);
  }

  85% {
    opacity: 0;
    transform: translateY(-10px);
    animation-timing-function: cubic-bezier(0.9, 0.03, 0.69, 0.22);
  }

  100% {
    opacity: 0;
    transform: translateY(-10px);
  }
}

@keyframes anim-down-out {
  0% {
    opacity: 0;
    transform: translateY(-15px);
  }

  15% {
    opacity: 1;
    transform: translateY(0);
    animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275);
  }

  45% {
    opacity: 1;
    transform: translateY(0);
  }

  75% {
    opacity: 0;
    transform: translateY(40px);
    animation-timing-function: cubic-bezier(0.9, 0.03, 0.69, 0.22);
  }

  100% {
    opacity: 0;
    transform: translateY(60px);
  }
}

#word-pixel {
  animation-name: anim-up-out;
  animation-delay: 0s;
}

#word-voxel {
  animation-name: anim-up-out;
  animation-delay: 0.15s;
}

#word-drop {
  animation-name: anim-down-out;
  animation-delay: 0.25s;
}

.content {
  position: fixed;
  top: 0;
  left: 0;
  padding: 0;
  width: 100vw;
  height: 100vh;
}



/* Tweakpane */
.tp-rotv {
  /* --tp-base-font-family: 'Share Tech Mono', monospace; */
  --tp-base-font-family: "Share Tech", sans-serif;
  --tp-base-background-color: var(--color-containerBg);
  font-size: 13px !important;
}

.tp-lblv>* {
  color: var(--color-pvd-text1) !important;
}


.tp-fldv_t {
  text-transform: uppercase !important;
  letter-spacing: 0.1em !important;
}

.tp-dfwv {
  user-select: none !important;
  -webkit-user-select: none !important;
}

.tp-btnv_b {
  font-size: 22px !important;
  font-weight: bold !important;
  height: 50px !important;
  background-color: var(--color-primary) !important;
  color: var(--color-pvd-text2) !important;
  border-radius: 4px !important;
  transition: background-color 0.2s ease-in;
}

@media (hover: hover) {
  .tp-btnv_b:hover {
    background-color: var(--color-secondary) !important;
  }
}
함께 쓰는 파일 19개 보기
src/index.html
파일 저장

<!DOCTYPE html>
<html lang="en" class="no-js">

  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Pixel-Voxel-Drop | Codrops</title>
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    <meta name="author" content="Codrops" />
    <link rel="icon" type="image/svg+xml" href="https://tympanus.net/favicon/favicon.svg" />
    <link rel="shortcut icon" href="https://tympanus.net/favicon/favicon.ico" />
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Share+Tech&display=swap" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="./css/base.css" />
    <link rel="stylesheet" type="text/css" href="./css/style.css">
    <script>
      document.documentElement.className = 'js';
    </script>
    <!--script src="//tympanus.net/codrops/adpacks/analytics.js"></script-->
  </head>

  <body class="demo-1">
    <main>
      <header class="frame">
        <h1 class="frame__title">Pixel-Voxel-Drop by <a href="https://x.com/1kkaku0608" target="_blank">Junichi Kasahara</a></h1>
        <a class="frame__back" href="https://tympanus.net/codrops/?p=">Article</a>
        <a class="frame__archive" href="https://tympanus.net/codrops/hub/">All demos</a>
        <a class="frame__github" href="https://github.com/codrops/">GitHub</a>
        <nav class="frame__tags">
          <a href="https://tympanus.net/codrops/demos/?tag=three-js">#three.js</a>
          <a href="https://tympanus.net/codrops/demos/?tag=rapier">#rapier</a>
          <a href="https://tympanus.net/codrops/demos/?tag=webgl">#webgl</a>
          <a href="https://tympanus.net/codrops/demos/?tag=physics">#physics</a>
          <a href="https://tympanus.net/codrops/demos/?tag=morphing">#morphing</a>
        </nav>
      </header>
      <div id="loading-overlay">
        <div class="loader-word" id="word-pixel">PIXEL</div>
        <div class="loader-word" id="word-voxel">VOXEL</div>
        <div class="loader-word" id="word-drop">DROP</div>
      </div>
      <div class="content">
      </div>
    </main>
    <!--script src="https://tympanus.net/codrops/adpacks/cda_sponsor.js"></script-->
    <script type="module" src="./js/index.js"></script>
  </body>

</html>
src/js/config/constants.js
파일 저장

export const STATES = {
  LOADING: "LOADING",
  DEFAULT: "DEFAULT",
  ANIMATING: "ANIMATING",
  COLLAPSED: "COLLAPSED",
  REVERSING: "REVERSING",
};

export const BUTTON_CONFIG = {
  [STATES.LOADING]: () => ({title: "LOADING...", disabled: true}),
  [STATES.DEFAULT]: (manual) => ({title: manual ? "CLICK ON THE PLANE" : "START EFFECT", disabled: manual}),
  [STATES.COLLAPSED]: () => ({title: "BACK TO PLANE", disabled: false}),
  [STATES.ANIMATING]: () => ({title: "ANIMATING...", disabled: true}),
  [STATES.REVERSING]: () => ({title: "RESTORING...", disabled: true}),
};

export const DEFAULT_PARAMS = {
  // Box
  gridCols: 50,
  gridSpacing: 1,
  shape: "cube",
  gridCount: "0",

  // Visual
  baseDuration: 2.2,
  usePixelate: true,
  useRGBShift: true,
  organicMode: true,
  effectSpread: 0.35,
  effectDepth: 1.5,
  highlightColor: "#f2f2f2",
  highlightIntensity: 0.0,

  // Physics
  dropDelay: 0.0,
  isDancing: true,
  dancingLevel: 4,

  // Controls
  manualMode: false,
};

export const INTERNAL_PARAMS = {
  playbackRate: 1.0,
  cameraDistance: 10,
  fitMargin: 0.55,
  gridOffsetY: 0,
  gravityY: 0,
  bodyRestitution: 1.3,
  bodyDamping: 0.8,
};
src/js/controllers/InteractionController.js
파일 저장

import * as THREE from "three";
import {getNormalizedPointer} from "../utils/common.js";
import {STATES} from "../config/constants.js";

export class InteractionController {
  constructor(main) {
    this.main = main;

    this.raycaster = new THREE.Raycaster();
    this.pointer = new THREE.Vector2();
    this.intersectionPoint = new THREE.Vector3();
    this.distanceToCamera = 0;

    this.onPointerDown = this.onPointerDown.bind(this);
    this.onPointerMove = this.onPointerMove.bind(this);
    this.onPointerUp = this.onPointerUp.bind(this);

    this.init();
  }

  init() {
    const {app} = this.main;
    app.renderer.domElement.addEventListener("pointerdown", this.onPointerDown);
    app.renderer.domElement.addEventListener("pointermove", this.onPointerMove);
    app.renderer.domElement.addEventListener("pointerup", this.onPointerUp);
  }

  onPointerDown(event) {
    const {app, pixelVoxelMesh, stateController, sequence, physics, params, gridInfo, container} = this.main;
    if (event.target !== app.domElement || !pixelVoxelMesh) return;

    const ndc = getNormalizedPointer(event, container.clientWidth, container.clientHeight);
    this.pointer.set(ndc.x, ndc.y);

    this.raycaster.setFromCamera(this.pointer, app.camera);
    const intersects = this.raycaster.intersectObject(pixelVoxelMesh.mesh);

    if (intersects.length > 0) {
      const {instanceId, point} = intersects[0];

      if (stateController.state === STATES.DEFAULT && params.manualMode) {
        const u = (instanceId % gridInfo.cols) / gridInfo.cols;
        const v = Math.floor(instanceId / gridInfo.cols) / gridInfo.rows;
        sequence.startCollapse(u, v);
        return;
      }

      if (stateController.state === STATES.COLLAPSED) {
        const success = physics.startDrag(point, instanceId);
        if (success) {
          app.controls.enabled = false;
          this.distanceToCamera = app.camera.position.distanceTo(point);
        }
      }
    }
  }

  onPointerMove(event) {
    const {app, physics, container} = this.main;

    if (physics.joint) {
      const ndc = getNormalizedPointer(event, container.clientWidth, container.clientHeight);
      this.pointer.set(ndc.x, ndc.y);
      this.raycaster.setFromCamera(this.pointer, app.camera);

      const targetPos = this.raycaster.ray.at(this.distanceToCamera, this.intersectionPoint);
      physics.moveDrag(targetPos);
    }
  }

  onPointerUp() {
    const {app, physics} = this.main;

    if (physics.joint) {
      physics.endDrag();
    }
    app.controls.enabled = true;
  }

  dispose() {
    const {app} = this.main;
    app.renderer.domElement.removeEventListener("pointerdown", this.onPointerDown);
    app.renderer.domElement.removeEventListener("pointermove", this.onPointerMove);
    app.renderer.domElement.removeEventListener("pointerup", this.onPointerUp);
  }
}
src/js/controllers/SequenceController.js
파일 저장

import * as THREE from "three";
import {gsap} from "gsap";
import {STATES} from "../config/constants.js";

export class SequenceController {
  constructor(main) {
    this.main = main;
  }

  startCollapse(u, v) {
    const {stateController, pixelVoxelMesh, physics, params, settings} = this.main;

    if (stateController.state === STATES.ANIMATING) return;
    stateController.changeState(STATES.ANIMATING);

    pixelVoxelMesh.setUniform("uRippleCenter", {x: u, y: v});
    const aspect = this.main.gridInfo.cols / this.main.gridInfo.rows;
    const centerX = u * aspect;
    const centerY = v;
    const corners = [
      {x: 0, y: 0},
      {x: aspect, y: 0},
      {x: 0, y: 1},
      {x: aspect, y: 1},
    ];
    const maxDist = Math.max(...corners.map((c) => Math.hypot(c.x - centerX, c.y - centerY)));

    const targetVal = maxDist + params.effectSpread + 0.1;

    gsap.to(pixelVoxelMesh.material.uniforms.uVoxelateProgress, {
      value: targetVal,
      duration: params.baseDuration * targetVal,
      ease: "none",
      onComplete: () => {
        physics.forceActivateDrop((index) => {
          gsap.delayedCall(params.dropDelay, () => {
            physics.resetBodyParameters(index, settings.bodyDamping);
          });
        });
        stateController.changeState(STATES.COLLAPSED);
      },
    });
  }

  startReverse() {
    const {stateController, pixelVoxelMesh, physics, settings} = this.main;

    if (stateController.state !== STATES.COLLAPSED) return;

    stateController.changeState(STATES.REVERSING);

    const cachedData = physics.prepareForReverse();
    const qTmp = new THREE.Quaternion();
    const progressObj = {value: 0};
    const staggerStrength = 2.0;

    gsap.to(progressObj, {
      value: 1 + staggerStrength,
      duration: 1,
      ease: "power2.inOut",
      onUpdate: () => {
        const globalT = progressObj.value;
        cachedData.forEach((data) => {
          let t = Math.max(0, Math.min(1, globalT - data.delay * staggerStrength));
          if (t <= 0 || (t >= 1 && globalT < 1)) return;
          const pos = {
            x: data.startPos.x + (data.endPos.x - data.startPos.x) * t,
            y: data.startPos.y + (data.endPos.y - data.startPos.y) * t,
            z: data.startPos.z + (data.endPos.z - data.startPos.z) * t,
          };
          qTmp.copy(data.startRot).slerp(data.endRot, t);
          data.rb.setTranslation(pos, true);
          data.rb.setRotation(qTmp, true);
        });
        physics.syncMesh(pixelVoxelMesh);
      },
      onComplete: () => {
        gsap.to(pixelVoxelMesh.material.uniforms.uVoxelateProgress, {
          value: 0.0,
          duration: 0.3,
          ease: "none",
          onComplete: () => {
            physics.setGravity(settings.gravityY);
            physics.resetDropFlags();
            stateController.changeState(STATES.DEFAULT);
          },
        });
      },
    });
  }

  update() {
    const {stateController, pixelVoxelMesh, physics, params, gridInfo, settings} = this.main;
    if (!physics.dropFlags || !physics.cachedUVs) return;
    if (stateController.state === STATES.ANIMATING) {
      const currentProgress = pixelVoxelMesh.material.uniforms.uVoxelateProgress.value;
      if (currentProgress < 0.01) return;

      const rippleCenter = pixelVoxelMesh.material.uniforms.uRippleCenter.value;
      const aspectVecX = gridInfo.cols / gridInfo.rows;

      physics.checkAndActivateDrop(rippleCenter, currentProgress, aspectVecX, params.organicMode, params.effectSpread, gridInfo.spacing, gridInfo.count, (index) => {
        gsap.delayedCall(params.dropDelay, () => {
          physics.resetBodyParameters(index, settings.bodyDamping);
        });
      });
    }
  }

  reset() {
    if (this.main.pixelVoxelMesh) {
      gsap.killTweensOf(this.main.pixelVoxelMesh.material.uniforms.uVoxelateProgress);
    }
    gsap.getTweensOf("*").forEach((t) => t.kill());
  }
}
src/js/controllers/StateController.js
파일 저장

import {STATES} from "../config/constants.js";

export class StateController {
  constructor(initialState = STATES.LOADING, callbacks) {
    this._state = initialState;
    this.callbacks = callbacks;
  }

  get state() {
    return this._state;
  }

  changeState(newState) {
    if (this._state === newState) return;
    this._state = newState;
    if (this.callbacks.onStateChange) {
      this.callbacks.onStateChange(newState);
    }
  }
}
src/js/controllers/UIController.js
파일 저장

import {Pane} from "tweakpane";
import {STATES, BUTTON_CONFIG} from "../config/constants.js";

export class UIController {
  constructor({params, callbacks}) {
    this.params = params;
    this.callbacks = callbacks;
    this.pane = new Pane();
    this.folders = {};
    this.actionButton = null;

    this.init();
  }

  init() {
    this.createGridFolder();
    this.createVisualFolder();
    this.createPhysicsFolder();
    this.createControlsFolder();
    this.createActionButton();
  }

  createGridFolder() {
    const f = this.pane.addFolder({title: "Box"});
    f.addBinding(this.params, "gridCols", {label: "Column", min: 10, max: 100, step: 1}).on("change", this.callbacks.onRebuild);
    f.addBinding(this.params, "gridSpacing", {label: "Space", min: 1.0, max: 2.0, step: 0.1}).on("change", this.callbacks.onRebuild);
    f.addBinding(this.params, "shape", {label: "Shape", options: {Cube: "cube", RandomBox: "random"}}).on("change", (e) => {
      this.callbacks.onUpdateUniform("uUseRandomDepth", e.value === "random" ? 1.0 : 0.0);
      this.callbacks.onRebuild();
    });
    f.addBinding(this.params, "gridCount", {readonly: true, label: "Count"});
    this.folders.grid = f;
  }

  createVisualFolder() {
    const f = this.pane.addFolder({title: "Visual"});
    f.addBinding(this.params, "baseDuration", {label: "Duration", min: 0.5, max: 5.0, step: 0.1});
    f.addBinding(this.params, "organicMode", {label: "Organic"}).on("change", (e) => this.callbacks.onUpdateUniform("uOrganicMode", e.value ? 1.0 : 0.0));
    f.addBinding(this.params, "usePixelate", {label: "Pixelate"}).on("change", (e) => this.callbacks.onUpdateUniform("uUsePixelate", e.value ? 1.0 : 0.0));
    f.addBinding(this.params, "useRGBShift", {label: "RGBShift"}).on("change", (e) => this.callbacks.onUpdateUniform("uUseRGBShift", e.value ? 1.0 : 0.0));
    f.addBinding(this.params, "effectSpread", {label: "Spread", min: 0.0, max: 0.5, step: 0.05}).on("change", (e) => this.callbacks.onUpdateUniform("uEffectSpread", e.value));
    f.addBinding(this.params, "effectDepth", {label: "Depth", min: 1.0, max: 3.0, step: 0.05}).on("change", (e) => this.callbacks.onUpdateUniform("uEffectDepth", e.value));
    f.addBinding(this.params, "highlightColor", {label: "Color"}).on("change", (e) => this.callbacks.onUpdateUniform("uHighlightColor", e.value));
    f.addBinding(this.params, "highlightIntensity", {label: "ColorInt", min: 0.0, max: 1.0, step: 0.05}).on("change", (e) =>
      this.callbacks.onUpdateUniform("uHighlightIntensity", e.value)
    );
    this.folders.visual = f;
  }

  createPhysicsFolder() {
    const f = this.pane.addFolder({title: "Physics"});
    f.addBinding(this.params, "dropDelay", {min: 0, max: 3, step: 0.1, label: "DropDelay"});
    f.addBinding(this.params, "isDancing", {label: "Dance"}).on("change", this.callbacks.onUpdatePhysics);
    f.addBinding(this.params, "dancingLevel", {min: 0, max: 10, step: 1, label: "DanceLV"}).on("change", this.callbacks.onUpdatePhysics);
    this.folders.physics = f;
  }

  createControlsFolder() {
    const f = this.pane.addFolder({title: "Controls"});
    f.addBinding(this.params, "manualMode", {label: "Manual"}).on("change", this.callbacks.onManualChange);
    this.folders.controls = f;
  }

  createActionButton() {
    const config = BUTTON_CONFIG[STATES.LOADING]();
    this.actionButton = this.pane.addButton({
      title: config.title,
      disabled: config.disabled,
    });
    this.actionButton.on("click", this.callbacks.onAction);
  }

  updateState(state, manualMode) {
    if (!this.actionButton) return;

    const isDefault = state === STATES.DEFAULT;
    const isCollapsed = state === STATES.COLLAPSED;

    this.folders.grid.disabled = !isDefault;
    this.folders.visual.disabled = !isDefault;
    this.folders.controls.disabled = !isDefault;
    this.folders.physics.disabled = !(isDefault || isCollapsed);

    const getConfig = BUTTON_CONFIG[state] || BUTTON_CONFIG[STATES.LOADING];
    const {title, disabled} = getConfig(manualMode);

    this.actionButton.title = title;
    this.actionButton.disabled = disabled;
    this.pane.refresh();
  }

  dispose() {
    this.pane.dispose();
  }
}
src/js/controllers/VideoController.js
파일 저장

import * as THREE from "three";

export class VideoController {
  constructor(container, sourceUrl, playbackRate = 1.0) {
    this.container = container;
    this.sourceUrl = sourceUrl;
    this.playbackRate = playbackRate;
    this.video = null;
    this._texture = null;
  }

  load() {
    return new Promise((resolve, reject) => {
      this.video = document.createElement("video");
      this.video.src = this.sourceUrl;
      this.video.muted = true;
      this.video.loop = true;
      this.video.playbackRate = this.playbackRate;
      this.video.crossOrigin = "anonymous";
      this.video.playsInline = true;
      this.video.setAttribute("playsinline", "");
      this.video.style.display = "none";
      this.container.appendChild(this.video);

      this._texture = new THREE.VideoTexture(this.video);
      this._texture.colorSpace = THREE.SRGBColorSpace;
      this._texture.minFilter = THREE.NearestFilter;
      this._texture.magFilter = THREE.NearestFilter;

      this.video.addEventListener(
        "loadeddata",
        () => {
          resolve();
        },
        {once: true}
      );

      this.video.addEventListener(
        "error",
        (e) => {
          reject(new Error("Video load failed"));
        },
        {once: true}
      );
      this.video.load();
    });
  }

  play() {
    this.video.playbackRate = this.playbackRate;
    return this.video.play();
  }

  pause() {
    this.video.pause();
  }

  seek(time) {
    this.video.currentTime = time;
  }

  setPlaybackRate(rate) {
    this.playbackRate = rate;
    if (this.video) {
      this.video.playbackRate = rate;
    }
  }

  get width() {
    return this.video.videoWidth;
  }

  get height() {
    return this.video.videoHeight;
  }

  get isReady() {
    return this.video.readyState >= this.video.HAVE_CURRENT_DATA;
  }

  get texture() {
    return this._texture;
  }
}
src/js/core/PhysicsWorld.js
파일 저장

import * as THREE from "three";
import RAPIER from "@dimforge/rapier3d-compat";
import {computeNoiseOffset} from "../utils/common.js";

export class PhysicsWorld {
  constructor() {
    this.world = null;
    this.rigidBodies = [];
    this.cachedReverseData = [];
    this.groundBody = null;
    this.mouseBody = null;
    this.joint = null;
    this.activeRigidBody = null;
    this.dropFlags = null;
    this.cachedUVs = null;
    this.noiseOffsets = null;
  }

  async init() {
    await RAPIER.init({});
    this.world = new RAPIER.World({x: 0.0, y: 0.0, z: 0.0});
    this._createBoundaries();
  }

  _createBoundaries() {
    const floorThickness = 20.0;
    const groundDesc = RAPIER.RigidBodyDesc.fixed();
    this.groundBody = this.world.createRigidBody(groundDesc);
    const groundCollider = RAPIER.ColliderDesc.cuboid(1000.0, floorThickness / 2, 1000.0)
      .setTranslation(0, -(floorThickness / 2), 0)
      .setFriction(0.1)
      .setRestitution(0.9);
    this.world.createCollider(groundCollider, this.groundBody);

    const mouseDesc = RAPIER.RigidBodyDesc.kinematicPositionBased();
    this.mouseBody = this.world.createRigidBody(mouseDesc);
  }

  setGravity(y) {
    if (this.world) {
      this.world.gravity = {x: 0, y: y, z: 0};
    }
  }

  createGridBodies(gridInfo, params, settings) {
    this.clearBodies();

    const {cols, rows, width, height, spacing, cellSize, count} = gridInfo;
    const startX = -width * 0.5 + spacing * 0.5;
    const startY = -height * 0.5 + spacing * 0.5 + settings.gridOffsetY;
    const halfSize = cellSize / 2;

    this.dropFlags = new Uint8Array(count);
    this.cachedUVs = new Float32Array(count * 2);
    this.noiseOffsets = new Float32Array(count);
    const randomDepths = new Float32Array(count);

    for (let i = 0; i < count; i++) {
      const col = i % cols;
      const row = Math.floor(i / cols);
      const x = startX + col * spacing;
      const y = startY + row * spacing;

      const u = (col + 0.5) / cols;
      const v = (row + 0.5) / rows;
      this.cachedUVs[i * 2] = u;
      this.cachedUVs[i * 2 + 1] = v;

      const noiseOffset = computeNoiseOffset(i);
      this.noiseOffsets[i] = noiseOffset;

      const depthScale = params.shape === "random" ? (Math.random() < 0.2 ? 1.0 : 1.0 + Math.random() * 1.5) : 1.0;
      randomDepths[i] = depthScale;

      const rbDesc = RAPIER.RigidBodyDesc.fixed().setTranslation(x, y, 0).setLinearDamping(settings.bodyDamping).setAngularDamping(settings.bodyDamping);
      const rb = this.world.createRigidBody(rbDesc);

      const clDesc = RAPIER.ColliderDesc.cuboid(halfSize, halfSize, halfSize * depthScale)
        .setFriction(0.0)
        .setRestitution(settings.bodyRestitution);
      this.world.createCollider(clDesc, rb);

      rb.userData = {
        index: i,
        initPos: {x, y, z: 0},
        initRot: {x: 0, y: 0, z: 0, w: 1},
        depthScale,
        noiseOffset,
      };

      this.rigidBodies.push(rb);

      this.cachedReverseData.push({
        rb: rb,
        startPos: new THREE.Vector3(),
        startRot: new THREE.Quaternion(),
        endPos: new THREE.Vector3(x, y, 0),
        endRot: new THREE.Quaternion(0, 0, 0, 1),
        delay: i / count,
      });
    }
    return {randomDepths};
  }

  clearBodies() {
    if (this.joint) {
      this.world.removeImpulseJoint(this.joint, true);
      this.joint = null;
      this.activeRigidBody = null;
    }

    this.rigidBodies.forEach((rb) => {
      if (this.world.getRigidBody(rb.handle)) {
        rb.wakeUp();
        this.world.removeRigidBody(rb);
      }
    });

    this.rigidBodies = [];
    this.cachedReverseData = [];
    this.dropFlags = null;
    this.cachedUVs = null;
    this.noiseOffsets = null;
  }

  checkAndActivateDrop(rippleCenter, currentProgress, aspectVecX, organicMode, spread, spacing, count, onDropCallback) {
    if (!this.dropFlags) return;
    const spreadThreshold = spread * 0.98;

    for (let i = 0; i < count; i++) {
      if (this.dropFlags[i] === 1) continue;

      const u = this.cachedUVs[i * 2];
      const v = this.cachedUVs[i * 2 + 1];
      const noiseOffset = organicMode ? this.noiseOffsets[i] : 0;
      const dx = (u - rippleCenter.x) * aspectVecX;
      const dy = v - rippleCenter.y;

      const distSq = dx * dx + dy * dy;
      const threshold = currentProgress - spreadThreshold - noiseOffset;

      if (threshold > 0 && threshold * threshold > distSq) {
        this.dropFlags[i] = 1;
        const force = spacing * 2.0;
        this.activateBody(i, force);
        onDropCallback(i);
      }
    }
  }

  forceActivateDrop(onDropCallback) {
    if (!this.dropFlags) return;
    const force = 2.0;
    for (let i = 0; i < this.dropFlags.length; i++) {
      if (this.dropFlags[i] === 1) continue;
      this.dropFlags[i] = 1;
      this.activateBody(i, force);
      if (onDropCallback) onDropCallback(i);
    }
  }

  activateBody(index, initialForceScale = 1.0) {
    const rb = this.rigidBodies[index];
    if (!rb) return;

    rb.setBodyType(RAPIER.RigidBodyType.Dynamic);
    rb.setGravityScale(0.01);
    rb.setLinearDamping(1.2);
    rb.wakeUp();

    const force = initialForceScale;
    rb.setLinvel(
      {
        x: (Math.random() - 0.5) * force,
        y: (Math.random() - 0.5) * force,
        z: (Math.random() - 0.5) * force,
      },
      true
    );
    rb.setAngvel(
      {
        x: Math.random() - 0.5,
        y: Math.random() - 0.5,
        z: Math.random() - 0.5,
      },
      true
    );
  }

  resetDropFlags() {
    if (this.dropFlags) {
      this.dropFlags.fill(0);
    }
  }

  updateAllPhysicsParams(bodyDamping, bodyRestitution) {
    this.rigidBodies.forEach((rb) => {
      rb.setLinearDamping(bodyDamping);
      rb.setAngularDamping(bodyDamping);
      const collider = rb.collider(0);
      if (collider) collider.setRestitution(bodyRestitution);
      rb.wakeUp();
    });
  }

  resetBodyParameters(index, damping) {
    const rb = this.rigidBodies[index];
    if (rb && this.world.getRigidBody(rb.handle)) {
      rb.setGravityScale(1.0);
      rb.setLinearDamping(damping);
      rb.setAngularDamping(damping);
      rb.wakeUp();
    }
  }

  step() {
    if (this.world) {
      this.world.step();
    }
  }

  syncMesh(mesh, forceUpdate = false) {
    let needsUpdate = false;
    for (let i = 0; i < this.rigidBodies.length; i++) {
      const rb = this.rigidBodies[i];
      if (!rb.isSleeping() || forceUpdate) {
        mesh.setMatrixAt(i, rb.translation(), rb.rotation());
        needsUpdate = true;
      }
    }
    if (needsUpdate) mesh.requestMatrixUpdate();
  }

  startDrag(hitPoint, instanceId) {
    this.activeRigidBody = this.rigidBodies[instanceId];
    if (!this.activeRigidBody || this.activeRigidBody.bodyType() !== RAPIER.RigidBodyType.Dynamic) {
      return false;
    }

    this.mouseBody.setNextKinematicTranslation(hitPoint);

    const bodyPos = this.activeRigidBody.translation();
    const bodyRot = this.activeRigidBody.rotation();
    const vecPoint = new THREE.Vector3(hitPoint.x, hitPoint.y, hitPoint.z);
    const vecBody = new THREE.Vector3(bodyPos.x, bodyPos.y, bodyPos.z);
    const quatBody = new THREE.Quaternion(bodyRot.x, bodyRot.y, bodyRot.z, bodyRot.w);
    const localAnchor = vecPoint.sub(vecBody).applyQuaternion(quatBody.clone().invert());

    this.joint = this.world.createImpulseJoint(
      RAPIER.JointData.spherical({x: localAnchor.x, y: localAnchor.y, z: localAnchor.z}, {x: 0, y: 0, z: 0}),
      this.activeRigidBody,
      this.mouseBody,
      true
    );
    this.activeRigidBody.wakeUp();
    return true;
  }

  moveDrag(targetPos) {
    if (this.joint) {
      this.mouseBody.setNextKinematicTranslation(targetPos);
      if (this.activeRigidBody) this.activeRigidBody.wakeUp();
    }
  }

  endDrag() {
    if (this.joint) {
      this.world.removeImpulseJoint(this.joint, true);
      this.joint = null;
      this.activeRigidBody = null;
    }
  }

  prepareForReverse() {
    this.world.gravity = {x: 0, y: 0, z: 0};
    this.cachedReverseData.forEach((data) => {
      const pos = data.rb.translation();
      const rot = data.rb.rotation();
      data.startPos.set(pos.x, pos.y, pos.z);
      data.startRot.set(rot.x, rot.y, rot.z, rot.w);
      data.rb.setBodyType(RAPIER.RigidBodyType.Fixed);
      data.rb.sleep();
    });

    return this.cachedReverseData;
  }
}
src/js/core/ThreeWorld.js
파일 저장

import * as THREE from "three";
import {OrbitControls} from "three/addons/controls/OrbitControls.js";

export class ThreeWorld {
  constructor(container = document.body, onResize = null) {
    this.container = container;
    this.onResize = onResize;
    this.scene = null;
    this.camera = null;
    this.renderer = null;
    this.controls = null;
    this.width = this.container.clientWidth;
    this.height = this.container.clientHeight;

    this.init();
    this.onWindowResize = this.onWindowResize.bind(this);
    window.addEventListener("resize", this.onWindowResize);
  }

  init() {
    this.scene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera(60, this.width / this.height, 0.01, 1000);
    this.camera.position.set(0, 10, 20);
    this.renderer = new THREE.WebGLRenderer({
      alpha: true,
      antialias: false,
      powerPreference: "high-performance",
    });
    this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
    this.renderer.setSize(this.width, this.height);
    this.container.appendChild(this.renderer.domElement);
    this.controls = new OrbitControls(this.camera, this.renderer.domElement);
    this.controls.enableDamping = true;
    this.controls.dampingFactor = 0.05;
    this.controls.zoomSpeed = 1.5;
    this.controls.maxPolarAngle = Math.PI;
    this.controls.maxDistance = 80;
  }

  adjustCamera(gridInfo, fitMargin, offsetY) {
    const vFovRad = THREE.MathUtils.degToRad(this.camera.fov);
    const distForWidth = gridInfo.width / this.camera.aspect / (2 * Math.tan(vFovRad / 2));
    const distForHeight = gridInfo.height / (2 * Math.tan(vFovRad / 2));

    const baseOffset = Math.max(distForWidth, distForHeight) / fitMargin;
    const targetY = offsetY;
    const targetZ = baseOffset;

    this.camera.position.set(0, targetY, targetZ);
    this.camera.lookAt(0, targetY, 0);
    this.controls.target.set(0, targetY, 0);
    this.controls.update();
  }

  onWindowResize() {
    this.width = this.container.clientWidth;
    this.height = this.container.clientHeight;
    this.camera.aspect = this.width / this.height;
    this.camera.updateProjectionMatrix();
    this.renderer.setSize(this.width, this.height);

    if (this.onResize) {
      this.onResize();
    }
  }

  render() {
    this.controls.update();
    this.renderer.render(this.scene, this.camera);
  }

  get domElement() {
    return this.renderer.domElement;
  }
}
src/js/index.js
파일 저장

import {gsap} from "gsap";

import {ThreeWorld} from "./core/ThreeWorld.js";
import {PhysicsWorld} from "./core/PhysicsWorld.js";
import {VideoController} from "./controllers/VideoController.js";
import {StateController} from "./controllers/StateController.js";
import {UIController} from "./controllers/UIController.js";
import {SequenceController} from "./controllers/SequenceController.js";
import {InteractionController} from "./controllers/InteractionController.js";
import {PixelVoxelMesh} from "./view/PixelVoxelMesh.js";

import {debounce} from "./utils/common.js";
import {calculateGridMetrics} from "./utils/gridMath.js";
import {STATES, DEFAULT_PARAMS, INTERNAL_PARAMS} from "./config/constants.js";

import videoSource from "../video/output1.mp4";

class PixelVoxelDrop {
  constructor() {
    this.container = document.querySelector(".content");
    this.params = {...DEFAULT_PARAMS};
    this.settings = {...INTERNAL_PARAMS};
    this.gridInfo = null;

    this.rebuildWorld = debounce(this.rebuildWorld.bind(this), 300);
    this.app = new ThreeWorld(this.container, this.rebuildWorld);
    this.physics = new PhysicsWorld();
    this.videoController = new VideoController(this.container, videoSource, this.settings.playbackRate);
    this.sequence = new SequenceController(this);
    this.interaction = new InteractionController(this);
    this.uiController = null;
    this.stateController = null;
    this.pixelVoxelMesh = null;
    this.init();
  }

  async init() {
    await this.physics.init();
    await this.videoController.load();
    this.onVideoReadyForBuildWorld();
    this.setupGUI();
    this.animate();
  }

  onVideoReadyForBuildWorld() {
    if (this.buildScene()) {
      this.videoController
        .play()
        .then(() => {
          this.videoController.pause();
          this.videoController.seek(0);
          this.app.adjustCamera(this.gridInfo, this.settings.fitMargin, this.settings.gridOffsetY);
          this.fadeoutLoadingScreen();
          this.stateController.changeState(STATES.DEFAULT);
        })
        .catch((e) => console.warn("Autoplay blocked", e));
    }
  }

  rebuildWorld() {
    if (this.stateController.state === STATES.ANIMATING || this.stateController.state === STATES.REVERSING) return;
    if (this.buildScene()) {
      this.app.adjustCamera(this.gridInfo, this.settings.fitMargin, this.settings.gridOffsetY);
      this.stateController.changeState(STATES.DEFAULT);
    }
  }

  buildScene() {
    if (!this.videoController.width) return false;

    this._cleanupBeforeBuild();

    this.gridInfo = calculateGridMetrics(
      this.videoController.width,
      this.videoController.height,
      this.app.camera,
      this.settings.cameraDistance,
      this.params,
      this.settings.fitMargin
    );

    this.settings.gridOffsetY = this.gridInfo.height;
    this.settings.gravityY = -(this.gridInfo.height * 5.0);
    this.params.gridCount = this.gridInfo.count.toFixed(0);

    this.physics.setGravity(this.settings.gravityY);
    const {randomDepths} = this.physics.createGridBodies(this.gridInfo, this.params, this.settings);
    this._setupVoxelMesh(randomDepths);

    return true;
  }

  _cleanupBeforeBuild() {
    this.sequence.reset();

    if (this.pixelVoxelMesh) {
      this.app.scene.remove(this.pixelVoxelMesh.mesh);
      this.pixelVoxelMesh.dispose();
      this.pixelVoxelMesh = null;
    }

    this.physics.clearBodies();
  }

  _setupVoxelMesh(randomDepths) {
    this.pixelVoxelMesh = new PixelVoxelMesh(this.gridInfo, this.params, this.videoController.texture);
    this.pixelVoxelMesh.setRandomDepthAttribute(randomDepths);
    this.physics.syncMesh(this.pixelVoxelMesh);
    this.app.scene.add(this.pixelVoxelMesh.mesh);
  }

  setupGUI() {
    this.stateController = new StateController(STATES.LOADING, {
      onStateChange: (newState) => this.uiController?.updateState(newState, this.params.manualMode),
    });

    this.uiController = new UIController({
      params: this.params,
      callbacks: {
        onRebuild: () => this.rebuildWorld(),
        onUpdateUniform: (key, val) => this.pixelVoxelMesh.setUniform(key, val),
        onUpdatePhysics: () => {
          const {dancingLevel, isDancing} = this.params;
          const levelNorm = dancingLevel / 10.0;
          this.settings.bodyDamping = isDancing ? 0.8 : 2.0;
          this.settings.bodyRestitution = isDancing ? 1.0 + 0.6 * levelNorm : 0.01;
          this.physics.updateAllPhysicsParams(this.settings.bodyDamping, this.settings.bodyRestitution);
        },
        onAction: () => this.handleMainAction(),
        onManualChange: () => this.uiController.updateState(this.stateController.state, this.params.manualMode),
      },
    });
    this.uiController.callbacks.onUpdatePhysics();
  }

  animate() {
    requestAnimationFrame(this.animate.bind(this));
    const state = this.stateController.state;
    this._updatePhysicsAndLogic(state);
    this._syncVisuals(state);
    if (this.videoController?.isReady) {
      this.app.render();
    }
  }

  _updatePhysicsAndLogic(state) {
    if (this.pixelVoxelMesh && state === STATES.ANIMATING) {
      this.sequence.update();
    }
    if (state !== STATES.REVERSING) {
      this.physics.step();
    }
  }

  _syncVisuals(state) {
    if (!this.pixelVoxelMesh || state === STATES.DEFAULT) {
      return;
    }
    const isReversing = state === STATES.REVERSING;
    this.physics.syncMesh(this.pixelVoxelMesh, isReversing);
  }

  handleMainAction() {
    const state = this.stateController.state;
    if (state === STATES.COLLAPSED) {
      this.sequence.startReverse();
      return;
    }
    if (state === STATES.DEFAULT && !this.params.manualMode) {
      const u = Math.random();
      const v = Math.random();
      this.sequence.startCollapse(u, v);
    }
  }

  fadeoutLoadingScreen() {
    const overlay = document.querySelector("#loading-overlay");
    gsap.to(overlay, {
      delay: 1.5,
      autoAlpha: 0,
      duration: 1.0,
      ease: "power4.inOut",
      onStart: () => {
        this.videoController.play();
      },
      onComplete: () => {
        overlay.classList.add("loaded");
        overlay.style.display = "none";
      },
    });
  }
}

window.addEventListener("load", () => {
  new PixelVoxelDrop();
});
src/js/utils/common.js
파일 저장

export function debounce(func, wait) {
  let timeout;
  return function (...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), wait);
  };
}

export function getNormalizedPointer(event, windowWidth, windowHeight) {
  return {
    x: (event.clientX / windowWidth) * 2 - 1,
    y: -(event.clientY / windowHeight) * 2 + 1,
  };
}

export function computeNoiseOffset(index) {
  const glslRandom = (x, y) => {
    const dot = x * 12.9898 + y * 78.233;
    const sin = Math.sin(dot);
    const val = sin * 43758.5453123;
    return val - Math.floor(val);
  };
  const instanceNoise = glslRandom(index, 123.456);
  return (instanceNoise - 0.5) * 0.3;
}
src/js/utils/gridMath.js
파일 저장

import * as THREE from "three";

export function calculateGridMetrics(videoWidth, videoHeight, camera, distance, params, fitMargin) {
  const aspect = videoWidth / videoHeight;
  const cols = params.gridCols;
  const rows = Math.round(cols / aspect);
  const vFovRad = THREE.MathUtils.degToRad(camera.fov);
  const visibleHeight = 2 * Math.tan(vFovRad / 2) * distance;
  const visibleWidth = visibleHeight * camera.aspect;

  let baseCellSize = (visibleWidth * fitMargin) / cols;
  if (baseCellSize * rows > visibleHeight * fitMargin) {
    baseCellSize = (visibleHeight * fitMargin) / rows;
  }

  const spacing = baseCellSize * params.gridSpacing;

  return {
    cols,
    rows,
    count: cols * rows,
    cellSize: baseCellSize,
    spacing: spacing,
    width: cols * spacing,
    height: rows * spacing,
  };
}
src/js/view/PixelVoxelMesh.js
파일 저장

import * as THREE from "three";
import vertexShader from "../../shaders/vertex.glsl?raw";
import fragmentShader from "../../shaders/fragment.glsl?raw";

export class PixelVoxelMesh {
  constructor(gridInfo, params, videoTexture) {
    this.gridInfo = gridInfo;
    this.params = params;
    this.dummy = new THREE.Object3D();

    this.geometry = this.createGeometry();
    this.material = this.createMaterial(videoTexture);
    this.mesh = new THREE.InstancedMesh(this.geometry, this.material, this.gridInfo.count);
    this.mesh.frustumCulled = false;
  }

  createGeometry() {
    return new THREE.BoxGeometry(this.gridInfo.cellSize, this.gridInfo.cellSize, this.gridInfo.cellSize);
  }

  createMaterial(videoTexture) {
    return new THREE.ShaderMaterial({
      uniforms: {
        uMap: {value: videoTexture},
        uGridDims: {value: new THREE.Vector2(this.gridInfo.cols, this.gridInfo.rows)},
        uCubeSize: {value: new THREE.Vector2(this.gridInfo.cellSize, this.gridInfo.cellSize)},
        uVoxelateProgress: {value: 0.0},
        uRippleCenter: {value: new THREE.Vector2(0.5, 0.5)},
        uEffectSpread: {value: this.params.effectSpread},
        uEffectDepth: {value: this.params.effectDepth},
        uHighlightIntensity: {value: this.params.highlightIntensity},
        uHighlightColor: {value: new THREE.Color(this.params.highlightColor)},
        uUseRandomDepth: {value: this.params.shape === "random" ? 1.0 : 0.0},
        uOrganicMode: {value: this.params.organicMode ? 1.0 : 0.0},
        uUsePixelate: {value: this.params.usePixelate ? 1.0 : 0.0},
        uUseRGBShift: {value: this.params.useRGBShift ? 1.0 : 0.0},
      },
      side: THREE.DoubleSide,
      vertexShader,
      fragmentShader,
    });
  }

  setMatrixAt(index, pos, rot) {
    this.dummy.position.set(pos.x, pos.y, pos.z);
    this.dummy.quaternion.set(rot.x, rot.y, rot.z, rot.w);
    this.dummy.scale.set(1, 1, 1);
    this.dummy.updateMatrix();
    this.mesh.setMatrixAt(index, this.dummy.matrix);
  }

  setUniform(key, value) {
    if (this.material.uniforms[key]) {
      if (key === "uHighlightColor") {
        this.material.uniforms[key].value.set(value);
      } else {
        this.material.uniforms[key].value = value;
      }
    }
  }

  setRandomDepthAttribute(randomDepths) {
    this.geometry.setAttribute("aRandomDepth", new THREE.InstancedBufferAttribute(randomDepths, 1));
  }

  requestMatrixUpdate() {
    this.mesh.instanceMatrix.needsUpdate = true;
  }

  dispose() {
    if (this.mesh) {
      this.mesh.geometry.dispose();
      this.mesh.material.dispose();
    }
    this.geometry = null;
    this.material = null;
    this.mesh = null;
  }
}
src/shaders/fragment.glsl
파일 저장

precision mediump float;

uniform sampler2D uMap;
uniform vec3 uHighlightColor;
uniform float uHighlightIntensity;

varying vec2 vUv;
varying vec3 vNormal;
varying float vHighlightStrength;
varying float vGlitchStrength;

const vec3 LIGHT_DIR = vec3(0.8, 0.85, 1.0);
const float AMBIENT_INTENSITY = 0.95;
const float DIFFUSE_INTENSITY = 0.1;
const float SHIFT_OFFSET = 0.075;

void main() {
  // --- 1. Texture Sampling with RGB Shift ---
  float shift = vGlitchStrength * SHIFT_OFFSET;

  float r = texture2D(uMap, vUv + vec2(shift, 0.0)).r;
  float g = texture2D(uMap, vUv).g;
  float b = texture2D(uMap, vUv - vec2(shift, 0.0)).b;

  vec4 texColor = vec4(r, g, b, 1.0);

  // --- 2. Lighting  ---
  vec3 normLightDir = normalize(LIGHT_DIR);

  float diff = max(dot(vNormal, normLightDir), 0.0);

  vec3 ambient = vec3(AMBIENT_INTENSITY);
  vec3 diffuse = vec3(DIFFUSE_INTENSITY) * diff;

  vec3 lighting = ambient + diffuse;

  vec3 finalColor = texColor.rgb * lighting;

  // --- 3. Highlight Composition ---
  float effectIntensity = vHighlightStrength * uHighlightIntensity;

  finalColor = mix(finalColor, uHighlightColor, effectIntensity);

  gl_FragColor = vec4(finalColor, texColor.a);
}
src/shaders/vertex.glsl
파일 저장

#ifdef GL_ES
precision highp float;
#endif

uniform vec2 uGridDims;
uniform vec2 uCubeSize;
uniform float uVoxelateProgress;
uniform vec2 uRippleCenter;
uniform float uEffectSpread;
uniform float uEffectDepth;
uniform float uOrganicMode;
uniform float uUseRandomDepth;
uniform float uUsePixelate;
uniform float uUseRGBShift;

attribute float aRandomDepth;

varying vec2 vUv;
varying vec3 vNormal;
varying float vHighlightStrength;
varying float vGlitchStrength;

const float PI = 3.141592653589793;
const float SUPPRESSION_RANGE = 0.05;
const float NORMAL_DAMPING = 6.0;
const float SLOW_DAMPING = 2.0;
const float PIXELATION_TIME = 0.9;

float random(vec2 st) {
  return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453123);
}

float elasticOut(float t, float p, float damp_exp) {
  float tClamped = clamp(t, 0.0, 1.0);
  if(tClamped <= 0.0001)
    return 0.0;
  if(tClamped >= 0.9999)
    return 1.0;
  return pow(2.0, -damp_exp * tClamped) * sin((tClamped - p / 4.0) * (2.0 * PI) / p) + 1.0;
}

void main() {
  // --- 1. Get basic instance information ---
  float instanceId = float(gl_InstanceID);

  float col = mod(instanceId, uGridDims.x);
  float row = floor(instanceId / uGridDims.x);
  vec2 uvStep = 1.0 / uGridDims;
  vec2 baseUv = vec2(col, row) * uvStep;
  vec2 centerUv = baseUv + (uvStep * 0.5);

  float gridAspect = uGridDims.x / uGridDims.y;
  vec2 aspectVec = vec2(gridAspect, 1.0);
  float distFromCenter = distance(centerUv * aspectVec, uRippleCenter * aspectVec);

  float rndPhase = random(vec2(instanceId, 123.456));
  float rndBounce = random(vec2(instanceId, 987.654));

  // --- 2. Animation Progress (Wave Progress)
  // A. Organic Mode (Noise, Elastic) 
  float noisyDist = max(0.0, distFromCenter + (rndPhase - 0.5) * 0.3);
  float progressOrganic = clamp((uVoxelateProgress - noisyDist) / uEffectSpread, 0.0, 1.0);

  float suppression = 1.0 - smoothstep(0.0, SUPPRESSION_RANGE, noisyDist);
  float currentDamp = mix(NORMAL_DAMPING, SLOW_DAMPING, suppression);

  float valOrganic = elasticOut(progressOrganic, 0.2 + rndPhase * 0.2, currentDamp);
  float bounceDiff = max(0.0, valOrganic - 1.0);
  valOrganic += bounceDiff * (uEffectDepth + rndBounce * 1.1);

  float highlightOrganic = step(0.01, bounceDiff) * smoothstep(0.0, 0.35, 1.0 - progressOrganic) * (0.5 + rndPhase * 0.5);

  // B. Smooth Mode (No-Noise, Sine)
  float progressSmooth = smoothstep(distFromCenter, distFromCenter + uEffectSpread, uVoxelateProgress);

  float valSmoothBounce = sin(progressSmooth * PI) * step(progressSmooth, 0.99);
  float valSmooth = progressSmooth + (valSmoothBounce * uEffectDepth);

  float highlightSmooth = valSmoothBounce;

  float finalScaleVal = mix(valSmooth, valOrganic, uOrganicMode);
  vHighlightStrength = mix(highlightSmooth, highlightOrganic, uOrganicMode);

  // --- 3. UV Coordinates (Pixelate and Glitch) ---
  vec3 nMask = step(0.5, abs(normal));
  vec2 faceCoords = (position.zy * nMask.x) + (position.xz * nMask.y) + (position.xy * nMask.z);
  vec2 localRatio = clamp((faceCoords / uCubeSize.x) + 0.5, 0.0, 1.0);
  vec2 smoothUv = baseUv + (localRatio * uvStep);

  float effectiveProgress = mix(progressSmooth, progressOrganic, uOrganicMode);
  float pixelPhase = smoothstep(0.0, PIXELATION_TIME, effectiveProgress);

  float glitchIntensity = pow(sin(pixelPhase * PI), 0.5);

  vec2 noiseOffset = vec2(random(vec2(instanceId + pixelPhase * 100.0, 0.0)), random(vec2(instanceId + pixelPhase * 100.0, 1.0))) - 0.5;
  vec2 pixelateUv = mix(smoothUv, centerUv, pixelPhase) + (noiseOffset * glitchIntensity * 0.3);

  vUv = mix(smoothUv, pixelateUv, uUsePixelate);
  vGlitchStrength = glitchIntensity * uUseRGBShift;

  // --- 4. Coordinate Transformation (Depth) ---
  float baseDepth = 0.05;
  float targetDepth = mix(1.0, aRandomDepth, uUseRandomDepth);
  float currentDepth = baseDepth + (targetDepth - baseDepth) * finalScaleVal;

  vec3 transformed = position;
  transformed.z *= currentDepth;

  vNormal = normalize((instanceMatrix * vec4(normal, 0.0)).xyz);
  gl_Position = projectionMatrix * modelViewMatrix * instanceMatrix * vec4(transformed, 1.0);
}
vite.config.js
파일 저장

import { defineConfig } from 'vite';
import path from 'path';

export default defineConfig(({ mode }) => {
  const isProduction = mode === 'production';

  return {
    root: 'src',
    base: './',
    publicDir: path.resolve(__dirname, 'src/public'),
    server: {
      open: true,
      port: 8888,
    },

    build: {
      outDir: path.resolve(__dirname, 'dist'),
      emptyOutDir: true,
      target: 'esnext',
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: isProduction,
        },
      },

      rollupOptions: {
        output: {
          entryFileNames: 'assets/js/[name]-[hash].js',
          chunkFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: (assetInfo) => {
            const name = assetInfo.name || '';
            if (name.endsWith('.css')) {
              return 'assets/css/[name]-[hash].[ext]';
            }
            if (name.endsWith('.mp4')) {
              return 'assets/video/[name]-[hash].[ext]';
            }
            return 'assets/[name]-[hash].[ext]';
          },

          manualChunks: {
            'three-vendor': [ 'three' ],
            'physics-vendor': [ '@dimforge/rapier3d-compat' ],
            'utils-vendor': [ 'gsap', 'tweakpane' ],
          }
        },
      },
    },
  };
});
Media credits and license evidence실행 안내·자료
파일 저장

README.md
## Credits

- Shibuya Crossing Video from [pexels.com](https://www.pexels.com/video/timelapse-of-shibuya-crossing-in-tokyo-at-night-32173699/)


## License

[MIT](LICENSE)
LICENSE실행 안내·자료
파일 저장

MIT License

Copyright (c) 2009 - 2025 [Codrops](https://codrops.com) and [Junichi Kasahara](https://1kkaku.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Bundled dependency licenses실행 안내·자료
파일 저장

GSAP standard license snapshot
Source: https://gsap.com/community/standard-license/
Retrieved: 2026-09-22T04:22:49.089Z
Original distribution copyright and version headers remain in the runtime code.

Standard "No Charge" GSAP License

 I. DEFINITIONS

 “GSAP License” means the terms and conditions of this GSAP Software License Agreement.

 "GSAP Products" means any Software made available at gsap.com (https://gsap.com) or any successor sites, including but not limited to the GSAP animation library and related plugins, tools, or extensions.

 "Permitted Uses" means the implementation and/or use of GSAP Products on any website, web application, or digital interface by any person or entity (which may include, for clarity, those of companies that compete with Webflow in other areas of business).

 "Prohibited Uses" means any implementation and/or use of GSAP Products in tools that allow users to build visual animations without code that encourages, induces, or materially assists in creating a solution that competes with Webflow’s visual animation building capabilities.

 "Competitive Products" means any software, tool, or service that enables users to create, edit, or manage animations through a visual interface or builder similar to Webflow (https://webflow.com).

 II. GRANT OF LICENSE

 Subject to the terms and conditions of this GSAP License, Webflow grants you a non-exclusive, worldwide license to use, reproduce, display, and implement GSAP Products solely for Permitted Uses.

 III. RESTRICTIONS

 You may not:

 Use any GSAP Products for any Prohibited Uses without prior written consent;

 Reverse engineer any GSAP Products for the purpose of creating Competitive Products;

 Remove or alter any proprietary notices or branding from GSAP Products.

 IV. OWNERSHIP AND INTELLECTUAL PROPERTY

 All intellectual property rights in GSAP Products, including but not limited to copyright, patents, trademarks, and trade secrets, remain the exclusive property of Webflow. This GSAP License does not transfer any ownership rights in GSAP Products to you.

 V. TERMINATION

 Webflow may terminate this GSAP License and revoke your access in its discretion if you fail to comply with any of these terms and conditions. Upon termination, you must cease all use of GSAP Products and destroy all copies in your possession.

 VI. MISCELLANEOUS PROVISIONS

 General: This GSAP License is incorporated into and subject to Webflow’s Terms of Service available here (https://webflow.com/legal/terms) ("Terms of Service"). In the event of any conflict or inconsistency between this GSAP License and the Terms of Service, the terms of this GSAP License shall govern in relation to your use of any GSAP Products.

 Amendments: Webflow reserves the right to update or modify this GSAP License at any time by posting the revised terms on this website, provided that any such updates or modifications shall not result in any material degradation to the security, integrity, or functionality of any GSAP Products. You understand and agree that your continued use of any GSAP Products after such revisions to this GSAP License constitutes your acceptance of this GSAP License as revised. If you do not accept the revised GSAP License, you are prohibited from using versions of the GSAP Products released after the effective date of the revised GSAP License (as well as any updates made to previous versions). Notwithstanding, you may continue using previous versions of GSAP Products under the applicable terms licensed to you prior to the effective date of the revised GSAP License (for clarity, excluding any updates made thereto).

 No Waiver: Failure of Webflow to enforce any provision of this GSAP License shall not constitute a waiver of future enforcement of that or any other provision.

 FAQ

 Is it acceptable for AI tools like ChatGPT, Cursor, Lovable, Webstudio, etc. to generate GSAP code?
 Absolutely! AI-generated code is not a "Prohibited Use".

 What if a WordPress plugin or theme or other niche tool allows users to create GSAP-driven effects through a visual interface? Is that prohibited?
 We want to encourage developers to build on top of GSAP, including visual tools that don't directly compete with Webflow's rich animation-building capabilities. If you are not sure if your product might be considered a "Prohibited Use", feel free to contact us (https://gsap.com/contact) so we can talk through it!

 Can I really use GSAP in commercial projects without paying anything?
 Yes, really! Commercial usage is covered under the standard license. All of GSAP including the plugins that were formerly "members-only" like SplitText (https://gsap.com/docs/v3/Plugins/SplitText/) and MorphSVG (https://gsap.com/docs/v3/Plugins/MorphSVGPlugin) can be used in commercial projects at no charge. Enjoy! 💚

 Effective date: April 30, 2025

 Last modified date: May 30, 2025

 Copyright (©) 2025, Webflow


three@0.181.2 — LICENSE
The MIT License

Copyright © 2010-2025 three.js authors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.