This repository was archived by the owner on Aug 21, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathWebGLRendererSystem.ts
More file actions
396 lines (329 loc) Β· 13.4 KB
/
Copy pathWebGLRendererSystem.ts
File metadata and controls
396 lines (329 loc) Β· 13.4 KB
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import _ from 'lodash'
import {
BloomEffect,
BrightnessContrastEffect,
ColorDepthEffect,
DepthOfFieldEffect,
EffectComposer,
HueSaturationEffect,
NormalPass,
OutlineEffect,
RenderPass,
SMAAEffect,
SSAOEffect,
ToneMappingEffect
} from 'postprocessing'
import { useEffect } from 'react'
import {
LinearToneMapping,
PCFSoftShadowMap,
PerspectiveCamera,
ShadowMapType,
sRGBEncoding,
ToneMapping,
WebGL1Renderer,
WebGLRenderer,
WebGLRendererParameters
} from 'three'
import { defineState, dispatchAction, getMutableState, getState, none, useHookstate } from '@etherealengine/hyperflux'
import { CSM } from '../assets/csm/CSM'
import { ExponentialMovingAverage } from '../common/classes/ExponentialAverageCurve'
import { nowMilliseconds } from '../common/functions/nowMilliseconds'
import { overrideOnBeforeCompile } from '../common/functions/OnBeforeCompilePlugin'
import { Engine } from '../ecs/classes/Engine'
import { EngineActions, EngineState } from '../ecs/classes/EngineState'
import { SceneState } from '../ecs/classes/Scene'
import { defineSystem } from '../ecs/functions/SystemFunctions'
import { ObjectLayers } from '../scene/constants/ObjectLayers'
import { defaultPostProcessingSchema } from '../scene/constants/PostProcessing'
import { createWebXRManager, WebXRManager } from '../xr/WebXRManager'
import { XRState } from '../xr/XRState'
import { LinearTosRGBEffect } from './effects/LinearTosRGBEffect'
import { changeRenderMode } from './functions/changeRenderMode'
import { configureEffectComposer } from './functions/configureEffectComposer'
import { updateShadowMap } from './functions/RenderSettingsFunction'
import { RendererState } from './RendererState'
import WebGL from './THREE.WebGL'
export interface EffectComposerWithSchema extends EffectComposer {
OutlineEffect: OutlineEffect
// FXAAEffect: FXAAEffect
SMAAEffect: SMAAEffect
SSAOEffect: SSAOEffect
DepthOfFieldEffect: DepthOfFieldEffect
BloomEffect: BloomEffect
ToneMappingEffect: ToneMappingEffect
BrightnessContrastEffect: BrightnessContrastEffect
HueSaturationEffect: HueSaturationEffect
ColorDepthEffect: ColorDepthEffect
LinearTosRGBEffect: LinearTosRGBEffect
}
let lastRenderTime = 0
export class EngineRenderer {
static instance: EngineRenderer
/** Is resize needed? */
needsResize: boolean
/** Maximum Quality level of the rendered. **Default** value is 5. */
maxQualityLevel = 5
/** point at which we downgrade quality level (large delta) */
maxRenderDelta = 1000 / 28 // 28 fps = 35 ms (on some devices, rAF updates at 30fps, e.g., Low Power Mode)
/** point at which we upgrade quality level (small delta) */
minRenderDelta = 1000 / 55 // 55 fps = 18 ms
/** Resoulion scale. **Default** value is 1. */
scaleFactor = 1
renderPass: RenderPass
normalPass: NormalPass
renderContext: WebGLRenderingContext | WebGL2RenderingContext
supportWebGL2: boolean
canvas: HTMLCanvasElement
averageFrameTime = 1000 / 60
timeSamples = new Array(60 * 1).fill(1000 / 60) // 3 seconds @ 60fps
index = 0
averageTimePeriods = 3 * 60 // 3 seconds @ 60fps
/** init ExponentialMovingAverage */
movingAverage = new ExponentialMovingAverage(this.averageTimePeriods)
renderer: WebGLRenderer = null!
effectComposer: EffectComposerWithSchema = null!
/** @todo deprecate and replace with engine implementation */
xrManager: WebXRManager = null!
csm: CSM = null!
webGLLostContext: any = null
initialize() {
overrideOnBeforeCompile()
this.onResize = this.onResize.bind(this)
this.handleWebGLConextLost = this.handleWebGLConextLost.bind(this)
this.handleWebGLConextRestore = this.handleWebGLConextRestore.bind(this)
this.supportWebGL2 = WebGL.isWebGL2Available()
if (!this.supportWebGL2 && !WebGL.isWebGLAvailable()) {
WebGL.dispatchWebGLDisconnectedEvent()
}
const canvas: HTMLCanvasElement = document.querySelector('canvas')!
const context = this.supportWebGL2 ? canvas.getContext('webgl2')! : canvas.getContext('webgl')!
if (!context) {
dispatchAction(
EngineActions.browserNotSupported({
msg: 'Your browser does not have WebGL enabled. Please enable WebGL, or try another browser.'
}) as any
)
}
this.renderContext = context!
const options: WebGLRendererParameters = {
precision: 'highp',
powerPreference: 'high-performance',
stencil: false,
antialias: false,
depth: true,
logarithmicDepthBuffer: true,
canvas,
context,
preserveDrawingBuffer: false,
//@ts-ignore
multiviewStereo: true
}
this.canvas = canvas
canvas.focus()
canvas.ondragstart = (e) => {
e.preventDefault()
return false
}
const renderer = this.supportWebGL2 ? new WebGLRenderer(options) : new WebGL1Renderer(options)
this.renderer = renderer
// @ts-ignore
this.renderer.useLegacyLights = false //true
this.renderer.outputEncoding = sRGBEncoding
// DISABLE THIS IF YOU ARE SEEING SHADER MISBEHAVING - UNCHECK THIS WHEN TESTING UPDATING THREEJS
this.renderer.debug.checkShaderErrors = false //isDev
// @ts-ignore
this.xrManager = renderer.xr = createWebXRManager()
this.xrManager.cameraAutoUpdate = false
this.xrManager.enabled = true
window.addEventListener('resize', this.onResize, false)
this.onResize()
this.renderer.autoClear = true
this.effectComposer = new EffectComposer(this.renderer) as any
//Todo: WebGL restore context
this.webGLLostContext = context.getExtension('WEBGL_lose_context')
// TODO: for test purpose, need to remove when PR is merging
// webGLLostContext.loseContext() in inspect can simulate the conext lost
//@ts-ignore
window.webGLLostContext = this.webGLLostContext
if (this.webGLLostContext) {
canvas.addEventListener('webglcontextlost', this.handleWebGLConextLost)
canvas.addEventListener('webglcontextrestored', this.handleWebGLConextRestore)
} else {
console.log('Browser does not support `WEBGL_lose_context` extension')
}
}
handleWebGLConextLost(e) {
console.log('Browser lost the context.', e)
e.preventDefault()
this.needsResize = false
setTimeout(() => {
this.effectComposer.setSize(0, 0, true)
if (this.webGLLostContext) this.webGLLostContext.restoreContext()
}, 1000)
}
handleWebGLConextRestore(e) {
console.log("Browser's context is restored.", e)
this.canvas.removeEventListener('webglcontextlost', this.handleWebGLConextLost)
this.canvas.removeEventListener('webglcontextrestored', this.handleWebGLConextRestore)
this.initialize()
this.needsResize = true
}
/** Called on resize, sets resize flag. */
onResize(): void {
this.needsResize = true
}
/**
* Executes the system. Called each frame by default from the Engine.instance.
* @param delta Time since last frame.
*/
execute(delta: number): void {
const xrCamera = EngineRenderer.instance.xrManager.getCamera()
const xrFrame = Engine.instance.xrFrame
/** Postprocessing does not support multipass yet, so just use basic renderer when in VR */
if (xrFrame) {
// Assume Engine.instance.camera.layers is source of truth for all xr cameras
const camera = Engine.instance.camera as PerspectiveCamera
xrCamera.layers.mask = camera.layers.mask
for (const c of xrCamera.cameras) c.layers.mask = camera.layers.mask
this.renderer.render(Engine.instance.scene, Engine.instance.camera)
} else {
const state = getState(RendererState)
const engineState = getState(EngineState)
if (!engineState.isEditor && state.automatic && engineState.joinedWorld) this.changeQualityLevel()
if (this.needsResize) {
const curPixelRatio = this.renderer.getPixelRatio()
const scaledPixelRatio = window.devicePixelRatio * this.scaleFactor
if (curPixelRatio !== scaledPixelRatio) this.renderer.setPixelRatio(scaledPixelRatio)
const width = window.innerWidth
const height = window.innerHeight
if ((Engine.instance.camera as PerspectiveCamera).isPerspectiveCamera) {
const cam = Engine.instance.camera as PerspectiveCamera
cam.aspect = width / height
cam.updateProjectionMatrix()
}
state.qualityLevel > 0 && this.csm?.updateFrustums()
// Effect composer calls renderer.setSize internally
this.effectComposer.setSize(width, height, true)
this.needsResize = false
}
/**
* Editor should always use post processing, even if no postprocessing schema is in the scene,
* it still uses post processing for effects such as outline.
*/
this.effectComposer.render(delta)
}
}
/**
* Change the quality of the renderer.
*/
changeQualityLevel(): void {
const time = nowMilliseconds()
const delta = time - lastRenderTime
lastRenderTime = time
const { qualityLevel } = getState(RendererState)
let newQualityLevel = qualityLevel
this.movingAverage.update(Math.min(delta, 50))
const averageDelta = this.movingAverage.mean
if (averageDelta > this.maxRenderDelta && newQualityLevel > 1) {
newQualityLevel--
} else if (averageDelta < this.minRenderDelta && newQualityLevel < this.maxQualityLevel) {
newQualityLevel++
}
if (newQualityLevel !== qualityLevel) {
getMutableState(RendererState).qualityLevel.set(newQualityLevel)
}
}
}
export const DefaultRenderSettingsState = {
// LODs: { ...DEFAULT_LOD_DISTANCES },{
csm: true,
toneMapping: LinearToneMapping as ToneMapping,
toneMappingExposure: 0.8,
shadowMapType: PCFSoftShadowMap as ShadowMapType
}
export const DefaultPostProcessingState = {
enabled: false,
effects: defaultPostProcessingSchema
}
export const RendererSceneMetadataLabel = 'renderSettings'
export const PostProcessingSceneMetadataLabel = 'postprocessing'
export const RenderSettingsState = defineState({
name: 'RenderSettingsState',
initial: DefaultRenderSettingsState
})
export const PostProcessingSettingsState = defineState({
name: 'PostProcessingSettingsState',
initial: DefaultPostProcessingState
})
/** @deprecated use getMutableState(RenderSettingsState) */
export const getRendererSceneMetadataState = () => getMutableState(RenderSettingsState)
/** @deprecated use getMutableState(PostProcessingSettingsState) */
export const getPostProcessingSceneMetadataState = () => getMutableState(PostProcessingSettingsState)
const execute = () => {
EngineRenderer.instance.execute(Engine.instance.deltaSeconds)
}
globalThis.EngineRenderer = EngineRenderer
const reactor = () => {
const renderSettings = useHookstate(getMutableState(RenderSettingsState))
const engineRendererSettings = useHookstate(getMutableState(RendererState))
const postprocessing = useHookstate(getMutableState(PostProcessingSettingsState))
const xrState = useHookstate(getMutableState(XRState))
useEffect(() => {
getMutableState(SceneState).sceneMetadataRegistry.merge({
[RendererSceneMetadataLabel]: {
data: () => getState(RenderSettingsState),
dataState: () => getMutableState(RenderSettingsState),
default: DefaultRenderSettingsState
},
[PostProcessingSceneMetadataLabel]: {
data: () => getState(PostProcessingSettingsState),
dataState: () => getMutableState(PostProcessingSettingsState),
default: DefaultPostProcessingState
}
})
return () => {
getMutableState(SceneState).sceneMetadataRegistry[RendererSceneMetadataLabel].set(none)
getMutableState(SceneState).sceneMetadataRegistry[PostProcessingSceneMetadataLabel].set(none)
}
}, [])
useEffect(() => {
EngineRenderer.instance.renderer.toneMapping = renderSettings.toneMapping.value
}, [renderSettings.toneMapping])
useEffect(() => {
EngineRenderer.instance.renderer.toneMappingExposure = renderSettings.toneMappingExposure.value
}, [renderSettings.toneMappingExposure])
useEffect(() => {
updateShadowMap()
}, [xrState.supportedSessionModes, renderSettings.shadowMapType, engineRendererSettings.useShadows])
useEffect(() => {
configureEffectComposer()
}, [postprocessing, engineRendererSettings.usePostProcessing])
useEffect(() => {
EngineRenderer.instance.scaleFactor =
engineRendererSettings.qualityLevel.value / EngineRenderer.instance.maxQualityLevel
EngineRenderer.instance.renderer.setPixelRatio(window.devicePixelRatio * EngineRenderer.instance.scaleFactor)
EngineRenderer.instance.needsResize = true
}, [engineRendererSettings.qualityLevel])
useEffect(() => {
changeRenderMode()
}, [engineRendererSettings.renderMode])
useEffect(() => {
if (engineRendererSettings.debugEnable.value) Engine.instance.camera.layers.enable(ObjectLayers.PhysicsHelper)
else Engine.instance.camera.layers.disable(ObjectLayers.PhysicsHelper)
}, [engineRendererSettings.debugEnable])
useEffect(() => {
if (engineRendererSettings.gridVisibility.value) Engine.instance.camera.layers.enable(ObjectLayers.Gizmos)
else Engine.instance.camera.layers.disable(ObjectLayers.Gizmos)
}, [engineRendererSettings.gridVisibility])
useEffect(() => {
if (engineRendererSettings.nodeHelperVisibility.value) Engine.instance.camera.layers.enable(ObjectLayers.NodeHelper)
else Engine.instance.camera.layers.disable(ObjectLayers.NodeHelper)
}, [engineRendererSettings.nodeHelperVisibility])
return null
}
export const WebGLRendererSystem = defineSystem({
uuid: 'ee.engine.WebGLRendererSystem',
execute,
reactor
})