File size: 12,532 Bytes
18b0fa5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
<!-- Credits to Fyrestar for the https://github.com/Fyrestar/THREE.InfiniteGridHelper  -->
<script lang="ts">
	import { T, useTask, useThrelte } from "@threlte/core";
	import { Color, DoubleSide, Plane, Vector3, Mesh } from "three";
	import * as THREE from "three";

	// Grid shader code with improved precision and stability
	import { revision } from "@threlte/core";

	// Props
	let {
		cellColor = "#71717A",
		sectionColor = "#707070",
		cellSize = 1,
		backgroundColor = "#000000",
		backgroundOpacity = 0,
		sectionSize = 10,
		plane = "xz",
		gridSize = [20, 20],
		followCamera = false,
		infiniteGrid = false,
		fadeDistance = 100,
		fadeStrength = 1,
		fadeOrigin = undefined,
		cellThickness = 1,
		sectionThickness = 2,
		side = DoubleSide,
		type = "grid",
		axis = "x",
		maxRadius = 0,
		cellDividers = 6,
		sectionDividers = 2,
		floorColor = "#2a2a2a",
		floorOpacity = 0.3,
		ref = $bindable(),
		children = undefined,
		...props
	} = $props();

	// Shared fade calculation function for both shaders
	const fadeCalculation = /*glsl*/ `
		float calculateFade(vec3 worldPos, float viewZ, vec3 fadeOrigin, float fadeDistance, float fadeStrength, float cameraNear, float cameraFar) {
			float dist = distance(fadeOrigin, worldPos);
			float fadeFactor = 1.0 - clamp(dist / fadeDistance, 0.0, 1.0);
			fadeFactor = pow(fadeFactor, fadeStrength);
			
			float viewDepthFade = 1.0 - clamp((viewZ - cameraNear) / (cameraFar - cameraNear), 0.0, 1.0);
			viewDepthFade = smoothstep(0.0, 0.3, viewDepthFade);
			
			return min(fadeFactor, viewDepthFade);
		}
	`;

	const vertexShader = /*glsl*/ `
		varying vec3 localPosition;
		varying vec4 worldPosition;
		varying float vViewZ;

		uniform vec3 worldCamProjPosition;
		uniform vec3 worldPlanePosition;
		uniform float fadeDistance;
		uniform bool infiniteGrid;
		uniform bool followCamera;
		uniform int coord0, coord1, coord2;

		void main() {
			localPosition = vec3(position[coord0], position[coord1], position[coord2]);
			if (infiniteGrid) localPosition *= 1.0 + fadeDistance;

			worldPosition = modelMatrix * vec4(localPosition, 1.0);
			if (followCamera) {
				worldPosition.xyz += (worldCamProjPosition - worldPlanePosition);
				localPosition = (inverse(modelMatrix) * worldPosition).xyz;
			}

			vec4 mvPosition = viewMatrix * worldPosition;
			vViewZ = -mvPosition.z;
			gl_Position = projectionMatrix * mvPosition;
		}
	`;

	const fragmentShader = /*glsl*/ `
		#define PI 3.141592653589793
		
		varying vec3 localPosition;
		varying vec4 worldPosition;
		varying float vViewZ;

		uniform float cellSize, sectionSize, cellThickness, sectionThickness;
		uniform vec3 cellColor, sectionColor, backgroundColor, fadeOrigin;
		uniform float backgroundOpacity, fadeDistance, fadeStrength, cameraNear, cameraFar;
		uniform bool infiniteGrid;
		uniform int coord0, coord1, coord2, gridType, lineGridCoord;
		uniform float circleGridMaxRadius, polarCellDividers, polarSectionDividers;

		${fadeCalculation}

		float getSquareGrid(float size, float thickness, vec3 localPos) {
			vec2 coord = localPos.xy / size;
			vec2 derivative = fwidth(coord);
			vec2 grid = abs(fract(coord - 0.5) - 0.5) / derivative;
			float line = min(grid.x, grid.y) + 1.0 - thickness;
			return clamp(1.0 - line, 0.0, 1.0);
		}

		float getLinesGrid(float size, float thickness, vec3 localPos) {
			float coord = localPos[lineGridCoord] / size;
			float derivative = fwidth(coord);
			float line = abs(fract(coord - 0.5) - 0.5) / derivative - thickness * 0.5;
			return clamp(1.0 - line, 0.0, 1.0);
		}

		float getCirclesGrid(float size, float thickness, vec3 localPos) {
			float coord = length(localPos.xy) / size;
			float derivative = fwidth(coord);
			float line = abs(fract(coord - 0.5) - 0.5) / derivative - thickness * 0.5;
			if (!infiniteGrid && circleGridMaxRadius > 0.0 && coord > circleGridMaxRadius + thickness * 0.1) discard;
			return clamp(1.0 - line, 0.0, 1.0);
		}

		float getPolarGrid(float size, float thickness, float polarDividers, vec3 localPos) {
			float rad = length(localPos.xy) / size;
			vec2 coord = vec2(rad, atan(localPos.x, localPos.y) * polarDividers / PI);
			vec2 derivative = fwidth(coord);
			vec2 grid = abs(fract(coord - 0.5) - 0.5) / derivative;
			float line = min(grid.x, grid.y) + 1.0 - thickness;
			if (!infiniteGrid && circleGridMaxRadius > 0.0 && rad > circleGridMaxRadius + thickness * 0.1) discard;
			return clamp(1.0 - line, 0.0, 1.0);
		}

		void main() {
			float g1 = 0.0, g2 = 0.0;
			vec3 localPos = vec3(localPosition[coord0], localPosition[coord1], localPosition[coord2]);

			if (gridType == 0) {
				g1 = getSquareGrid(cellSize, cellThickness, localPos);
				g2 = getSquareGrid(sectionSize, sectionThickness, localPos);
			} else if (gridType == 1) {
				g1 = getLinesGrid(cellSize, cellThickness, localPos);
				g2 = getLinesGrid(sectionSize, sectionThickness, localPos);
			} else if (gridType == 2) {
				g1 = getCirclesGrid(cellSize, cellThickness, localPos);
				g2 = getCirclesGrid(sectionSize, sectionThickness, localPos);
			} else if (gridType == 3) {
				g1 = getPolarGrid(cellSize, cellThickness, polarCellDividers, localPos);
				g2 = getPolarGrid(sectionSize, sectionThickness, polarSectionDividers, localPos);
			}

			float fadeFactor = calculateFade(worldPosition.xyz, vViewZ, fadeOrigin, fadeDistance, fadeStrength, cameraNear, cameraFar);
			vec3 color = mix(cellColor, sectionColor, clamp(sectionThickness * g2, 0.0, 1.0));
			float gridAlpha = clamp((g1 + g2) * fadeFactor, 0.0, 1.0);

			if (backgroundOpacity > 0.0) {
				vec3 finalColor = mix(backgroundColor, color, gridAlpha);
				float blendedAlpha = clamp(max(gridAlpha, backgroundOpacity * fadeFactor), 0.0, 1.0);
				gl_FragColor = vec4(finalColor, blendedAlpha);
			} else {
				gl_FragColor = vec4(color, gridAlpha);
			}

			if (gl_FragColor.a < 0.05) discard;

			#include <tonemapping_fragment>
			#include <${revision < 154 ? "encodings_fragment" : "colorspace_fragment"}>
		}
	`;

	// Simple floor shader
	const floorVertexShader = /*glsl*/ `
		varying vec3 vWorldPosition;
		varying float vViewZ;
		
		void main() {
			vec4 worldPosition = modelMatrix * vec4(position, 1.0);
			vWorldPosition = worldPosition.xyz;
			vec4 mvPosition = viewMatrix * worldPosition;
			vViewZ = -mvPosition.z;
			gl_Position = projectionMatrix * mvPosition;
		}
	`;

	const floorFragmentShader = /*glsl*/ `
		uniform vec3 floorColor, fadeOrigin;
		uniform float floorOpacity, fadeDistance, fadeStrength, cameraNear, cameraFar;
		varying vec3 vWorldPosition;
		varying float vViewZ;
		
		${fadeCalculation}
		
		void main() {
			float fadeFactor = calculateFade(vWorldPosition, vViewZ, fadeOrigin, fadeDistance, fadeStrength, cameraNear, cameraFar);
			float finalOpacity = floorOpacity * fadeFactor;
			gl_FragColor = vec4(floorColor, finalOpacity);
			if (gl_FragColor.a < 0.01) discard;
		}
	`;

	const mesh = new Mesh();
	const { invalidate, camera } = useThrelte();
	const gridPlane = new Plane();
	const upVector = new Vector3(0, 1, 0);
	const zeroVector = new Vector3(0, 0, 0);

	const axisToInt: Record<string, number> = { x: 0, y: 1, z: 2 };
	const planeToAxes: Record<string, string> = { xz: "xzy", xy: "xyz", zy: "zyx" };
	const gridType = { grid: 0, lines: 1, circular: 2, polar: 3 };

	// Shared uniforms (used by both grid and floor)
	const sharedUniforms = {
		fadeOrigin: { value: new Vector3() },
		fadeDistance: { value: fadeDistance },
		fadeStrength: { value: fadeStrength },
		cameraNear: { value: 0.1 },
		cameraFar: { value: 1000 }
	};

	// Grid uniforms
	const uniforms = {
		...sharedUniforms,
		cellSize: { value: cellSize },
		sectionSize: { value: sectionSize },
		cellColor: { value: new Color(cellColor) },
		sectionColor: { value: new Color(sectionColor) },
		backgroundColor: { value: new Color(backgroundColor) },
		backgroundOpacity: { value: backgroundOpacity },
		cellThickness: { value: cellThickness },
		sectionThickness: { value: sectionThickness },
		infiniteGrid: { value: infiniteGrid },
		followCamera: { value: followCamera },
		coord0: { value: 0 },
		coord1: { value: 2 },
		coord2: { value: 1 },
		gridType: { value: gridType.grid },
		lineGridCoord: { value: axisToInt[axis as keyof typeof axisToInt] || 0 },
		circleGridMaxRadius: { value: maxRadius },
		polarCellDividers: { value: cellDividers },
		polarSectionDividers: { value: sectionDividers },
		worldCamProjPosition: { value: new Vector3() },
		worldPlanePosition: { value: new Vector3() }
	};

	// Floor uniforms (simpler, reusing shared uniforms)
	const floorUniforms = {
		...sharedUniforms,
		floorColor: { value: new Color(floorColor) },
		floorOpacity: { value: floorOpacity }
	};

	// Single update effect for all uniforms
	$effect.pre(() => {
		const axes = planeToAxes[plane] || "xzy";
		const [c0, c1, c2] = [axes.charAt(0), axes.charAt(1), axes.charAt(2)].map(
			(c) => axisToInt[c as keyof typeof axisToInt]
		);

		// Update grid uniforms
		Object.assign(uniforms, {
			coord0: { value: c0 },
			coord1: { value: c1 },
			coord2: { value: c2 },
			cellSize: { value: cellSize },
			sectionSize: { value: sectionSize },
			cellThickness: { value: cellThickness },
			sectionThickness: { value: sectionThickness },
			backgroundOpacity: { value: backgroundOpacity },
			infiniteGrid: { value: infiniteGrid },
			followCamera: { value: followCamera }
		});

		uniforms.cellColor.value.set(cellColor);
		uniforms.sectionColor.value.set(sectionColor);
		uniforms.backgroundColor.value.set(backgroundColor);

		// Update shared uniforms (affects both grid and floor)
		sharedUniforms.fadeDistance.value = fadeDistance;
		sharedUniforms.fadeStrength.value = fadeStrength;
		floorUniforms.floorColor.value.set(floorColor);
		floorUniforms.floorOpacity.value = floorOpacity;

		// Update camera uniforms
		if (camera.current && "near" in camera.current && "far" in camera.current) {
			const cam = camera.current as THREE.PerspectiveCamera;
			sharedUniforms.cameraNear.value = cam.near;
			sharedUniforms.cameraFar.value = cam.far;
		}

		// Update grid type
		const typeMap = { grid: 0, lines: 1, circular: 2, polar: 3 };
		uniforms.gridType.value = typeMap[type as keyof typeof typeMap] || 0;
		if (type === "lines")
			uniforms.lineGridCoord.value = axisToInt[axis as keyof typeof axisToInt] || 0;
		if (type === "circular" || type === "polar") {
			uniforms.circleGridMaxRadius.value = maxRadius;
			if (type === "polar") {
				uniforms.polarCellDividers.value = cellDividers;
				uniforms.polarSectionDividers.value = sectionDividers;
			}
		}

		invalidate();
	});

	// Single task for both grid and floor fade origins
	useTask(
		() => {
			gridPlane.setFromNormalAndCoplanarPoint(upVector, zeroVector).applyMatrix4(mesh.matrixWorld);
			const material = mesh.material as THREE.ShaderMaterial;
			if (material?.uniforms) {
				const { worldCamProjPosition, worldPlanePosition } = material.uniforms;
				const projectedPoint = gridPlane.projectPoint(
					camera.current.position,
					worldCamProjPosition.value
				);
				if (!fadeOrigin) sharedUniforms.fadeOrigin.value = projectedPoint;
				worldPlanePosition.value.set(0, 0, 0).applyMatrix4(mesh.matrixWorld);
			}
		},
		{ autoInvalidate: false }
	);
</script>

<!-- Shadow-receiving floor underneath -->
<T.Mesh rotation={[-Math.PI / 2, 0, 0]} receiveShadow position.y={0} {...props}>
	<T.PlaneGeometry
		args={infiniteGrid
			? [1000, 1000]
			: typeof gridSize == "number"
				? [gridSize, gridSize]
				: gridSize}
	/>
	<T.ShadowMaterial
		transparent={true}
		opacity={0.3}
		polygonOffset={true}
		polygonOffsetFactor={1}
		polygonOffsetUnits={1}
	/>
</T.Mesh>

<!-- Fading floor -->
<T.Mesh rotation={[-Math.PI / 2, 0, 0]} position.y={0} {...props}>
	<T.PlaneGeometry
		args={infiniteGrid
			? [1000, 1000]
			: typeof gridSize == "number"
				? [gridSize, gridSize]
				: gridSize}
	/>
	<T.ShaderMaterial
		vertexShader={floorVertexShader}
		fragmentShader={floorFragmentShader}
		uniforms={floorUniforms}
		transparent={true}
		side={THREE.DoubleSide}
		depthTest={true}
		depthWrite={false}
		polygonOffset={true}
		polygonOffsetFactor={-1}
		polygonOffsetUnits={-1}
	/>
</T.Mesh>

<!-- Grid lines -->
<T is={mesh} bind:ref frustumCulled={false} position.y={0.005} {...props}>
	<T.ShaderMaterial
		{fragmentShader}
		{vertexShader}
		{uniforms}
		transparent
		{side}
		depthTest={true}
		depthWrite={false}
	/>
	{#if children}
		{@render children({ ref: mesh })}
	{:else}
		<T.PlaneGeometry args={typeof gridSize == "number" ? [gridSize, gridSize] : gridSize} />
	{/if}
</T>