Created
July 16, 2023 12:51
-
-
Save ixxie/878aa2d1435cbee99965cb6e352941b6 to your computer and use it in GitHub Desktop.
Tile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script lang="ts"> | |
import { T, useLoader } from '@threlte/core'; | |
import { TextureLoader, DoubleSide, RepeatWrapping, type Texture } from 'three'; | |
import type { Pattern } from '$lib/types'; | |
export let x = 1000; | |
export let y = 1000; | |
export let z: number = 20; | |
export let color: string = 'white'; | |
export let pattern: Pattern | undefined; | |
export let box = true; | |
const f = 1000; | |
const { load } = useLoader(TextureLoader); | |
// Identify which textures files are available | |
$: displacement = pattern ? { displacementMap: `${pattern.prefix}/${pattern.files.bump}` } : {}; | |
$: normal = pattern ? { normalMap: `${pattern.prefix}/${pattern.files.normal}` } : {}; | |
$: files = { map: `colors/${color}`, ...displacement, ...normal }; | |
// Load textures asyncronously | |
let textures: { [key: string]: Texture } | undefined; | |
$: promise = load(files, { | |
transform: (texture) => { | |
texture.wrapT = RepeatWrapping; | |
texture.wrapS = RepeatWrapping; | |
texture.repeat.set(x / f, y / f); | |
return texture; | |
} | |
}).then((res) => { | |
textures = res; | |
}); | |
// Ensure textures are reactive to size changes | |
$: if (textures) | |
Object.keys(textures).forEach((map) => { | |
textures![map].repeat.set(x / f, y / f); | |
}); | |
</script> | |
{#await promise then} | |
{#if textures} | |
<T.Mesh castShadow receiveShadow> | |
{#if pattern} | |
<T.PlaneGeometry args={[x / f, y / f, x, y]} /> | |
{/if} | |
<T.MeshStandardMaterial {...textures} displacementScale={50 / f} side={DoubleSide} /> | |
</T.Mesh> | |
{#if box} | |
<T.Mesh receiveShadow> | |
<T.BoxGeometry args={[x / f, y / f, z / f]} /> | |
<T.MeshStandardMaterial map={textures.map} /> | |
</T.Mesh> | |
{/if} | |
{/if} | |
{/await} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment