refactor: update engine and canvas doc

This commit is contained in:
eyworldwide
2025-01-24 15:26:15 +08:00
parent 24338689e5
commit 346d83409e
4 changed files with 194 additions and 164 deletions

View File

@@ -5,11 +5,7 @@ group: Basics
label: Core
---
Galacean Engine encapsulates canvases for different platforms, such as [WebCanvas](/en/apis/rhi-webgl/#WebCanvas) which supports using [Engine](/en/apis/core/#Engine) to control [HTMLCanvasElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement) or [OffscreenCanvas](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas).
<img src="https://mdn.alipayobjects.com/huamei_yo47yq/afts/img/A*ZC9gRY-KCTgAAAAAAAAAAAAADhuCAQ/original" alt="image.png" style="zoom:50%;" />
> Unless otherwise specified, the canvas in the documentation generally refers to `WebCanvas`.
The engine encapsulates canvases for different platforms, such as [WebCanvas](/apis/rhi-webgl/#WebCanvas), allowing [Engine](/apis/core/#Engine) to control [HTMLCanvasElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement) or [OffscreenCanvas](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas). Unless otherwise specified, canvases in the documentation generally refer to `WebCanvas`.
## Basic Usage
@@ -21,9 +17,9 @@ Insert a `<canvas>` tag in HTML and specify an id:
<canvas id="canvas" style="width: 500px; height: 500px" />
```
> Developers should check the height and width of the canvas to avoid rendering issues caused by a height or width value of **0**.
> Developers should check the height and width of the canvas to avoid rendering issues caused by values of **0**.
When creating an instance of WebGLEngine, a WebCanvas instance is automatically created. The parameter `canvas` is the `id` of the _Canvas_ element.
When creating a WebGLEngine instance, a WebCanvas instance is automatically created. The `canvas` parameter is the _Canvas_ element's `id`.
```typescript
const engine = await WebGLEngine.create({ canvas: "canvas" });
@@ -33,7 +29,7 @@ console.log(engine.canvas); // => WebCanvas instance
### Basic Adaptation
The canvas size is generally controlled by the **device pixel ratio**, taking [WebCanvas](/en/apis/rhi-webgl/#WebCanvas) as an example:
Canvas size is generally controlled by the **device pixel ratio**. Taking [WebCanvas](/apis/rhi-webgl/#WebCanvas) as an example:
```mermaid
flowchart TD
@@ -41,79 +37,75 @@ flowchart TD
C[HtmlCanvas.clientHeight] -->|pixelRatio| D[WebCanvas.height]
```
If developing by exporting an **NPM package** through the editor, you only need to control the **device pixel ratio** in the [project export](/en/docs/platform/platform) rendering export configuration.
<img src="https://mdn.alipayobjects.com/huamei_yo47yq/afts/img/A*afw5QrbrxkQAAAAAAAAAAAAADhuCAQ/original" alt="image.png" style="zoom:50%;" />
Or actively call `resizeByClientSize` in the code to adapt the canvas.
Call `resizeByClientSize` to adapt the canvas:
```typescript
// 使用设备像素比( window.devicePixelRatio )调整画布尺寸,
// Adjust canvas size using the device pixel ratio (window.devicePixelRatio)
engine.canvas.resizeByClientSize();
// 自定义像素比调整画布尺寸
// Adjust canvas size using a custom pixel ratio
engine.canvas.resizeByClientSize(1.5);
```
> When the display size of the canvas changes (such as when the browser window changes), the image may appear stretched or compressed. You can call `resizeByClientSize` to restore it to normal. In most cases, this line of code can meet the adaptation needs. If you have more complex adaptation requirements, please read the "Advanced Usage" section.
When the display size of the canvas changes (e.g., when the browser window changes), the image may appear stretched or compressed. You can restore it to normal by calling `resizeByClientSize`. In most cases, this line of code can meet the adaptation requirements. If you have more complex adaptation needs, please read the "Advanced Usage" section.
## Advanced Usage
Regarding adaptation, the core point to note is the **device pixel ratio**. Taking iPhoneX as an example, the device pixel ratio `window.devicePixelRatio` is _3_, the window width `window.innerWidth` is _375_, and the screen physical pixel width is: 375 * 3 = *1125*.
Regarding adaptation, the key point is the **device pixel ratio**. Taking iPhone X as an example, the device pixel ratio `window.devicePixelRatio` is _3_, the window width `window.innerWidth` is _375_, and the physical screen pixel width is: 375 * 3 = *1125*.
Rendering pressure is proportional to the physical pixel height and width of the screen. The larger the physical pixels, the greater the rendering pressure, and the more power it consumes. It is recommended to set the height and width of the canvas through the API exposed by [WebCanvas](/en/apis/rhi-webgl/WebCanvas), rather than using the native canvas API, such as modifying `canvas.width` or `canvas.style.width`.
Rendering pressure is proportional to the physical pixel width and height of the screen. The larger the physical pixel, the greater the rendering pressure and the more power it consumes. It is recommended to set the canvas width and height through APIs exposed by [WebCanvas](/apis/rhi-webgl/WebCanvas), rather than using native canvas APIs such as `canvas.width` or `canvas.style.width`.
> **Note**: Some front-end scaffolds insert the following tag to modify the page's zoom ratio:
> **Note**: Some front-end scaffolds may insert the following tag to modify the page's zoom ratio:
>
> `<meta name="viewport" content="width=device-width, initial-scale=0.333333333">`
>
> This line of code will change the value of `window.innerWidth` from 375 to 1125.
> This line of code changes the value of `window.innerWidth` from 375 to 1125.
除了 `resizeByClientSize` 自动适配,推荐使用以下两种模式:
Apart from `resizeByClientSize`, which automatically adapts, the following two modes are recommended:
### Energy-saving Mode
### Energy-Saving Mode
Considering that mobile devices, although having high-definition screens (high device pixel ratio), the actual GPU performance may not meet the performance requirements for high-definition real-time rendering (the rendering area ratio of 3x screens to 2x screens is 9:4, and 3x screens can easily cause the phone to overheat), in this mode, the engine achieves adaptation by scaling and stretching the canvas. The code is as follows:
Considering that mobile devices, despite having high-definition screens (high device pixel ratio), may not have graphics card performance that meets the performance requirements for HD real-time rendering (the rendering area ratio of 3x screen to 2x screen is 9:4, and 3x screens can easily cause phones to overheat), the engine achieves adaptation by scaling the canvas in this mode. The code is as follows:
```typescript
const canvas = document.getElementById("canvas");
const webcanvas = new WebCanvas(canvas);
const pixelRatio = window.devicePixelRatio; // 如果已经设置 meta scale,请设置为 1
const scale = 3 / 2; // 3 倍高清屏按 2 倍屏来计算画布尺寸
const pixelRatio = window.devicePixelRatio; // If meta scale is set, please set to 1
const scale = 3 / 2; // Calculate canvas size for 3x HD screen as if it were 2x
/**
* 设置节能模式,默认全屏,也可以自己设置任意高宽
* Set energy-saving mode, defaults to full screen, but you can set any width and height
*/
webcanvas.width = (window.innerWidth * pixelRatio) / scale;
webcanvas.height = (window.innerHeight * pixelRatio) / scale;
webcanvas.setScale(scale, scale); // 拉伸画布
webcanvas.setScale(scale, scale); // Scale canvas
```
If the canvas height and width have already been set via CSS (e.g., `width: 100vw; height: 100vh;`), you can achieve canvas scaling by passing parameters to `resizeByClientSize`:
If the canvas width and height have been set via CSS (e.g., `width: 100vw; height: 100vh;`), you can scale the canvas by passing parameters to `resizeByClientSize`:
```typescript
const canvas = document.getElementById("canvas");
const webcanvas = new WebCanvas(canvas);
const scale = 2 / 3; // 3 倍高清屏按 2 倍屏来计算画布尺寸
const scale = 2 / 3; // Calculate canvas size for 3x HD screen as if it were 2x
webcanvas.resizeByClientSize(scale); // 拉伸画布
webcanvas.resizeByClientSize(scale); // Scale canvas
```
### Fixed Width Mode
In some cases, such as when the design draft has a fixed width of 750, developers might hardcode the canvas width to reduce adaptation costs. The code is as follows:
In certain situations, such as when a design draft has a fixed width of 750, developers might hard-code the canvas width to reduce adaptation costs. The code is as follows:
```typescript
import { WebCanvas } from "@galacean/engine";
const canvas = document.getElementById("canvas");
const webcanvas = new WebCanvas(canvas);
const fixedWidth = 750; // 固定 750 宽度
const fixedWidth = 750; // Fixed width of 750
/**
* 设置固定宽度模式
* Set fixed width mode
*/
const scale = window.innerWidth / fixedWidth;
webcanvas.width = fixedWidth;
webcanvas.height = window.innerHeight / scale;
webcanvas.setScale(scale, scale); // 拉伸画布
```
webcanvas.setScale(scale, scale); // Scale canvas
```

View File

@@ -5,104 +5,72 @@ type: Core
label: Core
---
`Engine` plays the role of the main controller in the Galacean Engine, mainly including functions such as **canvas**, **render control**, and **engine subsystem management**:
`Engine` plays the role of the main controller, primarily encompassing functions such as **canvas**, **render control**, and **engine subsystem management**:
- **[Canvas](/en/docs/core/canvas)**: Operations related to the main canvas, such as modifying the canvas width and height.
- **Render Control**: Controls the execution/pause/resume of rendering, vertical synchronization, and other functions.
- **Engine Subsystem Management**:
- [Scene Management](/en/docs/core/scene)
- [Resource Management](/en/docs/assets/overall)
- [Physics System](/en/docs/physics/overall)
- [Interaction System](/en/docs/input)
- [XR System](/en/docs/xr/overall)
- **Execution Environment Context Management**: Controls the context management of execution environments such as WebGL.
- **[Canvas](/docs/core/canvas)**: Operations related to the main canvas, such as modifying the canvas width and height.
- **Render Control**: Functions to control the execution, pause, resume of rendering, vertical synchronization, etc.
- **Engine Subsystem Management**: [Scene Management](/docs/core/scene), [Resource Management](/docs/assets/overall), [Physics System](/docs/physics/overall), [Interaction System](/docs/input/input/), [XR System](/docs/xr/overall)
- **Execution Environment Context Management**: Management of context for execution environments like WebGL.
## Initialization
To facilitate users to directly create a web engine, Galacean provides [WebGLEngine](/apis/rhi-webgl/WebGLEngine):
```typescript
const engine = await WebGLEngine.create({ canvas: "canvas" });
```
`WebGLEngine` supports WebGL1.0 and WebGL2.0. It can control all behaviors of the canvas, as well as resource management, scene management, execution/pause/resume, vertical synchronization, and other functions. `WebGLEngine.create`. Below is the type description of the configuration passed in when creating the engine:
```mermaid
---
title: WebGLEngineConfiguration Interface
---
classDiagram
EngineConfiguration <|-- WebGLEngineConfiguration
class EngineConfiguration {
<<interface>>
+IPhysics physics
+IXRDevice xrDevice
+ColorSpace colorSpace
+IShaderLab shaderLab
+IInputOptions input
}
class WebGLEngineConfiguration{
<<interface>>
+HTMLCanvasElement | OffscreenCanvas | string canvas
+WebGLGraphicDeviceOptions graphicDeviceOptions
}
```
Projects exported by the editor usually automatically set the relevant options configured by the editor. For example, developers can set the rendering configuration of the context in the [export interface](/en/docs/platform/platform):
<img src="https://mdn.alipayobjects.com/huamei_yo47yq/afts/img/A*WZHzRYIpUzQAAAAAAAAAAAAADhuCAQ/original" style="zoom:50%;" />
Or select the physics backend and XR backend in the project settings interface of the editor:
<img src="https://mdn.alipayobjects.com/huamei_yo47yq/afts/img/A*iBDlTbGGuroAAAAAAAAAAAAADhuCAQ/original" style="zoom:50%;" />
You can also modify the code to change the engine configuration. Take **canvas transparency** as an example. By default, the engine enables the transparency channel of the canvas, which means the canvas will blend with the elements behind it. If you need to disable transparency, you can set it like this:
To facilitate users directly creating a web engine, we provide the [WebGLEngine](/apis/rhi-webgl/#WebGLEngine), which supports WebGL1.0 and WebGL2.0.
```typescript
const engine = await WebGLEngine.create({
canvas: htmlCanvas,
graphicDeviceOptions: { alpha: false }
canvas: "canvas-id",
colorSpace: {...},
graphicDeviceOptions: {...},
gltf: {...},
ktx2Loader: {...}
});
```
Similarly, you can use `webGLMode` to control WebGL1/2. Properties other than `webGLMode` will be passed to the context. For details, refer to [getContext parameter explanation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext#parameters).
Below is a description of the [configuration](/apis/galacean/#WebGLEngineConfiguration) types passed when creating the engine:
For more related configuration information, refer to [Physics System](/en/docs/physics/overall), [Interaction System](/en/docs/input), [XR System](/en/docs/xr/overall).
| Configuration | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| canvas | Can be a canvas ID (`string`) or a canvas object (`HTMLCanvasElement | OffscreenCanvas`) |
| [graphicDeviceOptions](/apis/galacean/#WebGLGraphicDeviceOptions) | Configuration related to the graphics device, e.g., `webGLMode` can control WebGL1/2. Properties other than `webGLMode` will be passed to the context, more details can be found in [getContext parameters explanation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext#parameters). |
| [colorSpace](/apis/galacean/#ColorSpace) | Color space, `ColorSpace.Gamma` or `ColorSpace.Linear`. |
| gltf | GLTF Loader configuration, `workerCount` is used to configure the number of workers for meshOpt: `{ meshOpt: { workerCount: number } }`. |
| ktx2Loader | KTX2 Loader configuration, `workerCount` is used to configure the number of workers for the ktx2 decoder: `{ priorityFormats: Array<KTX2TargetFormat>; transcoder: KTX2Transcoder; workerCount: number }`. If workerCount is greater than 0, worker threads will be created; if it equals 0, only the main thread will be used. |
For more related configuration information, please refer to [Physics System](/docs/physics/overall), [Interaction System](/docs/input/input/), [XR System](/docs/xr/overall).
## Properties
| Property Name | Property Description |
| Property Name | Description |
| --- | --- |
| [time](/apis/core/#Engine-time) | Engine time-related information. For details, refer to [Time](/en/docs/core/time/) |
| [vSyncCount](/apis/core/#Engine-vSyncCount) | Vertical synchronization refresh rate. The engine enables [vertical synchronization](https://baike.baidu.com/item/%E5%9E%82%E7%9B%B4%E5%90%8C%E6%AD%A5/7263524?fromtitle=V-Sync&fromid=691778) by default, and the refresh rate `vSyncCount` is `1` (consistent with the screen refresh rate). If `vSyncCount` is set to `2`, the engine updates once every 2 frames of screen refresh. |
| [resourceManager](/apis/core/#Engine-resourceManager) | Resource manager, generally used for [loading](/en/docs/assets/load/) and [releasing](/en/docs/assets/gc/) assets |
| [sceneManager](/apis/core/#Engine-sceneManager) | Scene manager. Galacean supports rendering multiple scenes simultaneously. The scene manager can be used to conveniently manage the addition, deletion, modification, and query of the current scene. For details, refer to [Scene](/en/docs/core/scene/) |
| [inputManager](/apis/core/#Engine-inputManager) | Interaction manager, generally used to obtain keyboard, touch, and scroll information. For details, refer to [Interaction](/en/docs/input/input/) |
| [time](/apis/core/#Engine-time) | Engine time-related information, more details can be found in [Time](/docs/core/time/) |
| [vSyncCount](/apis/core/#Engine-vSyncCount) | Vertical sync refresh rate. The engine defaults to enable [vertical sync](https://baike.baidu.com/item/%E5%9E%82%E7%9B%B4%E5%90%8C%E6%AD%A5/7263524?fromtitle=V-Sync&fromid=691778) with a refresh rate `vSyncCount` of `1` (same as the screen refresh rate). If `vSyncCount` is set to `2`, the engine updates once every 2 screen refresh frames. |
| [resourceManager](/apis/core/#Engine-resourceManager) | Resource manager, generally used for [loading](/docs/assets/load/) and [releasing](/docs/assets/gc/) assets. |
| [sceneManager](/apis/core/#Engine-sceneManager) | Scene manager. Galacean supports rendering multiple scenes simultaneously, and the scene manager allows convenient management of scene additions, deletions, modifications, and queries. More details can be found in [Scene](/docs/core/scene/). |
| [inputManager](/apis/core/#Engine-inputManager) | Interaction manager, generally used to get information about keyboards, touch, and wheel inputs. More details can be found in [Interaction](/docs/input/input/). |
### Refresh Rate
By default, the engine uses vertical synchronization mode and controls the rendering refresh rate with [vSyncCount](/apis/core/#Engine-vSyncCount). In this mode, the rendered frame will wait for the screen's vertical sync signal. [vSyncCount](/apis/core/#Engine-vSyncCount) represents the desired number of screen sync signals between rendered frames. The default value is 1, and this property must be an integer. For example, if we want to render 30 frames per second on a device with a screen refresh rate of 60 frames, we can set this value to 2.
By default, the engine uses vertical sync mode and controls the rendering refresh rate with [vSyncCount](/apis/core/#Engine-vSyncCount). In this mode, the rendering frame waits for the screen's vertical sync signal, and [vSyncCount](/apis/core/#Engine-vSyncCount) represents the desired number of screen sync signals between rendering frames. The default value is 1, and this property must be an integer. For example, if we want to render 30 frames per second on a device with a 60Hz screen refresh rate, we can set this value to 2.
Additionally, users can disable vertical synchronization by setting [vSyncCount](/apis/core/#Engine-vSyncCount) to 0 and then setting [targetFrameRate](/apis/core/#Engine-targetFrameRate) to the desired frame rate. In this mode, rendering does not consider the vertical sync signal. For example, 120 means 120 frames, i.e., the expectation is to refresh 120 times per second.
Users can also disable vertical sync by setting [vSyncCount](/apis/core/#Engine-vSyncCount) to 0 and then setting [targetFrameRate](/apis/core/#Engine-targetFrameRate) to the desired frame rate. In this mode, rendering does not consider vertical sync signals. For instance, a value of 120 means 120 frames, which indicates a desired refresh rate of 120 times per second.
```typescript
// 垂直同步
// Vertical sync
engine.vSyncCount = 1;
engine.vSyncCount = 2;
// 非垂直同步
// No vertical sync
engine.vSyncCount = 0;
engine.targetFrameRate = 120;
```
> ⚠️ It is not recommended to use non-vertical synchronization
> ⚠️ Non-vertical sync is not recommended.
## Methods
| Method Name | Description |
| Method Name | Description |
| ------------------------------------- | ------------------ |
| [run](/apis/core/#Engine-run) | Execute engine rendering frame loop |
| [pause](/apis/core/#Engine-pause) | Pause engine rendering frame loop |
| [resume](/apis/core/#Engine-resume)| Resume engine rendering loop |
| [destroy](/apis/core/#Engine-destroy)| Destroy the engine |
| [run](/apis/core/#Engine-run) | Executes the engine render frame loop |
| [pause](/apis/core/#Engine-pause) | Pauses the engine render frame loop |
| [resume](/apis/core/#Engine-resume) | Resumes the engine render loop |
| [destroy](/apis/core/#Engine-destroy) | Destroys the engine |

View File

@@ -5,11 +5,7 @@ group: 基础
label: Core
---
Galacean Engine 封装了不同平台的画布,如 [WebCanvas](/apis/rhi-webgl/#WebCanvas)  支持用 [Engine](/apis/core/#Engine) 控制 [HTMLCanvasElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement) 或者 [OffscreenCanvas](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas) 
<img src="https://mdn.alipayobjects.com/huamei_yo47yq/afts/img/A*ZC9gRY-KCTgAAAAAAAAAAAAADhuCAQ/original" alt="image.png" style="zoom:50%;" />
> 若无特殊说明,文档中画布一般都为 `WebCanvas` 。
引擎封装了不同平台的画布,如 [WebCanvas](/apis/rhi-webgl/#WebCanvas) 支持用 [Engine](/apis/core/#Engine) 控制 [HTMLCanvasElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement) 或者 [OffscreenCanvas](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas) 。若无特殊说明,文档中画布一般都为 `WebCanvas`
## 基础使用
@@ -41,11 +37,7 @@ flowchart TD
C[HtmlCanvas.clientHeight] -->|pixelRatio| D[WebCanvas.height]
```
若通过编辑器导出 **NPM package** 进行开发,只需在[项目导出](/docs/platform/platform)渲染导出配置处控制**设备像素比**即可。
<img src="https://mdn.alipayobjects.com/huamei_yo47yq/afts/img/A*afw5QrbrxkQAAAAAAAAAAAAADhuCAQ/original" alt="image.png" style="zoom:50%;" />
或在代码中主动调用 `resizeByClientSize` 适配画布。
调用 `resizeByClientSize` 适配画布:
```typescript
// 使用设备像素比( window.devicePixelRatio )调整画布尺寸,
@@ -54,7 +46,7 @@ engine.canvas.resizeByClientSize();
engine.canvas.resizeByClientSize(1.5);
```
> 当画布的显示尺寸发生变化时(比如浏览器窗口发生变化时),画面可能出现拉伸或压缩,可以通过调用 `resizeByClientSize` 来恢复正常。一般情况下这行代码已经可以满足适配的需求,如果你有更复杂的适配需求,请阅读“高级使用”部分。
当画布的显示尺寸发生变化时(比如浏览器窗口发生变化时),画面可能出现拉伸或压缩,可以通过调用 `resizeByClientSize` 来恢复正常。一般情况下这行代码已经可以满足适配的需求,如果你有更复杂的适配需求,请阅读“高级使用”部分。
## 高级使用

View File

@@ -5,68 +5,38 @@ type: 核心
label: Core
---
`Engine` Galacean Engine 中扮演着总控制器的角色,主要包含了**画布**、**渲染控制**和**引擎子系统管理**等功能:
`Engine` 在扮演着总控制器的角色,主要包含了**画布**、**渲染控制**和**引擎子系统管理**等功能:
- **[画布](/docs/core/canvas)**:主画布相关的操作,如修改画布宽高等。
- **渲染控制** 控制渲染的执行/暂停/继续、垂直同步等功能。
- **引擎子系统管理**
- [场景管理](/docs/core/scene)
- [资源管理](/docs/assets/overall)
- [物理系统](/docs/physics/overall)
- [交互系统](/docs/input/input/)
- [XR 系统](/docs/xr/overall)
- **引擎子系统管理** [场景管理](/docs/core/scene)、[资源管理](/docs/assets/overall)、[物理系统](/docs/physics/overall) 、[交互系统](/docs/input/input/)、[XR 系统](/docs/xr/overall)
- **执行环境的上下文管理**:控制 WebGL 等执行环境的上下文管理。
## 初始化
为了方便用户直接创建 web 端 engineGalacean 提供了 [WebGLEngine](/apis/rhi-webgl/#WebGLEngine) 
```typescript
const engine = await WebGLEngine.create({ canvas: "canvas" });
```
`WebGLEngine` 支持 WebGL1.0 和 WebGL2.0,它能够控制画布的一切行为,此外还有资源管理、场景管理、执行/暂停/继续、垂直同步等功能。`WebGLEngine.create` 。下方是创建引擎时传入配置的类型说明:
```mermaid
---
title: WebGLEngineConfiguration Interface
---
classDiagram
EngineConfiguration <|-- WebGLEngineConfiguration
class EngineConfiguration {
<<interface>>
+IPhysics physics
+IXRDevice xrDevice
+ColorSpace colorSpace
+IShaderLab shaderLab
+IInputOptions input
}
class WebGLEngineConfiguration{
<<interface>>
+HTMLCanvasElement | OffscreenCanvas | string canvas
+WebGLGraphicDeviceOptions graphicDeviceOptions
}
```
编辑器导出的项目通常自动设置了编辑器配置的相关选项,比如开发者可以在 [导出界面](/docs/platform/platform) 设置上下文的渲染配置:
<img src="https://mdn.alipayobjects.com/huamei_yo47yq/afts/img/A*WZHzRYIpUzQAAAAAAAAAAAAADhuCAQ/original" style="zoom:50%;" />
又或者在编辑器的项目设置界面选择物理后端与 XR 后端:
<img src="https://mdn.alipayobjects.com/huamei_yo47yq/afts/img/A*iBDlTbGGuroAAAAAAAAAAAAADhuCAQ/original" style="zoom:50%;" />
您也可以修改代码变更引擎配置,拿**画布透明**来举例,引擎默认是将画布的透明通道开启的,即画布会和背后的网页元素混合,如果需要关闭透明,可以这样设置:
为了方便用户直接创建 web 端 engine我们提供了 [WebGLEngine](/apis/rhi-webgl/#WebGLEngine),支持 WebGL1.0 和 WebGL2.0。
```typescript
const engine = await WebGLEngine.create({
canvas: htmlCanvas,
graphicDeviceOptions: { alpha: false }
canvas: "canvas-id",
colorSpace: {...},
graphicDeviceOptions: {...}
gltf: {...},
ktx2Loader: {...}
});
```
类似的,可以用 `webGLMode` 控制 WebGL1/2`webGLMode` 外的属性将透传给上下文,详情可参考 [getContext 参数释义](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext#parameters)。
下方是创建引擎时传入[配置](/apis/galacean/#WebGLEngineConfiguration)的类型说明:
| 配置 | 解释 |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| canvas | 可以是画布 ID `string` 或画布对象(`HTMLCanvasElement |OffscreenCanvas`)。 |
| [graphicDeviceOptions](/apis/galacean/#WebGLGraphicDeviceOptions) | 图形设备相关配置,比如 `webGLMode` 可以用 控制 WebGL1/2。除 `webGLMode` 外的属性将透传给上下文,详情可参考 [getContext 参数释义](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext#parameters)。 |
| [colorSpace](/apis/galacean/#ColorSpace) | 颜色空间, `ColorSpace.Gamma``ColorSpace.Linear`。 |
| gltf | gltf Loader 配置,`workerCount` 用来配置 meshOpt 的 worker 数量:`{ meshOpt: { workerCount: number } }` 。 |
| ktx2Loader | KTX2 Loader 配置,`workerCount` 用来配置 ktx2 解码器的worker 数量:`{ priorityFormats: Array<KTX2TargetFormat>; transcoder: KTX2Transcoder; workerCount: number }`。如果 workCount 大于 0将会创建 worker 线程,等于 0 则只用主线程。 |
更多相关配置信息,可参考[物理系统](/docs/physics/overall)、[交互系统](/docs/input/input/)、[XR 系统](/docs/xr/overall)。
@@ -106,3 +76,111 @@ engine.targetFrameRate = 120;
| [pause](/apis/core/#Engine-pause) | 暂停引擎渲染帧循环 |
| [resume](/apis/core/#Engine-resume) | 恢复引擎渲渲染循环 |
| [destroy](/apis/core/#Engine-destroy) | 销毁引擎 |
## 画布
### 创建画布
在 HTML 中插入一个 `<canvas>` 标签,指定一个 id
```html
<canvas id="canvas" style="width: 500px; height: 500px" />
```
> 开发者要注意检查 canvas 的高度和宽度,避免出现高度或宽度的值为 **0** 导致渲染不出来。
创建 WebGLEngine 实例的时候会自动创建一个 WebCanvas 实例。其中,参数 `canvas`_Canvas_ 元素的 `id`
```typescript
const engine = await WebGLEngine.create({ canvas: "canvas" });
console.log(engine.canvas); // => WebCanvas 实例
```
### 基础适配
画布尺寸一般通过**设备像素比**控制,以 [WebCanvas](/apis/rhi-webgl/#WebCanvas) 为例:
```mermaid
flowchart TD
A[HtmlCanvas.clientWidth] -->|pixelRatio| B[WebCanvas.width]
C[HtmlCanvas.clientHeight] -->|pixelRatio| D[WebCanvas.height]
```
若通过编辑器导出 **NPM package** 进行开发,只需在[项目导出](/docs/platform/platform)渲染导出配置处控制**设备像素比**即可。
<img src="https://mdn.alipayobjects.com/huamei_yo47yq/afts/img/A*afw5QrbrxkQAAAAAAAAAAAAADhuCAQ/original" alt="image.png" style="zoom:50%;" />
或在代码中主动调用 `resizeByClientSize` 适配画布。
```typescript
// 使用设备像素比( window.devicePixelRatio )调整画布尺寸,
engine.canvas.resizeByClientSize();
// 自定义像素比调整画布尺寸
engine.canvas.resizeByClientSize(1.5);
```
> 当画布的显示尺寸发生变化时(比如浏览器窗口发生变化时),画面可能出现拉伸或压缩,可以通过调用 `resizeByClientSize` 来恢复正常。一般情况下这行代码已经可以满足适配的需求,如果你有更复杂的适配需求,请阅读“高级使用”部分。
## 高级使用
关于适配,核心要注意的点是**设备像素比**,以 iPhoneX 为例,设备像素比 `window.devicePixelRatio`_3_  窗口宽度 `window.innerWidth`_375_屏幕物理像素宽度则为375 * 3 = *1125\*
渲染压力和屏幕物理像素高宽成正比,物理像素越大,渲染压力越大,也就越耗电。画布的高宽建议通过 [WebCanvas](/apis/rhi-webgl/WebCanvas) 暴露的 API 设置,不建议使用原生 canvas 的 API ,如 `canvas.width``canvas.style.width` 这些方法修改。
> **注意**:有些前端脚手架会插入以下标签修改页面的缩放比:
>
> `<meta name="viewport" content="width=device-width, initial-scale=0.333333333">`
>
> 这行代码会把 `window.innerWidth` 的值从 375 修改为 1125。
除了 `resizeByClientSize` 自动适配,推荐使用以下两种模式:
### 节能模式
考虑到移动端设备虽然是高清屏幕(设别像素比高)但实际显卡性能并不能很好地满足高清实时渲染的性能要求的情况(**3 倍屏和 2 倍屏渲染面积比是 9:43 倍屏较容易造成手机发烫**),此模式下引擎通过对画布缩放拉伸来达到适配的目的。代码如下:
```typescript
const canvas = document.getElementById("canvas");
const webcanvas = new WebCanvas(canvas);
const pixelRatio = window.devicePixelRatio; // 如果已经设置 meta scale请设置为 1
const scale = 3 / 2; // 3 倍高清屏按 2 倍屏来计算画布尺寸
/**
* 设置节能模式,默认全屏,也可以自己设置任意高宽
*/
webcanvas.width = (window.innerWidth * pixelRatio) / scale;
webcanvas.height = (window.innerHeight * pixelRatio) / scale;
webcanvas.setScale(scale, scale); // 拉伸画布
```
如果已经通过 CSS 设置了画布高宽(比如 `width: 100vw; height: 100vh;`),那么可以通过 `resizeByClientSize` 传参实现画布的缩放:
```typescript
const canvas = document.getElementById("canvas");
const webcanvas = new WebCanvas(canvas);
const scale = 2 / 3; // 3 倍高清屏按 2 倍屏来计算画布尺寸
webcanvas.resizeByClientSize(scale); // 拉伸画布
```
### 固定宽度模式
某些情况下,比如设计稿固定 750 宽度的情况,开发者有可能会写死画布宽度来降低适配成本。代码如下:
```typescript
import { WebCanvas } from "@galacean/engine";
const canvas = document.getElementById("canvas");
const webcanvas = new WebCanvas(canvas);
const fixedWidth = 750; // 固定 750 宽度
/**
* 设置固定宽度模式
*/
const scale = window.innerWidth / fixedWidth;
webcanvas.width = fixedWidth;
webcanvas.height = window.innerHeight / scale;
webcanvas.setScale(scale, scale); // 拉伸画布
```