Parcourir la source

docs(useTexture): add comprehensive documentation for useTexture composable

- Create detailed documentation for `useTexture` composable
- Add extensive code examples covering various use cases
- Include API reference and feature highlights
- Provide insights into loading textures with Tres.js
- Enhance documentation with practical examples and best practices
alvarosabu il y a 6 mois
Parent
commit
c8e3403b0c
4 fichiers modifiés avec 225 ajouts et 96 suppressions
  1. 7 1
      docs/.vitepress/config/en.ts
  2. 0 95
      docs/api/composables.md
  3. 1 0
      docs/components.d.ts
  4. 217 0
      docs/composables/use-texture.md

+ 7 - 1
docs/.vitepress/config/en.ts

@@ -37,7 +37,13 @@ export const enConfig: LocaleSpecificConfig<DefaultTheme.Config> = {
           },
         ],
       },
-
+      {
+        text: 'Composables',
+        link: '/api/composables',
+        items: [
+          { text: 'useTexture', link: '/composables/use-texture' },
+        ],
+      },
       {
         text: 'Advanced',
 

+ 0 - 95
docs/api/composables.md

@@ -264,101 +264,6 @@ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader'
 The `UseLoader` component needs to be wrapped in a `Suspense` component in order to work
 :::
 
-## useTexture
-
-The `useTexture` composable allows you to load textures using the [THREE.js texture loader](https://threejs.org/docs/#api/en/loaders/TextureLoader). It returns a promise with the loaded texture(s).
-
-```ts
-const texture = await useTexture(['path/to/texture.png'])
-```
-
-**useTexture** also accepts an object with the following properties:
-
-- `map`: a basic texture that is applied to the surface of an object
-- `displacementMap`: a texture that is used to add bumps or indentations to the object's surface
-- `normalMap`: a texture that is used to add surface detail to and variations in shading to the object
-- `roughnessMap`: a texture that is used to add roughness or a matte finish to the object's surface
-- `metalnessMap`: a texture that is used to add a metallic effect to the object's surface
-- `aoMap`: a texture that is used to add ambient occlusion (shading in areas where light is blocked by other objects) to the object.
-- `alphaMap`: a texture that is used to add alpha (the black part render as transparent) to the object. It's necessary to set :trasparent="true" on the material to use this map
-- `matcap`: this textures encodes the material color and shading.
-
-In that case it will return an object with the loaded textures.
-
-```ts
-const { map, displacementMap, normalMap, roughnessMap, metalnessMap, aoMap, alphaMap, matcap } = await useTexture({
-  map: 'path/to/albedo.png',
-  displacementMap: 'path/to/height.png',
-  normalMap: 'path/to/normal.png',
-  roughnessMap: 'path/to/roughness.png',
-  metalnessMap: 'path/to/metalness.png',
-  aoMap: 'path/to/ambien-occlusion.png',
-  alphaMap: 'path/to/alpha.png',
-  matcap: 'path/to/matcap.png',
-})
-```
-
-Then you can bind the textures to the material.
-
-```vue
-<template>
-  <TresCanvas>
-    <TresMesh>
-      <TresSphereGeometry />
-      <TresMeshStandardMaterial
-        :map="map"
-        :displacement-map="displacementMap"
-        :normal-map="normalMap"
-        :roughness-map="roughnessMap"
-        :metalness-map="metalnessMap"
-        :ao-map="aoMap"
-        :alpha-map="alphaMap"
-      />
-    </TresMesh>
-  </TresCanvas>
-</template>
-```
-
-`useTexture` by default takes the second argument 'manager' as LoadingManager. When omitted, it will automatically be added to `THREE.DefaultLoadingManager`. Of course, you can also add your own LoadingManager, like this:
-```ts
-const loadingManager = new LoadingManager()
-const texture = await useTexture({ map: 'path/to/texture.png' }, loadingManager)
-```
-
-Similar to above composable, the `useTexture` composable returns a promise, you can use it with `async/await` or `then/catch`. If you are using it on a component make sure you wrap it with a `Suspense` component.
-
-### UseTexture as component
-
-You can also use `UseTexture` (with uppercase) as component like so:
-
-```html
-<Suspense>
-  <UseTexture v-slot="{ textures }" map="path/to/texture.png">
-    <TresMesh>
-      <TresBoxGeometry />
-      <TresMeshStandardMaterial :map="textures.map" />
-    </TresMesh>
-  </UseTexture>
-</Suspense>
-```
-
-### Props
-
-| Prop | type |
-| ---- | --- |
-| **map?** | `String` |
-| **displacementMap?** | `String` |
-| **normalMap?** | `String` |
-| **roughnessMap?** | `String` |
-| **metalnessMap?** | `String` |
-| **aoMap?** | `String` |
-| **alphaMap?** | `String` |
-| **matcap?** | `String` |
-
-::: warning
-The `UseTexture` component needs to be wrapped in a `Suspense` component in order to work
-:::
-
 ## useSeek
 
 The `useSeek` composable provides utilities to easily traverse and navigate through complex ThreeJS scenes and object children graphs. It exports 4 functions which allow you to find child objects based on specific properties.

+ 1 - 0
docs/components.d.ts

@@ -2,6 +2,7 @@
 // @ts-nocheck
 // Generated by unplugin-vue-components
 // Read more: https://github.com/vuejs/core/pull/3399
+// biome-ignore lint: disable
 export {}
 
 /* prettier-ignore */

+ 217 - 0
docs/composables/use-texture.md

@@ -0,0 +1,217 @@
+# useTexture
+
+The `useTexture` composable allows you to load textures using the [THREE.js texture loader](https://threejs.org/docs/#api/en/loaders/TextureLoader). This composable provides a convenient way to load single or multiple textures with built-in loading state management.
+
+## Features
+
+- 🔄 Reactive texture loading
+- 🔢 Support for single or multiple textures
+- ⏳ Loading state tracking
+- ❌ Error handling
+- ⏱️ Async/await support with Suspense
+- 🔄 Manual reload capability
+
+## Basic Usage
+
+```ts
+import { useTexture } from '@tresjs/core'
+```
+
+### Loading a Single Texture
+
+```ts
+const { data: texture } = useTexture('path/to/texture.png')
+```
+
+### Loading Multiple Textures
+
+```ts
+const { data: textures } = useTexture([
+  'path/to/albedo.png',
+  'path/to/normal.png',
+  'path/to/roughness.png'
+])
+
+// Access individual textures
+const [albedo, normal, roughness] = textures.value
+```
+
+## Advanced Usage
+
+### With Async/Await and Suspense
+
+The composable can be awaited directly, making it compatible with Vue's Suspense component:
+
+```ts
+// In an async setup function
+const { data: texture } = await useTexture('path/to/texture.png')
+```
+
+### Using a Custom Loading Manager
+
+You can provide a THREE.js LoadingManager to track loading progress across multiple resources:
+
+```ts
+import { LoadingManager } from 'three'
+
+const manager = new LoadingManager()
+manager.onProgress = (url, loaded, total) => {
+  console.log(`Loading ${url}: ${loaded} of ${total} files.`)
+}
+
+const { data: texture } = useTexture('path/to/texture.png', manager)
+```
+
+### Handling Loading States
+
+The composable provides reactive references for tracking loading state:
+
+```ts
+const { data: texture, isLoading, error } = useTexture('path/to/texture.png')
+
+watch(isLoading, (value) => {
+  if (value) {
+    console.log('Texture is loading...')
+  }
+})
+
+watch(error, (value) => {
+  if (value) {
+    console.error('Error loading texture:', value)
+  }
+})
+```
+
+### Manual Loading
+
+```ts
+const { data: texture, load } = useTexture('path/to/initial-texture.png')
+
+// Later, load a different texture
+const newTexture = await load('path/to/new-texture.png')
+
+// Or load multiple textures
+const newTextures = await load([
+  'path/to/texture1.png',
+  'path/to/texture2.png'
+])
+```
+
+## Common Use Cases
+
+### Material Textures
+
+```ts
+const { data: textures } = useTexture([
+  'textures/wood/albedo.jpg',
+  'textures/wood/normal.jpg',
+  'textures/wood/roughness.jpg',
+  'textures/wood/ao.jpg'
+])
+
+// In your setup function
+const material = computed(() => {
+  if (!textures.value) { return null }
+
+  const [albedo, normal, roughness, ao] = textures.value
+
+  return {
+    map: albedo,
+    normalMap: normal,
+    roughnessMap: roughness,
+    aoMap: ao
+  }
+})
+```
+
+### Environment Maps
+
+```ts
+const { data: envMap } = useTexture('textures/environment.hdr')
+
+// Use with a scene or material
+const scene = computed(() => {
+  if (envMap.value) {
+    return {
+      background: envMap.value,
+      environment: envMap.value
+    }
+  }
+  return {}
+})
+```
+
+### Texture Atlas
+
+```ts
+const { data: atlas } = useTexture('textures/sprite-atlas.png')
+
+// Configure texture for sprite use
+watchEffect(() => {
+  if (atlas.value) {
+    atlas.value.wrapS = atlas.value.wrapT = THREE.RepeatWrapping
+    atlas.value.repeat.set(1 / 8, 1 / 8) // For an 8x8 grid
+  }
+})
+```
+
+## API Reference
+
+### Parameters
+
+| Parameter | Type | Description |
+| --- | --- | --- |
+| `path` | `string \| string[]` | Path or array of paths to texture file(s) |
+| `manager` | `LoadingManager` | Optional THREE.js LoadingManager |
+
+### Returns
+
+| Property | Type | Description |
+| --- | --- | --- |
+| `data` | `Ref<Texture \| Texture[] \| null>` | The loaded texture(s) |
+| `isLoading` | `Ref<boolean>` | Whether the texture is currently loading |
+| `error` | `Ref<Error \| null>` | Any error that occurred during loading |
+| `promise` | `Promise<Texture \| Texture[]>` | Promise that resolves when the texture is loaded |
+| `load` | `Function` | Method to manually load texture(s) |
+
+## Notes
+
+- Textures are loaded both synchronously and asynchronously. The initial texture object is created immediately, but the actual image data loads asynchronously.
+- The composable uses `shallowRef` for better performance when dealing with complex THREE.js objects.
+- Error handling is built-in, with detailed error messages available in the `error` ref.
+
+## Component Usage
+
+The `UseTexture` component provides a slot-based API for loading textures directly in your template:
+
+```vue
+<script setup lang="ts">
+import { UseTexture } from '@tresjs/core'
+
+const paths = [
+  'textures/black-rock/color.jpg',
+  'textures/black-rock/displacement.jpg',
+]
+</script>
+
+<template>
+  <UseTexture v-slot="{ data: texture }" :path="paths">
+    <TresMesh :position="[-3, 1, 0]">
+      <TresSphereGeometry :args="[1, 32, 32]" />
+      <TresMeshStandardMaterial
+        v-if="texture"
+        :map="texture[0]"
+        :displacement-map="texture[1]"
+        :displacement-scale="0.1"
+      />
+    </TresMesh>
+  </UseTexture>
+</template>
+```
+
+The component provides the loaded texture(s) through its default slot prop. This approach is particularly useful when:
+- You want to scope texture loading to a specific part of your scene
+- You need to ensure a mesh and its textures are loaded together
+- You prefer a more declarative template-based approach
+
+The slot provides the same properties as the composable (`data`, `isLoading`, `error`).