实现贴纸粒子系统,添加 HeroScene 组件,优化 Next.js 配置,更新依赖
This commit is contained in:
@@ -4,6 +4,7 @@ import "./globals.css";
|
|||||||
import SmoothScroller from "@/components/dom/SmoothScroller";
|
import SmoothScroller from "@/components/dom/SmoothScroller";
|
||||||
import Header from "@/components/dom/Header";
|
import Header from "@/components/dom/Header";
|
||||||
import BackgroundGrid from "@/components/dom/BackgroundGrid";
|
import BackgroundGrid from "@/components/dom/BackgroundGrid";
|
||||||
|
import { HeroScene } from "@/components/canvas/HeroScene";
|
||||||
|
|
||||||
const tiktokSans = localFont({
|
const tiktokSans = localFont({
|
||||||
src: "./fonts/TikTokSans.ttf",
|
src: "./fonts/TikTokSans.ttf",
|
||||||
@@ -37,6 +38,7 @@ export default function RootLayout({
|
|||||||
<html lang="en" className={`${tiktokSans.variable} ${geistMono.variable} ${departureMono.variable}`}>
|
<html lang="en" className={`${tiktokSans.variable} ${geistMono.variable} ${departureMono.variable}`}>
|
||||||
<body className="min-h-screen relative">
|
<body className="min-h-screen relative">
|
||||||
<BackgroundGrid />
|
<BackgroundGrid />
|
||||||
|
<HeroScene />
|
||||||
<SmoothScroller />
|
<SmoothScroller />
|
||||||
<Header />
|
<Header />
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
+14
-2
@@ -4,7 +4,7 @@ export default function Home() {
|
|||||||
<div>
|
<div>
|
||||||
{/* Hero Section */}
|
{/* Hero Section */}
|
||||||
<div className="grid grid-cols-12 grid-rows-[auto_1fr] px-4 lg:px-14 py-18 lg:py-24 w-full h-dvh lg:h-screen">
|
<div className="grid grid-cols-12 grid-rows-[auto_1fr] px-4 lg:px-14 py-18 lg:py-24 w-full h-dvh lg:h-screen">
|
||||||
<div className="flex flex-col order-2 lg:order-1 lg:grid lg:grid-cols-12 col-span-12 font-mono text-base">
|
<div className="flex flex-col order-2 lg:order-1 lg:grid lg:grid-cols-12 col-span-12 font-mono text-base relative z-30">
|
||||||
<span className="hidden lg:block lg:col-span-3 xl:col-span-2 lg:col-start-1 xl:col-start-1 p-2 font-sans font-medium text-[4svw] sm:text-2xl lg:text-3xl leading-tight">
|
<span className="hidden lg:block lg:col-span-3 xl:col-span-2 lg:col-start-1 xl:col-start-1 p-2 font-sans font-medium text-[4svw] sm:text-2xl lg:text-3xl leading-tight">
|
||||||
Design &<br />Engineering
|
Design &<br />Engineering
|
||||||
</span>
|
</span>
|
||||||
@@ -20,7 +20,7 @@ export default function Home() {
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
className="flex flex-col self-end order-1 lg:order-2 col-span-12 px-2 font-bold text-[7.2svw] lg:text-[6svw] 2xl:text-[5svw] xl:text-[5.6svw] uppercase leading-none"
|
className="flex flex-col self-end order-1 lg:order-2 col-span-12 px-2 font-bold text-[7.2svw] lg:text-[6svw] 2xl:text-[5svw] xl:text-[5.6svw] uppercase leading-none relative z-30"
|
||||||
style={{ fontVariationSettings: '"wdth" 120' }}
|
style={{ fontVariationSettings: '"wdth" 120' }}
|
||||||
>
|
>
|
||||||
<span>I bring</span>
|
<span>I bring</span>
|
||||||
@@ -28,6 +28,18 @@ export default function Home() {
|
|||||||
<span>to digital work</span>
|
<span>to digital work</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* About Section Placeholder */}
|
||||||
|
<div className="grid grid-cols-12 grid-rows-1 px-4 lg:px-14 py-24 w-full min-h-screen relative z-30">
|
||||||
|
<div className="col-span-12 lg:col-span-10 xl:col-span-8 lg:col-start-2 xl:col-start-3 flex flex-col justify-center font-medium text-[5svw] lg:text-[4svw] leading-snug">
|
||||||
|
<p className="mb-12">
|
||||||
|
I explore how to shape AI-era workflows with craft and taste, building the next generation of digital products.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
I’m building <a href="https://reunimos.cc/" target="_blank" rel="noreferrer" className="underline decoration-1 underline-offset-4 hover:opacity-70 transition-opacity">reunimos™</a>, and previously worked on Alibaba <a href="https://www.alipan.com/" target="_blank" rel="noreferrer" className="underline decoration-1 underline-offset-4 hover:opacity-70 transition-opacity">aDrive</a>, <a href="https://www.teambition.com/" target="_blank" rel="noreferrer" className="underline decoration-1 underline-offset-4 hover:opacity-70 transition-opacity">Teambition</a>, and 100offer.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Canvas } from "@react-three/fiber";
|
||||||
|
import { PerspectiveCamera } from "@react-three/drei";
|
||||||
|
|
||||||
|
import { StickerDrop, StickerCamera } from "@/components/canvas/StickerDrop";
|
||||||
|
|
||||||
|
export function HeroScene() {
|
||||||
|
return (
|
||||||
|
// z-30 keeps it above the BackgroundGrid (z-20) to prevent mix-blend-difference from making it gray
|
||||||
|
<div className="z-30 fixed inset-0 w-full h-full pointer-events-none">
|
||||||
|
<Canvas
|
||||||
|
dpr={[1, 2]}
|
||||||
|
gl={{ alpha: true, antialias: true }}
|
||||||
|
>
|
||||||
|
{/* Camera rig: horizontal FOV 60/38 + scroll-driven distance lerp(24, 32).
|
||||||
|
StickerCamera drives fov/aspect/z every frame; PerspectiveCamera is the
|
||||||
|
makeDefault camera it mutates. */}
|
||||||
|
<PerspectiveCamera makeDefault position={[0, 0, 24]} near={0.1} far={200} />
|
||||||
|
<StickerCamera />
|
||||||
|
|
||||||
|
{/* Falling stickers: 1:1 re-implementation of the original particle system */}
|
||||||
|
<StickerDrop />
|
||||||
|
</Canvas>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default HeroScene;
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import { Effect, BlendFunction } from 'postprocessing';
|
||||||
|
import * as THREE from 'three';
|
||||||
|
import { wrapEffect } from '@react-three/postprocessing';
|
||||||
|
|
||||||
|
const fragmentShader = `
|
||||||
|
uniform float pixelSize;
|
||||||
|
uniform float uFeather;
|
||||||
|
uniform float uAspect;
|
||||||
|
uniform float uHoleRadius;
|
||||||
|
uniform float uProgress;
|
||||||
|
uniform vec3 uOverlayColor;
|
||||||
|
|
||||||
|
void dotsMainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) {
|
||||||
|
vec2 normalizedPixelSize = vec2(pixelSize) / resolution;
|
||||||
|
float a = clamp(inputColor.a, 0.0, 1.0);
|
||||||
|
vec2 cellUV = fract(uv / normalizedPixelSize);
|
||||||
|
float radius = 0.8 * a;
|
||||||
|
vec2 circleCenter = vec2(0.5, 0.5);
|
||||||
|
float distanceFromCenter = distance(cellUV, circleCenter);
|
||||||
|
float aa = fwidth(distanceFromCenter) * 1.5;
|
||||||
|
// Safe smoothstep: edge0 must be < edge1 in GLSL
|
||||||
|
float circleMask = 1.0 - smoothstep(radius - aa, radius, distanceFromCenter);
|
||||||
|
outputColor = vec4(vec3(circleMask), circleMask);
|
||||||
|
}
|
||||||
|
|
||||||
|
float radialMaskAlpha(vec2 uv) {
|
||||||
|
vec2 p = uv * 2.0 - 1.0;
|
||||||
|
if (uAspect > 1.0) {
|
||||||
|
p.x *= uAspect;
|
||||||
|
} else {
|
||||||
|
p.y /= max(uAspect, 0.0001);
|
||||||
|
}
|
||||||
|
float d = length(p);
|
||||||
|
float edge = max(uFeather, uHoleRadius * 0.12);
|
||||||
|
float alphaHole = smoothstep(uHoleRadius, uHoleRadius + edge, d);
|
||||||
|
float fillMix = smoothstep(0.92, 1.0, uProgress);
|
||||||
|
return mix(alphaHole, 1.0, fillMix);
|
||||||
|
}
|
||||||
|
|
||||||
|
void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) {
|
||||||
|
vec2 normalizedPixelSize = vec2(pixelSize) / resolution;
|
||||||
|
vec2 cellId = floor(uv / normalizedPixelSize);
|
||||||
|
vec2 uvCellCenter = (cellId + vec2(0.5)) * normalizedPixelSize;
|
||||||
|
float cellAlpha = clamp(radialMaskAlpha(uvCellCenter), 0.0, 1.0);
|
||||||
|
|
||||||
|
vec4 dotOut;
|
||||||
|
dotsMainImage(vec4(0.0, 0.0, 0.0, cellAlpha), uv, dotOut);
|
||||||
|
float dotMask = clamp(dotOut.a, 0.0, 1.0);
|
||||||
|
|
||||||
|
float finalAlpha = dotMask;
|
||||||
|
vec3 outRgb = uOverlayColor * finalAlpha;
|
||||||
|
|
||||||
|
// Blend with inputColor to only apply mask where finalAlpha > 0
|
||||||
|
// Since we use BlendFunction.NORMAL, we just return the color and alpha
|
||||||
|
outputColor = vec4(outRgb, finalAlpha);
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
export class MaskedDotsEffectImpl extends Effect {
|
||||||
|
constructor({
|
||||||
|
pixelSize = 32,
|
||||||
|
feather = 0.5,
|
||||||
|
aspect = 1,
|
||||||
|
holeRadius = 2,
|
||||||
|
progress = 0,
|
||||||
|
overlayColor = new THREE.Color('#fbfaf4')
|
||||||
|
} = {}) {
|
||||||
|
super('MaskedDotsEffect', fragmentShader, {
|
||||||
|
blendFunction: BlendFunction.NORMAL,
|
||||||
|
uniforms: new Map<string, THREE.Uniform<number> | THREE.Uniform<THREE.Color>>([
|
||||||
|
['pixelSize', new THREE.Uniform(pixelSize)],
|
||||||
|
['uFeather', new THREE.Uniform(feather)],
|
||||||
|
['uAspect', new THREE.Uniform(aspect)],
|
||||||
|
['uHoleRadius', new THREE.Uniform(holeRadius)],
|
||||||
|
['uProgress', new THREE.Uniform(progress)],
|
||||||
|
['uOverlayColor', new THREE.Uniform(overlayColor)]
|
||||||
|
])
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
update(
|
||||||
|
_renderer: THREE.WebGLRenderer,
|
||||||
|
_inputBuffer: THREE.WebGLRenderTarget,
|
||||||
|
_deltaTime?: number
|
||||||
|
) {
|
||||||
|
// Uniforms are driven externally via ref.current.uniforms.get(...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const MaskedDots = wrapEffect(MaskedDotsEffectImpl);
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useRef } from "react";
|
||||||
|
import { useFrame, useThree } from "@react-three/fiber";
|
||||||
|
import * as THREE from "three";
|
||||||
|
import { StickerLayer } from "@/components/webgl/StickerLayer";
|
||||||
|
import { scrollBus } from "@/lib/scrollBus";
|
||||||
|
|
||||||
|
const STICKER_IMAGES = Array.from(
|
||||||
|
{ length: 12 },
|
||||||
|
(_, i) => `/sticker_img/s_${String(i + 1).padStart(2, "0")}.png`
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Falling-sticker particle layer.
|
||||||
|
*
|
||||||
|
* Simulation constants live in StickerLayer (reverse-engineered 1:1 from the
|
||||||
|
* production bundle): 12 persistent particles, 48-unit fall distance, wind
|
||||||
|
* sway, respawn with texture de-duplication, 12-particle click bursts.
|
||||||
|
*
|
||||||
|
* This component only wires the layer into the R3F scene graph and runs the
|
||||||
|
* pointer→raycast→burst interaction (drag threshold 4px/10px, 600ms window,
|
||||||
|
* text-selection guard — same as the original).
|
||||||
|
*/
|
||||||
|
export function StickerDrop() {
|
||||||
|
const scene = useThree((s) => s.scene);
|
||||||
|
const camera = useThree((s) => s.camera);
|
||||||
|
const gl = useThree((s) => s.gl);
|
||||||
|
const layerRef = useRef<StickerLayer | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const layer = new StickerLayer(scene);
|
||||||
|
layerRef.current = layer;
|
||||||
|
layer.load(STICKER_IMAGES).catch(() => {});
|
||||||
|
return () => {
|
||||||
|
layer.dispose();
|
||||||
|
layerRef.current = null;
|
||||||
|
};
|
||||||
|
}, [scene]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const raycaster = new THREE.Raycaster();
|
||||||
|
const ndc = new THREE.Vector2();
|
||||||
|
const plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
|
||||||
|
const hit = new THREE.Vector3();
|
||||||
|
|
||||||
|
type Pending = {
|
||||||
|
id: number;
|
||||||
|
startX: number;
|
||||||
|
startY: number;
|
||||||
|
startAt: number;
|
||||||
|
cancelled: boolean;
|
||||||
|
};
|
||||||
|
let pending: Pending | null = null;
|
||||||
|
|
||||||
|
const onPointerDown = (e: PointerEvent) => {
|
||||||
|
if (
|
||||||
|
e.isPrimary &&
|
||||||
|
((e.pointerType !== "mouse" && e.pointerType !== "pen") || e.button === 0)
|
||||||
|
) {
|
||||||
|
pending = {
|
||||||
|
id: e.pointerId,
|
||||||
|
startX: e.clientX,
|
||||||
|
startY: e.clientY,
|
||||||
|
startAt: e.timeStamp || performance.now(),
|
||||||
|
cancelled: false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onPointerMove = (e: PointerEvent) => {
|
||||||
|
if (!pending || e.pointerId !== pending.id || pending.cancelled) return;
|
||||||
|
const dx = e.clientX - pending.startX;
|
||||||
|
const dy = e.clientY - pending.startY;
|
||||||
|
const threshold = e.pointerType === "touch" ? 10 : 4;
|
||||||
|
if (dx * dx + dy * dy > threshold * threshold) pending.cancelled = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const onPointerUp = (e: PointerEvent) => {
|
||||||
|
const p = pending;
|
||||||
|
if (!p || e.pointerId !== p.id) return;
|
||||||
|
pending = null;
|
||||||
|
if (p.cancelled || (e.timeStamp || performance.now()) - p.startAt > 600) return;
|
||||||
|
|
||||||
|
const selection = window.getSelection();
|
||||||
|
if (selection && !selection.isCollapsed && selection.toString().trim().length > 0) return;
|
||||||
|
|
||||||
|
const rect = gl.domElement.getBoundingClientRect();
|
||||||
|
ndc.set(
|
||||||
|
((e.clientX - rect.left) / rect.width) * 2 - 1,
|
||||||
|
-(((e.clientY - rect.top) / rect.height) * 2 - 1)
|
||||||
|
);
|
||||||
|
raycaster.setFromCamera(ndc, camera);
|
||||||
|
if (!raycaster.ray.intersectPlane(plane, hit)) return;
|
||||||
|
layerRef.current?.burst(hit);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onPointerCancel = (e: PointerEvent) => {
|
||||||
|
if (pending && e.pointerId === pending.id) pending = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const options = { capture: true, passive: true } as const;
|
||||||
|
window.addEventListener("pointerdown", onPointerDown, options);
|
||||||
|
window.addEventListener("pointermove", onPointerMove, options);
|
||||||
|
window.addEventListener("pointerup", onPointerUp, options);
|
||||||
|
window.addEventListener("pointercancel", onPointerCancel, options);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("pointerdown", onPointerDown, true);
|
||||||
|
window.removeEventListener("pointermove", onPointerMove, true);
|
||||||
|
window.removeEventListener("pointerup", onPointerUp, true);
|
||||||
|
window.removeEventListener("pointercancel", onPointerCancel, true);
|
||||||
|
};
|
||||||
|
}, [camera, gl]);
|
||||||
|
|
||||||
|
useFrame((_, delta) => {
|
||||||
|
layerRef.current?.update(delta);
|
||||||
|
});
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Camera rig matching the original: horizontal FOV 60° (desktop) / 38°
|
||||||
|
* (mobile) converted to vertical FOV per aspect, and camera distance
|
||||||
|
* lerp(24, 32) driven by page scroll progress.
|
||||||
|
*/
|
||||||
|
export function StickerCamera() {
|
||||||
|
const camera = useThree((s) => s.camera) as THREE.PerspectiveCamera;
|
||||||
|
const size = useThree((s) => s.size);
|
||||||
|
|
||||||
|
useFrame(() => {
|
||||||
|
const aspect = size.width / Math.max(1, size.height);
|
||||||
|
const horizontalFov = size.width >= 1024 ? 60 : 38;
|
||||||
|
const verticalFov =
|
||||||
|
2 * Math.atan(Math.tan(THREE.MathUtils.degToRad(horizontalFov) / 2) / aspect);
|
||||||
|
camera.fov = THREE.MathUtils.radToDeg(verticalFov);
|
||||||
|
camera.aspect = aspect;
|
||||||
|
const progress = THREE.MathUtils.clamp(scrollBus.progress, 0, 1);
|
||||||
|
camera.position.z = THREE.MathUtils.lerp(24, 32, progress);
|
||||||
|
camera.updateProjectionMatrix();
|
||||||
|
});
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,471 @@
|
|||||||
|
import * as THREE from "three";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sticker particle layer — pixel-faithful re-implementation of the
|
||||||
|
* haoqi.design falling-sticker system.
|
||||||
|
*
|
||||||
|
* Reverse-engineered constants (from the production bundle):
|
||||||
|
* particleCount: 12 (one per texture)
|
||||||
|
* spawnWidth: 32
|
||||||
|
* clickSpawnWidth: 24
|
||||||
|
* spawnHeight: 24
|
||||||
|
* clickSpawnHeight: 24
|
||||||
|
* positionY: 24
|
||||||
|
* fallDistance: 48
|
||||||
|
* zDepth: 4
|
||||||
|
* zOffset: -6
|
||||||
|
* windStrength: 1.8
|
||||||
|
* windFrequency: 0.3
|
||||||
|
* scale: 1.4
|
||||||
|
* clickScale: 1.4
|
||||||
|
* rotationSpeed: 0.8
|
||||||
|
* fallSpeed: 1.8
|
||||||
|
* enterDurationRatio 0.05 (scale-in over first 5% of fall)
|
||||||
|
* exit over last 10% of fall
|
||||||
|
* one-shot cap: 384
|
||||||
|
* burst count: particleCount (12 per click)
|
||||||
|
* burst emit spacing 0.04 + 0.04s random
|
||||||
|
* respawn delay 0.04 + 0.04s random
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const STICKER_CONFIG = {
|
||||||
|
particleCount: 12,
|
||||||
|
spawnWidth: 32,
|
||||||
|
clickSpawnWidth: 24,
|
||||||
|
spawnHeight: 24,
|
||||||
|
clickSpawnHeight: 24,
|
||||||
|
positionY: 24,
|
||||||
|
fallDistance: 48,
|
||||||
|
zDepth: 4,
|
||||||
|
zOffset: -6,
|
||||||
|
windStrength: 1.8,
|
||||||
|
windFrequency: 0.3,
|
||||||
|
scale: 1.4,
|
||||||
|
clickScale: 1.4,
|
||||||
|
rotationSpeed: 0.8,
|
||||||
|
fallSpeed: 1.8,
|
||||||
|
enterDurationRatio: 0.05,
|
||||||
|
oneShotCap: 384,
|
||||||
|
burstCount: 12,
|
||||||
|
maxVisible: 2048
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
type StickerConfig = typeof STICKER_CONFIG;
|
||||||
|
|
||||||
|
type Particle = {
|
||||||
|
position: THREE.Vector3;
|
||||||
|
startY: number;
|
||||||
|
fallSpeed: number;
|
||||||
|
rotation: number;
|
||||||
|
rotationSpeed: number;
|
||||||
|
scale: number;
|
||||||
|
textureIndex: number;
|
||||||
|
windPhase: number;
|
||||||
|
windAmplitude: number;
|
||||||
|
emitAt: number;
|
||||||
|
hasStarted: boolean;
|
||||||
|
dead: boolean;
|
||||||
|
isOneShot: boolean;
|
||||||
|
originX: number;
|
||||||
|
originY: number;
|
||||||
|
originZ: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
const VERTEX_SHADER = /* glsl */ `
|
||||||
|
attribute vec4 uvRect;
|
||||||
|
|
||||||
|
varying vec2 vAtlasUv;
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
vAtlasUv = uvRect.xy + uv * uvRect.zw;
|
||||||
|
|
||||||
|
vec4 mvPosition = modelViewMatrix * instanceMatrix * vec4(position, 1.0);
|
||||||
|
gl_Position = projectionMatrix * mvPosition;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const FRAGMENT_SHADER = /* glsl */ `
|
||||||
|
uniform sampler2D map;
|
||||||
|
|
||||||
|
varying vec2 vAtlasUv;
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
vec4 color = texture2D(map, vAtlasUv);
|
||||||
|
if (color.a < 0.01) discard;
|
||||||
|
|
||||||
|
gl_FragColor = color;
|
||||||
|
#include <tonemapping_fragment>
|
||||||
|
#include <colorspace_fragment>
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
function nextPow2(v: number) {
|
||||||
|
return Math.pow(2, Math.ceil(Math.log2(Math.max(1, v))));
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeParticle(textureCount: number, isOneShot: boolean): Particle {
|
||||||
|
return {
|
||||||
|
position: new THREE.Vector3(),
|
||||||
|
startY: 0,
|
||||||
|
fallSpeed: 0,
|
||||||
|
rotation: 0,
|
||||||
|
rotationSpeed: 0,
|
||||||
|
scale: 1,
|
||||||
|
textureIndex: Math.floor(Math.random() * textureCount),
|
||||||
|
windPhase: 0,
|
||||||
|
windAmplitude: 0,
|
||||||
|
emitAt: 0,
|
||||||
|
hasStarted: true,
|
||||||
|
dead: false,
|
||||||
|
isOneShot,
|
||||||
|
originX: 0,
|
||||||
|
originY: 0,
|
||||||
|
originZ: 0
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Shuffle texture indices across the initial particle pool. */
|
||||||
|
function makePool(count: number, textureCount: number, isOneShot: boolean): Particle[] {
|
||||||
|
const pool = Array.from({ length: count }, () => makeParticle(textureCount, isOneShot));
|
||||||
|
if (count > 0 && count <= textureCount) {
|
||||||
|
const indices = Array.from({ length: textureCount }, (_, i) => i);
|
||||||
|
for (let i = indices.length - 1; i > 0; i--) {
|
||||||
|
const j = Math.floor(Math.random() * (i + 1));
|
||||||
|
[indices[i], indices[j]] = [indices[j], indices[i]];
|
||||||
|
}
|
||||||
|
for (let i = 0; i < count; i++) pool[i].textureIndex = indices[i];
|
||||||
|
}
|
||||||
|
return pool;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keep the one-shot population bounded (cap 384, newest kept). */
|
||||||
|
function compactOneShots(particles: Particle[]): Particle[] {
|
||||||
|
const alive = particles.filter((p) => !p.isOneShot || !p.dead);
|
||||||
|
const persistent = alive.filter((p) => !p.isOneShot);
|
||||||
|
const oneShots = alive.filter((p) => p.isOneShot);
|
||||||
|
if (oneShots.length <= STICKER_CONFIG.oneShotCap) return alive;
|
||||||
|
oneShots.sort((a, b) => b.emitAt - a.emitAt);
|
||||||
|
return persistent.concat(oneShots.slice(0, STICKER_CONFIG.oneShotCap));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Spawn a particle at a randomized position (mode: "scroll" | "click"). */
|
||||||
|
function spawn(p: Particle, cfg: StickerConfig, mode: "scroll" | "click") {
|
||||||
|
const {
|
||||||
|
spawnWidth, clickSpawnWidth, positionY, spawnHeight, clickSpawnHeight,
|
||||||
|
scale, clickScale, rotationSpeed, windStrength, zDepth, zOffset, fallSpeed
|
||||||
|
} = cfg;
|
||||||
|
const height = mode === "click" ? clickSpawnHeight : spawnHeight;
|
||||||
|
const jitter = Math.min(0.5 * Math.max(height, 0), 8);
|
||||||
|
const offset = mode === "click"
|
||||||
|
? positionY + (2 * Math.random() - 1) * jitter
|
||||||
|
: positionY + Math.random() * Math.max(height, 0);
|
||||||
|
|
||||||
|
p.position.set(
|
||||||
|
p.originX + (Math.random() - 0.5) * (mode === "click" ? clickSpawnWidth : spawnWidth),
|
||||||
|
p.originY + offset,
|
||||||
|
p.originZ + (Math.random() - 0.5) * zDepth + zOffset
|
||||||
|
);
|
||||||
|
p.startY = p.position.y;
|
||||||
|
p.fallSpeed = fallSpeed * (0.6 + 0.8 * Math.random());
|
||||||
|
p.rotation = Math.random() * Math.PI * 2;
|
||||||
|
p.rotationSpeed = (Math.random() - 0.5) * rotationSpeed * 2;
|
||||||
|
p.scale = mode === "click" ? clickScale : scale;
|
||||||
|
p.windPhase = Math.random() * Math.PI * 2;
|
||||||
|
p.windAmplitude = 0.3 + Math.random() * windStrength;
|
||||||
|
p.dead = false;
|
||||||
|
p.hasStarted = true;
|
||||||
|
p.emitAt = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pick a texture index not currently in flight (falls back to a random one).
|
||||||
|
*/
|
||||||
|
function pickUnusedTexture(count: number, used: Set<number>): number {
|
||||||
|
if (count <= 0) return 0;
|
||||||
|
if (used.size >= count) return Math.floor(Math.random() * count);
|
||||||
|
const free: number[] = [];
|
||||||
|
for (let i = 0; i < count; i++) if (!used.has(i)) free.push(i);
|
||||||
|
return free[Math.floor(Math.random() * free.length)];
|
||||||
|
}
|
||||||
|
|
||||||
|
type AtlasResult = {
|
||||||
|
texture: THREE.CanvasTexture;
|
||||||
|
uvRects: Float32Array;
|
||||||
|
aspects: number[];
|
||||||
|
};
|
||||||
|
|
||||||
|
type Loaded = { image: HTMLImageElement; width: number; height: number };
|
||||||
|
|
||||||
|
function buildAtlas(loaded: Loaded[]): AtlasResult | null {
|
||||||
|
if (loaded.length === 0) return null;
|
||||||
|
const maxWidth = Math.max(...loaded.map((l) => l.width));
|
||||||
|
const maxHeight = Math.max(...loaded.map((l) => l.height));
|
||||||
|
const cols = Math.ceil(Math.sqrt(loaded.length));
|
||||||
|
const rows = Math.ceil(loaded.length / cols);
|
||||||
|
const cellW = maxWidth + 4;
|
||||||
|
const cellH = maxHeight + 4;
|
||||||
|
const size = nextPow2(Math.max(cols * cellW, rows * cellH));
|
||||||
|
const cw = nextPow2(cols * cellW);
|
||||||
|
const ch = nextPow2(rows * cellH);
|
||||||
|
|
||||||
|
const canvas = document.createElement("canvas");
|
||||||
|
canvas.width = cw;
|
||||||
|
canvas.height = ch;
|
||||||
|
const ctx = canvas.getContext("2d");
|
||||||
|
if (!ctx) return null;
|
||||||
|
ctx.clearRect(0, 0, cw, ch);
|
||||||
|
|
||||||
|
const uvRects = new Float32Array(4 * loaded.length);
|
||||||
|
const aspects: number[] = [];
|
||||||
|
|
||||||
|
loaded.forEach((item, i) => {
|
||||||
|
const row = Math.floor(i / cols);
|
||||||
|
const x = (i % cols) * cellW + 2;
|
||||||
|
const y = row * cellH + 2;
|
||||||
|
ctx.drawImage(item.image, x, y, item.width, item.height);
|
||||||
|
const k = 4 * i;
|
||||||
|
uvRects[k] = (x + 0.5) / cw;
|
||||||
|
uvRects[k + 1] = 1 - (y + item.height - 0.5) / ch;
|
||||||
|
uvRects[k + 2] = (item.width - 1) / cw;
|
||||||
|
uvRects[k + 3] = (item.height - 1) / ch;
|
||||||
|
aspects.push(item.width / item.height);
|
||||||
|
});
|
||||||
|
|
||||||
|
const texture = new THREE.CanvasTexture(canvas);
|
||||||
|
texture.colorSpace = THREE.SRGBColorSpace;
|
||||||
|
texture.minFilter = THREE.LinearFilter;
|
||||||
|
texture.magFilter = THREE.LinearFilter;
|
||||||
|
texture.wrapS = THREE.ClampToEdgeWrapping;
|
||||||
|
texture.wrapT = THREE.ClampToEdgeWrapping;
|
||||||
|
texture.generateMipmaps = false;
|
||||||
|
texture.needsUpdate = true;
|
||||||
|
|
||||||
|
return { texture, uvRects, aspects };
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadImage(url: string): Promise<Loaded> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const image = new Image();
|
||||||
|
image.onload = () => resolve({ image, width: image.naturalWidth, height: image.naturalHeight });
|
||||||
|
image.onerror = () => reject(new Error(`Failed to load ${url}`));
|
||||||
|
image.src = url;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Insert keeping ascending-z order (far → near, matches painter order). */
|
||||||
|
function insertSorted(list: Particle[], p: Particle) {
|
||||||
|
const z = p.position.z;
|
||||||
|
let lo = 0;
|
||||||
|
let hi = list.length;
|
||||||
|
while (lo < hi) {
|
||||||
|
const mid = (lo + hi) >>> 1;
|
||||||
|
if (list[mid].position.z <= z) lo = mid + 1;
|
||||||
|
else hi = mid;
|
||||||
|
}
|
||||||
|
list.push(p);
|
||||||
|
for (let i = list.length - 1; i > lo; i--) list[i] = list[i - 1];
|
||||||
|
list[lo] = p;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class StickerLayer {
|
||||||
|
private scene: THREE.Scene;
|
||||||
|
private config: StickerConfig;
|
||||||
|
private mesh: THREE.InstancedMesh | null = null;
|
||||||
|
private geometry: THREE.PlaneGeometry | null = null;
|
||||||
|
private material: THREE.ShaderMaterial | null = null;
|
||||||
|
private atlas: AtlasResult | null = null;
|
||||||
|
private particles: Particle[] = [];
|
||||||
|
private sortBuffer: Particle[] = [];
|
||||||
|
private dummy = new THREE.Object3D();
|
||||||
|
private time = 0;
|
||||||
|
private lastEmit = 0;
|
||||||
|
private usedTextures = new Set<number>();
|
||||||
|
private initialized = false;
|
||||||
|
private disposed = false;
|
||||||
|
private loader: THREE.TextureLoader | null = null;
|
||||||
|
|
||||||
|
constructor(scene: THREE.Scene, config?: Partial<StickerConfig>) {
|
||||||
|
this.scene = scene;
|
||||||
|
this.config = { ...STICKER_CONFIG, ...config };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Load all sticker textures and build the shared atlas + instanced mesh. */
|
||||||
|
async load(images: string[]) {
|
||||||
|
if (this.initialized || this.disposed) return;
|
||||||
|
const loader = new THREE.TextureLoader();
|
||||||
|
this.loader = loader;
|
||||||
|
|
||||||
|
// Load via Image elements (needed for the canvas atlas anyway).
|
||||||
|
const loaded = await Promise.all(images.map(loadImage));
|
||||||
|
if (this.disposed) return;
|
||||||
|
|
||||||
|
this.atlas = buildAtlas(loaded);
|
||||||
|
if (!this.atlas) return;
|
||||||
|
|
||||||
|
const geometry = new THREE.PlaneGeometry(2, 2);
|
||||||
|
geometry.setAttribute(
|
||||||
|
"uvRect",
|
||||||
|
new THREE.InstancedBufferAttribute(new Float32Array(STICKER_CONFIG.maxVisible * 4), 4)
|
||||||
|
);
|
||||||
|
const material = new THREE.ShaderMaterial({
|
||||||
|
uniforms: { map: { value: this.atlas.texture } },
|
||||||
|
vertexShader: VERTEX_SHADER,
|
||||||
|
fragmentShader: FRAGMENT_SHADER,
|
||||||
|
transparent: true,
|
||||||
|
depthWrite: false,
|
||||||
|
side: THREE.FrontSide,
|
||||||
|
toneMapped: false
|
||||||
|
});
|
||||||
|
const mesh = new THREE.InstancedMesh(
|
||||||
|
geometry,
|
||||||
|
material,
|
||||||
|
STICKER_CONFIG.maxVisible
|
||||||
|
);
|
||||||
|
mesh.frustumCulled = false;
|
||||||
|
mesh.count = 0;
|
||||||
|
|
||||||
|
this.geometry = geometry;
|
||||||
|
this.material = material;
|
||||||
|
this.mesh = mesh;
|
||||||
|
this.scene.add(mesh);
|
||||||
|
|
||||||
|
// Seed the persistent pool: one particle per texture, shuffled.
|
||||||
|
const particles = makePool(
|
||||||
|
Math.max(1, this.config.particleCount ?? images.length),
|
||||||
|
this.atlas.aspects.length,
|
||||||
|
false
|
||||||
|
); for (const p of particles) spawn(p, this.config, "scroll");
|
||||||
|
this.particles = particles;
|
||||||
|
this.initialized = true;
|
||||||
|
|
||||||
|
// Debug hook for browser-console inspection.
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
(window as unknown as Record<string, unknown>).__stickerLayer = this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Spawn a one-shot burst at a world-space point. */
|
||||||
|
burst(point: THREE.Vector3) {
|
||||||
|
if (!this.atlas || !this.initialized) return;
|
||||||
|
const pool = makePool(this.config.burstCount, this.atlas.aspects.length, true);
|
||||||
|
let delay = 0.05 * Math.random();
|
||||||
|
for (const p of pool) {
|
||||||
|
p.hasStarted = false;
|
||||||
|
p.dead = false;
|
||||||
|
p.emitAt = delay;
|
||||||
|
delay += 0.04 + 0.04 * Math.random();
|
||||||
|
}
|
||||||
|
const originX = point.x;
|
||||||
|
const originY = point.y - this.config.positionY;
|
||||||
|
for (const p of pool) {
|
||||||
|
p.originX = originX;
|
||||||
|
p.originY = originY;
|
||||||
|
p.originZ = 0;
|
||||||
|
p.emitAt += this.time;
|
||||||
|
}
|
||||||
|
this.particles = compactOneShots(this.particles.concat(pool));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Advance the simulation and update instance buffers. dt in seconds. */
|
||||||
|
update(dt: number) {
|
||||||
|
const mesh = this.mesh;
|
||||||
|
const atlas = this.atlas;
|
||||||
|
if (!mesh || !atlas || !this.initialized) return;
|
||||||
|
|
||||||
|
const step = Math.min(dt, 0.1);
|
||||||
|
this.time += step;
|
||||||
|
|
||||||
|
const used = this.usedTextures;
|
||||||
|
used.clear();
|
||||||
|
for (const p of this.particles) {
|
||||||
|
if (!p.isOneShot && !p.dead && p.hasStarted) used.add(p.textureIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sortBuffer = this.sortBuffer;
|
||||||
|
sortBuffer.length = 0;
|
||||||
|
|
||||||
|
const { fallDistance, windFrequency, enterDurationRatio } = this.config;
|
||||||
|
|
||||||
|
for (const p of this.particles) {
|
||||||
|
// Both persistent respawns and queued one-shots wait for emitAt,
|
||||||
|
// then spawn with click-mode jitter (same as the original).
|
||||||
|
if (!p.hasStarted) {
|
||||||
|
if (this.time < p.emitAt) continue;
|
||||||
|
spawn(p, this.config, "click");
|
||||||
|
}
|
||||||
|
if (p.dead) continue;
|
||||||
|
|
||||||
|
p.position.y -= p.fallSpeed * step;
|
||||||
|
const wind = Math.sin(this.time * windFrequency + p.windPhase) * p.windAmplitude;
|
||||||
|
p.position.x += wind * step;
|
||||||
|
p.rotation += p.rotationSpeed * step;
|
||||||
|
|
||||||
|
const progress = (p.startY - p.position.y) / fallDistance;
|
||||||
|
const clamped = THREE.MathUtils.clamp(progress, 0, 1);
|
||||||
|
let factor = 1;
|
||||||
|
const enter = enterDurationRatio ?? 0.05;
|
||||||
|
if (enter > 0 && clamped < enter) factor = clamped / enter;
|
||||||
|
else if (clamped > 0.9) factor = (1 - clamped) / 0.1;
|
||||||
|
factor = THREE.MathUtils.clamp(factor, 0, 1);
|
||||||
|
|
||||||
|
if (p.position.y < p.startY - fallDistance) {
|
||||||
|
if (p.isOneShot) {
|
||||||
|
p.dead = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Retire, then respawn with a different texture after a short delay.
|
||||||
|
used.delete(p.textureIndex);
|
||||||
|
p.textureIndex = pickUnusedTexture(atlas.aspects.length, used);
|
||||||
|
p.emitAt = Math.max(this.lastEmit, this.time) + (0.04 + 0.04 * Math.random());
|
||||||
|
this.lastEmit = p.emitAt;
|
||||||
|
p.hasStarted = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
p.scale = factor;
|
||||||
|
if (sortBuffer.length < 96) insertSorted(sortBuffer, p);
|
||||||
|
else sortBuffer.push(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sortBuffer.length > 96) sortBuffer.sort((a, b) => a.position.z - b.position.z);
|
||||||
|
|
||||||
|
const uvRect = mesh.geometry.getAttribute("uvRect") as THREE.InstancedBufferAttribute;
|
||||||
|
const count = Math.min(sortBuffer.length, this.config.maxVisible);
|
||||||
|
const dummy = this.dummy;
|
||||||
|
|
||||||
|
for (let i = 0; i < count; i++) {
|
||||||
|
const p = sortBuffer[i];
|
||||||
|
const aspect = atlas.aspects[p.textureIndex] ?? 1;
|
||||||
|
const size = (p.isOneShot ? this.config.clickScale : this.config.scale) * p.scale;
|
||||||
|
const k = 4 * p.textureIndex;
|
||||||
|
dummy.position.copy(p.position);
|
||||||
|
dummy.rotation.set(0, 0, p.rotation);
|
||||||
|
dummy.scale.set(size * aspect, size, 1);
|
||||||
|
dummy.updateMatrix();
|
||||||
|
mesh.setMatrixAt(i, dummy.matrix);
|
||||||
|
uvRect.setXYZW(i, atlas.uvRects[k], atlas.uvRects[k + 1], atlas.uvRects[k + 2], atlas.uvRects[k + 3]);
|
||||||
|
}
|
||||||
|
|
||||||
|
mesh.count = count;
|
||||||
|
mesh.visible = count > 0;
|
||||||
|
mesh.instanceMatrix.needsUpdate = true;
|
||||||
|
uvRect.needsUpdate = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose() {
|
||||||
|
this.disposed = true;
|
||||||
|
if (this.mesh) {
|
||||||
|
this.scene.remove(this.mesh);
|
||||||
|
this.mesh.dispose();
|
||||||
|
this.mesh = null;
|
||||||
|
}
|
||||||
|
this.geometry?.dispose();
|
||||||
|
this.material?.dispose();
|
||||||
|
if (this.atlas) {
|
||||||
|
this.atlas.texture.dispose();
|
||||||
|
this.atlas = null;
|
||||||
|
}
|
||||||
|
this.loader = null;
|
||||||
|
this.particles = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-1
@@ -1,7 +1,8 @@
|
|||||||
import type { NextConfig } from "next";
|
import type { NextConfig } from "next";
|
||||||
|
|
||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
/* config options here */
|
// Next 16 blocks dev resources from "cross-origin" hosts like 127.0.0.1 by default.
|
||||||
|
allowedDevOrigins: ["127.0.0.1", "localhost"],
|
||||||
};
|
};
|
||||||
|
|
||||||
export default nextConfig;
|
export default nextConfig;
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
"lenis": "^1.3.26",
|
"lenis": "^1.3.26",
|
||||||
"lucide-react": "^1.37.0",
|
"lucide-react": "^1.37.0",
|
||||||
"next": "16.3.3",
|
"next": "16.3.3",
|
||||||
|
"postprocessing": "^6.39.4",
|
||||||
"react": "19.2.8",
|
"react": "19.2.8",
|
||||||
"react-dom": "19.2.8",
|
"react-dom": "19.2.8",
|
||||||
"tailwind-merge": "^3.6.0",
|
"tailwind-merge": "^3.6.0",
|
||||||
|
|||||||
Generated
+3
@@ -35,6 +35,9 @@ importers:
|
|||||||
next:
|
next:
|
||||||
specifier: 16.3.3
|
specifier: 16.3.3
|
||||||
version: 16.3.3(@babel/core@7.29.7(supports-color@7.1.0))(@types/node@20.19.43)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)
|
version: 16.3.3(@babel/core@7.29.7(supports-color@7.1.0))(@types/node@20.19.43)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)
|
||||||
|
postprocessing:
|
||||||
|
specifier: ^6.39.4
|
||||||
|
version: 6.39.4(three@0.185.1)
|
||||||
react:
|
react:
|
||||||
specifier: 19.2.8
|
specifier: 19.2.8
|
||||||
version: 19.2.8
|
version: 19.2.8
|
||||||
|
|||||||
Reference in New Issue
Block a user