Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: useTexture callback parameter and behavior #1970 #2142

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 12 additions & 18 deletions src/core/Texture.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
/* eslint react-hooks/exhaustive-deps: 1 */
import * as React from 'react'
clementroche marked this conversation as resolved.
Show resolved Hide resolved
import { Texture as _Texture, TextureLoader } from 'three'
import { useLoader, useThree } from '@react-three/fiber'
import { useLayoutEffect, useEffect, useMemo } from 'react'
import { useEffect, useLayoutEffect, useMemo } from 'react'

export const IsObject = (url: unknown): url is Record<string, string> =>
url === Object(url) && !Array.isArray(url) && typeof url !== 'function'
Expand All @@ -20,31 +21,20 @@ export function useTexture<Url extends string[] | string | Record<string, string
onLoad?: (texture: MappedTextureType<Url>) => void
): MappedTextureType<Url> {
const gl = useThree((state) => state.gl)
const textures = useLoader(TextureLoader, IsObject(input) ? Object.values(input) : input) as MappedTextureType<Url>

useLayoutEffect(() => {
onLoad?.(textures)
}, [onLoad])
const textures = useLoader(TextureLoader, IsObject(input) ? Object.values(input) : input)

// https://github.com/mrdoob/three.js/issues/22696
// Upload the texture to the GPU immediately instead of waiting for the first render
// NOTE: only available for WebGLRenderer
useEffect(() => {
if ('initTexture' in gl) {
let textureArray: _Texture[] = []
if (Array.isArray(textures)) {
textureArray = textures
} else if (textures instanceof _Texture) {
textureArray = [textures]
} else if (IsObject(textures)) {
textureArray = Object.values(textures)
}

textureArray.forEach((texture) => {
if (texture instanceof _Texture) {
for (const texture of textures) {
gl.initTexture(texture)
}
})
} else {
gl.initTexture(textures)
}
}
}, [gl, textures])

Expand All @@ -55,10 +45,14 @@ export function useTexture<Url extends string[] | string | Record<string, string
for (const key in input) keyed[key] = textures[i++]
return keyed
} else {
return textures
return textures as MappedTextureType<Url>
}
}, [input, textures])

useLayoutEffect(() => {
onLoad?.(mappedTextures)
}, [mappedTextures, onLoad])

return mappedTextures
}

Expand Down