V3.8.2 pipeline (#16244)

This commit is contained in:
hyde zhou
2023-11-07 11:36:32 +08:00
committed by GitHub
parent daf1699b72
commit e2d0ec3658
54 changed files with 5412 additions and 1099 deletions
+152 -14
View File
@@ -24,17 +24,17 @@
import { EDITOR } from 'internal:constants';
import { BufferInfo, Buffer, BufferUsageBit, ClearFlagBit, Color, DescriptorSet, LoadOp,
Format, Rect, Sampler, StoreOp, Texture, Viewport, MemoryUsageBit, Filter, Address } from '../../gfx';
Format, Rect, Sampler, StoreOp, Texture, Viewport, MemoryUsageBit, Filter, Address, DescriptorSetLayoutInfo, DescriptorSetLayoutBinding } from '../../gfx';
import { ProbeType, ReflectionProbe } from '../../render-scene/scene/reflection-probe';
import { Camera, SKYBOX_FLAG } from '../../render-scene/scene/camera';
import { CSMLevel, ShadowType } from '../../render-scene/scene/shadows';
import { CSMLevel, ShadowType, Shadows } from '../../render-scene/scene/shadows';
import { Light, LightType } from '../../render-scene/scene/light';
import { DirectionalLight } from '../../render-scene/scene/directional-light';
import { RangedDirectionalLight } from '../../render-scene/scene/ranged-directional-light';
import { PointLight } from '../../render-scene/scene/point-light';
import { SphereLight } from '../../render-scene/scene/sphere-light';
import { SpotLight } from '../../render-scene/scene/spot-light';
import { supportsR32FloatTexture, supportsRGBA16HalfFloatTexture } from '../define';
import { UBOForwardLight, supportsR32FloatTexture, supportsRGBA16HalfFloatTexture } from '../define';
import { BasicPipeline, Pipeline } from './pipeline';
import {
AccessType, AttachmentType, CopyPair, LightInfo,
@@ -46,7 +46,7 @@ import { getProfilerCamera, SRGBToLinear } from '../pipeline-funcs';
import { RenderWindow } from '../../render-scene/core/render-window';
import { RenderData, RenderGraph } from './render-graph';
import { WebComputePassBuilder, WebPipeline } from './web-pipeline';
import { DescriptorSetData, LayoutGraph, LayoutGraphData } from './layout-graph';
import { DescriptorSetData, DescriptorSetLayoutData, LayoutGraph, LayoutGraphData } from './layout-graph';
import { AABB } from '../../core/geometry';
import { DebugViewCompositeType, DebugViewSingleType } from '../debug-view';
import { ReflectionProbeManager } from '../../3d/reflection-probe/reflection-probe-manager';
@@ -682,11 +682,10 @@ export function buildShadowPass (
);
}
const queue = shadowPass.addQueue(QueueHint.RENDER_OPAQUE, 'shadow-caster');
queue.addSceneOfCamera(
queue.addScene(
camera,
new LightInfo(light, level),
SceneFlags.SHADOW_CASTER | SceneFlags.OPAQUE_OBJECT | SceneFlags.TRANSPARENT_OBJECT,
);
SceneFlags.SHADOW_CASTER | SceneFlags.OPAQUE_OBJECT | SceneFlags.MASK,
).useLightFrustum(light, light.type !== LightType.DIRECTIONAL ? 0 : level);
queue.setViewport(new Viewport(area.x, area.y, area.width, area.height));
}
@@ -755,8 +754,10 @@ export function buildReflectionProbePass (
probeCamera.clearStencil,
probeCamera.clearFlag,
);
const passBuilder = probePass.addQueue(QueueHint.RENDER_OPAQUE);
passBuilder.addSceneOfCamera(camera, new LightInfo(), SceneFlags.REFLECTION_PROBE);
const passBuilder = probePass.addQueue(QueueHint.RENDER_OPAQUE, 'reflect-map');
const lightInfo = new LightInfo();
lightInfo.probe = probe;
passBuilder.addSceneOfCamera(camera, lightInfo, SceneFlags.REFLECTION_PROBE | SceneFlags.OPAQUE_OBJECT);
updateCameraUBO(passBuilder as unknown as any, probeCamera, ppl);
}
@@ -2481,6 +2482,140 @@ export function bool (val): boolean {
return !!val;
}
export function AlignUp (value: number, alignment: number): number {
return (value + (alignment - 1)) & ~(alignment - 1);
}
const kLightMeterScale = 10000;
export function SetLightUBO (
light: Light | null,
bHDR: boolean,
exposure: number,
shadowInfo: Shadows | null,
buffer: Float32Array,
offset: number,
elemSize: number,
): void {
const vec4Array = new Float32Array(4);
let size = 0.0;
let range = 0.0;
let luminanceHDR = 0.0;
let luminanceLDR = 0.0;
if (light && light.type === LightType.SPHERE) {
const sphereLight = light as SphereLight;
vec4Array[0] = sphereLight.position.x;
vec4Array[1] = sphereLight.position.y;
vec4Array[2] = sphereLight.position.z;
vec4Array[3] = LightType.SPHERE;
size = sphereLight.size;
range = sphereLight.range;
luminanceHDR = sphereLight.luminanceHDR;
luminanceLDR = sphereLight.luminanceLDR;
} else if (light && light.type === LightType.SPOT) {
const spotLight = light as SpotLight;
vec4Array[0] = spotLight.position.x;
vec4Array[1] = spotLight.position.y;
vec4Array[2] = spotLight.position.z;
vec4Array[3] = LightType.SPOT;
size = spotLight.size;
range = spotLight.range;
luminanceHDR = spotLight.luminanceHDR;
luminanceLDR = spotLight.luminanceLDR;
} else if (light && light.type === LightType.POINT) {
const pointLight = light as PointLight;
vec4Array[0] = pointLight.position.x;
vec4Array[1] = pointLight.position.y;
vec4Array[2] = pointLight.position.z;
vec4Array[3] = LightType.POINT;
size = 0.0;
range = pointLight.range;
luminanceHDR = pointLight.luminanceHDR;
luminanceLDR = pointLight.luminanceLDR;
} else if (light && light.type === LightType.RANGED_DIRECTIONAL) {
const rangedDirLight = light as RangedDirectionalLight;
vec4Array[0] = rangedDirLight.position.x;
vec4Array[1] = rangedDirLight.position.y;
vec4Array[2] = rangedDirLight.position.z;
vec4Array[3] = LightType.RANGED_DIRECTIONAL;
size = 0.0;
range = 0.0;
luminanceHDR = rangedDirLight.illuminanceHDR;
luminanceLDR = rangedDirLight.illuminanceLDR;
}
let index = offset + UBOForwardLight.LIGHT_POS_OFFSET;
buffer.set(vec4Array, index);
index = offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET;
vec4Array.set([size, range, 0, 0]);
buffer.set(vec4Array, index);
index = offset + UBOForwardLight.LIGHT_COLOR_OFFSET;
const color = light ? light.color : new Color();
if (light && light.useColorTemperature) {
const tempRGB = light.colorTemperatureRGB;
buffer[index++] = color.x * tempRGB.x;
buffer[index++] = color.y * tempRGB.y;
buffer[index++] = color.z * tempRGB.z;
} else {
buffer[index++] = color.x;
buffer[index++] = color.y;
buffer[index++] = color.z;
}
if (bHDR) {
buffer[index] = luminanceHDR * exposure * kLightMeterScale;
} else {
buffer[index] = luminanceLDR;
}
switch (light ? light.type : LightType.UNKNOWN) {
case LightType.SPHERE:
buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 2] = 0;
buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 3] = 0;
break;
case LightType.SPOT: {
const spotLight = light as SpotLight;
buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 2] = spotLight.spotAngle;
buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 3] = (shadowInfo && shadowInfo.enabled
&& spotLight.shadowEnabled
&& shadowInfo.type === ShadowType.ShadowMap) ? 1.0 : 0.0;
index = offset + UBOForwardLight.LIGHT_DIR_OFFSET;
const direction = spotLight.direction;
buffer[index++] = direction.x;
buffer[index++] = direction.y;
buffer[index] = direction.z;
} break;
case LightType.POINT:
buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 2] = 0;
buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 3] = 0;
break;
case LightType.RANGED_DIRECTIONAL: {
const rangedDirLight = light as RangedDirectionalLight;
const right = rangedDirLight.right;
buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 0] = right.x;
buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 1] = right.y;
buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 2] = right.z;
buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 3] = 0;
const direction = rangedDirLight.direction;
buffer[offset + UBOForwardLight.LIGHT_DIR_OFFSET + 0] = direction.x;
buffer[offset + UBOForwardLight.LIGHT_DIR_OFFSET + 1] = direction.y;
buffer[offset + UBOForwardLight.LIGHT_DIR_OFFSET + 2] = direction.z;
buffer[offset + UBOForwardLight.LIGHT_DIR_OFFSET + 3] = 0;
const scale = rangedDirLight.scale;
buffer[offset + UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET + 0] = scale.x * 0.5;
buffer[offset + UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET + 1] = scale.y * 0.5;
buffer[offset + UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET + 2] = scale.z * 0.5;
buffer[offset + UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET + 3] = 0;
} break;
default:
break;
}
}
export function getSubpassOrPassID (sceneId: number, rg: RenderGraph, lg: LayoutGraphData): number {
const queueId = rg.getParent(sceneId);
assert(queueId !== 0xFFFFFFFF);
@@ -2500,10 +2635,13 @@ export function getSubpassOrPassID (sceneId: number, rg: RenderGraph, lg: Layout
assert(passLayoutId !== lg.nullVertex());
const subpassLayoutName: string = rg.getLayout(subpassOrPassID);
assert(!!subpassLayoutName);
const subpassLayoutId = lg.locateChild(passLayoutId, subpassLayoutName);
assert(subpassLayoutId !== lg.nullVertex());
layoutId = subpassLayoutId;
if (subpassLayoutName.length === 0) {
layoutId = passLayoutId;
} else {
const subpassLayoutId = lg.locateChild(passLayoutId, subpassLayoutName);
assert(subpassLayoutId !== lg.nullVertex());
layoutId = subpassLayoutId;
}
}
assert(layoutId !== lg.nullVertex());
return layoutId;
+80 -164
View File
@@ -28,7 +28,7 @@
* ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! =========================
*/
/* eslint-disable max-len */
import { getPhaseID, InstancedBuffer, PipelineStateManager } from '..';
import { getPhaseID, PipelineStateManager } from '..';
import { assert, cclegacy, RecyclePool } from '../../core';
import intersect from '../../core/geometry/intersect';
import { Sphere } from '../../core/geometry/sphere';
@@ -36,7 +36,6 @@ import {
AccessFlagBit,
Attribute,
Buffer,
BufferFlagBit,
BufferInfo,
BufferUsageBit,
BufferViewInfo,
@@ -63,7 +62,6 @@ import {
Rect,
RenderPass,
RenderPassInfo,
Shader,
StoreOp,
SurfaceTransform,
Swapchain,
@@ -76,11 +74,10 @@ import {
import { legacyCC } from '../../core/global-exports';
import { Vec3 } from '../../core/math/vec3';
import { Vec4 } from '../../core/math/vec4';
import { Pass } from '../../render-scene';
import { Camera } from '../../render-scene/scene/camera';
import { ShadowType } from '../../render-scene/scene/shadows';
import { Root } from '../../root';
import { IRenderPass, isEnableEffect, SetIndex, UBODeferredLight, UBOForwardLight, UBOLocal } from '../define';
import { IRenderPass, SetIndex, UBODeferredLight, UBOForwardLight, UBOLocal } from '../define';
import { PipelineSceneData } from '../pipeline-scene-data';
import { PipelineInputAssemblerData } from '../render-pipeline';
import { DescriptorSetData, LayoutGraphData, PipelineLayoutData, RenderPhaseData, RenderStageData } from './layout-graph';
@@ -135,6 +132,7 @@ import { RenderAdditiveLightQueue } from '../render-additive-light-queue';
import { DefaultVisitor, depthFirstSearch, ReferenceGraphView } from './graph';
import { VectorGraphColorMap } from './effect';
import {
bool,
getDescriptorSetDataFromLayout,
getDescriptorSetDataFromLayoutId,
getRenderArea,
@@ -143,8 +141,9 @@ import {
validPunctualLightsCulling,
} from './define';
import { RenderReflectionProbeQueue } from '../render-reflection-probe-queue';
import { SceneCulling } from './scene-culling';
import { WebPipeline } from './web-pipeline';
import { LightResource, SceneCulling } from './scene-culling';
import { Pass } from '../../render-scene';
import { WebProgramLibrary } from './web-program-library';
class ResourceVisitor implements ResourceGraphVisitor {
name: string;
@@ -221,10 +220,10 @@ class ResourceVisitor implements ResourceGraphVisitor {
this.createDeviceTex(value);
}
formatView (value: FormatView): void {
// noop
// do nothing
}
subresourceView (value: SubresourceView): void {
// noop
// do nothing
}
}
@@ -248,26 +247,11 @@ class DeviceTexture extends DeviceResource {
get description (): ResourceDesc | null { return this._desc; }
get trait (): ResourceTraits | null { return this._trait; }
get swapchain (): Swapchain | null { return this._swapchain; }
private _setDesc (desc: ResourceDesc): void {
if (!this._desc) {
this._desc = new ResourceDesc();
}
this._desc.alignment = desc.alignment;
this._desc.depthOrArraySize = desc.depthOrArraySize;
this._desc.dimension = desc.dimension;
this._desc.flags = desc.flags;
this._desc.format = desc.format;
this._desc.height = desc.height;
this._desc.mipLevels = desc.mipLevels;
this._desc.sampleCount = desc.sampleCount;
this._desc.textureFlags = desc.textureFlags;
this._desc.width = desc.width;
}
constructor (name: string, tex: PersistentTexture | Framebuffer | RenderSwapchain | ManagedResource) {
super(name);
const resGraph = context.resourceGraph;
const verID = resGraph.vertex(name);
this._setDesc(resGraph.getDesc(verID));
this._desc = resGraph.getDesc(verID);
this._trait = resGraph.getTraits(verID);
if (tex instanceof Texture) {
this._texture = tex;
@@ -282,7 +266,7 @@ class DeviceTexture extends DeviceResource {
return;
}
const info = this._desc!;
const info = this._desc;
let type = TextureType.TEX2D;
switch (info.dimension) {
@@ -523,7 +507,6 @@ class BlitDesc {
const deferredLitsBufView = context.blit.deferredLitsBufView;
this._lightBufferData = context.blit.lightBufferData;
this._lightBufferData.fill(0);
// const binding = isEnableEffect() ? getDescBindingFromName('CCForwardLight') : UBOForwardLight.BINDING;
this._stageDesc.bindBuffer(UBOForwardLight.BINDING, deferredLitsBufView);
}
this._stageDesc.bindBuffer(UBOLocal.BINDING, context.blit.emptyLocalUBO);
@@ -728,51 +711,45 @@ class RenderPassLayoutInfo {
this._stage = lg.getRenderStage(layoutId);
this._layout = lg.getLayout(layoutId);
const layoutData = this._layout.descriptorSets.get(UpdateFrequency.PER_PASS);
// const globalDesc = context.descriptorSet;
if (layoutData) {
const layoutDesc = layoutData.descriptorSet!;
// find resource
const deviceTex = context.deviceTextures.get(this._inputName);
const gfxTex = deviceTex?.texture;
if (!layoutData) {
return;
}
const layoutDesc = layoutData.descriptorSet!;
// find resource
const deviceTex = context.deviceTextures.get(this._inputName);
const gfxTex = deviceTex?.texture;
const deviceBuf = context.deviceBuffers.get(this._inputName);
const gfxBuf = deviceBuf?.buffer;
if (!gfxTex && !gfxBuf) {
throw Error(`Could not find texture with resource name ${this._inputName}`);
}
const resId = context.resourceGraph.vertex(this._inputName);
const samplerInfo = context.resourceGraph.getSampler(resId);
// bind descriptors
for (const descriptor of input[1]) {
const descriptorName = descriptor.name;
const descriptorID = lg.attributeIndex.get(descriptorName);
// find descriptor binding
for (const block of layoutData.descriptorSetLayoutData.descriptorBlocks) {
for (let i = 0; i !== block.descriptors.length; ++i) {
// const buffer = layoutDesc.getBuffer(block.offset + i);
// const texture = layoutDesc.getTexture(block.offset + i);
if (descriptorID === block.descriptors[i].descriptorID) {
if (gfxTex) {
layoutDesc.bindTexture(block.offset + i, gfxTex);
layoutDesc.bindSampler(block.offset + i, context.device.getSampler(samplerInfo));
const deviceBuf = context.deviceBuffers.get(this._inputName);
const gfxBuf = deviceBuf?.buffer;
if (!gfxTex && !gfxBuf) {
throw Error(`Could not find texture with resource name ${this._inputName}`);
}
const resId = context.resourceGraph.vertex(this._inputName);
const samplerInfo = context.resourceGraph.getSampler(resId);
// bind descriptors
for (const descriptor of input[1]) {
const descriptorName = descriptor.name;
const descriptorID = lg.attributeIndex.get(descriptorName);
// find descriptor binding
for (const block of layoutData.descriptorSetLayoutData.descriptorBlocks) {
for (let i = 0; i !== block.descriptors.length; ++i) {
if (descriptorID === block.descriptors[i].descriptorID) {
if (gfxTex) {
layoutDesc.bindTexture(block.offset + i, gfxTex);
const renderData = context.renderGraph.getData(this._vertID);
layoutDesc.bindSampler(block.offset + i, renderData.samplers.get(descriptorID) || context.device.getSampler(samplerInfo));
} else {
const desc = context.resourceGraph.getDesc(resId);
if (desc.flags & ResourceFlags.STORAGE) {
const access = input[1][0].accessType !== AccessType.READ ? AccessFlagBit.COMPUTE_SHADER_WRITE
: AccessFlagBit.COMPUTE_SHADER_READ_OTHER;
(layoutDesc as any).bindBuffer(block.offset + i, gfxBuf!, 0, access);
} else {
const desc = context.resourceGraph.getDesc(resId);
if (desc.flags & ResourceFlags.STORAGE) {
const access = input[1][0].accessType !== AccessType.READ ? AccessFlagBit.COMPUTE_SHADER_WRITE
: AccessFlagBit.COMPUTE_SHADER_READ_OTHER;
(layoutDesc as any).bindBuffer(block.offset + i, gfxBuf!, 0, access);
} else {
layoutDesc.bindBuffer(block.offset + i, gfxBuf!);
}
layoutDesc.bindBuffer(block.offset + i, gfxBuf!);
}
if (!this._descriptorSet) this._descriptorSet = layoutDesc;
continue;
}
// if (!buffer && !texture) {
// layoutDesc.bindBuffer(block.offset + i, globalDesc.getBuffer(block.offset + i));
// layoutDesc.bindTexture(block.offset + i, globalDesc.getTexture(block.offset + i));
// layoutDesc.bindSampler(block.offset + i, globalDesc.getSampler(block.offset + i));
// }
if (!this._descriptorSet) this._descriptorSet = layoutDesc;
continue;
}
}
}
@@ -945,15 +922,6 @@ class DeviceRenderPass {
const currTex = device.createTexture(new TextureInfo());
colorTexs.push(currTex);
}
// if (!depthTex && !swapchain && !framebuffer) {
// depthTex = device.createTexture(new TextureInfo(
// TextureType.TEX2D,
// TextureUsageBit.DEPTH_STENCIL_ATTACHMENT | TextureUsageBit.SAMPLED,
// Format.DEPTH_STENCIL,
// colorTexs[0].width,
// colorTexs[0].height,
// ));
// }
const depth = swapchain ? swapchain.depthStencilTexture : depthTex;
if (!depth) {
depthStencilAttachment.format = Format.UNKNOWN;
@@ -1089,7 +1057,6 @@ class DeviceRenderPass {
}
postPass (): void {
// this.submitMap.clear();
for (const queue of this._deviceQueues) {
queue.postRecord();
}
@@ -1320,23 +1287,15 @@ class DeviceSceneTransversal extends WebSceneTransversal {
}
get graphScene (): GraphScene { return this._graphScene; }
public preRenderPass (visitor: WebSceneVisitor): DevicePreSceneTask {
if (!this._preSceneTask) {
this._preSceneTask = new DevicePreSceneTask(this._currentQueue, this._graphScene, visitor);
}
this._preSceneTask.apply(this._currentQueue, this.graphScene);
this._preSceneTask = new DevicePreSceneTask(this._currentQueue, this._graphScene, visitor);
return this._preSceneTask;
}
public transverse (visitor: WebSceneVisitor): DeviceSceneTask {
if (!this._sceneTask) {
this._sceneTask = new DeviceSceneTask(this._currentQueue, this._graphScene, visitor);
}
this._sceneTask.apply(this._currentQueue, this.graphScene);
this._sceneTask = new DeviceSceneTask(this._currentQueue, this._graphScene, visitor);
return this._sceneTask;
}
public postRenderPass (visitor: WebSceneVisitor): DevicePostSceneTask {
if (!this._postSceneTask) {
this._postSceneTask = new DevicePostSceneTask(this._sceneData, context.ubo, this._camera, visitor);
}
this._postSceneTask = new DevicePostSceneTask(this._sceneData, context.ubo, this._camera, visitor);
return this._postSceneTask;
}
}
@@ -1355,6 +1314,7 @@ class GraphScene {
this.scene.light.light = scene.light.light;
this.scene.flags = scene.flags;
this.scene.camera = scene.camera;
this.scene.shadingLight = scene.shadingLight;
return;
}
this.scene = null;
@@ -1412,30 +1372,17 @@ class DevicePreSceneTask extends WebSceneTask {
public start (): void {
if (this.graphScene.blit) {
this._currentQueue.createBlitDesc(this.graphScene.blit);
return;
}
if (!this.camera) {
return;
}
const sceneFlag = this._graphScene.scene!.flags;
if (sceneFlag & SceneFlags.DEFAULT_LIGHTING) {
this._sceneCulling();
validPunctualLightsCulling(context.pipeline, this.camera);
context.additiveLight.gatherLightPasses(this.camera, this._cmdBuff, this._currentQueue.devicePass.layoutName);
}
context.lightResource.buildLightBuffer(context.commandBuffer);
context.lightResource.tryUpdateRenderSceneLocalDescriptorSet(context.culling);
}
public submit (): void {
if (this.graphScene.blit) {
this._currentQueue.blitDesc!.update();
}
// if (isShadowMap(this.graphScene)) {
// }
// this._uploadInstanceBuffers();
}
}
const sceneViewport = new Viewport();
class DeviceSceneTask extends WebSceneTask {
protected _currentQueue: DeviceRenderQueue;
@@ -1464,7 +1411,7 @@ class DeviceSceneTask extends WebSceneTask {
}
get graphScene (): GraphScene { return this._graphScene; }
public start (): void {
// noop
// do nothing
}
protected _recordUI (): void {
@@ -1512,17 +1459,6 @@ class DeviceSceneTask extends WebSceneTask {
}
}
protected _recordReflectionProbe (): void {
const submitMap = context.submitMap;
const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!;
currSubmitInfo.reflectionProbe?.recordCommandBuffer(
context.device,
this._renderPass,
context.commandBuffer,
);
}
private _clearExtBlitDesc (desc, extResId: number[]): void {
const toGpuDesc = desc.gpuDescriptorSet;
for (let i = 0; i < extResId.length; i++) {
@@ -1590,7 +1526,9 @@ class DeviceSceneTask extends WebSceneTask {
const queueId = this._currentQueue.queueId;
const queueRenderData = context.renderGraph.getData(queueId)!;
this._updateGlobal(queueRenderData);
const sceneId = this.graphScene.sceneID;
const sceneRenderData = context.renderGraph.getData(sceneId)!;
if (sceneRenderData) this._updateGlobal(sceneRenderData);
const layoutName = context.renderGraph.getLayout(rasterId);
const descSetData = getDescriptorSetDataFromLayout(layoutName);
mergeSrcToTargetDesc(descSetData!.descriptorSet, context.descriptorSet, true);
@@ -1618,14 +1556,6 @@ class DeviceSceneTask extends WebSceneTask {
}
}
private _recordAdditiveLights (): void {
context.additiveLight?.recordCommandBuffer(
context.device,
this._renderPass,
context.commandBuffer,
);
}
public submit (): void {
const devicePass = this._currentQueue.devicePass;
const sceneCulling = context.culling;
@@ -1636,21 +1566,11 @@ class DeviceSceneTask extends WebSceneTask {
this._recordBlit();
return;
}
const renderQueueDesc = sceneCulling.sceneQueryIndex.get(this.graphScene.sceneID)!;
const renderQueueDesc = sceneCulling.renderQueueIndex.get(this.graphScene.sceneID)!;
const renderQueue = sceneCulling.renderQueues[renderQueueDesc.renderQueueTarget];
const graphSceneData = this.graphScene.scene!;
renderQueue.opaqueQueue.recordCommandBuffer(deviceManager.gfxDevice, this._renderPass, context.commandBuffer);
renderQueue.opaqueInstancingQueue.recordCommandBuffer(this._renderPass, context.commandBuffer);
if (graphSceneData.flags & SceneFlags.DEFAULT_LIGHTING) {
this._recordAdditiveLights();
this.visitor.bindDescriptorSet(
SetIndex.GLOBAL,
context.descriptorSet!,
);
}
renderQueue.transparentInstancingQueue.recordCommandBuffer(this._renderPass, context.commandBuffer);
renderQueue.transparentQueue.recordCommandBuffer(deviceManager.gfxDevice, this._renderPass, context.commandBuffer);
renderQueue.recordCommands(context.commandBuffer, this._renderPass);
if (bool(graphSceneData.flags & SceneFlags.REFLECTION_PROBE)) renderQueue.probeQueue.removeMacro();
if (graphSceneData.flags & SceneFlags.GEOMETRY) {
this.camera!.geometryRenderer?.render(
devicePass.renderPass,
@@ -1661,9 +1581,6 @@ class DeviceSceneTask extends WebSceneTask {
if (graphSceneData.flags & SceneFlags.UI) {
this._recordUI();
}
if (graphSceneData.flags & SceneFlags.REFLECTION_PROBE) {
this._recordReflectionProbe();
}
}
}
@@ -1686,12 +1603,6 @@ class ExecutorPools {
passIdx: 0,
}), 64);
}
addPassInfo (): IRenderPass {
return this.passPool.add();
}
resetPassInfo (): void {
this.passPool.reset();
}
addDeviceQueue (): DeviceRenderQueue {
return this.deviceQueuePool.add();
}
@@ -1715,7 +1626,6 @@ class ExecutorPools {
this.computeQueuePool.reset();
this.graphScenePool.reset();
this.reflectionProbe.reset();
this.resetPassInfo();
this.computePassInfoPool.reset();
}
readonly deviceQueuePool: RecyclePool<DeviceRenderQueue>;
@@ -1942,6 +1852,7 @@ class ExecutorContext {
for (const infoMap of this.submitMap) {
for (const info of infoMap[1]) info[1].reset();
}
this.lightResource.clear();
}
resize (width: number, height: number): void {
this.width = width;
@@ -1964,6 +1875,7 @@ class ExecutorContext {
readonly pools: ExecutorPools;
readonly blit: BlitInfo;
readonly culling: SceneCulling;
lightResource: LightResource = new LightResource();
renderGraph: RenderGraph;
width: number;
height: number;
@@ -1991,6 +1903,8 @@ export class Executor {
width,
height,
);
const programLib: WebProgramLibrary = cclegacy.rendering.programLib;
context.lightResource.init(programLib, device, 16);
}
resize (width: number, height: number): void {
@@ -2044,8 +1958,10 @@ export class Executor {
context.renderGraph = rg;
context.reset();
const cmdBuff = context.commandBuffer;
context.culling.buildRenderQueues(rg, context.layoutGraph, context.pipelineSceneData);
context.culling.uploadInstancing(cmdBuff);
const culling = context.culling;
culling.buildRenderQueues(rg, context.layoutGraph, context.pipelineSceneData);
context.lightResource.buildLights(culling, context.pipelineSceneData.isHDR, context.pipelineSceneData.shadows);
culling.uploadInstancing(cmdBuff);
this._removeDeviceResource();
cmdBuff.begin();
if (!this._visitor) this._visitor = new RenderVisitor();
@@ -2139,19 +2055,19 @@ class PreRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor {
}
}
rasterSubpass (value: RasterSubpass): void {
// noop
// do nothing
}
computeSubpass (value: ComputeSubpass): void {
// noop
// do nothing
}
resolve (value: ResolvePass): void {
// noop
// do nothing
}
move (value: MovePass): void {
// noop
// do nothing
}
raytrace (value: RaytracePass): void {
// noop
// do nothing
}
compute (pass: ComputePass): void {
if (!this.rg.getValid(this.passID)) return;
@@ -2267,25 +2183,25 @@ class PostRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor
this.currPass.postPass();
}
rasterSubpass (value: RasterSubpass): void {
// noop
// do nothing
}
computeSubpass (value: ComputeSubpass): void {
// noop
// do nothing
}
resolve (value: ResolvePass): void {
// noop
// do nothing
}
compute (value: ComputePass): void {
// noop
// do nothing
}
copy (value: CopyPass): void {
// noop
// do nothing
}
move (value: MovePass): void {
// noop
// do nothing
}
raytrace (value: RaytracePass): void {
// noop
// do nothing
}
queue (value: RenderQueue): void {
// collect scene results
@@ -2294,10 +2210,10 @@ class PostRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor
// scene command list finished
}
blit (value: Blit): void {
// noop
// do nothing
}
dispatch (value: Dispatch): void {
// noop
// do nothing
}
}
+185 -76
View File
@@ -24,8 +24,9 @@
/* eslint-disable max-len */
import { EffectAsset } from '../../asset/assets';
import { assert } from '../../core';
import { DescriptorSetInfo, DescriptorSetLayout, DescriptorSetLayoutBinding, DescriptorSetLayoutInfo, DescriptorType, Device, PipelineLayout, PipelineLayoutInfo, ShaderStageFlagBit, Type, Uniform, UniformBlock } from '../../gfx';
import { assert, error, log, warn } from '../../core';
import { DescriptorSetInfo, DescriptorSetLayout, DescriptorSetLayoutBinding, DescriptorSetLayoutInfo, DescriptorType, Device, Feature, Format, FormatFeatureBit, GetTypeSize, PipelineLayout, PipelineLayoutInfo, ShaderStageFlagBit, Type, Uniform, UniformBlock } from '../../gfx';
import { UBOForwardLight, UBOSkinning } from '../define';
import { DefaultVisitor, depthFirstSearch, GraphColor, MutableVertexPropertyMap } from './graph';
import { DescriptorBlockData, DescriptorData, DescriptorDB, DescriptorSetData, DescriptorSetLayoutData, LayoutGraph, LayoutGraphData, LayoutGraphDataValue, LayoutGraphValue, PipelineLayoutData, RenderPassType, RenderPhase, RenderPhaseData, RenderStageData, ShaderProgramData } from './layout-graph';
import { UpdateFrequency, getUpdateFrequencyName, getDescriptorTypeOrderName, Descriptor, DescriptorBlock, DescriptorBlockFlattened, DescriptorBlockIndex, DescriptorTypeOrder, ParameterType } from './types';
@@ -109,7 +110,7 @@ export function getGfxDescriptorType (type: DescriptorTypeOrder): DescriptorType
case DescriptorTypeOrder.INPUT_ATTACHMENT:
return DescriptorType.INPUT_ATTACHMENT;
default:
console.error('DescriptorType not found');
error('DescriptorType not found');
return DescriptorType.INPUT_ATTACHMENT;
}
}
@@ -137,7 +138,7 @@ export function getDescriptorTypeOrder (type: DescriptorType): DescriptorTypeOrd
return DescriptorTypeOrder.INPUT_ATTACHMENT;
case DescriptorType.UNKNOWN:
default:
console.error('DescriptorTypeOrder not found');
error('DescriptorTypeOrder not found');
return DescriptorTypeOrder.INPUT_ATTACHMENT;
}
}
@@ -460,7 +461,7 @@ export class VisibilityBlock {
public getVisibility (name: string): ShaderStageFlagBit {
const v = this.descriptors.get(name);
if (v === undefined) {
console.error(`Can't find visibility for descriptor: ${name}`);
error(`Can't find visibility for descriptor: ${name}`);
return ShaderStageFlagBit.NONE;
}
return v;
@@ -496,6 +497,50 @@ export class VisibilityPass {
phases = new Map<string, VisibilityDB>();
}
export const DEFAULT_UNIFORM_COUNTS: Map<string, number> = new Map([
['cc_lightPos', UBOForwardLight.LIGHTS_PER_PASS],
['cc_lightColor', UBOForwardLight.LIGHTS_PER_PASS],
['cc_lightSizeRangeAngle', UBOForwardLight.LIGHTS_PER_PASS],
['cc_lightDir', UBOForwardLight.LIGHTS_PER_PASS],
['cc_lightBoundingSizeVS', UBOForwardLight.LIGHTS_PER_PASS],
]);
export const DYNAMIC_UNIFORM_BLOCK: Set<string> = new Set([
'CCCamera',
'CCForwardLight',
'CCUILocal',
]);
export function getUniformBlockSize (blockMembers: Array<Uniform>): number {
let prevSize: number = 0;
for (const m of blockMembers) {
if (m.count) {
prevSize += GetTypeSize(m.type) * m.count;
continue;
}
const iter = DEFAULT_UNIFORM_COUNTS.get(m.name);
if (iter !== undefined) {
prevSize += GetTypeSize(m.type) * iter;
continue;
}
if (m.name === 'cc_joints') {
const sz = GetTypeSize(m.type) * UBOSkinning.LAYOUT.members[0].count;
assert(sz !== UBOSkinning.SIZE);
prevSize += sz;
continue;
}
error(`Invalid uniform count: ${m.name}`);
}
assert(!!prevSize);
return prevSize;
}
export class VisibilityGraph {
public getPass (passName: string): VisibilityPass {
const pass = this.passes.get(passName);
@@ -542,7 +587,7 @@ export class VisibilityGraph {
continue;
}
if (shader.descriptors === undefined) {
console.warn(`No descriptors in shader: ${programName}, please reimport ALL effects`);
warn(`No descriptors in shader: ${programName}, please reimport ALL effects`);
continue;
}
const passName = getPassName(pass);
@@ -595,8 +640,10 @@ export class LayoutGraphInfo {
let passID = lg.locateChild(lg.nullVertex(), passName);
if (passID === lg.nullVertex()) {
passID = lg.addVertex<LayoutGraphValue.RenderStage>(
LayoutGraphValue.RenderStage, type,
passName, new DescriptorDB(),
LayoutGraphValue.RenderStage,
type,
passName,
new DescriptorDB(),
lg.nullVertex(),
);
}
@@ -608,8 +655,10 @@ export class LayoutGraphInfo {
let subpassID = lg.locateChild(passID, subpassName);
if (subpassID === lg.nullVertex()) {
subpassID = lg.addVertex<LayoutGraphValue.RenderStage>(
LayoutGraphValue.RenderStage, RenderPassType.RENDER_SUBPASS,
subpassName, new DescriptorDB(),
LayoutGraphValue.RenderStage,
RenderPassType.RENDER_SUBPASS,
subpassName,
new DescriptorDB(),
passID,
);
}
@@ -621,8 +670,10 @@ export class LayoutGraphInfo {
let phaseID = lg.locateChild(subpassOrPassID, phaseName);
if (phaseID === lg.nullVertex()) {
phaseID = lg.addVertex<LayoutGraphValue.RenderPhase>(
LayoutGraphValue.RenderPhase, new RenderPhase(),
phaseName, new DescriptorDB(),
LayoutGraphValue.RenderPhase,
new RenderPhase(),
phaseName,
new DescriptorDB(),
subpassOrPassID,
);
}
@@ -675,18 +726,21 @@ export class LayoutGraphInfo {
return;
}
if (value.type !== type) {
console.warn(`Type mismatch for descriptor ${name}`);
warn(`Type mismatch for descriptor ${name}`);
}
}
private addUniformBlock (block: DescriptorBlock,
name: string, gfxBlock: UniformBlock): void {
private addUniformBlock (
block: DescriptorBlock,
name: string,
gfxBlock: UniformBlock,
): void {
const value = block.uniformBlocks.get(name);
if (value === undefined) {
block.uniformBlocks.set(name, gfxBlock);
return;
}
if (!this.checkConsistency(value, gfxBlock)) {
console.warn(`Uniform block ${name} is inconsistent in the same block`);
warn(`Uniform block ${name} is inconsistent in the same block`);
}
}
private buildBlocks (visDB: VisibilityDB, rate: UpdateFrequency, blocks: EffectAsset.IBlockInfo[], db: DescriptorDB, counter: DescriptorCounter): void {
@@ -716,7 +770,9 @@ export class LayoutGraphInfo {
visDB: VisibilityDB,
rate: UpdateFrequency,
infoArray: EffectAsset.IBufferInfo[],
type: Type, db: DescriptorDB, counter: DescriptorCounter,
type: Type,
db: DescriptorDB,
counter: DescriptorCounter,
): void {
const visBlock = visDB.getBlock({
updateFrequency: rate,
@@ -744,7 +800,9 @@ export class LayoutGraphInfo {
rate: UpdateFrequency,
order: DescriptorTypeOrder,
infoArray: EffectAsset.ISamplerInfo[] | EffectAsset.IInputAttachmentInfo[],
type: Type, db: DescriptorDB, counter: DescriptorCounter,
type: Type,
db: DescriptorDB,
counter: DescriptorCounter,
): void {
const visBlock = visDB.getBlock({
updateFrequency: rate,
@@ -772,7 +830,8 @@ export class LayoutGraphInfo {
rate: UpdateFrequency,
order: DescriptorTypeOrder,
infoArray: EffectAsset.IImageInfo[] | EffectAsset.ISamplerTextureInfo[] | EffectAsset.ITextureInfo[],
db: DescriptorDB, counter: DescriptorCounter,
db: DescriptorDB,
counter: DescriptorCounter,
): void {
const visBlock = visDB.getBlock({
updateFrequency: rate,
@@ -807,11 +866,11 @@ export class LayoutGraphInfo {
}
}
if (!shader) {
console.warn(`program: ${programName} not found`);
warn(`program: ${programName} not found`);
continue;
}
if (shader.descriptors === undefined) {
console.warn(`No descriptors in shader: ${programName}, please reimport ALL effects`);
warn(`No descriptors in shader: ${programName}, please reimport ALL effects`);
continue;
}
// get database
@@ -872,13 +931,13 @@ export class LayoutGraphInfo {
const phaseID = v;
const parentID = lg.getParent(phaseID);
if (lg.id(parentID) !== LayoutGraphValue.RenderStage) {
console.error(`phase: ${lg.getName(phaseID)} has no parent stage`);
error(`phase: ${lg.getName(phaseID)} has no parent stage`);
return 1;
}
const phaseDB = lg.getDescriptors(phaseID);
const passVisDB = visMap.get(parentID);
if (!passVisDB) {
console.error(`pass: ${lg.getName(parentID)} has no visibility database`);
error(`pass: ${lg.getName(parentID)} has no visibility database`);
return 1;
}
// merge phase visibility to pass visibility
@@ -902,14 +961,14 @@ export class LayoutGraphInfo {
const phaseID = v;
const parentID = lg.getParent(phaseID);
if (lg.id(parentID) !== LayoutGraphValue.RenderStage) {
console.error(`phase: ${lg.getName(phaseID)} has no parent stage`);
error(`phase: ${lg.getName(phaseID)} has no parent stage`);
return 1;
}
const passDB = lg.getDescriptors(parentID);
const phaseDB = lg.getDescriptors(phaseID);
const passVisDB = visMap.get(parentID);
if (passVisDB === undefined) {
console.error(`pass: ${lg.getName(parentID)} has no visibility database`);
error(`pass: ${lg.getName(parentID)} has no visibility database`);
return 1;
}
for (const [key0, block] of phaseDB.blocks) {
@@ -917,9 +976,7 @@ export class LayoutGraphInfo {
if (index0.updateFrequency <= UpdateFrequency.PER_PHASE) {
continue;
}
const visIndex = new VisibilityIndex(
index0.updateFrequency, index0.parameterType, index0.descriptorType,
);
const visIndex = new VisibilityIndex(index0.updateFrequency, index0.parameterType, index0.descriptorType);
const passVisBlock = passVisDB.getBlock(visIndex);
for (const [name, d] of block.descriptors) {
@@ -943,7 +1000,7 @@ export class LayoutGraphInfo {
}
const b = block.uniformBlocks.get(name);
if (!b) {
console.error(`uniform block: ${name} not found`);
error(`uniform block: ${name} not found`);
return 1;
}
this.addUniformBlock(passBlock, name, b);
@@ -968,22 +1025,22 @@ export class LayoutGraphInfo {
for (const e of lg.children(passID)) {
const phaseID = lg.child(e);
if (lg.id(phaseID) !== LayoutGraphValue.RenderPhase) {
console.error(`pass: ${lg.getName(passID)} is not single_render_pass or render_subpass`);
error(`pass: ${lg.getName(passID)} is not single_render_pass or render_subpass`);
return 1;
}
const phaseDB = lg.getDescriptors(phaseID);
for (const [key, passBlock] of passDB.blocks) {
const index: DescriptorBlockIndex = JSON.parse(key);
if (index.updateFrequency !== UpdateFrequency.PER_PASS) {
console.error(`phase: ${lg.getName(phaseID)} update frequency is not PER_PASS`);
error(`phase: ${lg.getName(phaseID)} update frequency is not PER_PASS`);
return 1;
}
if (passBlock.count === 0) {
console.error(`pass: ${lg.getName(passID)} count is 0`);
error(`pass: ${lg.getName(passID)} count is 0`);
return 1;
}
if (passBlock.capacity !== passBlock.count) {
console.error(`pass: ${lg.getName(passID)} capacity does not equal count`);
error(`pass: ${lg.getName(passID)} capacity does not equal count`);
return 1;
}
const phaseBlock = this.getDescriptorBlock(key, phaseDB);
@@ -1047,7 +1104,7 @@ function buildLayoutGraphDataImpl (graph: LayoutGraph, builder: LayoutGraphBuild
}
const vertID = builder.addRenderStage(graph.getName(v), parentID);
if (vertID !== v) {
console.error('vertex id mismatch');
error('vertex id mismatch');
}
minLevel = UpdateFrequency.PER_PASS;
maxLevel = UpdateFrequency.PER_PASS;
@@ -1059,7 +1116,7 @@ function buildLayoutGraphDataImpl (graph: LayoutGraph, builder: LayoutGraphBuild
assert(parentType === RenderPassType.RENDER_SUBPASS || parentType === RenderPassType.SINGLE_RENDER_PASS);
const vertID = builder.addRenderPhase(graph.getName(v), parentID);
if (vertID !== v) {
console.error('vertex id mismatch');
error('vertex id mismatch');
}
const phase = graph.getRenderPhase(v);
for (const shaderName of phase.shaders) {
@@ -1070,7 +1127,7 @@ function buildLayoutGraphDataImpl (graph: LayoutGraph, builder: LayoutGraphBuild
break;
}
default:
console.error('unknown vertex type');
error('unknown vertex type');
minLevel = UpdateFrequency.PER_INSTANCE;
minLevel = UpdateFrequency.PER_PASS;
break;
@@ -1092,7 +1149,7 @@ function buildLayoutGraphDataImpl (graph: LayoutGraph, builder: LayoutGraphBuild
}
const flattened = convertDescriptorBlock(block);
if (block.capacity === 0) {
console.error('block capacity is 0');
error('block capacity is 0');
return;
}
if (index.updateFrequency > UpdateFrequency.PER_BATCH) {
@@ -1141,16 +1198,24 @@ class LayoutGraphBuilder2 {
addRenderStage (name: string, parentID: number): number {
return this.lg.addVertex<LayoutGraphDataValue.RenderStage>(
LayoutGraphDataValue.RenderStage,
new RenderStageData(), name,
UpdateFrequency.PER_PASS, new PipelineLayoutData(),
new RenderStageData(),
name,
UpdateFrequency.PER_PASS,
new PipelineLayoutData(),
parentID,
);
}
addRenderPhase (name: string, parentID: number): number {
return this.lg.addVertex<LayoutGraphDataValue.RenderPhase>(
LayoutGraphDataValue.RenderPhase,
new RenderPhaseData(), name,
UpdateFrequency.PER_PHASE, new PipelineLayoutData(),
new RenderPhaseData(),
name,
UpdateFrequency.PER_PHASE,
new PipelineLayoutData(),
parentID,
);
}
@@ -1176,20 +1241,20 @@ class LayoutGraphBuilder2 {
}
addDescriptorBlock (nodeID: number, index: DescriptorBlockIndex, block: Readonly<DescriptorBlockFlattened>): void {
if (block.capacity <= 0) {
console.error('empty block');
error('empty block');
return;
}
if (block.descriptorNames.length !== block.descriptors.length) {
console.error('error descriptor');
error('error descriptor');
return;
}
if (block.uniformBlockNames.length !== block.uniformBlocks.length) {
console.error('error uniform');
error('error uniform');
return;
}
if (!(index.updateFrequency >= UpdateFrequency.PER_INSTANCE
&& index.updateFrequency <= UpdateFrequency.PER_PASS)) {
console.error('invalid update frequency');
error('invalid update frequency');
return;
}
@@ -1230,7 +1295,7 @@ class LayoutGraphBuilder2 {
}
reserveDescriptorBlock (nodeID: number, index: DescriptorBlockIndex, block: DescriptorBlockFlattened): void {
if (block.capacity <= 0) {
console.error('empty block');
error('empty block');
return;
}
const g: LayoutGraphData = this.lg;
@@ -1337,9 +1402,12 @@ function getDescriptorBlockData (map: Map<string, DescriptorBlockData>, index: D
}
// make DescriptorSetLayoutData from effect directly
export function makeDescriptorSetLayoutData (lg: LayoutGraphData,
rate: UpdateFrequency, set: number,
descriptors: EffectAsset.IDescriptorInfo): DescriptorSetLayoutData {
export function makeDescriptorSetLayoutData (
lg: LayoutGraphData,
rate: UpdateFrequency,
set: number,
descriptors: EffectAsset.IDescriptorInfo,
): DescriptorSetLayoutData {
const map = new Map<string, DescriptorBlockData>();
const uniformBlocks: Map<number, UniformBlock> = new Map<number, UniformBlock>();
for (let i = 0; i < descriptors.blocks.length; i++) {
@@ -1435,7 +1503,7 @@ export function makeDescriptorSetLayoutData (lg: LayoutGraphData,
// update uniform buffer binding
const ub = uniformBlocks.get(d.descriptorID);
if (!ub) {
console.error(`Uniform block not found for ${d.descriptorID}`);
error(`Uniform block not found for ${d.descriptorID}`);
continue;
}
assert(ub.binding === 0xFFFFFFFF);
@@ -1446,7 +1514,7 @@ export function makeDescriptorSetLayoutData (lg: LayoutGraphData,
// update block capacity
const binding = data.bindingMap.get(d.descriptorID);
if (binding !== undefined) {
console.error(`Duplicated descriptor ${d.descriptorID}`);
error(`Duplicated descriptor ${d.descriptorID}`);
}
data.bindingMap.set(d.descriptorID, block.offset + block.capacity);
block.capacity += d.count;
@@ -1466,8 +1534,10 @@ export function makeDescriptorSetLayoutData (lg: LayoutGraphData,
}
// fill DescriptorSetLayoutInfo from DescriptorSetLayoutData
export function initializeDescriptorSetLayoutInfo (layoutData: DescriptorSetLayoutData,
info: DescriptorSetLayoutInfo): void {
export function initializeDescriptorSetLayoutInfo (
layoutData: DescriptorSetLayoutData,
info: DescriptorSetLayoutInfo,
): void {
for (let i = 0; i < layoutData.descriptorBlocks.length; ++i) {
const block = layoutData.descriptorBlocks[i];
let slot = block.offset;
@@ -1488,8 +1558,11 @@ export function initializeDescriptorSetLayoutInfo (layoutData: DescriptorSetLayo
let _emptyDescriptorSetLayout: DescriptorSetLayout;
let _emptyPipelineLayout: PipelineLayout;
function populatePipelineLayoutInfo (layout: PipelineLayoutData,
rate: UpdateFrequency, info: PipelineLayoutInfo): void {
export function populatePipelineLayoutInfo (
layout: PipelineLayoutData,
rate: UpdateFrequency,
info: PipelineLayoutInfo,
): void {
const set = layout.descriptorSets.get(rate);
if (set && set.descriptorSetLayout) {
info.setLayouts.push(set.descriptorSetLayout);
@@ -1498,6 +1571,19 @@ function populatePipelineLayoutInfo (layout: PipelineLayoutData,
}
}
export function generateConstantMacros (device: Device, constantMacros: string): void {
constantMacros = `
#define CC_DEVICE_SUPPORT_FLOAT_TEXTURE ${device.getFormatFeatures(Format.RGBA32F) & (
FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE
) ? '1' : '0'}
#define CC_DEVICE_MAX_VERTEX_UNIFORM_VECTORS ${device.capabilities.maxVertexUniformVectors}
#define CC_DEVICE_MAX_FRAGMENT_UNIFORM_VECTORS ${device.capabilities.maxFragmentUniformVectors}
#define CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT ${device.hasFeature(Feature.INPUT_ATTACHMENT_BENEFIT) ? '1' : '0'}
#define CC_PLATFORM_ANDROID_AND_WEBGL 0
#define CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES 0
#define CC_JOINT_UNIFORM_CAPACITY ${UBOSkinning.JOINT_UNIFORM_CAPACITY}`;
}
// initialize layout graph module
export function initializeLayoutGraphData (device: Device, lg: LayoutGraphData): void {
// create descriptor sets
@@ -1507,10 +1593,12 @@ export function initializeLayoutGraphData (device: Device, lg: LayoutGraphData):
const layoutData = lg.getLayout(v);
for (const [_, set] of layoutData.descriptorSets) {
if (set.descriptorSetLayout !== null) {
console.warn('descriptor set layout already initialized. It will be overwritten');
warn('descriptor set layout already initialized. It will be overwritten');
}
initializeDescriptorSetLayoutInfo(set.descriptorSetLayoutData,
set.descriptorSetLayoutInfo);
initializeDescriptorSetLayoutInfo(
set.descriptorSetLayoutData,
set.descriptorSetLayoutInfo,
);
set.descriptorSetLayout = device.createDescriptorSetLayout(set.descriptorSetLayoutInfo);
}
}
@@ -1558,14 +1646,18 @@ export function getEmptyPipelineLayout (): PipelineLayout {
}
// get descriptor set from LayoutGraphData (not from ProgramData)
export function getOrCreateDescriptorSetLayout (lg: LayoutGraphData,
subpassOrPassID: number, phaseID: number, rate: UpdateFrequency): DescriptorSetLayout {
export function getOrCreateDescriptorSetLayout (
lg: LayoutGraphData,
subpassOrPassID: number,
phaseID: number,
rate: UpdateFrequency,
): DescriptorSetLayout {
if (rate < UpdateFrequency.PER_PASS) {
const phaseData = lg.getLayout(phaseID);
const data = phaseData.descriptorSets.get(rate);
if (data) {
if (!data.descriptorSetLayout) {
console.error('descriptor set layout not initialized');
error('descriptor set layout not initialized');
return _emptyDescriptorSetLayout;
}
return data.descriptorSetLayout;
@@ -1580,7 +1672,7 @@ export function getOrCreateDescriptorSetLayout (lg: LayoutGraphData,
const data = passData.descriptorSets.get(rate);
if (data) {
if (!data.descriptorSetLayout) {
console.error('descriptor set layout not initialized');
error('descriptor set layout not initialized');
return _emptyDescriptorSetLayout;
}
return data.descriptorSetLayout;
@@ -1589,14 +1681,18 @@ export function getOrCreateDescriptorSetLayout (lg: LayoutGraphData,
}
// getDescriptorSetLayout from LayoutGraphData
export function getDescriptorSetLayout (lg: LayoutGraphData,
subpassOrPassID: number, phaseID: number, rate: UpdateFrequency): DescriptorSetLayout | null {
export function getDescriptorSetLayout (
lg: LayoutGraphData,
subpassOrPassID: number,
phaseID: number,
rate: UpdateFrequency,
): DescriptorSetLayout | null {
if (rate < UpdateFrequency.PER_PASS) {
const phaseData = lg.getLayout(phaseID);
const data = phaseData.descriptorSets.get(rate);
if (data) {
if (!data.descriptorSetLayout) {
console.error('descriptor set layout not initialized');
error('descriptor set layout not initialized');
return null;
}
return data.descriptorSetLayout;
@@ -1611,7 +1707,7 @@ export function getDescriptorSetLayout (lg: LayoutGraphData,
const data = passData.descriptorSets.get(rate);
if (data) {
if (!data.descriptorSetLayout) {
console.error('descriptor set layout not initialized');
error('descriptor set layout not initialized');
return null;
}
return data.descriptorSetLayout;
@@ -1620,8 +1716,11 @@ export function getDescriptorSetLayout (lg: LayoutGraphData,
}
// get or create DescriptorBlockData from DescriptorSetLayoutData
export function getOrCreateDescriptorBlockData (data: DescriptorSetLayoutData,
type: DescriptorType, vis: ShaderStageFlagBit): DescriptorBlockData {
export function getOrCreateDescriptorBlockData (
data: DescriptorSetLayoutData,
type: DescriptorType,
vis: ShaderStageFlagBit,
): DescriptorBlockData {
const order = getDescriptorTypeOrder(type);
for (const block of data.descriptorBlocks) {
if (block.type === order && block.visibility === vis) {
@@ -1658,8 +1757,10 @@ export function getDescriptorName (lg: LayoutGraphData, nameID: number): string
return lg.valueNames[nameID];
}
export function getPerPassDescriptorSetLayoutData (lg: LayoutGraphData,
subpassOrPassID: number): DescriptorSetLayoutData | null {
export function getPerPassDescriptorSetLayoutData (
lg: LayoutGraphData,
subpassOrPassID: number,
): DescriptorSetLayoutData | null {
assert(subpassOrPassID !== lg.nullVertex());
const node = lg.getLayout(subpassOrPassID);
const set = node.descriptorSets.get(UpdateFrequency.PER_PASS);
@@ -1669,8 +1770,10 @@ export function getPerPassDescriptorSetLayoutData (lg: LayoutGraphData,
return set.descriptorSetLayoutData;
}
export function getPerPhaseDescriptorSetLayoutData (lg: LayoutGraphData,
phaseID: number): DescriptorSetLayoutData | null {
export function getPerPhaseDescriptorSetLayoutData (
lg: LayoutGraphData,
phaseID: number,
): DescriptorSetLayoutData | null {
assert(phaseID !== lg.nullVertex());
const node = lg.getLayout(phaseID);
const set = node.descriptorSets.get(UpdateFrequency.PER_PHASE);
@@ -1680,8 +1783,11 @@ export function getPerPhaseDescriptorSetLayoutData (lg: LayoutGraphData,
return set.descriptorSetLayoutData;
}
export function getPerBatchDescriptorSetLayoutData (lg: LayoutGraphData,
phaseID: number, programID): DescriptorSetLayoutData | null {
export function getPerBatchDescriptorSetLayoutData (
lg: LayoutGraphData,
phaseID: number,
programID,
): DescriptorSetLayoutData | null {
assert(phaseID !== lg.nullVertex());
const phase = lg.getRenderPhase(phaseID);
assert(programID < phase.shaderPrograms.length);
@@ -1693,8 +1799,11 @@ export function getPerBatchDescriptorSetLayoutData (lg: LayoutGraphData,
return set.descriptorSetLayoutData;
}
export function getPerInstanceDescriptorSetLayoutData (lg: LayoutGraphData,
phaseID: number, programID): DescriptorSetLayoutData | null {
export function getPerInstanceDescriptorSetLayoutData (
lg: LayoutGraphData,
phaseID: number,
programID,
): DescriptorSetLayoutData | null {
assert(phaseID !== lg.nullVertex());
const phase = lg.getRenderPhase(phaseID);
assert(programID < phase.shaderPrograms.length);
+290 -2
View File
@@ -30,15 +30,22 @@
/* eslint-disable max-len */
import { AddressableGraph, AdjI, AdjacencyGraph, BidirectionalGraph, ComponentGraph, ED, InEI, MutableGraph, MutableReferenceGraph, NamedGraph, OutE, OutEI, PolymorphicGraph, PropertyGraph, PropertyMap, ReferenceGraph, VertexListGraph, directional, findRelative, getPath, parallel, reindexEdgeList, traversal } from './graph';
import { DescriptorSet, DescriptorSetLayout, DescriptorSetLayoutInfo, PipelineLayout, ShaderStageFlagBit, Type, UniformBlock } from '../../gfx';
import { DescriptorBlock, saveDescriptorBlock, loadDescriptorBlock, DescriptorBlockIndex, saveDescriptorBlockIndex, loadDescriptorBlockIndex, DescriptorTypeOrder, UpdateFrequency } from './types';
import { DescriptorBlock, saveDescriptorBlock, loadDescriptorBlock, DescriptorBlockIndex, saveDescriptorBlockIndex, loadDescriptorBlockIndex, DescriptorTypeOrder, UpdateFrequency, RenderCommonObjectPool } from './types';
import { OutputArchive, InputArchive } from './archive';
import { saveUniformBlock, loadUniformBlock, saveDescriptorSetLayoutInfo, loadDescriptorSetLayoutInfo } from './serialization';
import { RecyclePool } from '../../core/memop';
export class DescriptorDB {
reset (): void {
this.blocks.clear();
}
readonly blocks: Map<string, DescriptorBlock> = new Map<string, DescriptorBlock>();
}
export class RenderPhase {
reset (): void {
this.shaders.clear();
}
readonly shaders: Set<string> = new Set<string>();
}
@@ -587,6 +594,12 @@ export class UniformData {
this.uniformType = uniformType;
this.offset = offset;
}
reset (uniformID = 0xFFFFFFFF, uniformType: Type = Type.UNKNOWN, offset = 0): void {
this.uniformID = uniformID;
this.uniformType = uniformType;
this.offset = offset;
this.size = 0;
}
uniformID: number;
uniformType: Type;
offset: number;
@@ -594,6 +607,10 @@ export class UniformData {
}
export class UniformBlockData {
reset (): void {
this.bufferSize = 0;
this.uniforms.length = 0;
}
bufferSize = 0;
readonly uniforms: UniformData[] = [];
}
@@ -604,6 +621,11 @@ export class DescriptorData {
this.type = type;
this.count = count;
}
reset (descriptorID = 0, type: Type = Type.UNKNOWN, count = 1): void {
this.descriptorID = descriptorID;
this.type = type;
this.count = count;
}
descriptorID: number;
type: Type;
count: number;
@@ -615,6 +637,13 @@ export class DescriptorBlockData {
this.visibility = visibility;
this.capacity = capacity;
}
reset (type: DescriptorTypeOrder = DescriptorTypeOrder.UNIFORM_BUFFER, visibility: ShaderStageFlagBit = ShaderStageFlagBit.NONE, capacity = 0): void {
this.type = type;
this.visibility = visibility;
this.offset = 0;
this.capacity = capacity;
this.descriptors.length = 0;
}
type: DescriptorTypeOrder;
visibility: ShaderStageFlagBit;
offset = 0;
@@ -636,6 +665,18 @@ export class DescriptorSetLayoutData {
this.uniformBlocks = uniformBlocks;
this.bindingMap = bindingMap;
}
reset (
slot = 0xFFFFFFFF,
capacity = 0,
): void {
this.slot = slot;
this.capacity = capacity;
this.uniformBlockCapacity = 0;
this.samplerTextureCapacity = 0;
this.descriptorBlocks.length = 0;
this.uniformBlocks.clear();
this.bindingMap.clear();
}
slot: number;
capacity: number;
uniformBlockCapacity = 0;
@@ -651,6 +692,12 @@ export class DescriptorSetData {
this.descriptorSetLayout = descriptorSetLayout;
this.descriptorSet = descriptorSet;
}
reset (descriptorSetLayout: DescriptorSetLayout | null = null, descriptorSet: DescriptorSet | null = null): void {
this.descriptorSetLayoutData.reset();
this.descriptorSetLayoutInfo.reset();
this.descriptorSetLayout = descriptorSetLayout;
this.descriptorSet = descriptorSet;
}
readonly descriptorSetLayoutData: DescriptorSetLayoutData;
readonly descriptorSetLayoutInfo: DescriptorSetLayoutInfo = new DescriptorSetLayoutInfo();
/*refcount*/ descriptorSetLayout: DescriptorSetLayout | null;
@@ -658,36 +705,65 @@ export class DescriptorSetData {
}
export class PipelineLayoutData {
reset (): void {
this.descriptorSets.clear();
}
readonly descriptorSets: Map<UpdateFrequency, DescriptorSetData> = new Map<UpdateFrequency, DescriptorSetData>();
}
export class ShaderBindingData {
reset (): void {
this.descriptorBindings.clear();
}
readonly descriptorBindings: Map<number, number> = new Map<number, number>();
}
export class ShaderLayoutData {
reset (): void {
this.layoutData.clear();
this.bindingData.clear();
}
readonly layoutData: Map<UpdateFrequency, DescriptorSetLayoutData> = new Map<UpdateFrequency, DescriptorSetLayoutData>();
readonly bindingData: Map<UpdateFrequency, ShaderBindingData> = new Map<UpdateFrequency, ShaderBindingData>();
}
export class TechniqueData {
reset (): void {
this.passes.length = 0;
}
readonly passes: ShaderLayoutData[] = [];
}
export class EffectData {
reset (): void {
this.techniques.clear();
}
readonly techniques: Map<string, TechniqueData> = new Map<string, TechniqueData>();
}
export class ShaderProgramData {
reset (): void {
this.layout.reset();
this.pipelineLayout = null;
}
readonly layout: PipelineLayoutData = new PipelineLayoutData();
/*refcount*/ pipelineLayout: PipelineLayout | null = null;
}
export class RenderStageData {
reset (): void {
this.descriptorVisibility.clear();
}
readonly descriptorVisibility: Map<number, ShaderStageFlagBit> = new Map<number, ShaderStageFlagBit>();
}
export class RenderPhaseData {
reset (): void {
this.rootSignature = '';
this.shaderPrograms.length = 0;
this.shaderIndex.clear();
this.pipelineLayout = null;
}
rootSignature = '';
readonly shaderPrograms: ShaderProgramData[] = [];
readonly shaderIndex: Map<string, number> = new Map<string, number>();
@@ -1260,10 +1336,222 @@ export class LayoutGraphData implements BidirectionalGraph
constantMacros = '';
}
export class LayoutGraphObjectPoolSettings {
constructor (batchSize: number) {
this.descriptorDBBatchSize = batchSize;
this.renderPhaseBatchSize = batchSize;
this.layoutGraphBatchSize = batchSize;
this.uniformDataBatchSize = batchSize;
this.uniformBlockDataBatchSize = batchSize;
this.descriptorDataBatchSize = batchSize;
this.descriptorBlockDataBatchSize = batchSize;
this.descriptorSetLayoutDataBatchSize = batchSize;
this.descriptorSetDataBatchSize = batchSize;
this.pipelineLayoutDataBatchSize = batchSize;
this.shaderBindingDataBatchSize = batchSize;
this.shaderLayoutDataBatchSize = batchSize;
this.techniqueDataBatchSize = batchSize;
this.effectDataBatchSize = batchSize;
this.shaderProgramDataBatchSize = batchSize;
this.renderStageDataBatchSize = batchSize;
this.renderPhaseDataBatchSize = batchSize;
this.layoutGraphDataBatchSize = batchSize;
}
descriptorDBBatchSize = 16;
renderPhaseBatchSize = 16;
layoutGraphBatchSize = 16;
uniformDataBatchSize = 16;
uniformBlockDataBatchSize = 16;
descriptorDataBatchSize = 16;
descriptorBlockDataBatchSize = 16;
descriptorSetLayoutDataBatchSize = 16;
descriptorSetDataBatchSize = 16;
pipelineLayoutDataBatchSize = 16;
shaderBindingDataBatchSize = 16;
shaderLayoutDataBatchSize = 16;
techniqueDataBatchSize = 16;
effectDataBatchSize = 16;
shaderProgramDataBatchSize = 16;
renderStageDataBatchSize = 16;
renderPhaseDataBatchSize = 16;
layoutGraphDataBatchSize = 16;
}
export class LayoutGraphObjectPool {
constructor (settings: LayoutGraphObjectPoolSettings, renderCommon: RenderCommonObjectPool) {
this.renderCommon = renderCommon;
this._descriptorDB = new RecyclePool<DescriptorDB>(() => new DescriptorDB(), settings.descriptorDBBatchSize);
this._renderPhase = new RecyclePool<RenderPhase>(() => new RenderPhase(), settings.renderPhaseBatchSize);
this._layoutGraph = new RecyclePool<LayoutGraph>(() => new LayoutGraph(), settings.layoutGraphBatchSize);
this._uniformData = new RecyclePool<UniformData>(() => new UniformData(), settings.uniformDataBatchSize);
this._uniformBlockData = new RecyclePool<UniformBlockData>(() => new UniformBlockData(), settings.uniformBlockDataBatchSize);
this._descriptorData = new RecyclePool<DescriptorData>(() => new DescriptorData(), settings.descriptorDataBatchSize);
this._descriptorBlockData = new RecyclePool<DescriptorBlockData>(() => new DescriptorBlockData(), settings.descriptorBlockDataBatchSize);
this._descriptorSetLayoutData = new RecyclePool<DescriptorSetLayoutData>(() => new DescriptorSetLayoutData(), settings.descriptorSetLayoutDataBatchSize);
this._descriptorSetData = new RecyclePool<DescriptorSetData>(() => new DescriptorSetData(), settings.descriptorSetDataBatchSize);
this._pipelineLayoutData = new RecyclePool<PipelineLayoutData>(() => new PipelineLayoutData(), settings.pipelineLayoutDataBatchSize);
this._shaderBindingData = new RecyclePool<ShaderBindingData>(() => new ShaderBindingData(), settings.shaderBindingDataBatchSize);
this._shaderLayoutData = new RecyclePool<ShaderLayoutData>(() => new ShaderLayoutData(), settings.shaderLayoutDataBatchSize);
this._techniqueData = new RecyclePool<TechniqueData>(() => new TechniqueData(), settings.techniqueDataBatchSize);
this._effectData = new RecyclePool<EffectData>(() => new EffectData(), settings.effectDataBatchSize);
this._shaderProgramData = new RecyclePool<ShaderProgramData>(() => new ShaderProgramData(), settings.shaderProgramDataBatchSize);
this._renderStageData = new RecyclePool<RenderStageData>(() => new RenderStageData(), settings.renderStageDataBatchSize);
this._renderPhaseData = new RecyclePool<RenderPhaseData>(() => new RenderPhaseData(), settings.renderPhaseDataBatchSize);
this._layoutGraphData = new RecyclePool<LayoutGraphData>(() => new LayoutGraphData(), settings.layoutGraphDataBatchSize);
}
reset (): void {
this._descriptorDB.reset();
this._renderPhase.reset();
this._layoutGraph.reset();
this._uniformData.reset();
this._uniformBlockData.reset();
this._descriptorData.reset();
this._descriptorBlockData.reset();
this._descriptorSetLayoutData.reset();
this._descriptorSetData.reset();
this._pipelineLayoutData.reset();
this._shaderBindingData.reset();
this._shaderLayoutData.reset();
this._techniqueData.reset();
this._effectData.reset();
this._shaderProgramData.reset();
this._renderStageData.reset();
this._renderPhaseData.reset();
this._layoutGraphData.reset();
}
createDescriptorDB (): DescriptorDB {
const v = this._descriptorDB.add();
v.reset();
return v;
}
createRenderPhase (): RenderPhase {
const v = this._renderPhase.add();
v.reset();
return v;
}
createLayoutGraph (): LayoutGraph {
const v = this._layoutGraph.add();
v.clear();
return v;
}
createUniformData (
uniformID = 0xFFFFFFFF,
uniformType: Type = Type.UNKNOWN,
offset = 0,
): UniformData {
const v = this._uniformData.add();
v.reset(uniformID, uniformType, offset);
return v;
}
createUniformBlockData (): UniformBlockData {
const v = this._uniformBlockData.add();
v.reset();
return v;
}
createDescriptorData (
descriptorID = 0,
type: Type = Type.UNKNOWN,
count = 1,
): DescriptorData {
const v = this._descriptorData.add();
v.reset(descriptorID, type, count);
return v;
}
createDescriptorBlockData (
type: DescriptorTypeOrder = DescriptorTypeOrder.UNIFORM_BUFFER,
visibility: ShaderStageFlagBit = ShaderStageFlagBit.NONE,
capacity = 0,
): DescriptorBlockData {
const v = this._descriptorBlockData.add();
v.reset(type, visibility, capacity);
return v;
}
createDescriptorSetLayoutData (
slot = 0xFFFFFFFF,
capacity = 0,
): DescriptorSetLayoutData {
const v = this._descriptorSetLayoutData.add();
v.reset(slot, capacity);
return v;
}
createDescriptorSetData (
descriptorSetLayout: DescriptorSetLayout | null = null,
descriptorSet: DescriptorSet | null = null,
): DescriptorSetData {
const v = this._descriptorSetData.add();
v.reset(descriptorSetLayout, descriptorSet);
return v;
}
createPipelineLayoutData (): PipelineLayoutData {
const v = this._pipelineLayoutData.add();
v.reset();
return v;
}
createShaderBindingData (): ShaderBindingData {
const v = this._shaderBindingData.add();
v.reset();
return v;
}
createShaderLayoutData (): ShaderLayoutData {
const v = this._shaderLayoutData.add();
v.reset();
return v;
}
createTechniqueData (): TechniqueData {
const v = this._techniqueData.add();
v.reset();
return v;
}
createEffectData (): EffectData {
const v = this._effectData.add();
v.reset();
return v;
}
createShaderProgramData (): ShaderProgramData {
const v = this._shaderProgramData.add();
v.reset();
return v;
}
createRenderStageData (): RenderStageData {
const v = this._renderStageData.add();
v.reset();
return v;
}
createRenderPhaseData (): RenderPhaseData {
const v = this._renderPhaseData.add();
v.reset();
return v;
}
createLayoutGraphData (): LayoutGraphData {
const v = this._layoutGraphData.add();
v.clear();
return v;
}
public readonly renderCommon: RenderCommonObjectPool;
private readonly _descriptorDB: RecyclePool<DescriptorDB>;
private readonly _renderPhase: RecyclePool<RenderPhase>;
private readonly _layoutGraph: RecyclePool<LayoutGraph>;
private readonly _uniformData: RecyclePool<UniformData>;
private readonly _uniformBlockData: RecyclePool<UniformBlockData>;
private readonly _descriptorData: RecyclePool<DescriptorData>;
private readonly _descriptorBlockData: RecyclePool<DescriptorBlockData>;
private readonly _descriptorSetLayoutData: RecyclePool<DescriptorSetLayoutData>;
private readonly _descriptorSetData: RecyclePool<DescriptorSetData>;
private readonly _pipelineLayoutData: RecyclePool<PipelineLayoutData>;
private readonly _shaderBindingData: RecyclePool<ShaderBindingData>;
private readonly _shaderLayoutData: RecyclePool<ShaderLayoutData>;
private readonly _techniqueData: RecyclePool<TechniqueData>;
private readonly _effectData: RecyclePool<EffectData>;
private readonly _shaderProgramData: RecyclePool<ShaderProgramData>;
private readonly _renderStageData: RecyclePool<RenderStageData>;
private readonly _renderPhaseData: RecyclePool<RenderPhaseData>;
private readonly _layoutGraphData: RecyclePool<LayoutGraphData>;
}
export function saveDescriptorDB (ar: OutputArchive, v: DescriptorDB): void {
ar.writeNumber(v.blocks.size); // Map<string, DescriptorBlock>
for (const [k1, v1] of v.blocks) {
saveDescriptorBlockIndex(ar, JSON.parse(k1));
saveDescriptorBlockIndex(ar, JSON.parse(k1) as DescriptorBlockIndex);
saveDescriptorBlock(ar, v1);
}
}
+26 -24
View File
@@ -385,8 +385,18 @@ export interface Setter extends RenderNode {
setBuiltinSpotLightConstants (light: SpotLight, camera: Camera): void;
setBuiltinPointLightConstants (light: PointLight, camera: Camera): void;
setBuiltinRangedDirectionalLightConstants (light: RangedDirectionalLight, camera: Camera): void;
setBuiltinDirectionalLightViewConstants (light: DirectionalLight, level?: number): void;
setBuiltinSpotLightViewConstants (light: SpotLight): void;
setBuiltinDirectionalLightFrustumConstants (
camera: Camera,
light: DirectionalLight,
csmLevel?: number): void;
setBuiltinSpotLightFrustumConstants (light: SpotLight): void;
}
export interface SceneBuilder extends Setter {
useLightFrustum (
light: Light,
csmLevel?: number,
optCamera?: Camera): void;
}
/**
@@ -413,16 +423,7 @@ export interface RenderQueueBuilder extends Setter {
addScene (
camera: Camera,
sceneFlags: SceneFlags,
light?: Light | null): void;
addSceneCulledByDirectionalLight (
camera: Camera,
sceneFlags: SceneFlags,
light: DirectionalLight,
level: number): void;
addSceneCulledBySpotLight (
camera: Camera,
sceneFlags: SceneFlags,
light: SpotLight): void;
light?: Light): SceneBuilder;
/**
* @en Render a full-screen quad.
* @zh 渲染全屏四边形
@@ -515,7 +516,7 @@ export interface BasicRenderPassBuilder extends Setter {
addTexture (
name: string,
slotName: string,
sampler?: Sampler | null,
sampler?: Sampler,
plane?: number): void;
/**
* @en Add render queue.
@@ -689,14 +690,15 @@ export interface BasicPipeline extends PipelineRuntime {
size: number,
flags: ResourceFlags,
residency: ResourceResidency): number;
updateBuffer (
updateBuffer (name: string, size: number): void;
addExternalTexture (
name: string,
size: number): void;
addExternalTexture (name: string, texture: Texture, flags: ResourceFlags): number;
texture: Texture,
flags: ResourceFlags): number;
updateExternalTexture (name: string, texture: Texture): void;
addTexture (
name: string,
textureType: TextureType,
type: TextureType,
format: Format,
width: number,
height: number,
@@ -809,10 +811,11 @@ export interface BasicPipeline extends PipelineRuntime {
* @param copyPairs @en Array of copy source and target @zh 拷贝来源与目标的数组
*/
addCopyPass (copyPairs: CopyPair[]): void;
addBuiltinReflectionProbePass (camera: Camera): void;
/**
* @engineInternal
*/
getDescriptorSetLayout (shaderName: string, freq: UpdateFrequency): DescriptorSetLayout | null;
getDescriptorSetLayout (shaderName: string, freq: UpdateFrequency): DescriptorSetLayout | undefined;
}
/**
@@ -875,7 +878,7 @@ export interface RenderSubpassBuilder extends Setter {
addTexture (
name: string,
slotName: string,
sampler?: Sampler | null,
sampler?: Sampler,
plane?: number): void;
/**
* @en Add storage buffer.
@@ -1019,7 +1022,7 @@ export interface ComputeSubpassBuilder extends Setter {
addTexture (
name: string,
slotName: string,
sampler?: Sampler | null,
sampler?: Sampler,
plane?: number): void;
/**
* @en Add storage buffer.
@@ -1175,7 +1178,7 @@ export interface ComputePassBuilder extends Setter {
addTexture (
name: string,
slotName: string,
sampler?: Sampler | null,
sampler?: Sampler,
plane?: number): void;
/**
* @en Add storage buffer.
@@ -1389,7 +1392,7 @@ export interface Pipeline extends BasicPipeline {
addBuiltinGpuCullingPass (
camera: Camera,
hzbName?: string,
light?: Light | null): void;
light?: Light): void;
addBuiltinHzbGenerationPass (sourceDepthStencilName: string, targetHzbName: string): void;
/**
* @experimental
@@ -1423,8 +1426,7 @@ export interface PipelineBuilder {
* @param pipeline @en Current render pipeline @zh 当前管线
*/
setup (cameras: Camera[], pipeline: BasicPipeline): void;
onGlobalPipelineStateChanged?(): void;
onGlobalPipelineStateChanged? (): void;
}
/**
+1 -1
View File
@@ -64,7 +64,7 @@ export interface ProgramLibrary {
phaseID: number,
name: string,
defines: MacroRecord,
key?: string | null): ProgramProxy | null;
key?: string): ProgramProxy | null;
getBlockSizes (phaseID: number, programName: string): number[];
getHandleMap (phaseID: number, programName: string): Record<string, number>;
getProgramID (phaseID: number, programName: string): number;
+653 -19
View File
@@ -31,10 +31,12 @@
import { AdjI, AdjacencyGraph, BidirectionalGraph, ComponentGraph, ED, InEI, MutableGraph, MutableReferenceGraph, NamedGraph, OutE, OutEI, PolymorphicGraph, PropertyGraph, PropertyMap, ReferenceGraph, UuidGraph, VertexListGraph, directional, parallel, reindexEdgeList, traversal } from './graph';
import { Material } from '../../asset/assets';
import { Camera } from '../../render-scene/scene/camera';
import { AccessFlagBit, Buffer, ClearFlagBit, Color, Format, Framebuffer, LoadOp, RenderPass, SampleCount, Sampler, SamplerInfo, ShaderStageFlagBit, StoreOp, Swapchain, Texture, TextureFlagBit, Viewport, TextureType } from '../../gfx';
import { AccessType, AttachmentType, ClearValueType, CopyPair, LightInfo, MovePair, QueueHint, ResolvePair, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UploadPair } from './types';
import { AccessFlagBit, Buffer, ClearFlagBit, Color, Format, Framebuffer, LoadOp, RenderPass, SampleCount, Sampler, SamplerInfo, ShaderStageFlagBit, StoreOp, Swapchain, Texture, TextureFlagBit, TextureType, Viewport } from '../../gfx';
import { AccessType, AttachmentType, ClearValueType, CopyPair, LightInfo, MovePair, QueueHint, ResolvePair, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UploadPair, RenderCommonObjectPool } from './types';
import { RenderScene } from '../../render-scene/core/render-scene';
import { RenderWindow } from '../../render-scene/core/render-window';
import { Light } from '../../render-scene/scene';
import { RecyclePool } from '../../core/memop';
export class ClearValue {
constructor (x = 0, y = 0, z = 0, w = 0) {
@@ -43,6 +45,12 @@ export class ClearValue {
this.z = z;
this.w = w;
}
reset (x = 0, y = 0, z = 0, w = 0): void {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
x: number;
y: number;
z: number;
@@ -69,6 +77,26 @@ export class RasterView {
this.clearColor = clearColor;
this.shaderStageFlags = shaderStageFlags;
}
reset (
slotName = '',
accessType: AccessType = AccessType.WRITE,
attachmentType: AttachmentType = AttachmentType.RENDER_TARGET,
loadOp: LoadOp = LoadOp.LOAD,
storeOp: StoreOp = StoreOp.STORE,
clearFlags: ClearFlagBit = ClearFlagBit.ALL,
shaderStageFlags: ShaderStageFlagBit = ShaderStageFlagBit.NONE,
): void {
this.slotName = slotName;
this.slotName1 = '';
this.accessType = accessType;
this.attachmentType = attachmentType;
this.loadOp = loadOp;
this.storeOp = storeOp;
this.clearFlags = clearFlags;
this.clearColor.reset();
this.slotID = 0;
this.shaderStageFlags = shaderStageFlags;
}
slotName: string;
slotName1 = '';
accessType: AccessType;
@@ -97,6 +125,21 @@ export class ComputeView {
this.clearValue = clearValue;
this.shaderStageFlags = shaderStageFlags;
}
reset (
name = '',
accessType: AccessType = AccessType.READ,
clearFlags: ClearFlagBit = ClearFlagBit.NONE,
clearValueType: ClearValueType = ClearValueType.NONE,
shaderStageFlags: ShaderStageFlagBit = ShaderStageFlagBit.NONE,
): void {
this.name = name;
this.accessType = accessType;
this.plane = 0;
this.clearFlags = clearFlags;
this.clearValueType = clearValueType;
this.clearValue.reset();
this.shaderStageFlags = shaderStageFlags;
}
name: string;
accessType: AccessType;
plane = 0;
@@ -107,6 +150,19 @@ export class ComputeView {
}
export class ResourceDesc {
reset (): void {
this.dimension = ResourceDimension.BUFFER;
this.alignment = 0;
this.width = 0;
this.height = 0;
this.depthOrArraySize = 0;
this.mipLevels = 0;
this.format = Format.UNKNOWN;
this.sampleCount = SampleCount.X1;
this.textureFlags = TextureFlagBit.NONE;
this.flags = ResourceFlags.NONE;
this.viewType = TextureType.TEX2D;
}
dimension: ResourceDimension = ResourceDimension.BUFFER;
alignment = 0;
width = 0;
@@ -124,6 +180,9 @@ export class ResourceTraits {
constructor (residency: ResourceResidency = ResourceResidency.MANAGED) {
this.residency = residency;
}
reset (residency: ResourceResidency = ResourceResidency.MANAGED): void {
this.residency = residency;
}
residency: ResourceResidency;
}
@@ -131,6 +190,13 @@ export class RenderSwapchain {
constructor (swapchain: Swapchain | null = null) {
this.swapchain = swapchain;
}
reset (swapchain: Swapchain | null = null): void {
this.swapchain = swapchain;
this.renderWindow = null;
this.currentID = 0;
this.numBackBuffers = 0;
this.generation = 0xFFFFFFFF;
}
/*pointer*/ swapchain: Swapchain | null;
/*pointer*/ renderWindow: RenderWindow | null = null;
currentID = 0;
@@ -139,6 +205,9 @@ export class RenderSwapchain {
}
export class ResourceStates {
reset (): void {
this.states = AccessFlagBit.NONE;
}
states: AccessFlagBit = AccessFlagBit.NONE;
}
@@ -146,6 +215,10 @@ export class ManagedBuffer {
constructor (buffer: Buffer | null = null) {
this.buffer = buffer;
}
reset (buffer: Buffer | null = null): void {
this.buffer = buffer;
this.fenceValue = 0;
}
/*refcount*/ buffer: Buffer | null;
fenceValue = 0;
}
@@ -154,6 +227,10 @@ export class PersistentBuffer {
constructor (buffer: Buffer | null = null) {
this.buffer = buffer;
}
reset (buffer: Buffer | null = null): void {
this.buffer = buffer;
this.fenceValue = 0;
}
/*refcount*/ buffer: Buffer | null;
fenceValue = 0;
}
@@ -162,6 +239,10 @@ export class ManagedTexture {
constructor (texture: Texture | null = null) {
this.texture = texture;
}
reset (texture: Texture | null = null): void {
this.texture = texture;
this.fenceValue = 0;
}
/*refcount*/ texture: Texture | null;
fenceValue = 0;
}
@@ -170,15 +251,27 @@ export class PersistentTexture {
constructor (texture: Texture | null = null) {
this.texture = texture;
}
reset (texture: Texture | null = null): void {
this.texture = texture;
this.fenceValue = 0;
}
/*refcount*/ texture: Texture | null;
fenceValue = 0;
}
export class ManagedResource {
reset (): void {
this.unused = 0;
}
unused = 0;
}
export class Subpass {
reset (): void {
this.rasterViews.clear();
this.computeViews.clear();
this.resolvePairs.length = 0;
}
readonly rasterViews: Map<string, RasterView> = new Map<string, RasterView>();
readonly computeViews: Map<string, ComputeView[]> = new Map<string, ComputeView[]>();
readonly resolvePairs: ResolvePair[] = [];
@@ -486,11 +579,21 @@ export class SubpassGraph implements BidirectionalGraph
}
export class RasterSubpass {
constructor (subpassID: number, count: number, quality: number) {
constructor (subpassID = 0xFFFFFFFF, count = 1, quality = 0) {
this.subpassID = subpassID;
this.count = count;
this.quality = quality;
}
reset (subpassID = 0xFFFFFFFF, count = 1, quality = 0): void {
this.rasterViews.clear();
this.computeViews.clear();
this.resolvePairs.length = 0;
this.viewport.reset();
this.subpassID = subpassID;
this.count = count;
this.quality = quality;
this.showStatistics = false;
}
readonly rasterViews: Map<string, RasterView> = new Map<string, RasterView>();
readonly computeViews: Map<string, ComputeView[]> = new Map<string, ComputeView[]>();
readonly resolvePairs: ResolvePair[] = [];
@@ -502,7 +605,12 @@ export class RasterSubpass {
}
export class ComputeSubpass {
constructor (subpassID: number) {
constructor (subpassID = 0xFFFFFFFF) {
this.subpassID = subpassID;
}
reset (subpassID = 0xFFFFFFFF): void {
this.rasterViews.clear();
this.computeViews.clear();
this.subpassID = subpassID;
}
readonly rasterViews: Map<string, RasterView> = new Map<string, RasterView>();
@@ -511,6 +619,22 @@ export class ComputeSubpass {
}
export class RasterPass {
reset (): void {
this.rasterViews.clear();
this.computeViews.clear();
this.attachmentIndexMap.clear();
this.textures.clear();
this.subpassGraph.clear();
this.width = 0;
this.height = 0;
this.count = 1;
this.quality = 0;
this.viewport.reset();
this.versionName = '';
this.version = 0;
this.hashValue = 0;
this.showStatistics = false;
}
readonly rasterViews: Map<string, RasterView> = new Map<string, RasterView>();
readonly computeViews: Map<string, ComputeView[]> = new Map<string, ComputeView[]>();
readonly attachmentIndexMap: Map<string, number> = new Map<string, number>();
@@ -528,22 +652,42 @@ export class RasterPass {
}
export class PersistentRenderPassAndFramebuffer {
constructor (renderPass: RenderPass, framebuffer: Framebuffer) {
constructor (renderPass: RenderPass | null = null, framebuffer: Framebuffer | null = null) {
this.renderPass = renderPass;
this.framebuffer = framebuffer;
}
/*refcount*/ renderPass: RenderPass;
/*refcount*/ framebuffer: Framebuffer;
reset (renderPass: RenderPass | null = null, framebuffer: Framebuffer | null = null): void {
this.renderPass = renderPass;
this.framebuffer = framebuffer;
this.clearColors.length = 0;
this.clearDepth = 0;
this.clearStencil = 0;
}
/*refcount*/ renderPass: RenderPass | null;
/*refcount*/ framebuffer: Framebuffer | null;
readonly clearColors: Color[] = [];
clearDepth = 0;
clearStencil = 0;
}
export class FormatView {
reset (): void {
this.format = Format.UNKNOWN;
}
format: Format = Format.UNKNOWN;
}
export class SubresourceView {
reset (): void {
this.textureView = null;
this.format = Format.UNKNOWN;
this.indexOrFirstMipLevel = 0;
this.numMipLevels = 0;
this.firstArraySlice = 0;
this.numArraySlices = 0;
this.firstPlane = 0;
this.numPlanes = 0;
}
/*refcount*/ textureView: Texture | null = null;
format: Format = Format.UNKNOWN;
indexOrFirstMipLevel = 0;
@@ -612,14 +756,12 @@ export interface ResourceGraphVisitor {
export type ResourceGraphObject = ManagedResource
| ManagedBuffer
| ManagedTexture
| Buffer
| Texture
| PersistentBuffer
| PersistentTexture
| Framebuffer
| RenderSwapchain
| FormatView
| SubresourceView
| PersistentBuffer
| PersistentTexture;
| SubresourceView;
//-----------------------------------------------------------------
// Graph Concept
@@ -1308,24 +1450,41 @@ export class ResourceGraph implements BidirectionalGraph
}
export class ComputePass {
reset (): void {
this.computeViews.clear();
this.textures.clear();
}
readonly computeViews: Map<string, ComputeView[]> = new Map<string, ComputeView[]>();
readonly textures: Map<string, ShaderStageFlagBit> = new Map<string, ShaderStageFlagBit>();
}
export class ResolvePass {
reset (): void {
this.resolvePairs.length = 0;
}
readonly resolvePairs: ResolvePair[] = [];
}
export class CopyPass {
reset (): void {
this.copyPairs.length = 0;
this.uploadPairs.length = 0;
}
readonly copyPairs: CopyPair[] = [];
readonly uploadPairs: UploadPair[] = [];
}
export class MovePass {
reset (): void {
this.movePairs.length = 0;
}
readonly movePairs: MovePair[] = [];
}
export class RaytracePass {
reset (): void {
this.computeViews.clear();
}
readonly computeViews: Map<string, ComputeView[]> = new Map<string, ComputeView[]>();
}
@@ -1335,6 +1494,11 @@ export class ClearView {
this.clearFlags = clearFlags;
this.clearColor = clearColor;
}
reset (slotName = '', clearFlags: ClearFlagBit = ClearFlagBit.ALL): void {
this.slotName = slotName;
this.clearFlags = clearFlags;
this.clearColor.reset();
}
slotName: string;
clearFlags: ClearFlagBit;
readonly clearColor: Color;
@@ -1345,31 +1509,68 @@ export class RenderQueue {
this.hint = hint;
this.phaseID = phaseID;
}
reset (hint: QueueHint = QueueHint.RENDER_OPAQUE, phaseID = 0xFFFFFFFF): void {
this.hint = hint;
this.phaseID = phaseID;
this.viewport = null;
}
hint: QueueHint;
phaseID: number;
viewport: Viewport | null = null;
}
export enum CullingFlags {
NONE = 0,
CAMERA_FRUSTUM = 0x1,
LIGHT_FRUSTUM = 0x2,
LIGHT_BOUNDS = 0x4,
}
export class SceneData {
constructor (scene: RenderScene | null = null, camera: Camera | null = null, flags: SceneFlags = SceneFlags.NONE, light: LightInfo = new LightInfo()) {
constructor (
scene: RenderScene | null = null,
camera: Camera | null = null,
flags: SceneFlags = SceneFlags.NONE,
light: LightInfo = new LightInfo(),
cullingFlags: CullingFlags = CullingFlags.CAMERA_FRUSTUM,
shadingLight: Light | null = null,
) {
this.scene = scene;
this.camera = camera;
this.light = light;
this.flags = flags;
this.cullingFlags = cullingFlags;
this.shadingLight = shadingLight;
}
reset (
scene: RenderScene | null = null,
camera: Camera | null = null,
flags: SceneFlags = SceneFlags.NONE,
cullingFlags: CullingFlags = CullingFlags.CAMERA_FRUSTUM,
shadingLight: Light | null = null,
): void {
this.scene = scene;
this.camera = camera;
this.light.reset();
this.flags = flags;
this.cullingFlags = cullingFlags;
this.shadingLight = shadingLight;
}
/*pointer*/ scene: RenderScene | null;
/*pointer*/ camera: Camera | null;
readonly light: LightInfo;
flags: SceneFlags;
cullingFlags: CullingFlags;
/*refcount*/ shadingLight: Light | null;
}
export class Dispatch {
constructor (
material: Material | null,
passID: number,
threadGroupCountX: number,
threadGroupCountY: number,
threadGroupCountZ: number,
material: Material | null = null,
passID = 0,
threadGroupCountX = 0,
threadGroupCountY = 0,
threadGroupCountZ = 0,
) {
this.material = material;
this.passID = passID;
@@ -1377,6 +1578,19 @@ export class Dispatch {
this.threadGroupCountY = threadGroupCountY;
this.threadGroupCountZ = threadGroupCountZ;
}
reset (
material: Material | null = null,
passID = 0,
threadGroupCountX = 0,
threadGroupCountY = 0,
threadGroupCountZ = 0,
): void {
this.material = material;
this.passID = passID;
this.threadGroupCountX = threadGroupCountX;
this.threadGroupCountY = threadGroupCountY;
this.threadGroupCountZ = threadGroupCountZ;
}
/*refcount*/ material: Material | null;
passID: number;
threadGroupCountX: number;
@@ -1385,7 +1599,13 @@ export class Dispatch {
}
export class Blit {
constructor (material: Material | null, passID: number, sceneFlags: SceneFlags, camera: Camera | null) {
constructor (material: Material | null = null, passID = 0, sceneFlags: SceneFlags = SceneFlags.NONE, camera: Camera | null = null) {
this.material = material;
this.passID = passID;
this.sceneFlags = sceneFlags;
this.camera = camera;
}
reset (material: Material | null = null, passID = 0, sceneFlags: SceneFlags = SceneFlags.NONE, camera: Camera | null = null): void {
this.material = material;
this.passID = passID;
this.sceneFlags = sceneFlags;
@@ -1398,6 +1618,13 @@ export class Blit {
}
export class RenderData {
reset (): void {
this.constants.clear();
this.buffers.clear();
this.textures.clear();
this.samplers.clear();
this.custom = '';
}
readonly constants: Map<number, number[]> = new Map<number, number[]>();
readonly buffers: Map<number, Buffer> = new Map<number, Buffer>();
readonly textures: Map<number, Texture> = new Map<number, Texture>();
@@ -2288,3 +2515,410 @@ export class RenderGraph implements BidirectionalGraph
readonly index: Map<string, number> = new Map<string, number>();
readonly sortedVertices: number[] = [];
}
export class RenderGraphObjectPoolSettings {
constructor (batchSize: number) {
this.clearValueBatchSize = batchSize;
this.rasterViewBatchSize = batchSize;
this.computeViewBatchSize = batchSize;
this.resourceDescBatchSize = batchSize;
this.resourceTraitsBatchSize = batchSize;
this.renderSwapchainBatchSize = batchSize;
this.resourceStatesBatchSize = batchSize;
this.managedBufferBatchSize = batchSize;
this.persistentBufferBatchSize = batchSize;
this.managedTextureBatchSize = batchSize;
this.persistentTextureBatchSize = batchSize;
this.managedResourceBatchSize = batchSize;
this.subpassBatchSize = batchSize;
this.subpassGraphBatchSize = batchSize;
this.rasterSubpassBatchSize = batchSize;
this.computeSubpassBatchSize = batchSize;
this.rasterPassBatchSize = batchSize;
this.persistentRenderPassAndFramebufferBatchSize = batchSize;
this.formatViewBatchSize = batchSize;
this.subresourceViewBatchSize = batchSize;
this.resourceGraphBatchSize = batchSize;
this.computePassBatchSize = batchSize;
this.resolvePassBatchSize = batchSize;
this.copyPassBatchSize = batchSize;
this.movePassBatchSize = batchSize;
this.raytracePassBatchSize = batchSize;
this.clearViewBatchSize = batchSize;
this.renderQueueBatchSize = batchSize;
this.sceneDataBatchSize = batchSize;
this.dispatchBatchSize = batchSize;
this.blitBatchSize = batchSize;
this.renderDataBatchSize = batchSize;
this.renderGraphBatchSize = batchSize;
}
clearValueBatchSize = 16;
rasterViewBatchSize = 16;
computeViewBatchSize = 16;
resourceDescBatchSize = 16;
resourceTraitsBatchSize = 16;
renderSwapchainBatchSize = 16;
resourceStatesBatchSize = 16;
managedBufferBatchSize = 16;
persistentBufferBatchSize = 16;
managedTextureBatchSize = 16;
persistentTextureBatchSize = 16;
managedResourceBatchSize = 16;
subpassBatchSize = 16;
subpassGraphBatchSize = 16;
rasterSubpassBatchSize = 16;
computeSubpassBatchSize = 16;
rasterPassBatchSize = 16;
persistentRenderPassAndFramebufferBatchSize = 16;
formatViewBatchSize = 16;
subresourceViewBatchSize = 16;
resourceGraphBatchSize = 16;
computePassBatchSize = 16;
resolvePassBatchSize = 16;
copyPassBatchSize = 16;
movePassBatchSize = 16;
raytracePassBatchSize = 16;
clearViewBatchSize = 16;
renderQueueBatchSize = 16;
sceneDataBatchSize = 16;
dispatchBatchSize = 16;
blitBatchSize = 16;
renderDataBatchSize = 16;
renderGraphBatchSize = 16;
}
export class RenderGraphObjectPool {
constructor (settings: RenderGraphObjectPoolSettings, renderCommon: RenderCommonObjectPool) {
this.renderCommon = renderCommon;
this._clearValue = new RecyclePool<ClearValue>(() => new ClearValue(), settings.clearValueBatchSize);
this._rasterView = new RecyclePool<RasterView>(() => new RasterView(), settings.rasterViewBatchSize);
this._computeView = new RecyclePool<ComputeView>(() => new ComputeView(), settings.computeViewBatchSize);
this._resourceDesc = new RecyclePool<ResourceDesc>(() => new ResourceDesc(), settings.resourceDescBatchSize);
this._resourceTraits = new RecyclePool<ResourceTraits>(() => new ResourceTraits(), settings.resourceTraitsBatchSize);
this._renderSwapchain = new RecyclePool<RenderSwapchain>(() => new RenderSwapchain(), settings.renderSwapchainBatchSize);
this._resourceStates = new RecyclePool<ResourceStates>(() => new ResourceStates(), settings.resourceStatesBatchSize);
this._managedBuffer = new RecyclePool<ManagedBuffer>(() => new ManagedBuffer(), settings.managedBufferBatchSize);
this._persistentBuffer = new RecyclePool<PersistentBuffer>(() => new PersistentBuffer(), settings.persistentBufferBatchSize);
this._managedTexture = new RecyclePool<ManagedTexture>(() => new ManagedTexture(), settings.managedTextureBatchSize);
this._persistentTexture = new RecyclePool<PersistentTexture>(() => new PersistentTexture(), settings.persistentTextureBatchSize);
this._managedResource = new RecyclePool<ManagedResource>(() => new ManagedResource(), settings.managedResourceBatchSize);
this._subpass = new RecyclePool<Subpass>(() => new Subpass(), settings.subpassBatchSize);
this._subpassGraph = new RecyclePool<SubpassGraph>(() => new SubpassGraph(), settings.subpassGraphBatchSize);
this._rasterSubpass = new RecyclePool<RasterSubpass>(() => new RasterSubpass(), settings.rasterSubpassBatchSize);
this._computeSubpass = new RecyclePool<ComputeSubpass>(() => new ComputeSubpass(), settings.computeSubpassBatchSize);
this._rasterPass = new RecyclePool<RasterPass>(() => new RasterPass(), settings.rasterPassBatchSize);
this._persistentRenderPassAndFramebuffer = new RecyclePool<PersistentRenderPassAndFramebuffer>(() => new PersistentRenderPassAndFramebuffer(), settings.persistentRenderPassAndFramebufferBatchSize);
this._formatView = new RecyclePool<FormatView>(() => new FormatView(), settings.formatViewBatchSize);
this._subresourceView = new RecyclePool<SubresourceView>(() => new SubresourceView(), settings.subresourceViewBatchSize);
this._resourceGraph = new RecyclePool<ResourceGraph>(() => new ResourceGraph(), settings.resourceGraphBatchSize);
this._computePass = new RecyclePool<ComputePass>(() => new ComputePass(), settings.computePassBatchSize);
this._resolvePass = new RecyclePool<ResolvePass>(() => new ResolvePass(), settings.resolvePassBatchSize);
this._copyPass = new RecyclePool<CopyPass>(() => new CopyPass(), settings.copyPassBatchSize);
this._movePass = new RecyclePool<MovePass>(() => new MovePass(), settings.movePassBatchSize);
this._raytracePass = new RecyclePool<RaytracePass>(() => new RaytracePass(), settings.raytracePassBatchSize);
this._clearView = new RecyclePool<ClearView>(() => new ClearView(), settings.clearViewBatchSize);
this._renderQueue = new RecyclePool<RenderQueue>(() => new RenderQueue(), settings.renderQueueBatchSize);
this._sceneData = new RecyclePool<SceneData>(() => new SceneData(), settings.sceneDataBatchSize);
this._dispatch = new RecyclePool<Dispatch>(() => new Dispatch(), settings.dispatchBatchSize);
this._blit = new RecyclePool<Blit>(() => new Blit(), settings.blitBatchSize);
this._renderData = new RecyclePool<RenderData>(() => new RenderData(), settings.renderDataBatchSize);
this._renderGraph = new RecyclePool<RenderGraph>(() => new RenderGraph(), settings.renderGraphBatchSize);
}
reset (): void {
this._clearValue.reset();
this._rasterView.reset();
this._computeView.reset();
this._resourceDesc.reset();
this._resourceTraits.reset();
this._renderSwapchain.reset();
this._resourceStates.reset();
this._managedBuffer.reset();
this._persistentBuffer.reset();
this._managedTexture.reset();
this._persistentTexture.reset();
this._managedResource.reset();
this._subpass.reset();
this._subpassGraph.reset();
this._rasterSubpass.reset();
this._computeSubpass.reset();
this._rasterPass.reset();
this._persistentRenderPassAndFramebuffer.reset();
this._formatView.reset();
this._subresourceView.reset();
this._resourceGraph.reset();
this._computePass.reset();
this._resolvePass.reset();
this._copyPass.reset();
this._movePass.reset();
this._raytracePass.reset();
this._clearView.reset();
this._renderQueue.reset();
this._sceneData.reset();
this._dispatch.reset();
this._blit.reset();
this._renderData.reset();
this._renderGraph.reset();
}
createClearValue (
x = 0,
y = 0,
z = 0,
w = 0,
): ClearValue {
const v = this._clearValue.add();
v.reset(x, y, z, w);
return v;
}
createRasterView (
slotName = '',
accessType: AccessType = AccessType.WRITE,
attachmentType: AttachmentType = AttachmentType.RENDER_TARGET,
loadOp: LoadOp = LoadOp.LOAD,
storeOp: StoreOp = StoreOp.STORE,
clearFlags: ClearFlagBit = ClearFlagBit.ALL,
shaderStageFlags: ShaderStageFlagBit = ShaderStageFlagBit.NONE,
): RasterView {
const v = this._rasterView.add();
v.reset(slotName, accessType, attachmentType, loadOp, storeOp, clearFlags, shaderStageFlags);
return v;
}
createComputeView (
name = '',
accessType: AccessType = AccessType.READ,
clearFlags: ClearFlagBit = ClearFlagBit.NONE,
clearValueType: ClearValueType = ClearValueType.NONE,
shaderStageFlags: ShaderStageFlagBit = ShaderStageFlagBit.NONE,
): ComputeView {
const v = this._computeView.add();
v.reset(name, accessType, clearFlags, clearValueType, shaderStageFlags);
return v;
}
createResourceDesc (): ResourceDesc {
const v = this._resourceDesc.add();
v.reset();
return v;
}
createResourceTraits (
residency: ResourceResidency = ResourceResidency.MANAGED,
): ResourceTraits {
const v = this._resourceTraits.add();
v.reset(residency);
return v;
}
createRenderSwapchain (
swapchain: Swapchain | null = null,
): RenderSwapchain {
const v = this._renderSwapchain.add();
v.reset(swapchain);
return v;
}
createResourceStates (): ResourceStates {
const v = this._resourceStates.add();
v.reset();
return v;
}
createManagedBuffer (
buffer: Buffer | null = null,
): ManagedBuffer {
const v = this._managedBuffer.add();
v.reset(buffer);
return v;
}
createPersistentBuffer (
buffer: Buffer | null = null,
): PersistentBuffer {
const v = this._persistentBuffer.add();
v.reset(buffer);
return v;
}
createManagedTexture (
texture: Texture | null = null,
): ManagedTexture {
const v = this._managedTexture.add();
v.reset(texture);
return v;
}
createPersistentTexture (
texture: Texture | null = null,
): PersistentTexture {
const v = this._persistentTexture.add();
v.reset(texture);
return v;
}
createManagedResource (): ManagedResource {
const v = this._managedResource.add();
v.reset();
return v;
}
createSubpass (): Subpass {
const v = this._subpass.add();
v.reset();
return v;
}
createSubpassGraph (): SubpassGraph {
const v = this._subpassGraph.add();
v.clear();
return v;
}
createRasterSubpass (
subpassID = 0xFFFFFFFF,
count = 1,
quality = 0,
): RasterSubpass {
const v = this._rasterSubpass.add();
v.reset(subpassID, count, quality);
return v;
}
createComputeSubpass (
subpassID = 0xFFFFFFFF,
): ComputeSubpass {
const v = this._computeSubpass.add();
v.reset(subpassID);
return v;
}
createRasterPass (): RasterPass {
const v = this._rasterPass.add();
v.reset();
return v;
}
createPersistentRenderPassAndFramebuffer (
renderPass: RenderPass | null = null,
framebuffer: Framebuffer | null = null,
): PersistentRenderPassAndFramebuffer {
const v = this._persistentRenderPassAndFramebuffer.add();
v.reset(renderPass, framebuffer);
return v;
}
createFormatView (): FormatView {
const v = this._formatView.add();
v.reset();
return v;
}
createSubresourceView (): SubresourceView {
const v = this._subresourceView.add();
v.reset();
return v;
}
createResourceGraph (): ResourceGraph {
const v = this._resourceGraph.add();
v.clear();
return v;
}
createComputePass (): ComputePass {
const v = this._computePass.add();
v.reset();
return v;
}
createResolvePass (): ResolvePass {
const v = this._resolvePass.add();
v.reset();
return v;
}
createCopyPass (): CopyPass {
const v = this._copyPass.add();
v.reset();
return v;
}
createMovePass (): MovePass {
const v = this._movePass.add();
v.reset();
return v;
}
createRaytracePass (): RaytracePass {
const v = this._raytracePass.add();
v.reset();
return v;
}
createClearView (
slotName = '',
clearFlags: ClearFlagBit = ClearFlagBit.ALL,
): ClearView {
const v = this._clearView.add();
v.reset(slotName, clearFlags);
return v;
}
createRenderQueue (
hint: QueueHint = QueueHint.RENDER_OPAQUE,
phaseID = 0xFFFFFFFF,
): RenderQueue {
const v = this._renderQueue.add();
v.reset(hint, phaseID);
return v;
}
createSceneData (
scene: RenderScene | null = null,
camera: Camera | null = null,
flags: SceneFlags = SceneFlags.NONE,
cullingFlags: CullingFlags = CullingFlags.CAMERA_FRUSTUM,
shadingLight: Light | null = null,
): SceneData {
const v = this._sceneData.add();
v.reset(scene, camera, flags, cullingFlags, shadingLight);
return v;
}
createDispatch (
material: Material | null = null,
passID = 0,
threadGroupCountX = 0,
threadGroupCountY = 0,
threadGroupCountZ = 0,
): Dispatch {
const v = this._dispatch.add();
v.reset(material, passID, threadGroupCountX, threadGroupCountY, threadGroupCountZ);
return v;
}
createBlit (
material: Material | null = null,
passID = 0,
sceneFlags: SceneFlags = SceneFlags.NONE,
camera: Camera | null = null,
): Blit {
const v = this._blit.add();
v.reset(material, passID, sceneFlags, camera);
return v;
}
createRenderData (): RenderData {
const v = this._renderData.add();
v.reset();
return v;
}
createRenderGraph (): RenderGraph {
const v = this._renderGraph.add();
v.clear();
return v;
}
public readonly renderCommon: RenderCommonObjectPool;
private readonly _clearValue: RecyclePool<ClearValue>;
private readonly _rasterView: RecyclePool<RasterView>;
private readonly _computeView: RecyclePool<ComputeView>;
private readonly _resourceDesc: RecyclePool<ResourceDesc>;
private readonly _resourceTraits: RecyclePool<ResourceTraits>;
private readonly _renderSwapchain: RecyclePool<RenderSwapchain>;
private readonly _resourceStates: RecyclePool<ResourceStates>;
private readonly _managedBuffer: RecyclePool<ManagedBuffer>;
private readonly _persistentBuffer: RecyclePool<PersistentBuffer>;
private readonly _managedTexture: RecyclePool<ManagedTexture>;
private readonly _persistentTexture: RecyclePool<PersistentTexture>;
private readonly _managedResource: RecyclePool<ManagedResource>;
private readonly _subpass: RecyclePool<Subpass>;
private readonly _subpassGraph: RecyclePool<SubpassGraph>;
private readonly _rasterSubpass: RecyclePool<RasterSubpass>;
private readonly _computeSubpass: RecyclePool<ComputeSubpass>;
private readonly _rasterPass: RecyclePool<RasterPass>;
private readonly _persistentRenderPassAndFramebuffer: RecyclePool<PersistentRenderPassAndFramebuffer>;
private readonly _formatView: RecyclePool<FormatView>;
private readonly _subresourceView: RecyclePool<SubresourceView>;
private readonly _resourceGraph: RecyclePool<ResourceGraph>;
private readonly _computePass: RecyclePool<ComputePass>;
private readonly _resolvePass: RecyclePool<ResolvePass>;
private readonly _copyPass: RecyclePool<CopyPass>;
private readonly _movePass: RecyclePool<MovePass>;
private readonly _raytracePass: RecyclePool<RaytracePass>;
private readonly _clearView: RecyclePool<ClearView>;
private readonly _renderQueue: RecyclePool<RenderQueue>;
private readonly _sceneData: RecyclePool<SceneData>;
private readonly _dispatch: RecyclePool<Dispatch>;
private readonly _blit: RecyclePool<Blit>;
private readonly _renderData: RecyclePool<RenderData>;
private readonly _renderGraph: RecyclePool<RenderGraph>;
}
+574 -127
View File
@@ -1,18 +1,47 @@
import { Vec3, assert } from '../../core';
import { Vec3, assert, RecyclePool } from '../../core';
import { Frustum, intersect, AABB } from '../../core/geometry';
import { CommandBuffer } from '../../gfx';
import { CommandBuffer, Device, Buffer, BufferInfo, BufferViewInfo, MemoryUsageBit, BufferUsageBit } from '../../gfx';
import { BatchingSchemes, Pass, RenderScene } from '../../render-scene';
import { CSMLevel, Camera, DirectionalLight, Light, LightType, Model, SKYBOX_FLAG, ShadowType, SpotLight } from '../../render-scene/scene';
import { Node } from '../../scene-graph';
import { CSMLevel, Camera, DirectionalLight, Light, LightType, Model, PointLight, ProbeType,
RangedDirectionalLight,
ReflectionProbe, SKYBOX_FLAG, ShadowType, Shadows, SphereLight, SpotLight } from '../../render-scene/scene';
import { Layers, Node } from '../../scene-graph';
import { PipelineSceneData } from '../pipeline-scene-data';
import { hashCombineStr, getSubpassOrPassID, bool } from './define';
import { hashCombineStr, getSubpassOrPassID, bool, AlignUp, SetLightUBO } from './define';
import { LayoutGraphData } from './layout-graph';
import { RenderGraph, RenderGraphValue, SceneData } from './render-graph';
import { CullingFlags, RenderGraph, RenderGraphValue, SceneData } from './render-graph';
import { SceneFlags } from './types';
import { RenderQueue, RenderQueueDesc } from './web-pipeline-types';
import { RenderQueue, RenderQueueDesc, instancePool } from './web-pipeline-types';
import { ObjectPool } from './utils';
import { getUniformBlockSize } from './layout-graph-utils';
import { WebProgramLibrary } from './web-program-library';
function computeCullingKey (camera: Camera | null, light: Light | null, castShadows: boolean, lightLevel: number): number {
const vec3Pool = new ObjectPool(() => new Vec3());
class CullingPools {
frustumCullingKeyRecycle = new RecyclePool(() => new FrustumCullingKey(), 8);
frustumCullingsRecycle = new RecyclePool(() => new FrustumCulling(), 8);
lightBoundsCullingRecycle = new RecyclePool(() => new LightBoundsCulling(), 8);
lightBoundsCullingResultRecycle = new RecyclePool(() => new LightBoundsCullingResult(), 8);
lightBoundsCullingKeyRecycle = new RecyclePool(() => new LightBoundsCullingKey(), 8);
renderQueueRecycle = new RecyclePool(() => new RenderQueue(), 8);
renderQueueDescRecycle = new RecyclePool(() => new RenderQueueDesc(), 8);
}
const REFLECTION_PROBE_DEFAULT_MASK = Layers.makeMaskExclude([Layers.BitMask.UI_2D, Layers.BitMask.UI_3D,
Layers.BitMask.GIZMOS, Layers.BitMask.EDITOR,
Layers.BitMask.SCENE_GIZMO, Layers.BitMask.PROFILER]);
function computeCullingKey (
sceneData: SceneData,
castShadows: boolean,
refId: number = -1,
): number {
let hashCode = 0;
const camera = sceneData.camera;
const light = sceneData.light.light;
const lightLevel = sceneData.light.level;
const culledByLight = sceneData.light.culledByLight;
const reflectProbe = sceneData.light.probe;
const shadeLight = sceneData.shadingLight;
if (camera) {
// camera
hashCode = hashCombineStr(`u${camera.node.uuid}`, hashCode);
@@ -47,30 +76,77 @@ function computeCullingKey (camera: Camera | null, light: Light | null, castShad
// default:
// }
}
if (shadeLight) {
hashCode = hashCombineStr(`shadeLight${shadeLight.node!.uuid}`, hashCode);
}
hashCode = hashCombineStr(`culledByLight${culledByLight}`, hashCode);
hashCode = hashCombineStr(`cast${castShadows}`, hashCode);
hashCode = hashCombineStr(`level${lightLevel}`, hashCode);
if (reflectProbe) {
hashCode = hashCombineStr(`probe${reflectProbe.getProbeId()}`, hashCode);
}
hashCode = hashCombineStr(`refId${refId}`, hashCode);
return hashCode;
}
class CullingKey {
camera: Camera | null;
light: Light | null;
class FrustumCullingKey {
sceneData: SceneData | null = null;
castShadows = false;
lightLevel = 0xffffffff;
constructor (camera: Camera | null, light: Light | null, castShadows: boolean, lightLevel: number) {
this.camera = camera;
this.light = light;
constructor (sceneData: SceneData | null = null, castShadows: boolean = false) {
this.sceneData = sceneData;
this.castShadows = castShadows;
}
update (sceneData: SceneData, castShadows: boolean): void {
this.sceneData = sceneData;
this.castShadows = castShadows;
this.lightLevel = lightLevel;
}
}
class LightBoundsCullingKey {
sceneData: SceneData | null = null;
frustumCullingID: FrustumCullingID = -1;
constructor (sceneData: SceneData | null = null, frustumCullingID: FrustumCullingID = -1) {
this.sceneData = sceneData;
this.frustumCullingID = frustumCullingID;
}
update (sceneData: SceneData | null = null, frustumCullingID: FrustumCullingID = -1): void {
this.sceneData = sceneData;
this.frustumCullingID = frustumCullingID;
}
}
class LightBoundsCulling {
resultKeyIndex: Map<number, LightBoundsCullingKey> = new Map<number, LightBoundsCullingKey>();
resultIndex: Map<number, LightBoundsCullingID> = new Map<number, LightBoundsCullingID>();
update (): void {
this.resultIndex.clear();
this.resultKeyIndex.clear();
}
}
class LightBoundsCullingResult {
instances: Array<Model> = new Array<Model>();
lightByteOffset: number = 0xFFFFFFFF;
update (): LightBoundsCullingResult {
this.instances.length = 0;
this.lightByteOffset = 0xFFFFFFFF;
return this;
}
}
type FrustumCullingID = number;
type LightBoundsCullingID = number;
let pSceneData: PipelineSceneData;
class CullingQueries {
class FrustumCulling {
// key: hash val
culledResultIndex: Map<number, number> = new Map<number, number>();
cullingKeyResult: Map<number, CullingKey> = new Map<number, CullingKey>();
resultIndex: Map<number, FrustumCullingID> = new Map<number, FrustumCullingID>();
resultKeyIndex: Map<number, FrustumCullingKey> = new Map<number, FrustumCullingKey>();
update (): void {
this.resultIndex.clear();
this.resultKeyIndex.clear();
}
}
function isNodeVisible (node: Node, visibility: number): boolean {
@@ -80,6 +156,11 @@ function isNodeVisible (node: Node, visibility: number): boolean {
function isModelVisible (model: Model, visibility: number): boolean {
return !!(visibility & model.visFlags);
}
function isReflectProbeMask (model: Model): boolean {
return bool((model.node.layer & REFLECTION_PROBE_DEFAULT_MASK) === model.node.layer || (REFLECTION_PROBE_DEFAULT_MASK & model.visFlags));
}
const transWorldBounds = new AABB();
function isFrustumVisible (model: Model, frustum: Readonly<Frustum>, castShadow: boolean): boolean {
const modelWorldBounds = model.worldBounds;
@@ -94,31 +175,47 @@ function isFrustumVisible (model: Model, frustum: Readonly<Frustum>, castShadow:
return !intersect.aabbFrustum(transWorldBounds, frustum);
}
function isIntersectAABB (lAABB: AABB, rAABB: AABB): boolean {
return !intersect.aabbWithAABB(lAABB, rAABB);
}
function sceneCulling (
skyboxModelToSkip: Model | null,
scene: RenderScene,
camera: Camera,
camOrLightFrustum: Readonly<Frustum>,
castShadow: boolean,
probe: ReflectionProbe | null,
models: Array<Model>,
): void {
const skybox = pSceneData.skybox;
const skyboxModel = skybox.model;
const visibility = camera.visibility;
const camSkyboxFlag = camera.clearFlag & SKYBOX_FLAG;
if (!castShadow && skybox && skybox.enabled && skyboxModel && camSkyboxFlag) {
models.push(skyboxModel);
}
for (const model of scene.models) {
assert(!!model);
if (!model.enabled || model === skyboxModelToSkip || (castShadow && !model.castShadow)) {
if (!model.enabled || !model.node || (castShadow && !model.castShadow)) {
continue;
}
if (scene && scene.isCulledByLod(camera, model)) {
continue;
}
if (!probe || (probe && probe.probeType === ProbeType.CUBE)) {
if (isNodeVisible(model.node, visibility)
|| isModelVisible(model, visibility)) {
const wBounds = model.worldBounds;
// frustum culling
if (wBounds && ((!probe && isFrustumVisible(model, camOrLightFrustum, castShadow))
|| (probe && isIntersectAABB(wBounds, probe.boundingBox!)))) {
continue;
}
if (isNodeVisible(model.node, visibility)
|| isModelVisible(model, visibility)) {
// frustum culling
if (isFrustumVisible(model, camOrLightFrustum, castShadow)) {
continue;
models.push(model);
}
} else if (isReflectProbeMask(model)) {
models.push(model);
}
}
@@ -138,9 +235,10 @@ function computeSortingDepth (camera: Camera, model: Model): number {
let depth = 0;
if (model.node) {
const node = model.transform;
const tempVec3 = new Vec3();
const tempVec3 = vec3Pool.acquire();
const position = Vec3.subtract(tempVec3, node.worldPosition, camera.position);
depth = position.dot(camera.forward);
vec3Pool.release(tempVec3);
}
return depth;
}
@@ -149,17 +247,29 @@ function addRenderObject (
phaseLayoutId: number,
isDrawOpaqueOrMask: boolean,
isDrawBlend: boolean,
isDrawProbe: boolean,
camera: Camera,
model: Model,
queue: RenderQueue,
): void {
const probeQueue = queue.probeQueue;
if (isDrawProbe) {
probeQueue.applyMacro(model, phaseLayoutId);
}
const subModels = model.subModels;
const subModelCount = subModels.length;
const skyboxModel = pSceneData.skybox.model;
for (let subModelIdx = 0; subModelIdx < subModelCount; ++subModelIdx) {
const subModel = subModels[subModelIdx];
const passes = subModel.passes;
const passCount = passes.length;
const probePhase = probeQueue.probeMap.includes(subModel);
if (probePhase) phaseLayoutId = probeQueue.defaultId;
for (let passIdx = 0; passIdx < passCount; ++passIdx) {
if (model === skyboxModel && !subModelIdx && !passIdx && isDrawOpaqueOrMask) {
queue.opaqueQueue.add(model, computeSortingDepth(camera, model), subModelIdx, passIdx);
continue;
}
const pass = passes[passIdx];
// check phase
const phaseAllowed = phaseLayoutId === pass.phaseID;
@@ -180,12 +290,10 @@ function addRenderObject (
// add object to queue
if (pass.batchingScheme === BatchingSchemes.INSTANCING) {
const instancedBuffer = pass.getInstancedBuffer();
instancedBuffer.merge(subModel, passIdx);
if (is_blend) {
queue.transparentInstancingQueue.add(instancedBuffer);
queue.transparentInstancingQueue.add(pass, subModel, passIdx);
} else {
queue.opaqueInstancingQueue.add(instancedBuffer);
queue.opaqueInstancingQueue.add(pass, subModel, passIdx);
}
} else {
const depth = computeSortingDepth(camera, model);
@@ -198,30 +306,44 @@ function addRenderObject (
}
}
}
const rangedDirLightBoundingBox = new AABB(0, 0, 0, 0.5, 0.5, 0.5);
const lightAABB = new AABB();
export class SceneCulling {
sceneQueries: Map<RenderScene, CullingQueries> = new Map<RenderScene, CullingQueries>();
culledResults: Array<Array<Model>> = new Array<Array<Model>>();
frustumCullings: Map<RenderScene, FrustumCulling> = new Map<RenderScene, FrustumCulling>();
frustumCullingResults: Array<Array<Model>> = new Array<Array<Model>>();
lightBoundsCullings: Map<RenderScene, LightBoundsCulling> = new Map<RenderScene, LightBoundsCulling>();
lightBoundsCullingResults: Array<LightBoundsCullingResult> = new Array<LightBoundsCullingResult>();
renderQueues: Array<RenderQueue> = new Array<RenderQueue>();
sceneQueryIndex: Map<number, RenderQueueDesc> = new Map<number, RenderQueueDesc>();
renderQueueIndex: Map<number, RenderQueueDesc> = new Map<number, RenderQueueDesc>();
cullingPools = new CullingPools();
// source id
numCullingQueries = 0;
numFrustumCulling = 0;
numLightBoundsCulling = 0;
// target id
numRenderQueues = 0;
layoutGraph;
renderGraph;
resetPool (): void {
const cullingPools = this.cullingPools;
cullingPools.frustumCullingKeyRecycle.reset();
cullingPools.frustumCullingsRecycle.reset();
cullingPools.lightBoundsCullingRecycle.reset();
cullingPools.lightBoundsCullingResultRecycle.reset();
cullingPools.lightBoundsCullingKeyRecycle.reset();
cullingPools.renderQueueRecycle.reset();
cullingPools.renderQueueDescRecycle.reset();
instancePool.reset();
}
clear (): void {
this.sceneQueries.clear();
for (const c of this.culledResults) {
c.length = 0;
}
this.culledResults.length = 0;
for (const q of this.renderQueues) {
q.clear();
}
this.resetPool();
this.frustumCullings.clear();
this.frustumCullingResults.length = 0;
this.lightBoundsCullings.clear();
this.lightBoundsCullingResults.length = 0;
this.renderQueues.length = 0;
this.sceneQueryIndex.clear();
this.numCullingQueries = 0;
this.renderQueueIndex.clear();
this.numLightBoundsCulling = 0;
this.numFrustumCulling = 0;
this.numRenderQueues = 0;
}
@@ -230,41 +352,90 @@ export class SceneCulling {
this.renderGraph = rg;
pSceneData = pplSceneData;
this.collectCullingQueries(rg, lg);
this.batchCulling(pplSceneData);
this.batchFrustumCulling(pplSceneData);
this.batchLightBoundsCulling();
this.fillRenderQueues(rg, pplSceneData);
}
private getOrCreateSceneCullingQuery (sceneData: SceneData): number {
const scene = sceneData.scene!;
let queries = this.sceneQueries.get(scene);
if (!queries) {
this.sceneQueries.set(scene, new CullingQueries());
queries = this.sceneQueries.get(scene);
private getOrCreateLightBoundsCulling (sceneData: SceneData, frustumCullingID: FrustumCullingID): LightBoundsCullingID {
if (!(sceneData.cullingFlags & CullingFlags.LIGHT_BOUNDS)) {
return 0xFFFFFFFF; // Return an empty ID.
}
const castShadow = bool(sceneData.flags & SceneFlags.SHADOW_CASTER);
const key = computeCullingKey(sceneData.camera, sceneData.light.light, castShadow, sceneData.light.level);
const cullNum = queries!.culledResultIndex.get(key);
assert(!!sceneData.shadingLight, 'shadingLight is expected but not found.');
const scene = sceneData.scene;
assert(!!scene, 'scene is expected but not found.');
let queries = this.lightBoundsCullings.get(scene);
if (!queries) {
const cullingQuery = this.cullingPools.lightBoundsCullingRecycle.add();
cullingQuery.update();
this.lightBoundsCullings.set(scene, cullingQuery);
queries = this.lightBoundsCullings.get(scene)!;
}
const key = computeCullingKey(sceneData, false, frustumCullingID);
const cullNum = queries.resultIndex.get(key);
if (cullNum !== undefined) {
return cullNum;
}
const soureceID = this.numCullingQueries++;
if (this.numCullingQueries > this.culledResults.length) {
assert(this.numCullingQueries === (this.culledResults.length + 1));
this.culledResults.push([]);
const lightBoundsCullingID: LightBoundsCullingID = this.numLightBoundsCulling++;
if (this.numLightBoundsCulling > this.lightBoundsCullingResults.length) {
assert(this.numLightBoundsCulling === (this.lightBoundsCullingResults.length + 1));
this.lightBoundsCullingResults.push(this.cullingPools.lightBoundsCullingResultRecycle.add().update());
}
queries!.culledResultIndex.set(key, soureceID);
queries!.cullingKeyResult.set(key, new CullingKey(sceneData.camera, sceneData.light.light, castShadow, sceneData.light.level));
return soureceID;
queries.resultIndex.set(key, lightBoundsCullingID);
const cullingKey = this.cullingPools.lightBoundsCullingKeyRecycle.add();
cullingKey.update(
sceneData,
frustumCullingID,
);
queries.resultKeyIndex.set(key, cullingKey);
return lightBoundsCullingID;
}
private getOrCreateFrustumCulling (sceneId: number): number {
const sceneData: SceneData = this.renderGraph.getScene(sceneId);
const scene = sceneData.scene!;
let queries = this.frustumCullings.get(scene);
if (!queries) {
const cullingQuery = this.cullingPools.frustumCullingsRecycle.add();
cullingQuery.update();
this.frustumCullings.set(scene, cullingQuery);
queries = this.frustumCullings.get(scene)!;
}
const castShadow: boolean = bool(sceneData.flags & SceneFlags.SHADOW_CASTER);
const key = computeCullingKey(sceneData, castShadow);
const cullNum = queries.resultIndex.get(key);
if (cullNum !== undefined) {
return cullNum;
}
const frustumCulledResultID: FrustumCullingID = this.numFrustumCulling++;
if (this.numFrustumCulling > this.frustumCullingResults.length) {
assert(this.numFrustumCulling === (this.frustumCullingResults.length + 1));
this.frustumCullingResults.push([]);
}
queries.resultIndex.set(key, frustumCulledResultID);
const cullingKey = this.cullingPools.frustumCullingKeyRecycle.add();
cullingKey.update(
sceneData,
castShadow,
);
queries.resultKeyIndex.set(key, cullingKey);
return frustumCulledResultID;
}
private createRenderQueue (sceneFlags: SceneFlags, subpassOrPassLayoutID: number): number {
const targetID = this.numRenderQueues++;
if (this.numRenderQueues > this.renderQueues.length) {
assert(this.numRenderQueues === (this.renderQueues.length + 1));
this.renderQueues.push(new RenderQueue());
const renderQueue = this.cullingPools.renderQueueRecycle.add();
renderQueue.update();
this.renderQueues.push(renderQueue);
}
assert(targetID < this.renderQueues.length);
const rq = this.renderQueues[targetID];
assert(rq.empty());
assert(rq.sceneFlags === SceneFlags.NONE);
assert(rq.subpassOrPassLayoutID === 0xFFFFFFFF);
rq.sceneFlags = sceneFlags;
rq.subpassOrPassLayoutID = subpassOrPassLayoutID;
return targetID;
@@ -280,13 +451,16 @@ export class SceneCulling {
assert(!!sceneData.scene);
continue;
}
const sourceID = this.getOrCreateSceneCullingQuery(sceneData);
const layoutID = getSubpassOrPassID(v, rg, lg);
const frustumCulledResultID = this.getOrCreateFrustumCulling(v);
const lightBoundsCullingID = this.getOrCreateLightBoundsCulling(sceneData, frustumCulledResultID);
const layoutID: number = getSubpassOrPassID(v, rg, lg);
const targetID = this.createRenderQueue(sceneData.flags, layoutID);
const lightType = sceneData.light.light ? sceneData.light.light.type : LightType.UNKNOWN;
const renderQueueDesc = this.cullingPools.renderQueueDescRecycle.add();
renderQueueDesc.update(frustumCulledResultID, lightBoundsCullingID, targetID, lightType);
// add render queue to query source
this.sceneQueryIndex.set(v, new RenderQueueDesc(sourceID, targetID, lightType));
this.renderQueueIndex.set(v, renderQueueDesc);
}
}
@@ -299,69 +473,179 @@ export class SceneCulling {
}
}
private batchCulling (pplSceneData: PipelineSceneData): void {
const skybox = pplSceneData.skybox;
const skyboxModelToSkip = skybox ? skybox.model : null;
for (const [scene, queries] of this.sceneQueries) {
private _getPhaseIdFromScene (scene: number): number {
const rg: RenderGraph = this.renderGraph;
const renderQueueId = rg.getParent(scene);
assert(rg.holds(RenderGraphValue.Queue, renderQueueId));
const graphRenderQueue = rg.getQueue(renderQueueId);
return graphRenderQueue.phaseID;
}
private getBuiltinShadowFrustum (pplSceneData: PipelineSceneData, camera: Camera, mainLight: DirectionalLight, level: number): Readonly<Frustum> {
const csmLayers = pplSceneData.csmLayers;
const csmLevel = mainLight.csmLevel;
let frustum: Readonly<Frustum>;
const shadows = pplSceneData.shadows;
if (shadows.type === ShadowType.Planar) {
return camera.frustum;
}
if (shadows.enabled && shadows.type === ShadowType.ShadowMap && mainLight && mainLight.node) {
// pplSceneData.updateShadowUBORange(UBOShadow.SHADOW_COLOR_OFFSET, shadows.shadowColor);
csmLayers.update(pplSceneData, camera);
}
if (mainLight.shadowFixedArea || csmLevel === CSMLevel.LEVEL_1) {
return csmLayers.specialLayer.validFrustum;
}
return csmLayers.layers[level].validFrustum;
}
private batchFrustumCulling (pplSceneData: PipelineSceneData): void {
for (const [scene, queries] of this.frustumCullings) {
assert(!!scene);
for (const [key, sourceID] of queries.culledResultIndex) {
const cullingKey = queries.cullingKeyResult.get(key)!;
assert(!!cullingKey.camera);
assert(cullingKey.camera.scene === scene);
const camera = cullingKey.camera;
const light = cullingKey.light;
const level = cullingKey.lightLevel;
for (const [key, frustomCulledResultID] of queries.resultIndex) {
const cullingKey = queries.resultKeyIndex.get(key)!;
const sceneData = cullingKey.sceneData!;
assert(!!sceneData.camera);
assert(sceneData.camera.scene === scene);
const light = sceneData.light.light;
const level = sceneData.light.level;
const castShadow = cullingKey.castShadows;
assert(sourceID < this.culledResults.length);
const models = this.culledResults[sourceID];
const probe = sceneData.light.probe;
const camera = probe ? probe.camera : sceneData.camera;
assert(frustomCulledResultID < this.frustumCullingResults.length);
const models = this.frustumCullingResults[frustomCulledResultID];
if (probe) {
sceneCulling(scene, camera, camera.frustum, castShadow, probe, models);
continue;
}
if (light) {
switch (light.type) {
case LightType.SPOT:
sceneCulling(skyboxModelToSkip, scene, camera, (light as SpotLight).frustum, castShadow, models);
sceneCulling(scene, camera, (light as SpotLight).frustum, castShadow, null, models);
break;
case LightType.DIRECTIONAL: {
const csmLayers = pplSceneData.csmLayers;
const mainLight: DirectionalLight = light as DirectionalLight;
const csmLevel = mainLight.csmLevel;
let frustum: Readonly<Frustum>;
const shadows = pplSceneData.shadows;
if (shadows.type === ShadowType.Planar) {
frustum = camera.frustum;
} else {
if (shadows.enabled && shadows.type === ShadowType.ShadowMap && mainLight && mainLight.node) {
// pplSceneData.updateShadowUBORange(UBOShadow.SHADOW_COLOR_OFFSET, shadows.shadowColor);
csmLayers.update(pplSceneData, camera);
}
if (mainLight.shadowFixedArea || csmLevel === CSMLevel.LEVEL_1) {
frustum = csmLayers.specialLayer.validFrustum;
} else {
frustum = csmLayers.layers[level].validFrustum;
}
}
sceneCulling(skyboxModelToSkip, scene, camera, frustum, castShadow, models);
const frustum = this.getBuiltinShadowFrustum(pplSceneData, camera, light as DirectionalLight, level);
sceneCulling(scene, camera, frustum, castShadow, null, models);
}
break;
default:
}
} else {
sceneCulling(skyboxModelToSkip, scene, camera, camera.frustum, castShadow, models);
sceneCulling(scene, camera, camera.frustum, castShadow, null, models);
}
}
}
}
private executeSphereLightCulling (light: SphereLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
const lightAABB = light.aabb;
for (const model of frustumCullingResult) {
assert(!!model);
const modelBounds = model.worldBounds;
if (!modelBounds || intersect.aabbWithAABB(modelBounds, lightAABB)) {
lightBoundsCullingResult.push(model);
}
}
}
private executeSpotLightCulling (light: SpotLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
const lightAABB = light.aabb;
const lightFrustum: Frustum = light.frustum;
for (const model of frustumCullingResult) {
assert(!!model);
const modelBounds = model.worldBounds;
if (!modelBounds || (intersect.aabbWithAABB(lightAABB, modelBounds) && intersect.aabbFrustum(modelBounds, lightFrustum))) {
lightBoundsCullingResult.push(model);
}
}
}
private executePointLightCulling (light: PointLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
const lightAABB = light.aabb;
for (const model of frustumCullingResult) {
assert(!!model);
const modelBounds = model.worldBounds;
if (!modelBounds || intersect.aabbWithAABB(lightAABB, modelBounds)) {
lightBoundsCullingResult.push(model);
}
}
}
private executeRangedDirectionalLightCulling (
light: RangedDirectionalLight,
frustumCullingResult: Array<Model>,
lightBoundsCullingResult: Array<Model>,
): void {
rangedDirLightBoundingBox.transform(light.node!.worldMatrix, null, null, null, lightAABB);
for (const model of frustumCullingResult) {
assert(!!model);
const modelBounds = model.worldBounds;
if (!modelBounds || intersect.aabbWithAABB(lightAABB, modelBounds)) {
lightBoundsCullingResult.push(model);
}
}
}
private batchLightBoundsCulling (): void {
for (const [scene, queries] of this.lightBoundsCullings) {
assert(!!scene);
for (const [key, cullingID] of queries.resultIndex) {
const cullingKey = queries.resultKeyIndex.get(key)!;
const sceneData = cullingKey.sceneData!;
const frustumCullingID = cullingKey.frustumCullingID;
const frustumCullingResult = this.frustumCullingResults[frustumCullingID];
assert(!!sceneData.camera);
assert(!!sceneData.shadingLight);
assert(sceneData.camera.scene === scene);
assert(cullingID < this.frustumCullingResults.length);
const lightBoundsCullingResult = this.lightBoundsCullingResults[cullingID];
assert(lightBoundsCullingResult.instances.length === 0);
switch (sceneData.shadingLight.type) {
case LightType.SPHERE:
{
const light = sceneData.shadingLight as SphereLight;
this.executeSphereLightCulling(light, frustumCullingResult, lightBoundsCullingResult.instances);
}
break;
case LightType.SPOT:
{
const light = sceneData.shadingLight as SpotLight;
this.executeSpotLightCulling(light, frustumCullingResult, lightBoundsCullingResult.instances);
}
break;
case LightType.POINT:
{
const light = sceneData.shadingLight as PointLight;
this.executePointLightCulling(light, frustumCullingResult, lightBoundsCullingResult.instances);
}
break;
case LightType.RANGED_DIRECTIONAL:
{
const light = sceneData.shadingLight as RangedDirectionalLight;
this.executeRangedDirectionalLightCulling(light, frustumCullingResult, lightBoundsCullingResult.instances);
}
break;
case LightType.DIRECTIONAL:
case LightType.UNKNOWN:
default:
}
}
}
}
private fillRenderQueues (rg: RenderGraph, pplSceneData: PipelineSceneData): void {
const skybox = pplSceneData.skybox;
for (const [sceneId, desc] of this.sceneQueryIndex) {
for (const [sceneId, desc] of this.renderQueueIndex) {
assert(rg.holds(RenderGraphValue.Scene, sceneId));
const sourceId = desc.culledSource;
const frustomCulledResultID = desc.frustumCulledResultID;
const lightBoundsCullingID = desc.lightBoundsCulledResultID;
const targetId = desc.renderQueueTarget;
const sceneData = rg.getScene(sceneId);
const isDrawBlend = bool(sceneData.flags & SceneFlags.TRANSPARENT_OBJECT);
const isDrawOpaqueOrMask = bool(sceneData.flags & (SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT));
const isDrawShadowCaster = bool(sceneData.flags & SceneFlags.SHADOW_CASTER);
if (!isDrawShadowCaster && !isDrawBlend && !isDrawOpaqueOrMask) {
const isDrawBlend: boolean = bool(sceneData.flags & SceneFlags.TRANSPARENT_OBJECT);
const isDrawOpaqueOrMask: boolean = bool(sceneData.flags & (SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT));
const isDrawShadowCaster: boolean = bool(sceneData.flags & SceneFlags.SHADOW_CASTER);
const isDrawProbe: boolean = bool(sceneData.flags & SceneFlags.REFLECTION_PROBE);
if (!isDrawShadowCaster && !isDrawBlend && !isDrawOpaqueOrMask && !isDrawProbe) {
continue;
}
// render queue info
@@ -372,8 +656,23 @@ export class SceneCulling {
assert(phaseLayoutId !== this.layoutGraph.nullVertex());
// culling source
assert(sourceId < this.culledResults.length);
const sourceModels = this.culledResults[sourceId];
assert(frustomCulledResultID < this.frustumCullingResults.length);
const sourceModels = ((): Array<Model> => {
// is culled by light bounds
if (lightBoundsCullingID !== 0xFFFFFFFF) {
if (lightBoundsCullingID < this.lightBoundsCullingResults.length) {
return this.lightBoundsCullingResults[lightBoundsCullingID].instances;
} else {
return [];
}
}
// not culled by light bounds
if (frustomCulledResultID < this.frustumCullingResults.length) {
return this.frustumCullingResults[frustomCulledResultID];
} else {
return [];
}
})();
// queue target
assert(targetId < this.renderQueues.length);
@@ -383,27 +682,13 @@ export class SceneCulling {
// skybox
const camera = sceneData.camera;
assert(!!camera);
if (!bool(sceneData.flags & SceneFlags.SHADOW_CASTER)
&& skybox && skybox.enabled
&& (camera.clearFlag & SKYBOX_FLAG)) {
assert(!!skybox.model);
const model = skybox.model;
const node = model.node;
let depth = 0;
if (node) {
const tempVec3 = new Vec3();
Vec3.subtract(tempVec3, node.worldPosition, camera.position);
depth = tempVec3.dot(camera.forward);
}
renderQueue.opaqueQueue.add(model, depth, 0, 0);
}
// fill render queue
for (const model of sourceModels) {
addRenderObject(
phaseLayoutId,
isDrawOpaqueOrMask,
isDrawBlend,
isDrawProbe,
camera,
model,
renderQueue,
@@ -414,3 +699,165 @@ export class SceneCulling {
}
}
}
export class LightResource {
private cpuBuffer!: Float32Array;
private programLibrary?: WebProgramLibrary;
private device: Device | null = null;
private elementSize: number = 0;
private maxNumLights: number = 16;
private binding: number = 0xFFFFFFFF;
private resized: boolean = false;
private lightBuffer?: Buffer;
private firstLightBufferView: Buffer | null = null;
private lights: Array<Light | null> = [];
private lightIndex: Map<Light | null, number> = new Map();
init (programLib: WebProgramLibrary, deviceIn: Device, maxNumLights: number): void {
assert(!this.device);
this.device = deviceIn;
this.programLibrary = programLib;
const instanceLayout = this.programLibrary.localLayoutData;
const attrID: number = programLib.layoutGraph.attributeIndex.get('CCForwardLight')!;
const uniformBlock = instanceLayout.uniformBlocks.get(attrID);
this.elementSize = AlignUp(
getUniformBlockSize(uniformBlock!.members),
this.device.capabilities.uboOffsetAlignment,
);
this.maxNumLights = maxNumLights;
this.binding = programLib.localLayoutData.bindingMap.get(attrID)!;
const bufferSize = this.elementSize * this.maxNumLights;
this.lightBuffer = this.device.createBuffer(new BufferInfo(
BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST,
MemoryUsageBit.HOST | MemoryUsageBit.DEVICE,
bufferSize,
this.elementSize,
));
this.firstLightBufferView = this.device.createBuffer(new BufferViewInfo(
this.lightBuffer,
0,
this.elementSize,
));
this.cpuBuffer = new Float32Array(bufferSize / Float32Array.BYTES_PER_ELEMENT);
this.lights = new Array<Light | null>(this.maxNumLights);
this.lightIndex = new Map<Light | null, number>();
assert(!!(this.elementSize && this.maxNumLights));
this.resized = true;
}
buildLights (sceneCulling: SceneCulling, bHDR: boolean, shadowInfo: Shadows | null): void {
// Build light buffer
for (const [scene, lightBoundsCullings] of sceneCulling.lightBoundsCullings) {
for (const [key, lightBoundsCullingID] of lightBoundsCullings.resultIndex) {
const lightBoundsCulling = lightBoundsCullings.resultKeyIndex.get(key)!;
const sceneData = lightBoundsCulling.sceneData!;
let exposure: number = 1.0;
if (sceneData.camera) {
exposure = sceneData.camera.exposure;
} else if (sceneData.light.probe && sceneData.light.probe.camera) {
exposure = sceneData.light.probe.camera.exposure;
} else {
throw new Error('Unexpected situation: No camera or probe found.');
}
const lightByteOffset: number = this.addLight(
sceneData.shadingLight!,
bHDR,
exposure,
shadowInfo,
);
// Save light byte offset for each light bounds culling
const result: LightBoundsCullingResult = sceneCulling.lightBoundsCullingResults[lightBoundsCullingID];
result.lightByteOffset = lightByteOffset;
}
}
// Assign light byte offset to each queue
for (const [sceneID, desc] of sceneCulling.renderQueueIndex) {
if (desc.lightBoundsCulledResultID === 0xFFFFFFFF) {
continue;
}
const lightByteOffset: number = sceneCulling.lightBoundsCullingResults[desc.lightBoundsCulledResultID].lightByteOffset;
sceneCulling.renderQueues[desc.renderQueueTarget].lightByteOffset = lightByteOffset;
}
}
tryUpdateRenderSceneLocalDescriptorSet (sceneCulling: SceneCulling): void {
if (!this.resized || !sceneCulling.lightBoundsCullings.size) {
return;
}
for (const [scene, culling] of sceneCulling.frustumCullings) {
for (const model of scene.models) {
if (!model) {
throw new Error('Unexpected null model.');
}
for (const submodel of model.subModels) {
const set = submodel.descriptorSet;
set.bindBuffer(this.binding, this.firstLightBufferView!);
set.update();
}
}
}
this.resized = false;
}
clear (): void {
this.cpuBuffer.fill(0);
this.lights.length = 0;
this.lightIndex.clear();
}
addLight (light: Light, bHDR: boolean, exposure: number, shadowInfo: Shadows | null): number {
// Already added
const existingLightID = this.lightIndex.get(light);
if (existingLightID !== undefined) {
return existingLightID;
}
// Resize buffer if needed
if (this.lights.length === this.maxNumLights) {
this.resized = true;
this.maxNumLights *= 2;
const bufferSize = this.elementSize * this.maxNumLights;
this.lightBuffer!.resize(bufferSize);
this.firstLightBufferView = this.device!.createBuffer(new BufferViewInfo(
this.lightBuffer,
0,
this.elementSize,
));
this.cpuBuffer = new Float32Array(bufferSize / Float32Array.BYTES_PER_ELEMENT);
this.lights = new Array<Light | null>(this.maxNumLights);
this.lightIndex = new Map<Light | null, number>();
}
assert(this.lights.length < this.maxNumLights);
// Add light
const lightID = this.lights.length;
this.lights[lightID] = light;
this.lightIndex.set(light, lightID);
// Update buffer
const offset = this.elementSize / Float32Array.BYTES_PER_ELEMENT * lightID;
SetLightUBO(light, bHDR, exposure, shadowInfo, this.cpuBuffer, offset, this.elementSize);
return lightID * this.elementSize;
}
buildLightBuffer (cmdBuffer: CommandBuffer): void {
cmdBuffer.updateBuffer(
this.lightBuffer!,
this.cpuBuffer,
(this.lights.length * this.elementSize) / Float32Array.BYTES_PER_ELEMENT,
);
}
}
+273 -1
View File
@@ -29,9 +29,11 @@
*/
/* eslint-disable max-len */
import { ResolveMode, ShaderStageFlagBit, Type, UniformBlock } from '../../gfx';
import { ReflectionProbe } from '../../render-scene/scene/reflection-probe';
import { Light } from '../../render-scene/scene';
import { OutputArchive, InputArchive } from './archive';
import { saveUniformBlock, loadUniformBlock } from './serialization';
import { RecyclePool } from '../../core/memop';
export enum UpdateFrequency {
PER_INSTANCE,
@@ -208,6 +210,7 @@ export enum SceneFlags {
DRAW_NON_INSTANCING = 0x1000,
REFLECTION_PROBE = 0x2000,
GPU_DRIVEN = 0x4000,
NON_BUILTIN = 0x8000,
ALL = 0xFFFFFFFF,
}
@@ -288,12 +291,20 @@ export function getClearValueTypeName (e: ClearValueType): string {
}
export class LightInfo {
constructor (light: Light | null = null, level = 0, culledByLight = false) {
constructor (light: Light | null = null, level = 0, culledByLight = false, probe: ReflectionProbe | null = null) {
this.light = light;
this.probe = probe;
this.level = level;
this.culledByLight = culledByLight;
}
reset (light: Light | null = null, level = 0, culledByLight = false, probe: ReflectionProbe | null = null): void {
this.light = light;
this.probe = probe;
this.level = level;
this.culledByLight = culledByLight;
}
/*refcount*/ light: Light | null;
/*pointer*/ probe: ReflectionProbe | null;
level: number;
culledByLight: boolean;
}
@@ -339,11 +350,21 @@ export class Descriptor {
constructor (type: Type = Type.UNKNOWN) {
this.type = type;
}
reset (type: Type = Type.UNKNOWN): void {
this.type = type;
this.count = 1;
}
type: Type;
count = 1;
}
export class DescriptorBlock {
reset (): void {
this.descriptors.clear();
this.uniformBlocks.clear();
this.capacity = 0;
this.count = 0;
}
readonly descriptors: Map<string, Descriptor> = new Map<string, Descriptor>();
readonly uniformBlocks: Map<string, UniformBlock> = new Map<string, UniformBlock>();
capacity = 0;
@@ -351,6 +372,14 @@ export class DescriptorBlock {
}
export class DescriptorBlockFlattened {
reset (): void {
this.descriptorNames.length = 0;
this.uniformBlockNames.length = 0;
this.descriptors.length = 0;
this.uniformBlocks.length = 0;
this.capacity = 0;
this.count = 0;
}
readonly descriptorNames: string[] = [];
readonly uniformBlockNames: string[] = [];
readonly descriptors: Descriptor[] = [];
@@ -393,6 +422,19 @@ export class ResolvePair {
this.mode = mode;
this.mode1 = mode1;
}
reset (
source = '',
target = '',
resolveFlags: ResolveFlags = ResolveFlags.NONE,
mode: ResolveMode = ResolveMode.SAMPLE_ZERO,
mode1: ResolveMode = ResolveMode.SAMPLE_ZERO,
): void {
this.source = source;
this.target = target;
this.resolveFlags = resolveFlags;
this.mode = mode;
this.mode1 = mode1;
}
source: string;
target: string;
resolveFlags: ResolveFlags;
@@ -424,6 +466,29 @@ export class CopyPair {
this.targetFirstSlice = targetFirstSlice;
this.targetPlaneSlice = targetPlaneSlice;
}
reset (
source = '',
target = '',
mipLevels = 0xFFFFFFFF,
numSlices = 0xFFFFFFFF,
sourceMostDetailedMip = 0,
sourceFirstSlice = 0,
sourcePlaneSlice = 0,
targetMostDetailedMip = 0,
targetFirstSlice = 0,
targetPlaneSlice = 0,
): void {
this.source = source;
this.target = target;
this.mipLevels = mipLevels;
this.numSlices = numSlices;
this.sourceMostDetailedMip = sourceMostDetailedMip;
this.sourceFirstSlice = sourceFirstSlice;
this.sourcePlaneSlice = sourcePlaneSlice;
this.targetMostDetailedMip = targetMostDetailedMip;
this.targetFirstSlice = targetFirstSlice;
this.targetPlaneSlice = targetPlaneSlice;
}
source: string;
target: string;
mipLevels: number;
@@ -454,6 +519,22 @@ export class UploadPair {
this.targetFirstSlice = targetFirstSlice;
this.targetPlaneSlice = targetPlaneSlice;
}
reset (
target = '',
mipLevels = 0xFFFFFFFF,
numSlices = 0xFFFFFFFF,
targetMostDetailedMip = 0,
targetFirstSlice = 0,
targetPlaneSlice = 0,
): void {
// source: Uint8Array size unchanged
this.target = target;
this.mipLevels = mipLevels;
this.numSlices = numSlices;
this.targetMostDetailedMip = targetMostDetailedMip;
this.targetFirstSlice = targetFirstSlice;
this.targetPlaneSlice = targetPlaneSlice;
}
readonly source: Uint8Array;
target: string;
mipLevels: number;
@@ -481,6 +562,23 @@ export class MovePair {
this.targetFirstSlice = targetFirstSlice;
this.targetPlaneSlice = targetPlaneSlice;
}
reset (
source = '',
target = '',
mipLevels = 0xFFFFFFFF,
numSlices = 0xFFFFFFFF,
targetMostDetailedMip = 0,
targetFirstSlice = 0,
targetPlaneSlice = 0,
): void {
this.source = source;
this.target = target;
this.mipLevels = mipLevels;
this.numSlices = numSlices;
this.targetMostDetailedMip = targetMostDetailedMip;
this.targetFirstSlice = targetFirstSlice;
this.targetPlaneSlice = targetPlaneSlice;
}
source: string;
target: string;
mipLevels: number;
@@ -491,6 +589,19 @@ export class MovePair {
}
export class PipelineStatistics {
reset (): void {
this.numRenderPasses = 0;
this.numManagedTextures = 0;
this.totalManagedTextures = 0;
this.numUploadBuffers = 0;
this.numUploadBufferViews = 0;
this.numFreeUploadBuffers = 0;
this.numFreeUploadBufferViews = 0;
this.numDescriptorSets = 0;
this.numFreeDescriptorSets = 0;
this.numInstancingBuffers = 0;
this.numInstancingUniformBlocks = 0;
}
numRenderPasses = 0;
numManagedTextures = 0;
totalManagedTextures = 0;
@@ -504,14 +615,175 @@ export class PipelineStatistics {
numInstancingUniformBlocks = 0;
}
export class RenderCommonObjectPoolSettings {
constructor (batchSize: number) {
this.lightInfoBatchSize = batchSize;
this.descriptorBatchSize = batchSize;
this.descriptorBlockBatchSize = batchSize;
this.descriptorBlockFlattenedBatchSize = batchSize;
this.descriptorBlockIndexBatchSize = batchSize;
this.resolvePairBatchSize = batchSize;
this.copyPairBatchSize = batchSize;
this.uploadPairBatchSize = batchSize;
this.movePairBatchSize = batchSize;
this.pipelineStatisticsBatchSize = batchSize;
}
lightInfoBatchSize = 16;
descriptorBatchSize = 16;
descriptorBlockBatchSize = 16;
descriptorBlockFlattenedBatchSize = 16;
descriptorBlockIndexBatchSize = 16;
resolvePairBatchSize = 16;
copyPairBatchSize = 16;
uploadPairBatchSize = 16;
movePairBatchSize = 16;
pipelineStatisticsBatchSize = 16;
}
export class RenderCommonObjectPool {
constructor (settings: RenderCommonObjectPoolSettings) {
this._lightInfo = new RecyclePool<LightInfo>(() => new LightInfo(), settings.lightInfoBatchSize);
this._descriptor = new RecyclePool<Descriptor>(() => new Descriptor(), settings.descriptorBatchSize);
this._descriptorBlock = new RecyclePool<DescriptorBlock>(() => new DescriptorBlock(), settings.descriptorBlockBatchSize);
this._descriptorBlockFlattened = new RecyclePool<DescriptorBlockFlattened>(() => new DescriptorBlockFlattened(), settings.descriptorBlockFlattenedBatchSize);
this._descriptorBlockIndex = new RecyclePool<DescriptorBlockIndex>(() => new DescriptorBlockIndex(), settings.descriptorBlockIndexBatchSize);
this._resolvePair = new RecyclePool<ResolvePair>(() => new ResolvePair(), settings.resolvePairBatchSize);
this._copyPair = new RecyclePool<CopyPair>(() => new CopyPair(), settings.copyPairBatchSize);
this._uploadPair = new RecyclePool<UploadPair>(() => new UploadPair(), settings.uploadPairBatchSize);
this._movePair = new RecyclePool<MovePair>(() => new MovePair(), settings.movePairBatchSize);
this._pipelineStatistics = new RecyclePool<PipelineStatistics>(() => new PipelineStatistics(), settings.pipelineStatisticsBatchSize);
}
reset (): void {
this._lightInfo.reset();
this._descriptor.reset();
this._descriptorBlock.reset();
this._descriptorBlockFlattened.reset();
this._descriptorBlockIndex.reset();
this._resolvePair.reset();
this._copyPair.reset();
this._uploadPair.reset();
this._movePair.reset();
this._pipelineStatistics.reset();
}
createLightInfo (
light: Light | null = null,
level = 0,
culledByLight = false,
probe: ReflectionProbe | null = null,
): LightInfo {
const v = this._lightInfo.add();
v.reset(light, level, culledByLight, probe);
return v;
}
createDescriptor (
type: Type = Type.UNKNOWN,
): Descriptor {
const v = this._descriptor.add();
v.reset(type);
return v;
}
createDescriptorBlock (): DescriptorBlock {
const v = this._descriptorBlock.add();
v.reset();
return v;
}
createDescriptorBlockFlattened (): DescriptorBlockFlattened {
const v = this._descriptorBlockFlattened.add();
v.reset();
return v;
}
createDescriptorBlockIndex (
updateFrequency: UpdateFrequency = UpdateFrequency.PER_INSTANCE,
parameterType: ParameterType = ParameterType.CONSTANTS,
descriptorType: DescriptorTypeOrder = DescriptorTypeOrder.UNIFORM_BUFFER,
visibility: ShaderStageFlagBit = ShaderStageFlagBit.NONE,
): DescriptorBlockIndex {
const v = this._descriptorBlockIndex.add();
v.updateFrequency = updateFrequency;
v.parameterType = parameterType;
v.descriptorType = descriptorType;
v.visibility = visibility;
return v;
}
createResolvePair (
source = '',
target = '',
resolveFlags: ResolveFlags = ResolveFlags.NONE,
mode: ResolveMode = ResolveMode.SAMPLE_ZERO,
mode1: ResolveMode = ResolveMode.SAMPLE_ZERO,
): ResolvePair {
const v = this._resolvePair.add();
v.reset(source, target, resolveFlags, mode, mode1);
return v;
}
createCopyPair (
source = '',
target = '',
mipLevels = 0xFFFFFFFF,
numSlices = 0xFFFFFFFF,
sourceMostDetailedMip = 0,
sourceFirstSlice = 0,
sourcePlaneSlice = 0,
targetMostDetailedMip = 0,
targetFirstSlice = 0,
targetPlaneSlice = 0,
): CopyPair {
const v = this._copyPair.add();
v.reset(source, target, mipLevels, numSlices, sourceMostDetailedMip, sourceFirstSlice, sourcePlaneSlice, targetMostDetailedMip, targetFirstSlice, targetPlaneSlice);
return v;
}
createUploadPair (
target = '',
mipLevels = 0xFFFFFFFF,
numSlices = 0xFFFFFFFF,
targetMostDetailedMip = 0,
targetFirstSlice = 0,
targetPlaneSlice = 0,
): UploadPair {
const v = this._uploadPair.add();
v.reset(target, mipLevels, numSlices, targetMostDetailedMip, targetFirstSlice, targetPlaneSlice);
return v;
}
createMovePair (
source = '',
target = '',
mipLevels = 0xFFFFFFFF,
numSlices = 0xFFFFFFFF,
targetMostDetailedMip = 0,
targetFirstSlice = 0,
targetPlaneSlice = 0,
): MovePair {
const v = this._movePair.add();
v.reset(source, target, mipLevels, numSlices, targetMostDetailedMip, targetFirstSlice, targetPlaneSlice);
return v;
}
createPipelineStatistics (): PipelineStatistics {
const v = this._pipelineStatistics.add();
v.reset();
return v;
}
private readonly _lightInfo: RecyclePool<LightInfo>;
private readonly _descriptor: RecyclePool<Descriptor>;
private readonly _descriptorBlock: RecyclePool<DescriptorBlock>;
private readonly _descriptorBlockFlattened: RecyclePool<DescriptorBlockFlattened>;
private readonly _descriptorBlockIndex: RecyclePool<DescriptorBlockIndex>;
private readonly _resolvePair: RecyclePool<ResolvePair>;
private readonly _copyPair: RecyclePool<CopyPair>;
private readonly _uploadPair: RecyclePool<UploadPair>;
private readonly _movePair: RecyclePool<MovePair>;
private readonly _pipelineStatistics: RecyclePool<PipelineStatistics>;
}
export function saveLightInfo (ar: OutputArchive, v: LightInfo): void {
// skip, v.light: Light
// skip, v.probe: ReflectionProbe
ar.writeNumber(v.level);
ar.writeBool(v.culledByLight);
}
export function loadLightInfo (ar: InputArchive, v: LightInfo): void {
// skip, v.light: Light
// skip, v.probe: ReflectionProbe
v.level = ar.readNumber();
v.culledByLight = ar.readBool();
}
+30
View File
@@ -118,3 +118,33 @@ export function getUBOTypeCount (type: Type): number {
return 0;
}
}
export class ObjectPool<T, U extends any[]> {
// Array to store objects in the pool
private pool: T[] = [];
// Function to create new objects
private createFunction: (...args: U) => T;
// Constructor, takes a function to create objects as parameter
constructor (createFunction: (...args: U) => T) {
this.createFunction = createFunction;
}
// Get object from the pool, either take from the pool if available or create a new one
acquire (...args: U): T {
if (this.pool.length > 0) {
return this.pool.pop()!;
}
return this.createFunction(...args);
}
// Put the object back into the pool for later reuse
release (obj: T): void {
// Push the object to the end of the pool
if (!this.pool.includes(obj)) {
this.pool.push(obj);
}
}
create (...args: U): T {
return this.createFunction(...args);
}
}
+202 -37
View File
@@ -1,6 +1,8 @@
import { RecyclePool, assert, cclegacy } from '../../core';
import { CommandBuffer, DescriptorSet, Device, PipelineState, RenderPass, deviceManager } from '../../gfx';
import { RenderScene } from '../../render-scene';
import { Camera, Light, LightType, Model, SubModel } from '../../render-scene/scene';
import { IMacroPatch, Pass } from '../../render-scene';
import { LightType, Model, SubModel } from '../../render-scene/scene';
import { SetIndex } from '../define';
import { InstancedBuffer } from '../instanced-buffer';
import { PipelineStateManager } from '../pipeline-state-manager';
@@ -29,11 +31,108 @@ export class DrawInstance {
this.shaderID = shaderID;
this.passIndex = passIndex;
}
update (
subModel: SubModel | null = null,
priority = 0,
hash = 0,
depth = 0,
shaderID = 0,
passIndex = 0,
): void {
this.subModel = subModel;
this.priority = priority;
this.hash = hash;
this.depth = depth;
this.shaderID = shaderID;
this.passIndex = passIndex;
}
}
export const instancePool = new RecyclePool(() => new DrawInstance(), 8);
const CC_USE_RGBE_OUTPUT = 'CC_USE_RGBE_OUTPUT';
function getLayoutId (passLayout: string, phaseLayout: string): number {
const r = cclegacy.rendering;
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return r.getPhaseID(r.getPassID(passLayout), phaseLayout);
}
function getPassIndexFromLayout (subModel: SubModel, phaseLayoutId: number): number {
const passes = subModel.passes;
for (let k = 0; k < passes.length; k++) {
if ((passes[k].phaseID === phaseLayoutId)) {
return k;
}
}
return -1;
}
export class ProbeHelperQueue {
probeMap: Array<SubModel> = new Array<SubModel>();
defaultId: number = getLayoutId('default', 'default');
clear (): void {
this.probeMap.length = 0;
}
removeMacro (): void {
for (const subModel of this.probeMap) {
let patches: IMacroPatch[] = [];
patches = patches.concat(subModel.patches!);
if (!patches.length) continue;
for (let j = 0; j < patches.length; j++) {
const patch = patches[j];
if (patch.name === CC_USE_RGBE_OUTPUT) {
patches.splice(j, 1);
break;
}
}
subModel.onMacroPatchesStateChanged(patches);
}
}
applyMacro (model: Model, probeLayoutId: number): void {
const subModels = model.subModels;
for (let j = 0; j < subModels.length; j++) {
const subModel: SubModel = subModels[j];
//Filter transparent objects
const isTransparent = subModel.passes[0].blendState.targets[0].blend;
if (isTransparent) {
continue;
}
let passIdx = getPassIndexFromLayout(subModel, probeLayoutId);
let bUseReflectPass = true;
if (passIdx < 0) {
probeLayoutId = this.defaultId;
passIdx = getPassIndexFromLayout(subModel, probeLayoutId);
bUseReflectPass = false;
}
if (passIdx < 0) { continue; }
if (!bUseReflectPass) {
let patches: IMacroPatch[] = [];
patches = patches.concat(subModel.patches!);
const useRGBEPatchs: IMacroPatch[] = [
{ name: CC_USE_RGBE_OUTPUT, value: true },
];
patches = patches.concat(useRGBEPatchs);
subModel.onMacroPatchesStateChanged(patches);
this.probeMap.push(subModel);
}
}
}
}
export class RenderDrawQueue {
instances: Array<DrawInstance> = new Array<DrawInstance>();
empty (): boolean {
return this.instances.length === 0;
}
clear (): void {
this.instances.length = 0;
}
add (model: Model, depth: number, subModelIdx: number, passIdx: number): void {
const subModel = model.subModels[subModelIdx];
const pass = subModel.passes[passIdx];
@@ -42,8 +141,9 @@ export class RenderDrawQueue {
const shaderId = subModel.shaders[passIdx].typedID;
const hash = (0 << 30) | (passPriority as number << 16) | (modelPriority as number << 8) | passIdx;
const priority = model.priority;
this.instances.push(new DrawInstance(subModel, priority, hash, depth, shaderId, passIdx));
const instance = instancePool.add();
instance.update(subModel, priority, hash, depth, shaderId, passIdx);
this.instances.push(instance);
}
/**
* @en Comparison sorting function. Opaque objects are sorted by priority -> depth front to back -> shader ID.
@@ -83,6 +183,9 @@ export class RenderDrawQueue {
device: Device,
renderPass: RenderPass,
cmdBuffer: CommandBuffer,
ds: DescriptorSet | null = null,
offset = 0,
dynamicOffsets: number[] | null = null,
): void {
for (const instance of this.instances) {
const subModel = instance.subModel!;
@@ -95,7 +198,17 @@ export class RenderDrawQueue {
cmdBuffer.bindPipelineState(pso);
cmdBuffer.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
cmdBuffer.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet);
if (ds) {
cmdBuffer.bindDescriptorSet(SetIndex.GLOBAL, ds, [offset]);
}
if (dynamicOffsets) {
cmdBuffer.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet, dynamicOffsets);
} else {
cmdBuffer.bindDescriptorSet(
SetIndex.LOCAL,
subModel.descriptorSet,
);
}
cmdBuffer.bindInputAssembler(inputAssembler);
cmdBuffer.draw(inputAssembler);
}
@@ -103,19 +216,59 @@ export class RenderDrawQueue {
}
export class RenderInstancingQueue {
batches: Set<InstancedBuffer> = new Set<InstancedBuffer>();
passInstances: Map<Pass, number> = new Map<Pass, number>();
instanceBuffers: Array<InstancedBuffer> = new Array<InstancedBuffer>();
sortedBatches: Array<InstancedBuffer> = new Array<InstancedBuffer>();
add (instancedBuffer: InstancedBuffer): void {
this.batches.add(instancedBuffer);
empty (): boolean {
return this.passInstances.size === 0;
}
add (pass: Pass, subModel: SubModel, passID: number): void {
const iter = this.passInstances.get(pass);
if (iter === undefined) {
const instanceBufferID = this.passInstances.size;
if (instanceBufferID >= this.instanceBuffers.length) {
assert(instanceBufferID === this.instanceBuffers.length);
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
this.instanceBuffers.push(new InstancedBuffer(new Pass(cclegacy.director.root)));
}
this.passInstances.set(pass, instanceBufferID);
assert(instanceBufferID < this.instanceBuffers.length);
const instanceBuffer = this.instanceBuffers[instanceBufferID];
instanceBuffer.pass = pass;
const instances = instanceBuffer.instances;
for (const item of instances) {
assert(item.count === 0);
}
}
const instancedBuffer = this.instanceBuffers[this.passInstances.get(pass)!];
instancedBuffer.merge(subModel, passID);
}
clear (): void {
this.sortedBatches.length = 0;
this.passInstances.clear();
const instanceBuffers = this.instanceBuffers;
instanceBuffers.forEach((instance) => {
instance.clear();
});
this.instanceBuffers.length = 0;
}
sort (): void {
this.sortedBatches = Array.from(this.batches);
this.sortedBatches.length = this.passInstances.size;
let index = 0;
for (const [pass, bufferID] of this.passInstances.entries()) {
this.sortedBatches[index++] = this.instanceBuffers[bufferID];
}
}
uploadBuffers (cmdBuffer: CommandBuffer): void {
for (const instanceBuffer of this.batches) {
for (const [pass, bufferID] of this.passInstances.entries()) {
const instanceBuffer = this.instanceBuffers[bufferID];
if (instanceBuffer.hasPendingModels) {
instanceBuffer.uploadBuffers(cmdBuffer);
}
@@ -173,29 +326,44 @@ export class RenderInstancingQueue {
}
export class RenderQueueDesc {
culledSource: number;
frustumCulledResultID: number;
lightBoundsCulledResultID: number;
renderQueueTarget: number;
lightType: LightType;
constructor (
culledSourceIn = 0xFFFFFFFF,
frustumCulledResultID = 0xFFFFFFFF,
lightBoundsCulledResultID = 0xFFFFFFFF,
renderQueueTargetIn = 0xFFFFFFFF,
lightTypeIn: LightType = LightType.UNKNOWN,
) {
this.culledSource = culledSourceIn;
this.frustumCulledResultID = frustumCulledResultID;
this.lightBoundsCulledResultID = lightBoundsCulledResultID;
this.renderQueueTarget = renderQueueTargetIn;
this.lightType = lightTypeIn;
}
update (
culledSourceIn = 0xFFFFFFFF,
lightBoundsCulledResultID = 0xFFFFFFFF,
renderQueueTargetIn = 0xFFFFFFFF,
lightTypeIn: LightType = LightType.UNKNOWN,
): void {
this.frustumCulledResultID = culledSourceIn;
this.lightBoundsCulledResultID = lightBoundsCulledResultID;
this.renderQueueTarget = renderQueueTargetIn;
this.lightType = lightTypeIn;
}
}
export class RenderQueue {
probeQueue: ProbeHelperQueue = new ProbeHelperQueue();
opaqueQueue: RenderDrawQueue = new RenderDrawQueue();
transparentQueue: RenderDrawQueue = new RenderDrawQueue();
opaqueInstancingQueue: RenderInstancingQueue = new RenderInstancingQueue();
transparentInstancingQueue: RenderInstancingQueue = new RenderInstancingQueue();
sceneFlags: SceneFlags = SceneFlags.NONE;
subpassOrPassLayoutID = 0xffffffff;
subpassOrPassLayoutID = 0xFFFFFFFF;
lightByteOffset = 0xFFFFFFFF;
sort (): void {
this.opaqueQueue.sortOpaqueOrCutout();
this.transparentQueue.sortTransparent();
@@ -203,32 +371,29 @@ export class RenderQueue {
this.transparentInstancingQueue.sort();
}
private _clearInstances (instances: Set<InstancedBuffer>): void {
const it = instances.values(); let res = it.next();
while (!res.done) {
res.value.clear();
res = it.next();
}
instances.clear();
}
clear (): void {
this.opaqueQueue.instances.length = 0;
this.transparentQueue.instances.length = 0;
this._clearInstances(this.opaqueInstancingQueue.batches);
this.opaqueInstancingQueue.sortedBatches.length = 0;
this._clearInstances(this.transparentInstancingQueue.batches);
this.transparentInstancingQueue.sortedBatches.length = 0;
update (): void {
this.probeQueue.clear();
this.opaqueQueue.clear();
this.transparentQueue.clear();
this.opaqueInstancingQueue.clear();
this.transparentInstancingQueue.clear();
this.sceneFlags = SceneFlags.NONE;
this.subpassOrPassLayoutID = 0xFFFFFFFF;
}
empty (): boolean {
return this.opaqueQueue.instances.length === 0
&& this.transparentQueue.instances.length === 0
&& this.opaqueInstancingQueue.batches.size === 0
&& this.opaqueInstancingQueue.sortedBatches.length === 0
&& this.transparentInstancingQueue.batches.size === 0
&& this.transparentInstancingQueue.sortedBatches.length === 0;
return this.opaqueQueue.empty()
&& this.transparentQueue.empty()
&& this.opaqueInstancingQueue.empty()
&& this.transparentInstancingQueue.empty();
}
recordCommands (cmdBuffer: CommandBuffer, renderPass: RenderPass): void {
const offsets = this.lightByteOffset === 0xFFFFFFFF ? null : [this.lightByteOffset];
this.opaqueQueue.recordCommandBuffer(deviceManager.gfxDevice, renderPass, cmdBuffer, null, 0, offsets);
this.opaqueInstancingQueue.recordCommandBuffer(renderPass, cmdBuffer, null, 0, offsets);
this.transparentInstancingQueue.recordCommandBuffer(renderPass, cmdBuffer, null, 0, offsets);
this.transparentQueue.recordCommandBuffer(deviceManager.gfxDevice, renderPass, cmdBuffer, null, 0, offsets);
}
}
File diff suppressed because it is too large Load Diff
+124 -41
View File
@@ -25,7 +25,7 @@
/* eslint-disable max-len */
import { EffectAsset } from '../../asset/assets';
import { Attribute, DescriptorSetLayout, DescriptorType, DESCRIPTOR_BUFFER_TYPE, DESCRIPTOR_SAMPLER_TYPE, Device, MemoryAccessBit, PipelineLayout, PipelineLayoutInfo, Shader, ShaderInfo, ShaderStage, ShaderStageFlagBit, Type, Uniform, UniformBlock, UniformInputAttachment, UniformSampler, UniformSamplerTexture, UniformStorageBuffer, UniformStorageImage, UniformTexture, deviceManager } from '../../gfx';
import { Attribute, DescriptorSetLayout, DescriptorType, DESCRIPTOR_BUFFER_TYPE, DESCRIPTOR_SAMPLER_TYPE, Device, MemoryAccessBit, PipelineLayout, PipelineLayoutInfo, Shader, ShaderInfo, ShaderStage, ShaderStageFlagBit, Type, Uniform, UniformBlock, UniformInputAttachment, UniformSampler, UniformSamplerTexture, UniformStorageBuffer, UniformStorageImage, UniformTexture, deviceManager, PipelineState, DescriptorSetLayoutInfo, DescriptorSetInfo } from '../../gfx';
import { genHandles, getActiveAttributes, getCombinationDefines, getShaderInstanceName, getSize, getVariantKey, populateMacros, prepareDefines } from '../../render-scene/core/program-utils';
import { getDeviceShaderVersion, MacroRecord } from '../../render-scene';
import { IProgramInfo } from '../../render-scene/core/program-lib';
@@ -33,15 +33,15 @@ import { DescriptorBlockData, DescriptorData, DescriptorSetData, DescriptorSetLa
import { ProgramLibrary, ProgramProxy } from './private';
import { DescriptorTypeOrder, UpdateFrequency } from './types';
import { ProgramGroup, ProgramInfo } from './web-types';
import { getCustomPassID, getCustomPhaseID, getOrCreateDescriptorSetLayout, getEmptyDescriptorSetLayout, getEmptyPipelineLayout, initializeDescriptorSetLayoutInfo, makeDescriptorSetLayoutData, getDescriptorSetLayout, getOrCreateDescriptorID, getDescriptorTypeOrder, getProgramID, getDescriptorNameID, getDescriptorName, INVALID_ID, ENABLE_SUBPASS, getCustomSubpassID } from './layout-graph-utils';
import { assert } from '../../core/platform/debug';
import { IDescriptorSetLayoutInfo, localDescriptorSetLayout } from '../define';
import { getCustomPassID, getCustomPhaseID, getOrCreateDescriptorSetLayout, getEmptyDescriptorSetLayout, getEmptyPipelineLayout, initializeDescriptorSetLayoutInfo, makeDescriptorSetLayoutData, getDescriptorSetLayout, getOrCreateDescriptorID, getDescriptorTypeOrder, getProgramID, getDescriptorNameID, getDescriptorName, INVALID_ID, ENABLE_SUBPASS, getCustomSubpassID, generateConstantMacros, populatePipelineLayoutInfo } from './layout-graph-utils';
import { assert, error } from '../../core/platform/debug';
import { IDescriptorSetLayoutInfo, UBOSkinning, localDescriptorSetLayout } from '../define';
import { PipelineRuntime } from './pipeline';
const _setIndex = [2, 1, 3, 0];
// make IProgramInfo from IShaderInfo
function makeProgramInfo (effectName: string, shader: EffectAsset.IShaderInfo): IProgramInfo {
export function makeProgramInfo (effectName: string, shader: EffectAsset.IShaderInfo): IProgramInfo {
const programInfo = { ...shader } as IProgramInfo;
programInfo.effectName = effectName;
@@ -87,7 +87,7 @@ function findBinding (shaderInfo: ShaderInfo, name: string): { set: number, bind
}
}
// eslint-disable-next-line no-console
throw console.error('binding not found in shaderInfo!');
throw error('binding not found in shaderInfo!');
}
function overwriteShaderSourceBinding (shaderInfo: ShaderInfo, source: string): string {
@@ -138,7 +138,7 @@ function overwriteShaderProgramBinding (shaderInfo: ShaderInfo, programInfo: IPr
}
// overwrite IProgramInfo using gfx.ShaderInfo
function overwriteProgramBlockInfo (shaderInfo: ShaderInfo, programInfo: IProgramInfo): void {
export function overwriteProgramBlockInfo (shaderInfo: ShaderInfo, programInfo: IProgramInfo): void {
overwriteShaderProgramBinding(shaderInfo, programInfo);
const set = _setIndex[UpdateFrequency.PER_BATCH];
for (const block of programInfo.blocks) {
@@ -154,7 +154,7 @@ function overwriteProgramBlockInfo (shaderInfo: ShaderInfo, programInfo: IProgra
}
}
if (!found) {
console.error(`Block ${block.name} not found in shader ${shaderInfo.name}`);
error(`Block ${block.name} not found in shader ${shaderInfo.name}`);
}
}
}
@@ -270,7 +270,7 @@ function populateMergedShaderInfo (
for (const block of descriptorBlock.descriptors) {
const uniformBlock = layout.uniformBlocks.get(block.descriptorID);
if (uniformBlock === undefined) {
console.error(`Failed to find uniform block ${block.descriptorID} in layout`);
error(`Failed to find uniform block ${block.descriptorID} in layout`);
continue;
}
blockSizes.push(getSize(uniformBlock.members));
@@ -286,7 +286,7 @@ function populateMergedShaderInfo (
++binding;
}
if (binding !== descriptorBlock.offset + descriptorBlock.capacity) {
console.error(`Uniform buffer binding mismatch for set ${set}`);
error(`Uniform buffer binding mismatch for set ${set}`);
}
break;
case DescriptorTypeOrder.DYNAMIC_UNIFORM_BUFFER:
@@ -541,7 +541,7 @@ function calculateFlattenedBinding (
}
// make gfx.ShaderInfo
function makeShaderInfo (
export function makeShaderInfo (
lg: LayoutGraphData,
passLayouts: PipelineLayoutData,
phaseLayouts: PipelineLayoutData,
@@ -650,14 +650,23 @@ function makeShaderInfo (
return [shaderInfo, blockSizes];
}
class WebProgramProxy implements ProgramProxy {
constructor (shader: Shader) {
export function getGLSLSource (info: IProgramInfo, version: string): { vert: string, frag: string, compute?: string } {
if (version === 'glsl1') return info.glsl1;
if (version === 'glsl3') return info.glsl3;
if (version === 'glsl4') return info.glsl4;
return { vert: '', frag: '' };
}
export class WebProgramProxy implements ProgramProxy {
constructor (shader: Shader, pipelineStateIn: PipelineState | null = null) {
this.shader = shader;
this.pipelineState = pipelineStateIn;
}
get name (): string {
return this.shader.name;
}
readonly shader: Shader;
pipelineState: PipelineState | null = null;
}
// find name and type from local descriptor set info
@@ -675,12 +684,12 @@ function getDescriptorNameAndType (source: IDescriptorSetLayoutInfo, binding: nu
return [v.name, type];
}
}
console.error('descriptor not found');
error('descriptor not found');
return ['', Type.UNKNOWN];
}
// make DescriptorSetLayoutData from local descriptor set info
function makeLocalDescriptorSetLayoutData (
export function makeLocalDescriptorSetLayoutData (
lg: LayoutGraphData,
source: IDescriptorSetLayoutInfo,
): DescriptorSetLayoutData {
@@ -695,7 +704,7 @@ function makeLocalDescriptorSetLayoutData (
data.descriptorBlocks.push(block);
const binding = data.bindingMap.get(nameID);
if (binding !== undefined) {
console.error(`duplicate descriptor name '${name}'`);
error(`duplicate descriptor name '${name}'`);
}
data.bindingMap.set(nameID, b.binding);
const v = source.layouts[name];
@@ -707,7 +716,7 @@ function makeLocalDescriptorSetLayoutData (
}
// make descriptor sets for ShaderProgramData (PerBatch, PerInstance)
function buildProgramData (
export function buildProgramData (
programName: string,
srcShaderInfo: EffectAsset.IShaderInfo,
lg: LayoutGraphData,
@@ -737,7 +746,7 @@ function buildProgramData (
setData.descriptorSetLayoutInfo,
);
if (localDescriptorSetLayout.bindings.length !== setData.descriptorSetLayoutInfo.bindings.length) {
console.error('local descriptor set layout inconsistent');
error('local descriptor set layout inconsistent');
} else {
for (let k = 0; k !== localDescriptorSetLayout.bindings.length; ++k) {
const b = localDescriptorSetLayout.bindings[k];
@@ -746,7 +755,7 @@ function buildProgramData (
|| b.descriptorType !== b2.descriptorType
|| b.count !== b2.count
|| b.stageFlags !== b2.stageFlags) {
console.error('local descriptor set layout inconsistent');
error('local descriptor set layout inconsistent');
}
}
}
@@ -771,7 +780,7 @@ function buildProgramData (
}
// get or create PerProgram gfx.DescriptorSetLayout
function getOrCreateProgramDescriptorSetLayout (
export function getOrCreateProgramDescriptorSetLayout (
device: Device,
lg: LayoutGraphData,
phaseID: number,
@@ -798,7 +807,7 @@ function getOrCreateProgramDescriptorSetLayout (
}
// get PerProgram gfx.DescriptorSetLayout
function getProgramDescriptorSetLayout (
export function getProgramDescriptorSetLayout (
device: Device,
lg: LayoutGraphData,
phaseID: number,
@@ -825,7 +834,7 @@ function getProgramDescriptorSetLayout (
}
// find shader program in LayoutGraphData
function getEffectShader (
export function getEffectShader (
lg: LayoutGraphData,
effect: EffectAsset,
pass: EffectAsset.IPassInfo,
@@ -833,20 +842,20 @@ function getEffectShader (
const programName = pass.program;
const passID = getCustomPassID(lg, pass.pass);
if (passID === INVALID_ID) {
console.error(`Invalid render pass, program: ${programName}`);
error(`Invalid render pass, program: ${programName}`);
return [INVALID_ID, INVALID_ID, INVALID_ID, null, INVALID_ID];
}
const enableSubpass = pass.subpass && pass.subpass !== '' && ENABLE_SUBPASS;
const subpassID = enableSubpass ? getCustomSubpassID(lg, passID, pass.subpass!) : INVALID_ID;
if (enableSubpass && subpassID === INVALID_ID) {
console.error(`Invalid render subpass, program: ${programName}`);
error(`Invalid render subpass, program: ${programName}`);
return [INVALID_ID, INVALID_ID, INVALID_ID, null, INVALID_ID];
}
const phaseID = getCustomPhaseID(lg, subpassID === INVALID_ID ? passID : subpassID, pass.phase);
if (phaseID === INVALID_ID) {
console.error(`Invalid render phase, program: ${programName}`);
error(`Invalid render phase, program: ${programName}`);
return [INVALID_ID, INVALID_ID, INVALID_ID, null, INVALID_ID];
}
let srcShaderInfo: EffectAsset.IShaderInfo | null = null;
@@ -863,10 +872,10 @@ function getEffectShader (
}
// valid IShaderInfo is compatible
function validateShaderInfo (srcShaderInfo: EffectAsset.IShaderInfo): number {
export function validateShaderInfo (srcShaderInfo: EffectAsset.IShaderInfo): number {
// source shader info
if (srcShaderInfo.descriptors === undefined) {
console.error(`No descriptors in shader: ${srcShaderInfo.name}, please reimport ALL effects`);
error(`No descriptors in shader: ${srcShaderInfo.name}, please reimport ALL effects`);
return 1;
}
return 0;
@@ -881,6 +890,75 @@ export class WebProgramLibrary implements ProgramLibrary {
}
}
}
init (deviceIn: Device): void {
if (this.device === deviceIn) {
return;
}
this.device = deviceIn;
this.emptyDescriptorSetLayout = this.device.createDescriptorSetLayout(new DescriptorSetLayoutInfo());
this.emptyPipelineLayout = this.device.createPipelineLayout(new PipelineLayoutInfo());
// update ubo
// tips: for compatibility with old version, when maxVertexUniformVectors is 128, maxJoints = 30
let maxJoints: number = (this.device.capabilities.maxVertexUniformVectors - 38) / 3;
maxJoints = maxJoints < 256 ? maxJoints : 256;
UBOSkinning.initLayout(maxJoints);
// init layout graph
const lg = this.layoutGraph;
for (const v of lg.vertices()) {
const layout: PipelineLayoutData = lg.get('Layout').get(v) as PipelineLayoutData;
for (const [update, set] of layout.descriptorSets) {
initializeDescriptorSetLayoutInfo(set.descriptorSetLayoutData, set.descriptorSetLayoutInfo);
set.descriptorSetLayout = this.device.createDescriptorSetLayout(set.descriptorSetLayoutInfo);
assert(!!set.descriptorSetLayout);
set.descriptorSet = this.device.createDescriptorSet(new DescriptorSetInfo(set.descriptorSetLayout));
assert(!!set.descriptorSet);
}
}
for (const v of lg.vertices()) {
if (!lg.holds(LayoutGraphDataValue.RenderPhase, v)) {
continue;
}
const phaseID = v;
const subpassOrPassID = lg.getParent(phaseID);
const passLayout = lg.getLayout(subpassOrPassID);
const phaseLayout = lg.getLayout(phaseID);
const info = new PipelineLayoutInfo();
populatePipelineLayoutInfo(passLayout, UpdateFrequency.PER_PASS, info);
populatePipelineLayoutInfo(phaseLayout, UpdateFrequency.PER_PHASE, info);
populatePipelineLayoutInfo(phaseLayout, UpdateFrequency.PER_BATCH, info);
populatePipelineLayoutInfo(phaseLayout, UpdateFrequency.PER_INSTANCE, info);
const phase = lg.getRenderPhase(phaseID);
phase.pipelineLayout = this.device.createPipelineLayout(info);
}
// init local descriptor set
{
const localSetLayout = localDescriptorSetLayout;
this.localLayoutData = makeLocalDescriptorSetLayoutData(lg, localSetLayout);
const info = new DescriptorSetLayoutInfo();
initializeDescriptorSetLayoutInfo(this.localLayoutData, info);
this.localDescriptorSetLayout = this.device.createDescriptorSetLayout(info);
assert(!!this.localDescriptorSetLayout);
let numUniformBuffers = 0;
for (const block of this.localLayoutData.descriptorBlocks) {
if (block.type !== DescriptorTypeOrder.UNIFORM_BUFFER
&& block.type !== DescriptorTypeOrder.DYNAMIC_UNIFORM_BUFFER) {
continue;
}
for (const d of block.descriptors) {
numUniformBuffers += d.count;
}
}
assert(numUniformBuffers === 7); // 7 is currently max uniform binding
}
// generate constant macros string
generateConstantMacros(this.device, this.layoutGraph.constantMacros);
}
// add effect to database
addEffect (effect: EffectAsset): void {
const lg = this.layoutGraph;
@@ -889,7 +967,7 @@ export class WebProgramLibrary implements ProgramLibrary {
const programName = pass.program;
const [passID, subpassID, phaseID, srcShaderInfo] = getEffectShader(lg, effect, pass);
if (srcShaderInfo === null || validateShaderInfo(srcShaderInfo)) {
console.error(`program: ${programName} not found`);
error(`program: ${programName} not found`);
continue;
}
assert(passID !== INVALID_ID && phaseID !== INVALID_ID);
@@ -950,7 +1028,7 @@ export class WebProgramLibrary implements ProgramLibrary {
const programName = pass.program;
const [passID, subpassID, phaseID, srcShaderInfo, shaderID] = getEffectShader(lg, effect, pass);
if (srcShaderInfo === null || validateShaderInfo(srcShaderInfo)) {
console.error(`program: ${programName} not valid`);
error(`program: ${programName} not valid`);
continue;
}
assert(passID !== INVALID_ID && phaseID !== INVALID_ID && shaderID !== INVALID_ID);
@@ -986,13 +1064,13 @@ export class WebProgramLibrary implements ProgramLibrary {
// get phase
const group = this.phases.get(phaseID);
if (group === undefined) {
console.error(`Invalid render phase, program: ${programName}`);
error(`Invalid render phase, program: ${programName}`);
return '';
}
// get info
const info = group.programInfos.get(programName);
if (info === undefined) {
console.error(`Invalid program, program: ${programName}`);
error(`Invalid program, program: ${programName}`);
return '';
}
return getVariantKey(info.programInfo, defines);
@@ -1004,13 +1082,13 @@ export class WebProgramLibrary implements ProgramLibrary {
// get phase
const group = this.phases.get(phaseID);
if (group === undefined) {
console.error(`Invalid render phase, program: ${name}`);
error(`Invalid render phase, program: ${name}`);
return null;
}
// get info
const info = group.programInfos.get(name);
if (info === undefined) {
console.error(`Invalid program, program: ${name}`);
error(`Invalid program, program: ${name}`);
return null;
}
const programInfo = info.programInfo;
@@ -1035,7 +1113,7 @@ export class WebProgramLibrary implements ProgramLibrary {
if (deviceShaderVersion) {
src = programInfo[deviceShaderVersion];
} else {
console.error('Invalid GFX API!');
error('Invalid GFX API!');
}
// prepare shader info
@@ -1096,12 +1174,12 @@ export class WebProgramLibrary implements ProgramLibrary {
assert(phaseID !== INVALID_ID);
const group = this.phases.get(phaseID);
if (!group) {
console.error(`Invalid render phase, program: ${programName}`);
error(`Invalid render phase, program: ${programName}`);
return [];
}
const info = group.programInfos.get(programName);
if (!info) {
console.error(`Invalid program, program: ${programName}`);
error(`Invalid program, program: ${programName}`);
return [];
}
return info.blockSizes;
@@ -1111,12 +1189,12 @@ export class WebProgramLibrary implements ProgramLibrary {
assert(phaseID !== INVALID_ID);
const group = this.phases.get(phaseID);
if (!group) {
console.error(`Invalid render phase, program: ${programName}`);
error(`Invalid render phase, program: ${programName}`);
return {};
}
const info = group.programInfos.get(programName);
if (!info) {
console.error(`Invalid program, program: ${programName}`);
error(`Invalid program, program: ${programName}`);
return {};
}
return info.handleMap;
@@ -1177,7 +1255,12 @@ export class WebProgramLibrary implements ProgramLibrary {
}
readonly layoutGraph: LayoutGraphData;
readonly phases: Map<number, ProgramGroup> = new Map<number, ProgramGroup>();
mergeHighFrequency = false;
fixedLocal = true;
pipeline: PipelineRuntime | null = null;
public mergeHighFrequency: boolean = false;
public fixedLocal: boolean = true;
public localLayoutData: DescriptorSetLayoutData = new DescriptorSetLayoutData();
public localDescriptorSetLayout: DescriptorSetLayout | null = null;
public emptyDescriptorSetLayout: DescriptorSetLayout | null = null;
public emptyPipelineLayout: PipelineLayout | null = null;
public pipeline: PipelineRuntime | null = null;
public device: Device | null = null;
}
+2 -2
View File
@@ -136,13 +136,13 @@ export class WebSceneTask implements SceneTask {
}
public start (): void {
this._sceneCulling();
// do nothing
}
public join (): void {
// for web-pipeline, do nothing
}
public submit (): void {
// do nothing
}
get camera (): scene.Camera | null { return this._camera; }
get renderScene (): RenderScene | null {
+9 -2
View File
@@ -122,6 +122,7 @@ export class ForwardStage extends RenderStage {
}
public destroy (): void {
// do nothing
}
public render (camera: Camera): void {
@@ -179,8 +180,14 @@ export class ForwardStage extends RenderStage {
const framebuffer = camera.window.framebuffer;
const renderPass = pipeline.getRenderPass(camera.clearFlag & this._clearFlag, framebuffer);
cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea,
colors, camera.clearDepth, camera.clearStencil);
cmdBuff.beginRenderPass(
renderPass,
framebuffer,
this._renderArea,
colors,
camera.clearDepth,
camera.clearStencil,
);
cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
this._renderQueues[0].recordCommandBuffer(device, renderPass, cmdBuff);
@@ -41,14 +41,14 @@ export function disablePostProcessForDebugView (): boolean {
return debugView.singleMode as number > 0;
}
export function getShadowMapSampler (): Sampler | null {
export function getShadowMapSampler (): Sampler | undefined {
if (!_pointSampler) {
const director = cclegacy.director;
const pipeline = director.root.pipeline;
const device = pipeline.device;
_pointSampler = device.getSampler(_samplerPointInfo);
}
return _pointSampler;
return _pointSampler || undefined;
}
export abstract class BasePass {
@@ -1,6 +1,6 @@
import { Vec4 } from '../../../core';
import { ClearFlagBit, Format } from '../../../gfx';
import { Camera } from '../../../render-scene/scene';
import { Camera, SKYBOX_FLAG } from '../../../render-scene/scene';
import { getCameraUniqueID } from '../../custom/define';
import { Pipeline } from '../../custom/pipeline';
import { passContext } from '../utils/pass-context';
@@ -17,7 +17,7 @@ export class ForwardFinalPass extends BasePass {
return;
}
passContext.clearFlag = camera.clearFlag & ClearFlagBit.COLOR;
passContext.clearFlag = camera.clearFlag & ClearFlagBit.COLOR | (camera.clearFlag & SKYBOX_FLAG);
Vec4.set(passContext.clearColor, camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w);
passContext.material = this.material;
@@ -1,7 +1,7 @@
import { Vec4 } from '../../../core';
import { ClearFlagBit, Format } from '../../../gfx';
import { Camera, ShadowType } from '../../../render-scene/scene';
import { Camera, ShadowType, SKYBOX_FLAG } from '../../../render-scene/scene';
import { LightInfo, QueueHint, SceneFlags } from '../../custom/types';
import { getCameraUniqueID } from '../../custom/define';
import { Pipeline } from '../../custom/pipeline';
@@ -38,7 +38,7 @@ export class ForwardPass extends BasePass {
}
public render (camera: Camera, ppl: Pipeline): void {
passContext.clearFlag = ClearFlagBit.COLOR | (camera.clearFlag & ClearFlagBit.DEPTH_STENCIL);
passContext.clearFlag = ClearFlagBit.COLOR | (camera.clearFlag & ClearFlagBit.DEPTH_STENCIL) | (camera.clearFlag & SKYBOX_FLAG);
Vec4.set(passContext.clearColor, 0, 0, 0, 0);
Vec4.set(passContext.clearDepthColor, camera.clearDepth, camera.clearStencil, 0, 0);
@@ -70,13 +70,15 @@ export class ForwardPass extends BasePass {
}
}
}
pass.addQueue(QueueHint.RENDER_OPAQUE)
.addSceneOfCamera(
camera,
new LightInfo(),
SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT
| SceneFlags.DEFAULT_LIGHTING | SceneFlags.GEOMETRY,
);
const forwardQueue = pass.addQueue(QueueHint.RENDER_OPAQUE);
forwardQueue.addSceneOfCamera(
camera,
new LightInfo(),
SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT
| SceneFlags.GEOMETRY,
);
const forwardAddQueue = pass.addQueue(QueueHint.RENDER_TRANSPARENT, 'forward-add');
passContext.addSceneLights(forwardAddQueue, camera);
const shadowInfo = ppl.pipelineSceneData.shadows;
if (camera.scene?.mainLight && shadowInfo.enabled && shadowInfo.type === ShadowType.Planar) {
pass.addQueue(QueueHint.RENDER_TRANSPARENT, 'planar-shadow')
@@ -84,7 +86,7 @@ export class ForwardPass extends BasePass {
camera,
new LightInfo(camera.scene?.mainLight),
SceneFlags.TRANSPARENT_OBJECT | SceneFlags.SHADOW_CASTER
| SceneFlags.DEFAULT_LIGHTING | SceneFlags.GEOMETRY,
| SceneFlags.GEOMETRY,
);
}
passContext.forwardPass = this;
@@ -186,7 +186,7 @@ export class PostProcessBuilder implements PipelineBuilder {
this.applyPreviewCamera(camera);
}
buildReflectionProbePasss(camera, ppl);
ppl.addBuiltinReflectionProbePass(camera);
passContext.postProcess = camera.postProcess || globalPP;
@@ -1,14 +1,17 @@
import { EDITOR } from 'internal:constants';
import { QueueHint, ResourceResidency, SceneFlags } from '../../custom/types';
import { LightInfo, QueueHint, ResourceResidency, SceneFlags } from '../../custom/types';
import { ClearFlagBit, Color, Format, LoadOp, Rect, StoreOp, Viewport } from '../../../gfx';
import { Pipeline, RenderPassBuilder } from '../../custom/pipeline';
import { Camera } from '../../../render-scene/scene';
import { Pipeline, RenderPassBuilder, RenderQueueBuilder } from '../../custom/pipeline';
import { Camera, SKYBOX_FLAG } from '../../../render-scene/scene';
import { Material } from '../../../asset/assets';
import { PostProcess } from '../components';
import { getRenderArea } from '../../custom/define';
import { Vec4 } from '../../../core';
import { Vec4, geometry } from '../../../core';
const sphere = geometry.Sphere.create(0, 0, 0, 1);
const boundingBox = new geometry.AABB();
const rangedDirLightBoundingBox = new geometry.AABB(0.0, 0.0, 0.0, 0.5, 0.5, 0.5);
export class PassContext {
clearFlag: ClearFlagBit = ClearFlagBit.COLOR;
clearColor = new Color();
@@ -81,6 +84,50 @@ export class PassContext {
return this;
}
addSceneLights (queue: RenderQueueBuilder, camera: Camera, flags: SceneFlags = SceneFlags.BLEND): void {
const scene = camera.scene!;
for (let i = 0; i < scene.spotLights.length; i++) {
const light = scene.spotLights[i];
if (light.baked) {
continue;
}
geometry.Sphere.set(sphere, light.position.x, light.position.y, light.position.z, light.range);
if (geometry.intersect.sphereFrustum(sphere, camera.frustum)) {
queue.addSceneOfCamera(camera, new LightInfo(light), flags);
}
}
// sphere lights
for (let i = 0; i < scene.sphereLights.length; i++) {
const light = scene.sphereLights[i];
if (light.baked) {
continue;
}
geometry.Sphere.set(sphere, light.position.x, light.position.y, light.position.z, light.range);
if (geometry.intersect.sphereFrustum(sphere, camera.frustum)) {
queue.addSceneOfCamera(camera, new LightInfo(light), flags);
}
}
// point lights
for (let i = 0; i < scene.pointLights.length; i++) {
const light = scene.pointLights[i];
if (light.baked) {
continue;
}
geometry.Sphere.set(sphere, light.position.x, light.position.y, light.position.z, light.range);
if (geometry.intersect.sphereFrustum(sphere, camera.frustum)) {
queue.addSceneOfCamera(camera, new LightInfo(light), flags);
}
}
// ranged dir lights
for (let i = 0; i < scene.rangedDirLights.length; i++) {
const light = scene.rangedDirLights[i];
geometry.AABB.transform(boundingBox, rangedDirLightBoundingBox, light.node!.getWorldMatrix());
if (geometry.intersect.aabbFrustum(boundingBox, camera.frustum)) {
queue.addSceneOfCamera(camera, new LightInfo(light), flags);
}
}
}
updateViewPort (): void {
const camera = this.camera;
if (!camera) {
@@ -111,7 +158,7 @@ export class PassContext {
// return this;
// }
addRasterView (name: string, format: Format, offscreen = true, residency?: ResourceResidency): PassContext {
addRasterView (name: string, format: Format, offscreen = true, residency: ResourceResidency = ResourceResidency.MANAGED): PassContext {
const ppl = this.ppl;
const camera = this.camera;
const pass = this.pass;
@@ -154,10 +201,11 @@ export class PassContext {
const clearFlag = this.clearFlag & ClearFlagBit.COLOR;
let loadOp = LoadOp.CLEAR;
if (clearFlag === ClearFlagBit.NONE) {
if (clearFlag === ClearFlagBit.NONE && !(this.clearFlag & SKYBOX_FLAG)) {
loadOp = LoadOp.LOAD;
} else if (this.clearFlag & SKYBOX_FLAG) {
clearColor.set(0, 0, 0, 1);
}
pass.addRenderTarget(name, loadOp, StoreOp.STORE, clearColor);
}
return this;
@@ -183,7 +183,7 @@ export class RenderAdditiveLightQueue {
}
}
private _bindForwardAddLight(validPunctualLights: Light[], passLayout = 'default'): void {
private _bindForwardAddLight (validPunctualLights: Light[], passLayout = 'default'): void {
const renderObjects = this._pipeline.pipelineSceneData.renderObjects;
for (let i = 0; i < renderObjects.length; i++) {
const ro = renderObjects[i];
+1 -1
View File
@@ -41,7 +41,7 @@ const roPool = new Pool<IRenderObject>((): IRenderObject => ({ model: null!, dep
function getRenderObject (model: Model, camera: Camera): IRenderObject {
let depth = 0;
if (model.node) {
Vec3.subtract(_tempVec3, model.node.worldPosition, camera.position);
Vec3.subtract(_tempVec3, model.worldBounds ? model.worldBounds.center : model.node.worldPosition, camera.position);
depth = Vec3.dot(_tempVec3, camera.forward);
}
const ro = roPool.alloc();