Skip to content

Instantly share code, notes, and snippets.

@davo
Last active January 24, 2023 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davo/917ad2320c2f67ed053eb9c5d5d5eed9 to your computer and use it in GitHub Desktop.
Save davo/917ad2320c2f67ed053eb9c5d5d5eed9 to your computer and use it in GitHub Desktop.
Maxime's Grid
import { OrbitControls, useFBO } from "@react-three/drei";
import { Canvas, useFrame } from "@react-three/fiber";
import { useMemo, useRef } from "react";
import * as THREE from "three";
import { v4 as uuidv4 } from "uuid";
import "./scene.css";
import vertexShader from "./vertexShader";
import fragmentShader from "./fragmentShader";
const Geometries = () => {
// This reference gives us direct access to our mesh
const mesh = useRef();
const backgroundGroup = useRef();
// This is our main render target where we'll render and store the scene as a texture
const mainRenderTarget = useFBO();
const uniforms = useMemo(
() => ({
uTexture: {
value: null,
},
winResolution: {
value: new THREE.Vector2(
window.innerWidth,
window.innerHeight
).multiplyScalar(Math.min(window.devicePixelRatio, 2)), // if DPR is 3 the shader glitches 🤷‍♂️
},
}),
[]
);
useFrame((state) => {
const { gl, scene, camera } = state;
mesh.current.visible = false;
gl.setRenderTarget(mainRenderTarget);
gl.render(scene, camera);
mesh.current.material.uniforms.uTexture.value = mainRenderTarget.texture;
gl.setRenderTarget(null);
mesh.current.visible = true;
});
// Range from https://www.joshwcomeau.com/snippets/javascript/range/
const range = (start, end, step = 1) => {
let output = [];
if (typeof end === "undefined") {
end = start;
start = 0;
}
for (let i = start; i <= end; i += step) {
output.push(i);
}
return output;
};
const columns = range(-7.5, 7.5, 2.5);
const rows = range(-7.5, 7.5, 2.5);
return (
<>
<color attach="background" args={["black"]} />
<group ref={backgroundGroup}>
{columns.map((col, i) =>
rows.map((row, j) => (
<mesh position={[col, row, -4]}>
<icosahedronGeometry args={[0.333, 8]} />
<meshStandardMaterial color="white" />
</mesh>
))
)}
</group>
<mesh ref={mesh}>
<icosahedronGeometry args={[2.84, 20]} /> // 2.84 looks more balanced against the grid
<shaderMaterial
key={uuidv4()}
vertexShader={vertexShader}
fragmentShader={fragmentShader}
uniforms={uniforms}
/>
</mesh>
</>
);
};
const Scene = () => {
return (
<Canvas camera={{ position: [-3, 0, 6] }} dpr={[1, 2]}>
<ambientLight intensity={1.0} />
<Geometries />
<OrbitControls />
</Canvas>
);
};
export default Scene;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment