diff --git a/examples/index.ts b/examples/index.ts index 1a4d9d4454609a1f6ec1f06496656cc81d6a0f97..2887de25a4492158719963e1658f86b8de59ac2d 100644 --- a/examples/index.ts +++ b/examples/index.ts @@ -10,7 +10,8 @@ const files = { "sample8", ], "test":[ - "fractalCube" + "fractalCube", + "RenderObjectChanges", ], "regl-examples": [ "basic", diff --git a/examples/src/WebGL2Samples/buffer_copy.ts b/examples/src/WebGL2Samples/buffer_copy.ts index 541e38656c63433576502d49e79ce741a0d5940e..2929efc93830d504ddb10f2349cd647128405e4f 100644 --- a/examples/src/WebGL2Samples/buffer_copy.ts +++ b/examples/src/WebGL2Samples/buffer_copy.ts @@ -1,5 +1,5 @@ -import { ICopyBufferToBuffer, IRenderPass, IRenderPipeline, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, IGLVertexBuffer, WebGL, getIGLBuffer } from "@feng3d/webgl"; +import { GBuffer, CanvasContext, CopyBufferToBuffer, RenderPass, RenderPipeline, VertexAttributes } from "@feng3d/render-api"; +import { WebGL, getIGLBuffer } from "@feng3d/webgl"; import { getShaderSource } from "./utility"; (function () @@ -12,13 +12,12 @@ import { getShaderSource } from "./utility"; document.body.appendChild(canvas); // -- Init WebGL Context - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(rc); // -- Init Program - const program: IRenderPipeline = { + const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") }, - primitive: { topology: "triangle-list" }, }; // -- Init Buffer @@ -30,31 +29,34 @@ import { getShaderSource } from "./utility"; -1.0, 1.0, -1.0, -1.0 ]); - const vertexPosBufferSrc: IGLVertexBuffer = { target: "ARRAY_BUFFER", size: vertices.byteLength, data: vertices, usage: "STATIC_DRAW" }; + const vertexPosBufferSrc: GBuffer = { target: "ARRAY_BUFFER", size: vertices.byteLength, data: vertices, usage: "STATIC_DRAW" }; const vertexPosBufferDst = new Float32Array(vertices.length); - const cb: ICopyBufferToBuffer = { - __type: "CopyBufferToBuffer", + const cb: CopyBufferToBuffer = { + __type__: "CopyBufferToBuffer", source: vertexPosBufferSrc, destination: getIGLBuffer(vertexPosBufferDst, "ARRAY_BUFFER"), sourceOffset: 0, destinationOffset: 0, size: vertices.length * Float32Array.BYTES_PER_ELEMENT }; // -- Init Vertex Array - const vertexArray: { vertices?: IVertexAttributes } = { + const vertexArray: { vertices?: VertexAttributes } = { vertices: { pos: { data: vertexPosBufferDst, format: "float32x2" }, } }; // -- Render - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects: [{ pipeline: program, - vertices: vertexArray.vertices, - drawVertex: { vertexCount: 6 }, + geometry: { + primitive: { topology: "triangle-list" }, + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + }, }] }; diff --git a/examples/src/WebGL2Samples/buffer_uniform.ts b/examples/src/WebGL2Samples/buffer_uniform.ts index 4928f9c1ba054ec0063ef7afe2a47918d7e627cb..c5e19cd8ba12da4bbac7fddd866e953306402892 100644 --- a/examples/src/WebGL2Samples/buffer_uniform.ts +++ b/examples/src/WebGL2Samples/buffer_uniform.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, IRenderPipeline, ISubmit, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderObject, RenderPass, RenderPipeline, Submit, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource } from "./utility"; (function () @@ -12,11 +12,11 @@ import { getShaderSource } from "./utility"; document.body.appendChild(canvas); // --Init WebGL Context - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(rc); // -- Init Program - const program: IRenderPipeline = { + const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") }, }; @@ -73,7 +73,7 @@ import { getShaderSource } from "./utility"; }; // -- Init Vertex Array - const vertexArray: { vertices?: IVertexAttributes } = { + const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: vertices, format: "float32x3", arrayStride: 40, offset: 0 }, normal: { data: vertices, format: "float32x3", arrayStride: 40, offset: 12 }, @@ -81,24 +81,26 @@ import { getShaderSource } from "./utility"; }, }; - const ro: IRenderObject = { + const ro: RenderObject = { pipeline: program, - vertices: vertexArray.vertices, - indices: elementData, - uniforms: { + bindingResources: { PerDraw: transforms, PerPass: lightPos, PerScene: material, }, - drawIndexed: { indexCount: 6, firstIndex: 0 } + geometry:{ + vertices: vertexArray.vertices, + indices: elementData, + draw: { __type__: "DrawIndexed", indexCount: 6, firstIndex: 0 } + }, }; - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects: [ro], }; - const submit: ISubmit = { commandEncoders: [{ passEncoders: [rp] }] }; + const submit: Submit = { commandEncoders: [{ passEncoders: [rp] }] }; let uTime = 0; function render() diff --git a/examples/src/WebGL2Samples/draw_image_space.ts b/examples/src/WebGL2Samples/draw_image_space.ts index 9751293912288b687f4713a83ccff23b6d245d9e..c97064a04cc646aae81feb4728ffbabb6cd73d48 100644 --- a/examples/src/WebGL2Samples/draw_image_space.ts +++ b/examples/src/WebGL2Samples/draw_image_space.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPipeline, ISampler, ITexture } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderObject, RenderPipeline, Sampler, Texture } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource } from "./utility"; const canvas = document.createElement("canvas"); @@ -8,23 +8,22 @@ canvas.width = Math.min(window.innerWidth, window.innerHeight); canvas.height = canvas.width; document.body.appendChild(canvas); -const renderingContext: IGLCanvasContext = { canvasId: "glcanvas" }; +const renderingContext: CanvasContext = { canvasId: "glcanvas" }; const webgl = new WebGL(renderingContext); loadImage("../../assets/img/Di-3d.png", (img) => { - const texture: ITexture = { + const texture: Texture = { size: [img.width, img.height], sources: [{ image: img, flipY: false }], format: "rgba8unorm", }; - const sampler: ISampler = { + const sampler: Sampler = { minFilter: "linear", magFilter: "linear", }; - const program: IRenderPipeline = { - primitive: { topology: "triangle-list" }, + const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, @@ -34,12 +33,15 @@ loadImage("../../assets/img/Di-3d.png", (img) => } }; - const renderObject: IRenderObject = { - uniforms: { + const renderObject: RenderObject = { + bindingResources: { diffuse: { texture, sampler }, u_imageSize: [canvas.width / 2, canvas.height / 2], }, - drawVertex: { firstVertex: 0, vertexCount: 3 }, + geometry: { + primitive: { topology: "triangle-list" }, + draw: { __type__: "DrawVertex", firstVertex: 0, vertexCount: 3 }, + }, pipeline: program }; diff --git a/examples/src/WebGL2Samples/draw_instanced.ts b/examples/src/WebGL2Samples/draw_instanced.ts index b6f822eae92e0e58084806606b188293134860b9..dc8d4e9b3696d8dcf8b6f8f895d7d66d7722bd7f 100644 --- a/examples/src/WebGL2Samples/draw_instanced.ts +++ b/examples/src/WebGL2Samples/draw_instanced.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPipeline, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderObject, RenderPipeline, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource } from "./utility"; const canvas = document.createElement("canvas"); @@ -8,7 +8,7 @@ canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); -const renderingContext: IGLCanvasContext = { canvasId: "glcanvas" }; +const renderingContext: CanvasContext = { canvasId: "glcanvas" }; const webgl = new WebGL(renderingContext); const vertexPosBuffer = new Float32Array([-0.3, -0.5, @@ -18,23 +18,25 @@ const vertexColorBuffer = new Float32Array([ 1.0, 0.5, 0.0, 0.0, 0.5, 1.0]); -const program: IRenderPipeline = { - primitive: { topology: "triangle-list" }, +const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs"), targets: [{ blend: {} }] } }; -const vertexArray: { vertices?: IVertexAttributes } = { +const vertexArray: { vertices?: VertexAttributes } = { vertices: { pos: { data: vertexPosBuffer, format: "float32x2" }, color: { data: vertexColorBuffer, format: "float32x3", stepMode: "instance" }, }, }; -const renderObject: IRenderObject = { - vertices: vertexArray.vertices, - uniforms: {}, - drawVertex: { vertexCount: 3, instanceCount: 2 }, +const renderObject: RenderObject = { + bindingResources: {}, + geometry:{ + primitive: { topology: "triangle-list" }, + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 3, instanceCount: 2 }, + }, pipeline: program }; diff --git a/examples/src/WebGL2Samples/draw_instanced_ubo.ts b/examples/src/WebGL2Samples/draw_instanced_ubo.ts index 0f730efdbda6b5f8dbbf100cd81ffe3c224d7f24..6b37457c8b1db5827c58f9089e7e9d41e08e8c60 100644 --- a/examples/src/WebGL2Samples/draw_instanced_ubo.ts +++ b/examples/src/WebGL2Samples/draw_instanced_ubo.ts @@ -1,5 +1,5 @@ -import { IRenderPass, IRenderPipeline } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderPass, RenderPipeline } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource } from "./utility"; const canvas = document.createElement("canvas"); @@ -8,11 +8,11 @@ canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); -const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; +const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(rc); // -- Init program -const program: IRenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") } }; +const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") } }; // -- Init Buffer const vertices = new Float32Array([ @@ -46,18 +46,20 @@ const materials = { }; // -- Render -const rp: IRenderPass = { +const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0, 0, 0, 1], loadOp: "clear" }] }, renderObjects: [{ pipeline: program, - vertices: { - pos: { data: vertices, format: "float32x2" }, - }, - uniforms: { + bindingResources: { Transform: transforms, Material: materials, }, - drawVertex: { vertexCount: 3, instanceCount: 2 }, + geometry: { + vertices: { + pos: { data: vertices, format: "float32x2" }, + }, + draw: { __type__: "DrawVertex", vertexCount: 3, instanceCount: 2 }, + } }] }; diff --git a/examples/src/WebGL2Samples/draw_primitive_restart.ts b/examples/src/WebGL2Samples/draw_primitive_restart.ts index 7a2e4e52ce3915b94d1b909b1c12158673dd9eb8..e321c6eb49c7b99c26b26492bd5292c3ef2a716d 100644 --- a/examples/src/WebGL2Samples/draw_primitive_restart.ts +++ b/examples/src/WebGL2Samples/draw_primitive_restart.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPipeline, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderObject, RenderPipeline, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource } from "./utility"; const canvas = document.createElement("canvas"); @@ -8,7 +8,7 @@ canvas.width = Math.min(window.innerWidth, window.innerHeight); canvas.height = canvas.width; document.body.appendChild(canvas); -const renderingContext: IGLCanvasContext = { canvasId: "glcanvas" }; +const renderingContext: CanvasContext = { canvasId: "glcanvas" }; const webgl = new WebGL(renderingContext); // https://www.khronos.org/registry/webgl/specs/latest/2.0/#5.18 @@ -22,8 +22,7 @@ const vertexPosBuffer = new Float32Array([ 1.0, 1.0, ]); -const program: IRenderPipeline = { - primitive: { topology: "triangle-strip" }, +const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, @@ -37,17 +36,20 @@ const indices = new Uint16Array([ 0, 1, 2, MAX_UNSIGNED_SHORT, 2, 3, 1 ]); -const vertexArray: { vertices?: IVertexAttributes } = { +const vertexArray: { vertices?: VertexAttributes } = { vertices: { pos: { data: vertexPosBuffer, format: "float32x2" }, }, }; -const renderObject: IRenderObject = { - vertices: vertexArray.vertices, - indices, - uniforms: {}, - drawIndexed: { indexCount: 7, instanceCount: 2 }, +const renderObject: RenderObject = { + bindingResources: {}, + geometry: { + primitive: { topology: "triangle-strip" }, + vertices: vertexArray.vertices, + indices, + draw: { __type__: "DrawIndexed", indexCount: 7, instanceCount: 2 }, + }, pipeline: program, }; diff --git a/examples/src/WebGL2Samples/draw_range_arrays.ts b/examples/src/WebGL2Samples/draw_range_arrays.ts index 5cf681bb216e734956601aba46ad14739ff8a89a..114fdf8da14bb3fe986bde6c4e9dcf5033e1a464 100644 --- a/examples/src/WebGL2Samples/draw_range_arrays.ts +++ b/examples/src/WebGL2Samples/draw_range_arrays.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, IRenderPipeline, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderObject, RenderPass, RenderPipeline, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource } from "./utility"; const canvas = document.createElement("canvas"); @@ -8,7 +8,7 @@ canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); -const renderingContext: IGLCanvasContext = { canvasId: "glcanvas" }; +const renderingContext: CanvasContext = { canvasId: "glcanvas" }; const webgl = new WebGL(renderingContext); const vertexPosBuffer = new Float32Array([ @@ -26,8 +26,7 @@ const vertexPosBuffer = new Float32Array([ -0.5, -0.5, ]); -const pipeline: IRenderPipeline = { - primitive: { topology: "triangle-strip" }, +const pipeline: RenderPipeline = { vertex: { code: getShaderSource("vs") }, @@ -37,19 +36,23 @@ const pipeline: IRenderPipeline = { } }; -const vertexArray: { vertices?: IVertexAttributes } = { +const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: vertexPosBuffer, format: "float32x2" }, } }; const vertexCount = 12; -const renderObject: IRenderObject = { - vertices: vertexArray.vertices, - pipeline, +const renderObject: RenderObject = { + pipeline: pipeline, + geometry: { + primitive: { topology: "triangle-strip" }, + vertices: vertexArray.vertices, + draw: undefined, + } }; -const rp: IRenderPass = { +const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], @@ -60,12 +63,18 @@ const rp: IRenderPass = { { ...renderObject, viewport: { x: 0, y: 0, width: canvas.width / 2, height: canvas.height }, - drawVertex: { firstVertex: 0, vertexCount: vertexCount / 2 }, + geometry: { + ...renderObject.geometry, + draw: { __type__: "DrawVertex", firstVertex: 0, vertexCount: vertexCount / 2 }, + } }, { ...renderObject, viewport: { x: canvas.width / 2, y: 0, width: canvas.width / 2, height: canvas.height }, - drawVertex: { firstVertex: 6, vertexCount: vertexCount / 2 }, + geometry: { + ...renderObject.geometry, + draw: { __type__: "DrawVertex", firstVertex: 6, vertexCount: vertexCount / 2 }, + }, }, ], }; diff --git a/examples/src/WebGL2Samples/fbo_blit.ts b/examples/src/WebGL2Samples/fbo_blit.ts index 394d776a7f7687122037b40f1b6234451bcf585c..87b8080c8dfb48ea4df3388d442886d1630f7986 100644 --- a/examples/src/WebGL2Samples/fbo_blit.ts +++ b/examples/src/WebGL2Samples/fbo_blit.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, IRenderPassDescriptor, IRenderPipeline, ISampler, ITexture, ITextureView, IVertexAttributes } from "@feng3d/render-api"; -import { IGLBlitFramebuffer, IGLBlitFramebufferItem, IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderObject, RenderPass, RenderPassDescriptor, RenderPipeline, Sampler, Texture, TextureView, VertexAttributes } from "@feng3d/render-api"; +import { BlitFramebuffer, BlitFramebufferItem, WebGL } from "@feng3d/webgl"; import { getShaderSource, loadImage } from "./utility"; const canvas = document.createElement("canvas"); @@ -8,11 +8,10 @@ canvas.width = Math.min(window.innerWidth, window.innerHeight); canvas.height = canvas.width; document.body.appendChild(canvas); -const renderingContext: IGLCanvasContext = { canvasId: "glcanvas" }; +const renderingContext: CanvasContext = { canvasId: "glcanvas" }; const webgl = new WebGL(renderingContext); -const program: IRenderPipeline = { - primitive: { topology: "triangle-list" }, +const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, @@ -39,7 +38,7 @@ const vertexTexBuffer = new Float32Array([ 0.0, 1.0 ]); -const vertices: IVertexAttributes = { +const vertices: VertexAttributes = { position: { data: vertexPosBuffer, format: "float32x2" }, texcoord: { data: vertexTexBuffer, format: "float32x2" }, }; @@ -51,39 +50,38 @@ loadImage("../../assets/img/Di-3d.png", (image) => y: image.height }; - const textureDiffuse: ITexture = { + const textureDiffuse: Texture = { size: [image.width, image.height], format: "rgba8unorm", sources: [{ image, flipY: true }], }; - const samplerDiffuse: ISampler = { + const samplerDiffuse: Sampler = { minFilter: "linear", magFilter: "linear", }; - const textureColorBuffer: ITexture = { + const textureColorBuffer: Texture = { format: "rgba8unorm", size: [FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y], }; - const samplerColorBuffer: ISampler = { + const samplerColorBuffer: Sampler = { minFilter: "linear", magFilter: "linear", }; // 此处 Renderbuffer 直接使用 IGLTextureView 替代。 - const colorRenderbuffer: ITextureView = { texture: { format: "rgba8unorm", size: [FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y] } }; + const colorRenderbuffer: TextureView = { texture: { format: "rgba8unorm", size: [FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y] } }; - const vertexArray: { vertices?: IVertexAttributes } = { + const vertexArray: { vertices?: VertexAttributes } = { vertices, }; - const renderObject: IRenderObject = { + const renderObject: RenderObject = { viewport: { x: 0, y: 0, width: FRAMEBUFFER_SIZE.x, height: FRAMEBUFFER_SIZE.y }, pipeline: program, - vertices: vertexArray.vertices, - uniforms: { + bindingResources: { MVP: new Float32Array([ 0.8, 0.0, 0.0, 0.0, 0.0, 0.8, 0.0, 0.0, @@ -92,11 +90,15 @@ loadImage("../../assets/img/Di-3d.png", (image) => ]), diffuse: { texture: textureDiffuse, sampler: samplerDiffuse }, }, - drawVertex: { firstVertex: 0, vertexCount: 6 } + geometry: { + primitive: { topology: "triangle-list" }, + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", firstVertex: 0, vertexCount: 6 } + } }; // Render FBO - const fboRenderPass: IRenderPass = { + const fboRenderPass: RenderPass = { descriptor: { colorAttachments: [{ view: colorRenderbuffer, @@ -106,7 +108,7 @@ loadImage("../../assets/img/Di-3d.png", (image) => renderObjects: [renderObject], }; - const framebufferResolve: IRenderPassDescriptor = { + const framebufferResolve: RenderPassDescriptor = { colorAttachments: [{ view: { texture: textureColorBuffer, baseMipLevel: 0 }, clearValue: [0.7, 0.0, 0.0, 1.0] @@ -114,11 +116,11 @@ loadImage("../../assets/img/Di-3d.png", (image) => }; // - const renderPassResolve: IRenderPass = { + const renderPassResolve: RenderPass = { descriptor: framebufferResolve, }; - const blitFramebuffers: IGLBlitFramebufferItem[] = []; + const blitFramebuffers: BlitFramebufferItem[] = []; const TILE = 4; const BORDER = 2; for (let j = 0; j < TILE; j++) @@ -141,17 +143,16 @@ loadImage("../../assets/img/Di-3d.png", (image) => } } - const blitFramebuffer: IGLBlitFramebuffer = { - __type: "BlitFramebuffer", + const blitFramebuffer: BlitFramebuffer = { + __type__: "BlitFramebuffer", read: fboRenderPass.descriptor, draw: renderPassResolve.descriptor, blitFramebuffers, }; - const renderObject2: IRenderObject = { + const renderObject2: RenderObject = { viewport: { x: 0, y: 0, width: canvas.width, height: canvas.height }, - vertices: vertexArray.vertices, - uniforms: { + bindingResources: { MVP: new Float32Array([ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, @@ -160,11 +161,14 @@ loadImage("../../assets/img/Di-3d.png", (image) => ]), diffuse: { texture: textureColorBuffer, sampler: samplerColorBuffer }, }, - drawVertex: { firstVertex: 0, vertexCount: 6 }, + geometry: { + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", firstVertex: 0, vertexCount: 6 }, + }, pipeline: program, }; - const renderPass2: IRenderPass = { + const renderPass2: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], diff --git a/examples/src/WebGL2Samples/fbo_multisample.ts b/examples/src/WebGL2Samples/fbo_multisample.ts index 00a8f2ff43edd9f4d64ff3133e0991e8735476cc..5f7eb6c1e5d913396dc38a0eb0cbfef1f00cb2d4 100644 --- a/examples/src/WebGL2Samples/fbo_multisample.ts +++ b/examples/src/WebGL2Samples/fbo_multisample.ts @@ -1,5 +1,5 @@ -import { IRenderPass, IRenderPassDescriptor, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderPass, RenderPassDescriptor, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { mat4, vec3 } from "gl-matrix"; import { getShaderSource } from "./utility"; @@ -9,7 +9,7 @@ canvas.width = Math.min(window.innerWidth, window.innerHeight); canvas.height = canvas.width; document.body.appendChild(canvas); -const renderingContext: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; +const renderingContext: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(renderingContext); // -- Init program @@ -19,16 +19,14 @@ const PROGRAM = { MAX: 2 }; -const programs: IRenderPipeline[] = [ +const programs: RenderPipeline[] = [ { vertex: { code: getShaderSource("vs-render") }, fragment: { code: getShaderSource("fs-render") }, - primitive: { topology: "LINE_LOOP" }, }, { vertex: { code: getShaderSource("vs-splash") }, fragment: { code: getShaderSource("fs-splash") }, - primitive: { topology: "triangle-list" }, }, ]; @@ -70,20 +68,20 @@ const FRAMEBUFFER_SIZE = { x: canvas.width, y: canvas.height }; -const texture: ITexture = { +const texture: Texture = { format: "rgba8unorm", size: [FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y] }; -const sampler: ISampler = { minFilter: "nearest", magFilter: "nearest" }; +const sampler: Sampler = { minFilter: "nearest", magFilter: "nearest" }; // -- Init Frame Buffers -const framebuffer: IRenderPassDescriptor = { +const framebuffer: RenderPassDescriptor = { colorAttachments: [{ view: { texture, baseMipLevel: 0 }, clearValue: [0.0, 0.0, 0.0, 1.0] }], sampleCount: 4 // 多重采样 }; // -- Init VertexArray -const vertexArrays: { vertices?: IVertexAttributes }[] = [ +const vertexArrays: { vertices?: VertexAttributes }[] = [ { vertices: { position: { data, format: "float32x2" } } }, @@ -100,13 +98,16 @@ const IDENTITY = mat4.create(); // -- Render // Pass 1 -const renderPass1: IRenderPass = { +const renderPass1: RenderPass = { descriptor: framebuffer, renderObjects: [{ pipeline: programs[PROGRAM.TEXTURE], - vertices: vertexArrays[PROGRAM.TEXTURE].vertices, - uniforms: { MVP: IDENTITY }, - drawVertex: { vertexCount }, + bindingResources: { MVP: IDENTITY }, + geometry: { + primitive: { topology: "LINE_LOOP" }, + vertices: vertexArrays[PROGRAM.TEXTURE].vertices, + draw: { __type__: "DrawVertex", vertexCount }, + } }] }; @@ -117,14 +118,17 @@ vec3.set(scaleVector3, 8.0, 8.0, 8.0); const mvp = mat4.create(); mat4.scale(mvp, IDENTITY, scaleVector3); -const renderPass2: IRenderPass = { +const renderPass2: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects: [ { pipeline: programs[PROGRAM.SPLASH], - vertices: vertexArrays[PROGRAM.SPLASH].vertices, - uniforms: { diffuse: { texture, sampler }, MVP: mvp }, - drawVertex: { vertexCount: 6 }, + bindingResources: { diffuse: { texture, sampler }, MVP: mvp }, + geometry: { + primitive: { topology: "triangle-list" }, + vertices: vertexArrays[PROGRAM.SPLASH].vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } } ], }; diff --git a/examples/src/WebGL2Samples/fbo_new_blend_equation.ts b/examples/src/WebGL2Samples/fbo_new_blend_equation.ts index 1180ada0cac52210dcf02727493b954bed986172..ab0c3c8f1ec881c736dfdd8718f37ebba0829252 100644 --- a/examples/src/WebGL2Samples/fbo_new_blend_equation.ts +++ b/examples/src/WebGL2Samples/fbo_new_blend_equation.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, IRenderPassObject, IRenderPipeline, ISampler, ITexture, IVertexAttributes, IViewport } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderPassObject, RenderObject, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes, Viewport } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource, loadImage } from "./utility"; @@ -9,7 +9,7 @@ canvas.width = Math.min(window.innerWidth, window.innerHeight); canvas.height = canvas.width; document.body.appendChild(canvas); -const renderingContext: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; +const renderingContext: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(renderingContext); // -- Divide viewport @@ -59,7 +59,7 @@ viewport[Corners.TOP_LEFT] = { // -- Initialize program -const program: IRenderPipeline = { +const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs"), targets: [{ blend: {} }] }, }; @@ -84,7 +84,7 @@ const texcoords = new Float32Array([ ]); // -- Initilize vertex array -const vertexArray: { vertices?: IVertexAttributes } = { +const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x2" }, textureCoordinates: { data: texcoords, format: "float32x2" }, @@ -92,12 +92,12 @@ const vertexArray: { vertices?: IVertexAttributes } = { }; // -- Load texture then render -const sampler: ISampler = { +const sampler: Sampler = { minFilter: "linear", magFilter: "linear" }; const imageUrl = "../../assets/img/Di-3d.png"; -let texture: ITexture; +let texture: Texture; loadImage(imageUrl, function (image) { texture = { @@ -119,22 +119,24 @@ function render() 0.0, 0.0, 0.0, 1.0 ]); - const renderObject: IRenderObject = { + const renderObject: RenderObject = { pipeline: program, - vertices: vertexArray.vertices, - uniforms: { mvp: matrix, diffuse: { texture, sampler } }, - drawVertex: { vertexCount: 6 }, + bindingResources: { mvp: matrix, diffuse: { texture, sampler } }, + geometry:{ + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }; - const renderObjects: IRenderPassObject[] = []; - const renderPass: IRenderPass = { + const renderObjects: RenderPassObject[] = []; + const renderPass: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.5, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects, }; for (let i = 0; i < Corners.MAX; ++i) { - const viewport0: IViewport = { x: viewport[i].x, y: viewport[i].y, width: viewport[i].z, height: viewport[i].w }; + const viewport0: Viewport = { x: viewport[i].x, y: viewport[i].y, width: viewport[i].z, height: viewport[i].w }; if (i === Corners.TOP_LEFT) { diff --git a/examples/src/WebGL2Samples/fbo_read_pixels.ts b/examples/src/WebGL2Samples/fbo_read_pixels.ts index 21e86a53211cb3ba90d1d35863202f173089d10d..2c863bec045d43c8ffe1c47469845d28df36cb94 100644 --- a/examples/src/WebGL2Samples/fbo_read_pixels.ts +++ b/examples/src/WebGL2Samples/fbo_read_pixels.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, IRenderPassDescriptor, IRenderPassObject, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderPassObject, RenderObject, RenderPass, RenderPassDescriptor, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource } from "./utility"; const canvas = document.createElement("canvas"); @@ -8,7 +8,7 @@ canvas.width = Math.min(window.innerWidth, window.innerHeight); canvas.height = canvas.width; document.body.appendChild(canvas); -const renderingContext: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; +const renderingContext: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(renderingContext); // -- Divide viewport @@ -51,15 +51,13 @@ viewport[Textures.BLUE] = { // -- Initialize program // Multiple out shaders -const multipleOutputProgram: IRenderPipeline = { +const multipleOutputProgram: RenderPipeline = { vertex: { code: getShaderSource("vs-multiple-output") }, fragment: { code: getShaderSource("fs-multiple-output") }, - primitive: { topology: "triangle-list" }, }; // Layer shaders -const layerProgram: IRenderPipeline = { +const layerProgram: RenderPipeline = { vertex: { code: getShaderSource("vs-layer") }, fragment: { code: getShaderSource("fs-layer") }, - primitive: { topology: "triangle-list" }, }; // -- Initialize buffer @@ -84,13 +82,13 @@ const texcoords = new Float32Array([ // -- Initialize vertex array -const multipleOutputVertexArray: { vertices?: IVertexAttributes } = { +const multipleOutputVertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x2" }, } }; -const layerVertexArray: { vertices?: IVertexAttributes } = { +const layerVertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x2" }, textureCoordinates: { data: texcoords, format: "float32x2" }, @@ -102,16 +100,16 @@ const layerVertexArray: { vertices?: IVertexAttributes } = { const w = 16; const h = 16; -const texture: ITexture = { +const texture: Texture = { dimension: "2d-array", size: [w, h, 3], format: "rgba8unorm", }; -const sampler: ISampler = { lodMinClamp: 0, lodMaxClamp: 0, minFilter: "nearest", magFilter: "nearest" }; +const sampler: Sampler = { lodMinClamp: 0, lodMaxClamp: 0, minFilter: "nearest", magFilter: "nearest" }; // -- Initialize frame buffer -const frameBuffer: IRenderPassDescriptor = { +const frameBuffer: RenderPassDescriptor = { colorAttachments: [ { view: { texture, baseMipLevel: 0, baseArrayLayer: Textures.RED } }, { view: { texture, baseMipLevel: 0, baseArrayLayer: Textures.GREEN } }, @@ -128,34 +126,39 @@ const matrix = new Float32Array([ 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ]); -const rp1: IRenderPass = { +const rp1: RenderPass = { descriptor: frameBuffer, renderObjects: [ { viewport: { x: 0, y: 0, width: w, height: h }, pipeline: multipleOutputProgram, - uniforms: { mvp: matrix }, - vertices: multipleOutputVertexArray.vertices, - drawVertex: { vertexCount: 6 }, + bindingResources: { mvp: matrix }, + geometry: { + primitive: { topology: "triangle-list" }, + vertices: multipleOutputVertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }], }; -const renderObjects: IRenderPassObject[] = []; +const renderObjects: RenderPassObject[] = []; // Pass 2 -const rp: IRenderPass = { +const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects }; -const ro: IRenderObject = { +const ro: RenderObject = { pipeline: layerProgram, - uniforms: { + bindingResources: { mvp: matrix, diffuse: { texture, sampler }, layer: 0, }, - vertices: layerVertexArray.vertices, - drawVertex: { vertexCount: 6 }, + geometry: { + vertices: layerVertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }; for (let i = 0; i < Textures.MAX; ++i) @@ -164,7 +167,7 @@ for (let i = 0; i < Textures.MAX; ++i) { ...ro, viewport: { x: viewport[i].x, y: viewport[i].y, width: viewport[i].z, height: viewport[i].w }, - uniforms: { ...ro.uniforms, layer: i }, + bindingResources: { ...ro.bindingResources, layer: i }, }); } @@ -172,18 +175,24 @@ webgl.submit({ commandEncoders: [{ passEncoders: [rp1, rp] }] }); const data = new Uint8Array(w * h * 4 * 3); -webgl.runReadPixels({ - frameBuffer, attachmentPoint: "COLOR_ATTACHMENT0", - x: 0, y: 0, width: w, height: h, format: "RGBA", type: "UNSIGNED_BYTE", dstData: data, dstOffset: 0 +let result = webgl.readPixels({ + textureView: frameBuffer.colorAttachments[0].view, + origin: [0, 0], + copySize: [w, h], }); -webgl.runReadPixels({ - frameBuffer, attachmentPoint: "COLOR_ATTACHMENT1", - x: 0, y: 0, width: w, height: h, format: "RGBA", type: "UNSIGNED_BYTE", dstData: data, dstOffset: w * h * 4 +data.set(new Uint8Array(result.buffer), 0); +result = webgl.readPixels({ + textureView: frameBuffer.colorAttachments[1].view, + origin: [0, 0], + copySize: [w, h], }); -webgl.runReadPixels({ - frameBuffer, attachmentPoint: "COLOR_ATTACHMENT1", - x: 0, y: 0, width: w, height: h, format: "RGBA", type: "UNSIGNED_BYTE", dstData: data, dstOffset: w * h * 4 * 2 +data.set(new Uint8Array(result.buffer), w * h * 4); +result = webgl.readPixels({ + textureView: frameBuffer.colorAttachments[2].view, + origin: [0, 0], + copySize: [w, h], }); +data.set(new Uint8Array(result.buffer), w * h * 4 * 2); console.log(data); diff --git a/examples/src/WebGL2Samples/fbo_rtt_depth_texture.ts b/examples/src/WebGL2Samples/fbo_rtt_depth_texture.ts index 75f628d64205c80c488df3338bcad26c7e61904e..21b471e3364c9bbeb7e091eb6a862b15ba28fd2e 100644 --- a/examples/src/WebGL2Samples/fbo_rtt_depth_texture.ts +++ b/examples/src/WebGL2Samples/fbo_rtt_depth_texture.ts @@ -1,5 +1,5 @@ -import { IRenderPass, IRenderPassDescriptor, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderPass, RenderPassDescriptor, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource } from "./utility"; const canvas = document.createElement("canvas"); @@ -8,7 +8,7 @@ canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); -const renderingContext: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2", antialias: false }; +const renderingContext: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2", webGLContextAttributes: { antialias: false } }; const webgl = new WebGL(renderingContext); const windowSize = { @@ -19,16 +19,14 @@ const windowSize = { // -- Initialize program // Depth shaders -const depthProgram: IRenderPipeline = { +const depthProgram: RenderPipeline = { vertex: { code: getShaderSource("vs-depth") }, fragment: { code: getShaderSource("fs-depth") }, depthStencil: {}, - primitive: { topology: "triangle-list" }, }; // Draw shaders -const drawProgram: IRenderPipeline = { +const drawProgram: RenderPipeline = { vertex: { code: getShaderSource("vs-draw") }, fragment: { code: getShaderSource("fs-draw") }, - primitive: { topology: "triangle-list" }, }; // -- Initialize buffer @@ -59,13 +57,13 @@ const quadTexcoords = new Float32Array([ // -- Initialize vertex array -const triVertexArray: { vertices?: IVertexAttributes } = { +const triVertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: triPositions, format: "float32x3" }, } }; -const quadVertexArray: { vertices?: IVertexAttributes } = { +const quadVertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: quadPositions, format: "float32x2" }, textureCoordinates: { data: quadTexcoords, format: "float32x2" }, @@ -76,15 +74,15 @@ const quadVertexArray: { vertices?: IVertexAttributes } = { // the proper texture format combination can be found here // https://www.khronos.org/registry/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml -const depthTexture: ITexture = { +const depthTexture: Texture = { size: [windowSize.x, windowSize.y], format: "depth16unorm", }; -const depthSampler: ISampler = { addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge", minFilter: "nearest", magFilter: "nearest" }; +const depthSampler: Sampler = { addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge", minFilter: "nearest", magFilter: "nearest" }; // -- Initialize frame buffer -const frameBuffer: IRenderPassDescriptor = { +const frameBuffer: RenderPassDescriptor = { colorAttachments: [], depthStencilAttachment: { view: { texture: depthTexture, baseMipLevel: 0 }, depthLoadOp: "clear" }, }; @@ -92,26 +90,32 @@ const frameBuffer: IRenderPassDescriptor = { // -- Render // Pass 1: Depth -const renderPass: IRenderPass = { +const renderPass: RenderPass = { descriptor: frameBuffer, renderObjects: [{ pipeline: depthProgram, - vertices: triVertexArray.vertices, - drawVertex: { vertexCount: 3 }, + geometry: { + primitive: { topology: "triangle-list" }, + vertices: triVertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 3 }, + } }], }; // Pass 2: Draw -const rp2: IRenderPass = { +const rp2: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }], }, renderObjects: [{ pipeline: drawProgram, - uniforms: { depthMap: { texture: depthTexture, sampler: depthSampler } }, - vertices: quadVertexArray.vertices, - drawVertex: { vertexCount: 6 }, + bindingResources: { depthMap: { texture: depthTexture, sampler: depthSampler } }, + geometry: { + primitive: { topology: "triangle-list" }, + vertices: quadVertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }], }; diff --git a/examples/src/WebGL2Samples/fbo_rtt_draw_buffers.ts b/examples/src/WebGL2Samples/fbo_rtt_draw_buffers.ts index 70b60f8c4cce1b0a7e84ae34e69f6da0b15996b7..233ad8c8329df7dadad6537f005ae8dbd2f6ace2 100644 --- a/examples/src/WebGL2Samples/fbo_rtt_draw_buffers.ts +++ b/examples/src/WebGL2Samples/fbo_rtt_draw_buffers.ts @@ -1,5 +1,5 @@ -import { IRenderPass, IRenderPassDescriptor, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderPass, RenderPassDescriptor, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource } from "./utility"; const canvas = document.createElement("canvas"); @@ -8,7 +8,7 @@ canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); -const renderingContext: IGLCanvasContext = { canvasId: "glcanvas" }; +const renderingContext: CanvasContext = { canvasId: "glcanvas" }; const webgl = new WebGL(renderingContext); const windowSize = { @@ -19,17 +19,15 @@ const windowSize = { // -- Initialize program // Draw buffer shaders -const drawBufferProgram: IRenderPipeline = { +const drawBufferProgram: RenderPipeline = { vertex: { code: getShaderSource("vs-draw-buffer") }, fragment: { code: getShaderSource("fs-draw-buffer") }, - primitive: { topology: "triangle-list" }, }; // Draw shaders -const drawProgram: IRenderPipeline = { +const drawProgram: RenderPipeline = { vertex: { code: getShaderSource("vs-draw") }, fragment: { code: getShaderSource("fs-draw") }, - primitive: { topology: "triangle-list" }, }; // -- Initialize buffer @@ -60,13 +58,13 @@ const quadTexcoords = new Float32Array([ // -- Initialize vertex array -const triVertexArray: { vertices?: IVertexAttributes } = { +const triVertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: triPositions, format: "float32x3" } } }; -const quadVertexArray: { vertices?: IVertexAttributes } = { +const quadVertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: quadPositions, format: "float32x2" }, textureCoordinates: { data: quadTexcoords, format: "float32x2" }, @@ -75,21 +73,21 @@ const quadVertexArray: { vertices?: IVertexAttributes } = { // -- Initialize texture targets -const color1Texture: ITexture = { +const color1Texture: Texture = { format: "rgba8unorm", size: [windowSize.x, windowSize.y], }; -const color1Sampler: ISampler = { addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge", minFilter: "nearest", magFilter: "nearest" }; +const color1Sampler: Sampler = { addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge", minFilter: "nearest", magFilter: "nearest" }; -const color2Texture: ITexture = { +const color2Texture: Texture = { format: "rgba8unorm", size: [windowSize.x, windowSize.y], }; -const color2Sampler: ISampler = { addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge", minFilter: "nearest", magFilter: "nearest" }; +const color2Sampler: Sampler = { addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge", minFilter: "nearest", magFilter: "nearest" }; // -- Initialize frame buffer -const frameBuffer: IRenderPassDescriptor = { +const frameBuffer: RenderPassDescriptor = { colorAttachments: [ { view: { texture: color1Texture, baseMipLevel: 0 } }, { view: { texture: color2Texture, baseMipLevel: 0 } }, @@ -98,26 +96,32 @@ const frameBuffer: IRenderPassDescriptor = { // -- Render -const renderPass: IRenderPass = { +const renderPass: RenderPass = { descriptor: frameBuffer, renderObjects: [{ pipeline: drawBufferProgram, - vertices: triVertexArray.vertices, - drawVertex: { vertexCount: 3 }, + geometry:{ + primitive: { topology: "triangle-list" }, + vertices: triVertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 3 }, + } }], }; // Pass 2: Draw to screen -const renderPass2: IRenderPass = { +const renderPass2: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects: [{ pipeline: drawProgram, - uniforms: { + bindingResources: { color1Map: { texture: color1Texture, sampler: color1Sampler }, color2Map: { texture: color2Texture, sampler: color2Sampler }, }, - vertices: quadVertexArray.vertices, - drawVertex: { vertexCount: 6 }, + geometry:{ + primitive: { topology: "triangle-list" }, + vertices: quadVertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }], }; diff --git a/examples/src/WebGL2Samples/fbo_rtt_texture_array.ts b/examples/src/WebGL2Samples/fbo_rtt_texture_array.ts index d18b0806c1d27a8af146ba359eb94edc81bbf3f5..ddf9ca2996544d386aec55357bf51fc3252a7062 100644 --- a/examples/src/WebGL2Samples/fbo_rtt_texture_array.ts +++ b/examples/src/WebGL2Samples/fbo_rtt_texture_array.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, IRenderPassDescriptor, IRenderPassObject, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderPassObject, RenderObject, RenderPass, RenderPassDescriptor, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource } from "./utility"; const canvas = document.createElement("canvas"); @@ -8,7 +8,7 @@ canvas.width = Math.min(window.innerWidth, window.innerHeight); canvas.height = canvas.width; document.body.appendChild(canvas); -const renderingContext: IGLCanvasContext = { canvasId: "glcanvas" }; +const renderingContext: CanvasContext = { canvasId: "glcanvas" }; const webgl = new WebGL(renderingContext); // -- Divide viewport @@ -51,15 +51,13 @@ viewport[Textures.BLUE] = { // -- Initialize program // Multiple out shaders -const multipleOutputProgram: IRenderPipeline = { +const multipleOutputProgram: RenderPipeline = { vertex: { code: getShaderSource("vs-multiple-output") }, fragment: { code: getShaderSource("fs-multiple-output") }, - primitive: { topology: "triangle-list" }, }; // Layer shaders -const layerProgram: IRenderPipeline = { +const layerProgram: RenderPipeline = { vertex: { code: getShaderSource("vs-layer") }, fragment: { code: getShaderSource("fs-layer") }, - primitive: { topology: "triangle-list" }, }; // -- Initialize buffer @@ -84,13 +82,13 @@ const texcoords = new Float32Array([ // -- Initialize vertex array -const multipleOutputVertexArray: { vertices?: IVertexAttributes } = { +const multipleOutputVertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x2" }, } }; -const layerVertexArray: { vertices?: IVertexAttributes } = { +const layerVertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x2" }, textureCoordinates: { data: texcoords, format: "float32x2" }, @@ -102,16 +100,16 @@ const layerVertexArray: { vertices?: IVertexAttributes } = { const w = 16; const h = 16; -const texture: ITexture = { +const texture: Texture = { dimension: "2d-array", format: "rgba8unorm", size: [w, h, 3], }; -const sampler: ISampler = { minFilter: "nearest", magFilter: "nearest", lodMinClamp: 0, lodMaxClamp: 0 }; +const sampler: Sampler = { minFilter: "nearest", magFilter: "nearest", lodMinClamp: 0, lodMaxClamp: 0 }; // -- Initialize frame buffer -const frameBuffer: IRenderPassDescriptor = { +const frameBuffer: RenderPassDescriptor = { colorAttachments: [ { view: { texture, baseMipLevel: 0, baseArrayLayer: Textures.RED } }, { view: { texture, baseMipLevel: 0, baseArrayLayer: Textures.GREEN } }, @@ -130,32 +128,38 @@ const matrix = new Float32Array([ 0.0, 0.0, 0.0, 1.0 ]); -const renderPass1: IRenderPass = { +const renderPass1: RenderPass = { descriptor: frameBuffer, renderObjects: [ { viewport: { x: 0, y: 0, width: w, height: h }, pipeline: multipleOutputProgram, - uniforms: { mvp: matrix }, - vertices: multipleOutputVertexArray.vertices, - drawVertex: { vertexCount: 6 }, + bindingResources: { mvp: matrix }, + geometry:{ + primitive: { topology: "triangle-list" }, + vertices: multipleOutputVertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }] }; // Pass 2 -const renderObjects: IRenderPassObject[] = []; -const renderPass: IRenderPass = { +const renderObjects: RenderPassObject[] = []; +const renderPass: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }], }, renderObjects, }; -const renderObject: IRenderObject = { +const renderObject: RenderObject = { pipeline: layerProgram, - uniforms: { mvp: matrix, diffuse: { texture, sampler } }, - vertices: layerVertexArray.vertices, - + bindingResources: { mvp: matrix, diffuse: { texture, sampler } }, + geometry: { + primitive: { topology: "triangle-list" }, + vertices: layerVertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }; // @@ -165,8 +169,11 @@ for (let i = 0; i < Textures.MAX; ++i) { viewport: { x: viewport[i].x, y: viewport[i].y, width: viewport[i].z, height: viewport[i].w }, ...renderObject, - uniforms: { ...renderObject.uniforms, layer: i }, - drawVertex: { vertexCount: 6 }, + bindingResources: { ...renderObject.bindingResources, layer: i }, + geometry: { + ...renderObject.geometry, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } } ); } diff --git a/examples/src/WebGL2Samples/geo_vertex_format.ts b/examples/src/WebGL2Samples/geo_vertex_format.ts index 8b590d7e3d2d680edc833628ad677de1652e2dc4..8e419901ec5a6decc14af0a178a761da40227d5e 100644 --- a/examples/src/WebGL2Samples/geo_vertex_format.ts +++ b/examples/src/WebGL2Samples/geo_vertex_format.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderObject, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { mat4, vec3 } from "gl-matrix"; import { HalfFloat } from "./third-party/HalfFloatUtility"; import { getShaderSource, loadImage } from "./utility"; @@ -12,13 +12,12 @@ import { getShaderSource, loadImage } from "./utility"; canvas.height = canvas.width; document.body.appendChild(canvas); - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2", antialias: false }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2", webGLContextAttributes: { antialias: false } }; const webgl = new WebGL(rc); // -- Init program - const program: IRenderPipeline = { + const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") }, - primitive: { topology: "triangle-list", cullFace: "back" }, depthStencil: {}, }; @@ -150,7 +149,7 @@ import { getShaderSource, loadImage } from "./utility"; // -- Init VertexArray - const vertexArray: { vertices?: IVertexAttributes } = { + const vertexArray: { vertices?: VertexAttributes } = { vertices: { a_position: { data: positions, format: "float32x3" }, a_normal: { data: normals, format: "float16x4", arrayStride: 6 }, // 由于不支持类型 "float16x3",则需要设置 arrayStride 为6,表示每次间隔3个半浮点数。 @@ -161,8 +160,8 @@ import { getShaderSource, loadImage } from "./utility"; // -- Init Texture const imageUrl = "../../assets/img/Di-3d.png"; - let texture: ITexture; - let sampler: ISampler; + let texture: Texture; + let sampler: Sampler; loadImage(imageUrl, function (image) { // -- Init 2D Texture @@ -201,20 +200,23 @@ import { getShaderSource, loadImage } from "./utility"; const lightPosition = [0.0, 0.0, 5.0]; - const ro: IRenderObject = { + const ro: RenderObject = { pipeline: program, - vertices: vertexArray.vertices, - indices: new Uint16Array(cubeVertexIndices), - uniforms: { + bindingResources: { u_model: modelMatrix, u_modelInvTrans: modelInvTrans, u_lightPosition: lightPosition, u_ambient: 0.1, }, - drawIndexed: { indexCount: 36 }, + geometry: { + primitive: { topology: "triangle-list", cullFace: "back" }, + vertices: vertexArray.vertices, + indices: new Uint16Array(cubeVertexIndices), + draw: { __type__: "DrawIndexed", indexCount: 36 }, + } }; - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects: [ro], }; @@ -232,8 +234,8 @@ import { getShaderSource, loadImage } from "./utility"; mat4.multiply(viewProj, perspectiveMatrix, viewMatrix); // - ro.uniforms.u_viewProj = viewProj; - ro.uniforms.s_tex2D = { texture, sampler }; + ro.bindingResources.u_viewProj = viewProj; + ro.bindingResources.s_tex2D = { texture, sampler }; webgl.submit({ commandEncoders: [{ passEncoders: [rp] }] }); diff --git a/examples/src/WebGL2Samples/glsl_centroid.ts b/examples/src/WebGL2Samples/glsl_centroid.ts index de9255040b3d0cd58ee08f886200960ecf0ba018..aec18b7ed4b27e066526ab2bca84beab88c74495 100644 --- a/examples/src/WebGL2Samples/glsl_centroid.ts +++ b/examples/src/WebGL2Samples/glsl_centroid.ts @@ -1,5 +1,5 @@ -import { IPassEncoder, IRenderObject, IRenderPass, IRenderPassDescriptor, IRenderPassObject, IRenderPipeline, ISampler, ITexture, IVertexAttributes, IViewport } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, PassEncoder, RenderObject, RenderPass, RenderPassDescriptor, RenderPassObject, RenderPipeline, Sampler, Texture, VertexAttributes, Viewport } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { mat4, vec3 } from "gl-matrix"; import { getShaderSource } from "./utility"; @@ -9,7 +9,7 @@ canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); -const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; +const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(rc); // -- Divide viewport @@ -24,7 +24,7 @@ const VIEWPORTS = { MAX: 2 }; -const viewport: IViewport[] = new Array(VIEWPORTS.MAX); +const viewport: Viewport[] = new Array(VIEWPORTS.MAX); viewport[VIEWPORTS.LEFT] = { x: 0, @@ -48,18 +48,15 @@ const PROGRAM = { MAX: 3 }; -const programs: IRenderPipeline[] = [ +const programs: RenderPipeline[] = [ { vertex: { code: getShaderSource("vs-render") }, fragment: { code: getShaderSource("fs-render") }, - primitive: { topology: "triangle-list" }, }, { vertex: { code: getShaderSource("vs-render-centroid") }, fragment: { code: getShaderSource("fs-render-centroid") }, - primitive: { topology: "triangle-list" }, }, { vertex: { code: getShaderSource("vs-splash") }, fragment: { code: getShaderSource("fs-splash") }, - primitive: { topology: "triangle-list" }, } ]; @@ -104,8 +101,8 @@ const FRAMEBUFFER_SIZE = { x: canvas.width, y: canvas.height }; -const textures: ITexture[] = []; -const samplers: ISampler[] = []; +const textures: Texture[] = []; +const samplers: Sampler[] = []; for (let i = 0; i < VIEWPORTS.MAX; ++i) { @@ -125,13 +122,13 @@ const FRAMEBUFFER = { COLORBUFFER_CENTROID: 3 }; -const framebuffers: IRenderPassDescriptor[] = [ +const framebuffers: RenderPassDescriptor[] = [ { colorAttachments: [{ view: { texture: textures[0], baseMipLevel: 0 }, clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }], sampleCount: 4 }, { colorAttachments: [{ view: { texture: textures[1], baseMipLevel: 0 }, clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }], sampleCount: 4 }, ]; // -- Init VertexArray -const vertexArrays: { vertices?: IVertexAttributes }[] = [ +const vertexArrays: { vertices?: VertexAttributes }[] = [ { vertices: { position: { data: positions, format: "float32x2" }, @@ -153,33 +150,40 @@ const vertexArrays: { vertices?: IVertexAttributes }[] = [ ]; // -- Render -const passEncoders: IPassEncoder[] = []; +const passEncoders: PassEncoder[] = []; // Pass 1 const IDENTITY = mat4.create(); for (let i = 0; i < VIEWPORTS.MAX; ++i) { // render buffers - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: framebuffers[i], renderObjects: [{ pipeline: programs[i], - vertices: vertexArrays[i].vertices, - uniforms: { MVP: IDENTITY }, - drawVertex: { vertexCount }, + bindingResources: { MVP: IDENTITY }, + geometry: { + primitive: { topology: "triangle-list" }, + vertices: vertexArrays[i].vertices, + draw: { __type__: "DrawVertex", vertexCount }, + } }] }; passEncoders.push(rp); } -const renderObjects: IRenderPassObject[] = []; +const renderObjects: RenderPassObject[] = []; // Pass 2 -const rp2: IRenderPass = { +const rp2: RenderPass = { renderObjects, }; -const ro: IRenderObject = { +const ro: RenderObject = { pipeline: programs[PROGRAM.SPLASH], - vertices: vertexArrays[PROGRAM.SPLASH].vertices, + geometry: { + primitive: { topology: "triangle-list" }, + vertices: vertexArrays[PROGRAM.SPLASH].vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + }, }; const scaleVector3 = vec3.create(); @@ -194,11 +198,13 @@ for (let i = 0; i < VIEWPORTS.MAX; ++i) { ...ro, viewport: viewport[i], - uniforms: { + bindingResources: { MVP: mvp, diffuse: { texture: textures[i], sampler: samplers[i] }, }, - drawVertex: { vertexCount: 6 }, + geometry: { + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } } ); } diff --git a/examples/src/WebGL2Samples/glsl_flat_smooth_interpolators.ts b/examples/src/WebGL2Samples/glsl_flat_smooth_interpolators.ts index 769e1354748f264a0d60d08ec8331059828d764a..acae1e1e3283691ec64b6a25e9abcefd3dce113b 100644 --- a/examples/src/WebGL2Samples/glsl_flat_smooth_interpolators.ts +++ b/examples/src/WebGL2Samples/glsl_flat_smooth_interpolators.ts @@ -1,5 +1,5 @@ -import { IIndicesDataTypes, IRenderPass, IRenderPassObject, IRenderPipeline, IVertexAttributes, IViewport } from "@feng3d/render-api"; -import { getIVertexFormat, IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, IIndicesDataTypes, RenderPassObject, RenderPass, RenderPipeline, VertexAttributes, VertexFormat, Viewport } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { mat4, vec3 } from "gl-matrix"; import { GlTFLoader, Primitive } from "./third-party/gltf-loader"; import { getShaderSource } from "./utility"; @@ -10,7 +10,7 @@ canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); -const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; +const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(rc); // -- Divide viewport @@ -25,7 +25,7 @@ const VIEWPORTS = { MAX: 2 }; -const viewport: IViewport[] = new Array(VIEWPORTS.MAX); +const viewport: Viewport[] = new Array(VIEWPORTS.MAX); viewport[VIEWPORTS.LEFT] = { x: 0, @@ -42,15 +42,13 @@ viewport[VIEWPORTS.RIGHT] = { }; // -- Initialize program -const programs: IRenderPipeline[] = [ +const programs: RenderPipeline[] = [ { vertex: { code: getShaderSource("vs-flat") }, fragment: { code: getShaderSource("fs-flat") }, - primitive: { topology: "triangle-list" }, depthStencil: { depthCompare: "less-equal" }, }, { vertex: { code: getShaderSource("vs-smooth") }, fragment: { code: getShaderSource("fs-smooth") }, - primitive: { topology: "triangle-list" }, depthStencil: { depthCompare: "less-equal" }, } ]; @@ -64,7 +62,7 @@ glTFLoader.loadGLTF(gltfUrl, function (glTF) // -- Initialize vertex array const vertexArrayMaps: { - [key: string]: { vertexArray: { vertices?: IVertexAttributes }, indices: IIndicesDataTypes }[] + [key: string]: { vertexArray: { vertices?: VertexAttributes }, indices: IIndicesDataTypes }[] } = {}; // var in loop @@ -73,7 +71,7 @@ glTFLoader.loadGLTF(gltfUrl, function (glTF) }; let primitive: Primitive; // { matrix: mat4, attributes: { [key: string]: { size: number, type: number, stride: number, offset: number } }, vertexBuffer, indices }; - let vertexArray: { vertices?: IVertexAttributes }; + let vertexArray: { vertices?: VertexAttributes }; let i: number; let len: number; @@ -102,11 +100,11 @@ glTFLoader.loadGLTF(gltfUrl, function (glTF) vertexArray = { vertices: { position: { - data: vertices, format: getIVertexFormat(positionInfo.size), + data: vertices, format: (["float32", "float32x2", "float32x3", "float32x4"] as VertexFormat[])[positionInfo.size], arrayStride: positionInfo.stride, offset: positionInfo.offset }, normal: { - data: vertices, format: getIVertexFormat(normalInfo.size), + data: vertices, format: (["float32", "float32x2", "float32x3", "float32x4"] as VertexFormat[])[normalInfo.size], arrayStride: normalInfo.stride, offset: normalInfo.offset }, }, @@ -137,8 +135,8 @@ glTFLoader.loadGLTF(gltfUrl, function (glTF) // -- Render loop (function render() { - const renderObjects: IRenderPassObject[] = []; - const rp: IRenderPass = { + const renderObjects: RenderPassObject[] = []; + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }], depthStencilAttachment: { depthLoadOp: "clear" } @@ -171,13 +169,16 @@ glTFLoader.loadGLTF(gltfUrl, function (glTF) { viewport: viewport[i], pipeline: programs[i], - vertices: vertexArray.vertices, - indices, - uniforms: { + bindingResources: { mvp: localMVP, mvNormal: localMVNormal, }, - drawIndexed: { indexCount: primitive.indices.length, firstIndex: 0 }, + geometry: { + primitive: { topology: "triangle-list" }, + vertices: vertexArray.vertices, + indices, + draw: { __type__: "DrawIndexed", indexCount: primitive.indices.length, firstIndex: 0 }, + }, }); } } diff --git a/examples/src/WebGL2Samples/glsl_non_square_matrix.ts b/examples/src/WebGL2Samples/glsl_non_square_matrix.ts index 87f68bd9e9945d9115ecf1718163a0514b9fce08..2cdb8692fd848806acdd04f0b0d04f887e24105c 100644 --- a/examples/src/WebGL2Samples/glsl_non_square_matrix.ts +++ b/examples/src/WebGL2Samples/glsl_non_square_matrix.ts @@ -1,5 +1,5 @@ -import { IRenderPass, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource, loadImage } from "./utility"; const canvas = document.createElement("canvas"); @@ -8,13 +8,12 @@ canvas.width = Math.min(window.innerWidth, window.innerHeight); canvas.height = canvas.width; document.body.appendChild(canvas); -const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; +const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(rc); // -- Init program -const program: IRenderPipeline = { +const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") }, - primitive: { topology: "triangle-list" }, }; // -- Init buffers: vec2 Position, vec2 Texcoord @@ -37,7 +36,7 @@ const texCoords = new Float32Array([ ]); // -- Init VertexArray -const vertexArray: { vertices?: IVertexAttributes } = { +const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x2" }, texcoord: { data: texCoords, format: "float32x2" }, @@ -47,14 +46,14 @@ const vertexArray: { vertices?: IVertexAttributes } = { loadImage("../../assets/img/Di-3d.png", function (image) { // -- Init Texture - const texture: ITexture = { + const texture: Texture = { size: [image.width, image.height], format: "rgba8unorm", sources: [{ image, flipY: false, }] }; - const sampler: ISampler = { minFilter: "nearest", magFilter: "nearest" }; + const sampler: Sampler = { minFilter: "nearest", magFilter: "nearest" }; // -- Render const matrix = new Float32Array([ @@ -64,13 +63,16 @@ loadImage("../../assets/img/Di-3d.png", function (image) 0.2, -0.2, 0.0 //translation ]); - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects: [{ pipeline: program, - uniforms: { MVP: matrix, diffuse: { texture, sampler } }, - vertices: vertexArray.vertices, - drawVertex: { vertexCount: 6 }, + bindingResources: { MVP: matrix, diffuse: { texture, sampler } }, + geometry:{ + primitive: { topology: "triangle-list" }, + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }] }; diff --git a/examples/src/WebGL2Samples/query_occlusion.ts b/examples/src/WebGL2Samples/query_occlusion.ts index d15d4446f200cdbb4c13f76bed982be90a22b6dc..48bbc9de0e40e63b8c7955d8c28a65ff402ba266 100644 --- a/examples/src/WebGL2Samples/query_occlusion.ts +++ b/examples/src/WebGL2Samples/query_occlusion.ts @@ -1,7 +1,5 @@ -import { IRenderObject, IRenderPass, IRenderPassObject, IRenderPipeline, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, IGLOcclusionQuery, WebGL } from "@feng3d/webgl"; - -import { watcher } from "@feng3d/watcher"; +import { CanvasContext, OcclusionQuery, RenderObject, RenderPass, RenderPassObject, RenderPipeline, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource } from "./utility"; @@ -13,14 +11,13 @@ canvas.height = window.innerHeight; document.body.appendChild(canvas); // -- Init WebGL Context -const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; +const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(rc); // -- Init Program -const program: IRenderPipeline = { +const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") }, depthStencil: {}, - primitive: { topology: "triangle-list" }, }; // -- Init Buffer @@ -35,15 +32,15 @@ const vertices = new Float32Array([ ]); // -- Init Vertex Array -const vertexArray: { vertices?: IVertexAttributes } = { +const vertexArray: { vertices?: VertexAttributes } = { vertices: { pos: { data: vertices, format: "float32x3", arrayStride: 0, offset: 0 }, } }; -const renderObjects: IRenderPassObject[] = []; +const renderObjects: RenderPassObject[] = []; // -- Render -const rp: IRenderPass = { +const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }], depthStencilAttachment: { depthLoadOp: "clear" }, @@ -51,29 +48,33 @@ const rp: IRenderPass = { renderObjects, }; -const ro: IRenderObject = { - vertices: vertexArray.vertices, +const ro: RenderObject = { pipeline: program, - drawVertex: { firstVertex: 0, vertexCount: 3 }, + geometry: { + primitive: { topology: "triangle-list" }, + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", firstVertex: 0, vertexCount: 3 }, + } }; renderObjects.push(ro); -const occlusionQuery: IGLOcclusionQuery = { - __type: "OcclusionQuery", +const occlusionQuery: OcclusionQuery = { + __type__: "OcclusionQuery", renderObjects: [{ ...ro, - drawVertex: { firstVertex: 3, vertexCount: 3 }, - }] + geometry: { + ...ro.geometry, + draw: { __type__: "DrawVertex", firstVertex: 3, vertexCount: 3 }, + } + }], + onQuery(result: number) { + document.getElementById("samplesPassed").innerHTML = `Any samples passed: ${Number(result)}`; + } }; renderObjects.push(occlusionQuery); webgl.submit({ commandEncoders: [{ passEncoders: [rp] }] }); -watcher.watch(occlusionQuery, "result", () => -{ - document.getElementById("samplesPassed").innerHTML = `Any samples passed: ${Number(occlusionQuery.result.result)}`; -}); - // -- Delete WebGL resources webgl.deleteProgram(program); diff --git a/examples/src/WebGL2Samples/sampler_filter.ts b/examples/src/WebGL2Samples/sampler_filter.ts index 482de0fb757af4bcf0ed2cc14a82fc94310534b2..f3db340d31fed3eeb7c18b78ec85e07e640e512e 100644 --- a/examples/src/WebGL2Samples/sampler_filter.ts +++ b/examples/src/WebGL2Samples/sampler_filter.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, IRenderPassObject, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderPassObject, RenderObject, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource, loadImage } from "./utility"; const canvas = document.createElement("canvas"); @@ -8,7 +8,7 @@ canvas.width = Math.min(window.innerWidth, window.innerHeight); canvas.height = canvas.width; document.body.appendChild(canvas); -const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; +const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(rc); // -- Divide viewport @@ -58,9 +58,8 @@ viewport[Corners.TOP_LEFT] = { // -- Initialize program -const program: IRenderPipeline = { +const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") }, - primitive: { topology: "triangle-list" }, }; // -- Initialize buffer @@ -85,7 +84,7 @@ const texcoords = new Float32Array([ // -- Initialize vertex array -const vertexArray: { vertices?: IVertexAttributes } = { +const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x2" }, textureCoordinates: { data: texcoords, format: "float32x2" }, @@ -94,7 +93,7 @@ const vertexArray: { vertices?: IVertexAttributes } = { // -- Initialize samplers -const samplers: ISampler[] = new Array(Corners.MAX); +const samplers: Sampler[] = new Array(Corners.MAX); for (let i = 0; i < Corners.MAX; ++i) { samplers[i] = { addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge", addressModeW: "clamp-to-edge" }; @@ -119,7 +118,7 @@ samplers[Corners.BOTTOM_LEFT].mipmapFilter = "linear"; // -- Load texture then render const imageUrl = "../../assets/img/Di-3d.png"; -let texture: ITexture; +let texture: Texture; loadImage(imageUrl, function (image) { texture = { @@ -142,17 +141,20 @@ function render() 0.0, 0.0, 0.0, 1.0 ]); - const renderObjects: IRenderPassObject[] = []; - const rp: IRenderPass = { + const renderObjects: RenderPassObject[] = []; + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects }; - const ro: IRenderObject = { + const ro: RenderObject = { pipeline: program, - uniforms: { mvp: matrix }, - vertices: vertexArray.vertices, - drawVertex: { vertexCount: 6, instanceCount: 1 }, + bindingResources: { mvp: matrix }, + geometry:{ + primitive: { topology: "triangle-list" }, + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6, instanceCount: 1 }, + } }; // Bind samplers @@ -162,8 +164,8 @@ function render() { ...ro, viewport: { x: viewport[i].x, y: viewport[i].y, width: viewport[i].z, height: viewport[i].w }, - uniforms: { - ...ro.uniforms, + bindingResources: { + ...ro.bindingResources, diffuse: { texture, sampler: samplers[i] } diff --git a/examples/src/WebGL2Samples/sampler_object.ts b/examples/src/WebGL2Samples/sampler_object.ts index 79f995ff57fd62d55145a486d824a891b26cc91a..79041763dbb190a4ea23447cc7fa66e925f3f8dc 100644 --- a/examples/src/WebGL2Samples/sampler_object.ts +++ b/examples/src/WebGL2Samples/sampler_object.ts @@ -1,5 +1,5 @@ -import { IRenderPass, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource, loadImage } from "./utility"; @@ -9,14 +9,13 @@ canvas.width = Math.min(window.innerWidth, window.innerHeight); canvas.height = canvas.width; document.body.appendChild(canvas); -const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; +const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(rc); // -- Initialize program -const program: IRenderPipeline = { +const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") }, - primitive: { topology: "triangle-list" }, }; // -- Initialize buffer @@ -41,7 +40,7 @@ const texcoords = new Float32Array([ // -- Initialize vertex array -const vertexArray: { vertices?: IVertexAttributes } = { +const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x2" }, textureCoordinates: { data: texcoords, format: "float32x2" }, @@ -50,12 +49,12 @@ const vertexArray: { vertices?: IVertexAttributes } = { // -- Initialize samplers -const samplerA: ISampler = { +const samplerA: Sampler = { minFilter: "nearest", magFilter: "nearest", mipmapFilter: "nearest", addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge", addressModeW: "clamp-to-edge", lodMinClamp: -1000.0, lodMaxClamp: 1000.0, }; -const samplerB: ISampler = { +const samplerB: Sampler = { minFilter: "linear", magFilter: "linear", mipmapFilter: "linear", addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge", addressModeW: "clamp-to-edge", lodMinClamp: -1000.0, lodMaxClamp: 1000.0, @@ -64,7 +63,7 @@ const samplerB: ISampler = { // -- Load texture then render const imageUrl = "../../assets/img/Di-3d.png"; -let texture: ITexture; +let texture: Texture; loadImage(imageUrl, function (image) { texture = { @@ -86,17 +85,20 @@ function render() 0.0, 0.0, 0.0, 1.0 ]); - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects: [{ pipeline: program, - vertices: vertexArray.vertices, - uniforms: { + bindingResources: { mvp: matrix, materialDiffuse0: { texture, sampler: samplerA }, materialDiffuse1: { texture, sampler: samplerB }, }, - drawVertex: { vertexCount: 6, instanceCount: 1 }, + geometry:{ + primitive: { topology: "triangle-list" }, + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6, instanceCount: 1 }, + } }], }; diff --git a/examples/src/WebGL2Samples/sampler_wrap.ts b/examples/src/WebGL2Samples/sampler_wrap.ts index 91fbd8f348fb060ed92e9c62ffd2c6c33595a9ef..e1703b24b0442ac4bee36f290a10096983b77e76 100644 --- a/examples/src/WebGL2Samples/sampler_wrap.ts +++ b/examples/src/WebGL2Samples/sampler_wrap.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, IRenderPassObject, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderPassObject, RenderObject, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource, loadImage } from "./utility"; const canvas = document.createElement("canvas"); @@ -8,7 +8,7 @@ canvas.width = Math.min(window.innerWidth, window.innerHeight); canvas.height = canvas.width; document.body.appendChild(canvas); -const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2", antialias: false }; +const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2", webGLContextAttributes: { antialias: false }}; const webgl = new WebGL(rc); // -- Divide viewport @@ -58,9 +58,8 @@ viewport[Corners.TOP_LEFT] = { // -- Initialize program -const program: IRenderPipeline = { +const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") }, - primitive: { topology: "triangle-list" }, }; // -- Initialize buffer @@ -85,7 +84,7 @@ const texcoords = new Float32Array([ // -- Initilize vertex array -const vertexArray: { vertices?: IVertexAttributes } = { +const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x2" }, textureCoordinates: { data: texcoords, format: "float32x2" }, @@ -94,7 +93,7 @@ const vertexArray: { vertices?: IVertexAttributes } = { // -- Initialize samplers -const samplers: ISampler[] = new Array(Corners.MAX); +const samplers: Sampler[] = new Array(Corners.MAX); for (let i = 0; i < Corners.MAX; ++i) { @@ -118,7 +117,7 @@ samplers[Corners.BOTTOM_LEFT].addressModeV = "clamp-to-edge"; // -- Load texture then render const imageUrl = "../../assets/img/Di-3d.png"; -let texture: ITexture; +let texture: Texture; loadImage(imageUrl, function (image) { texture = { @@ -132,9 +131,9 @@ loadImage(imageUrl, function (image) function render() { - const renderObjects: IRenderPassObject[] = []; + const renderObjects: RenderPassObject[] = []; // Clear color buffer - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects, }; @@ -146,10 +145,14 @@ function render() 0.0, 0.0, 0.0, 1.0 ]); - const ro: IRenderObject = { + const ro: RenderObject = { pipeline: program, - uniforms: { mvp: matrix }, - vertices: vertexArray.vertices, + bindingResources: { mvp: matrix }, + geometry: { + primitive: { topology: "triangle-list" }, + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6, instanceCount: 1 }, + } }; for (let i = 0; i < Corners.MAX; ++i) @@ -158,11 +161,14 @@ function render() { ...ro, viewport: { x: viewport[i].x, y: viewport[i].y, width: viewport[i].z, height: viewport[i].w }, - uniforms: { - ...ro.uniforms, + bindingResources: { + ...ro.bindingResources, diffuse: { texture, sampler: samplers[i] }, }, - drawVertex: { vertexCount: 6, instanceCount: 1 }, + geometry: { + ...ro.geometry, + draw: { __type__: "DrawVertex", vertexCount: 6, instanceCount: 1 }, + } }); } diff --git a/examples/src/WebGL2Samples/texture_2d_array.ts b/examples/src/WebGL2Samples/texture_2d_array.ts index c69e0cb035d9b4ba068d6c9dbc99a90138264715..c4e0cd36503174203b4c920bd3f09e0ad6fcdc72 100644 --- a/examples/src/WebGL2Samples/texture_2d_array.ts +++ b/examples/src/WebGL2Samples/texture_2d_array.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderObject, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource, loadImage } from "./utility"; (function () @@ -10,11 +10,11 @@ import { getShaderSource, loadImage } from "./utility"; canvas.width = canvas.height * 960 / 540; document.body.appendChild(canvas); - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(rc); // -- Init program - const program: IRenderPipeline = { + const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") }, }; @@ -38,15 +38,15 @@ import { getShaderSource, loadImage } from "./utility"; ]); // -- Init VertexArray - const vertexArray: { vertices?: IVertexAttributes } = { + const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x2" }, texcoord: { data: texCoords, format: "float32x2" }, } }; - let texture: ITexture; - let sampler: ISampler; + let texture: Texture; + let sampler: Sampler; loadImage("../../assets/img/di-animation-array.jpg", function (image) { const NUM_IMAGES = 3; @@ -68,7 +68,7 @@ import { getShaderSource, loadImage } from "./utility"; size: [IMAGE_SIZE.width, IMAGE_SIZE.height, NUM_IMAGES], dimension: "2d-array", format: "rgba8unorm", - sources: [{ __type: "TextureDataSource", size: [IMAGE_SIZE.width, IMAGE_SIZE.height, NUM_IMAGES], data: pixels }], + sources: [{ __type__: "TextureDataSource", size: [IMAGE_SIZE.width, IMAGE_SIZE.height, NUM_IMAGES], data: pixels }], }; sampler = { minFilter: "linear", @@ -82,17 +82,19 @@ import { getShaderSource, loadImage } from "./utility"; 0.0, 0.0, 0.0, 1.0 ]); - const ro: IRenderObject = { + const ro: RenderObject = { pipeline: program, - vertices: vertexArray.vertices, - uniforms: { + bindingResources: { MVP: matrix, diffuse: { texture, sampler }, }, - drawVertex: { vertexCount: 6 }, + geometry:{ + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }; - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [1.0, 1.0, 1.0, 1.0], loadOp: "clear" }] }, renderObjects: [ro], }; @@ -101,7 +103,7 @@ import { getShaderSource, loadImage } from "./utility"; (function render() { // -- Render - ro.uniforms.layer = frame; + ro.bindingResources.layer = frame; webgl.submit({ commandEncoders: [{ passEncoders: [rp] }] }); diff --git a/examples/src/WebGL2Samples/texture_3d.ts b/examples/src/WebGL2Samples/texture_3d.ts index 48b1e93845a3138a86f79ad99638c82e0cf753b3..563bbfbcda684f8ebcfbd0641d2c24d457d1d677 100644 --- a/examples/src/WebGL2Samples/texture_3d.ts +++ b/examples/src/WebGL2Samples/texture_3d.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderObject, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { snoise } from "./third-party/noise3D"; import { getShaderSource } from "./utility"; @@ -11,7 +11,7 @@ import { getShaderSource } from "./utility"; canvas.height = canvas.width; document.body.appendChild(canvas); - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(rc); // -- Divide viewport @@ -79,14 +79,14 @@ import { getShaderSource } from "./utility"; } } - const texture: ITexture = { + const texture: Texture = { size: [SIZE, SIZE, SIZE], dimension: "3d", format: "r8unorm", generateMipmap: true, - sources: [{ __type: "TextureDataSource", mipLevel: 0, size: [SIZE, SIZE, SIZE], data }], + sources: [{ __type__: "TextureDataSource", mipLevel: 0, size: [SIZE, SIZE, SIZE], data }], }; - const sampler: ISampler = { + const sampler: Sampler = { lodMinClamp: 0, lodMaxClamp: Math.log2(SIZE), minFilter: "linear", @@ -95,7 +95,7 @@ import { getShaderSource } from "./utility"; }; // -- Initialize program - const program: IRenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") } }; + const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") } }; // -- Initialize buffer const positions = new Float32Array([ @@ -118,7 +118,7 @@ import { getShaderSource } from "./utility"; // -- Initilize vertex array - const vertexArray: { vertices?: IVertexAttributes } = { + const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x2" }, in_texcoord: { data: texCoords, format: "float32x2" }, @@ -157,16 +157,18 @@ import { getShaderSource } from "./utility"; ]; } - const ro: IRenderObject = { + const ro: RenderObject = { pipeline: program, - uniforms: { + bindingResources: { diffuse: { texture, sampler }, }, - vertices: vertexArray.vertices, - drawVertex: { vertexCount: 6 } + geometry:{ + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 } + } }; - const renderPassObjects: IRenderObject[] = []; + const renderPassObjects: RenderObject[] = []; for (let i = 0; i < Corners.MAX; ++i) { renderPassObjects.push({ @@ -175,7 +177,7 @@ import { getShaderSource } from "./utility"; }); } - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects: renderPassObjects, }; @@ -194,7 +196,7 @@ import { getShaderSource } from "./utility"; for (let i = 0; i < Corners.MAX; ++i) { - renderPassObjects[i].uniforms.orientation = matrices[i]; + renderPassObjects[i].bindingResources.orientation = matrices[i]; } webgl.submit({ commandEncoders: [{ passEncoders: [rp] }] }); diff --git a/examples/src/WebGL2Samples/texture_derivative.ts b/examples/src/WebGL2Samples/texture_derivative.ts index 5e5762d981222e435db3f233ad94c091ff487cf3..c10953c520a20311625f6122d715657ecb9c9dab 100644 --- a/examples/src/WebGL2Samples/texture_derivative.ts +++ b/examples/src/WebGL2Samples/texture_derivative.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderObject, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { mat4, vec3 } from "gl-matrix"; import { getShaderSource, loadImage } from "./utility"; @@ -12,18 +12,17 @@ import { getShaderSource, loadImage } from "./utility"; canvas.height = canvas.width; document.body.appendChild(canvas); - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(rc); // -- Init program - const program: IRenderPipeline = { + const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs"), targets: [{ }] }, depthStencil: {}, - primitive: { topology: "triangle-list", cullFace: "back" } }; // -- Init buffers @@ -116,7 +115,7 @@ import { getShaderSource, loadImage } from "./utility"; ]; // -- Init VertexArray - const vertexArray: { vertices?: IVertexAttributes } = { + const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x3" }, texcoord: { data: texCoords, format: "float32x2" }, @@ -126,8 +125,8 @@ import { getShaderSource, loadImage } from "./utility"; // -- Init Texture const imageUrl = "../../assets/img/Di-3d.png"; - let texture: ITexture; - let sampler: ISampler; + let texture: Texture; + let sampler: Sampler; loadImage(imageUrl, function (image) { // -- Init 2D Texture @@ -206,15 +205,18 @@ import { getShaderSource, loadImage } from "./utility"; lastMouseY = newY; }; - const ro: IRenderObject = { + const ro: RenderObject = { pipeline: program, - vertices: vertexArray.vertices, - indices: new Uint16Array(cubeVertexIndices), - uniforms: {}, - drawIndexed: { indexCount: 36 }, + bindingResources: {}, + geometry:{ + primitive: { topology: "triangle-list", cullFace: "back" }, + vertices: vertexArray.vertices, + indices: new Uint16Array(cubeVertexIndices), + draw: { __type__: "DrawIndexed", indexCount: 36 }, + } }; - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects: [ro] }; @@ -230,9 +232,9 @@ import { getShaderSource, loadImage } from "./utility"; mat4.rotateY(mvMatrix, mvMatrix, orientation[1] * Math.PI); mat4.rotateZ(mvMatrix, mvMatrix, orientation[2] * Math.PI); - ro.uniforms.mvMatrix = mvMatrix; - ro.uniforms.pMatrix = perspectiveMatrix; - ro.uniforms.diffuse = { texture, sampler }; + ro.bindingResources.mvMatrix = mvMatrix; + ro.bindingResources.pMatrix = perspectiveMatrix; + ro.bindingResources.diffuse = { texture, sampler }; webgl.submit({ commandEncoders: [{ passEncoders: [rp] }] }); diff --git a/examples/src/WebGL2Samples/texture_fetch.ts b/examples/src/WebGL2Samples/texture_fetch.ts index 4283d049198d71ec71ebb6f81ab71ee4e8055b2e..331ffdb28750ce841ccb0a8d1a8b6a39dc4d07f5 100644 --- a/examples/src/WebGL2Samples/texture_fetch.ts +++ b/examples/src/WebGL2Samples/texture_fetch.ts @@ -1,5 +1,5 @@ -import { IRenderPass, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource, loadImage } from "./utility"; @@ -11,11 +11,11 @@ import { getShaderSource, loadImage } from "./utility"; canvas.height = canvas.width; document.body.appendChild(canvas); - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(rc); // -- Init program - const program: IRenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") } }; + const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") } }; // -- Init buffers: vec2 Position, vec2 Texcoord const positions = new Float32Array([ @@ -37,7 +37,7 @@ import { getShaderSource, loadImage } from "./utility"; ]); // -- Init VertexArray - const vertexArray: { vertices?: IVertexAttributes } = { + const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x2" }, texcoord: { data: texCoords, format: "float32x2" }, @@ -47,14 +47,14 @@ import { getShaderSource, loadImage } from "./utility"; loadImage("../../assets/img/Di-3d.png", function (image) { // -- Init Texture - const texture: ITexture = { + const texture: Texture = { size: [image.width, image.height], format: "rgba8unorm", sources: [{ mipLevel: 0, image, flipY: false, }], }; - const sampler: ISampler = { + const sampler: Sampler = { minFilter: "nearest", magFilter: "nearest", }; @@ -68,17 +68,19 @@ import { getShaderSource, loadImage } from "./utility"; 0.0, 0.0, 0.0, 1.0 ]); - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects: [ { pipeline: program, - vertices: vertexArray.vertices, - uniforms: { + bindingResources: { MVP: matrix, diffuse: { texture, sampler }, }, - drawVertex: { vertexCount: 6 }, + geometry:{ + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } } ], }; diff --git a/examples/src/WebGL2Samples/texture_format.ts b/examples/src/WebGL2Samples/texture_format.ts index 30b0bade2ee06f33d4031ec039c4ff3c6d104aaa..945c2be554b406ad202b14569236c7195a640a1c 100644 --- a/examples/src/WebGL2Samples/texture_format.ts +++ b/examples/src/WebGL2Samples/texture_format.ts @@ -1,5 +1,5 @@ -import { IRenderPass, IRenderPassObject, IRenderPipeline, ISampler, ITexture, ITextureFormat, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderPassObject, RenderPass, RenderPipeline, Sampler, Texture, TextureFormat, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource, loadImage } from "./utility"; @@ -11,7 +11,7 @@ import { getShaderSource, loadImage } from "./utility"; canvas.height = canvas.width; document.body.appendChild(canvas); - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(rc); // -- Viewport @@ -49,9 +49,9 @@ import { getShaderSource, loadImage } from "./utility"; } // -- Init program - const programUint: IRenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs-uint") } }; + const programUint: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs-uint") } }; - const programNormalized: IRenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs-normalized") } }; + const programNormalized: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs-normalized") } }; // -- Init buffers: vec2 Position, vec2 Texcoord const positions = new Float32Array([ @@ -73,7 +73,7 @@ import { getShaderSource, loadImage } from "./utility"; ]); // -- Init VertexArray - const vertexArray: { vertices?: IVertexAttributes } = { + const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x2" }, texcoord: { data: texCoords, format: "float32x2" }, @@ -95,7 +95,7 @@ import { getShaderSource, loadImage } from "./utility"; MAX: 9 }; - const textureFormats: { format: ITextureFormat }[] = new Array(TextureTypes.MAX); + const textureFormats: { format: TextureFormat }[] = new Array(TextureTypes.MAX); textureFormats[TextureTypes.RGB] = { format: "rgba8unorm", @@ -135,8 +135,8 @@ import { getShaderSource, loadImage } from "./utility"; // -- Init Texture - const textures: ITexture[] = new Array(TextureTypes.MAX); - const samplers: ISampler[] = new Array(TextureTypes.MAX); + const textures: Texture[] = new Array(TextureTypes.MAX); + const samplers: Sampler[] = new Array(TextureTypes.MAX); let i = 0; for (i = 0; i < TextureTypes.MAX; ++i) { @@ -163,8 +163,8 @@ import { getShaderSource, loadImage } from "./utility"; 0.0, 0.0, 0.0, 1.0 ]); - const renderObjects: IRenderPassObject[] = []; - const rp: IRenderPass = { + const renderObjects: RenderPassObject[] = []; + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects }; @@ -174,13 +174,15 @@ import { getShaderSource, loadImage } from "./utility"; renderObjects.push( { viewport: { x: viewport[i].x, y: viewport[i].y, width: viewport[i].z, height: viewport[i].w }, - vertices: vertexArray.vertices, pipeline: programNormalized, - uniforms: { + bindingResources: { MVP: matrix, diffuse: { texture: textures[i], sampler: samplers[i] }, }, - drawVertex: { vertexCount: 6 }, + geometry:{ + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }); } @@ -190,13 +192,15 @@ import { getShaderSource, loadImage } from "./utility"; renderObjects.push( { viewport: { x: viewport[i].x, y: viewport[i].y, width: viewport[i].z, height: viewport[i].w }, - vertices: vertexArray.vertices, pipeline: programUint, - uniforms: { + bindingResources: { MVP: matrix, diffuse: { texture: textures[i], sampler: samplers[i] }, }, - drawVertex: { vertexCount: 6 }, + geometry:{ + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }); } diff --git a/examples/src/WebGL2Samples/texture_grad.ts b/examples/src/WebGL2Samples/texture_grad.ts index 7f38b7dc71792f94c2259fdea25a210b38a8c44e..39b30c337a113d6734d6c60bf16afd7d12696f41 100644 --- a/examples/src/WebGL2Samples/texture_grad.ts +++ b/examples/src/WebGL2Samples/texture_grad.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderObject, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { mat4, vec3 } from "gl-matrix"; import { getShaderSource, loadImage } from "./utility"; @@ -12,14 +12,13 @@ import { getShaderSource, loadImage } from "./utility"; canvas.height = canvas.width; document.body.appendChild(canvas); - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(rc); // -- Init program - const program: IRenderPipeline = { + const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") }, depthStencil: {}, - primitive: { cullFace: "back" }, }; // -- Init buffers @@ -111,7 +110,7 @@ import { getShaderSource, loadImage } from "./utility"; ]; // -- Init VertexArray - const vertexArray: { vertices?: IVertexAttributes } = { + const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x3" }, texcoord: { data: texCoords, format: "float32x2" }, @@ -121,8 +120,8 @@ import { getShaderSource, loadImage } from "./utility"; // -- Init Texture const imageUrl = "../../assets/img/Di-3d.png"; - let texture: ITexture; - let sampler: ISampler; + let texture: Texture; + let sampler: Sampler; loadImage(imageUrl, function (image) { // -- Init 2D Texture @@ -197,15 +196,18 @@ import { getShaderSource, loadImage } from "./utility"; lastMouseY = newY; }; - const ro: IRenderObject = { + const ro: RenderObject = { pipeline: program, - vertices: vertexArray.vertices, - indices: new Uint16Array(cubeVertexIndices), - uniforms: {}, - drawIndexed: { indexCount: 36 }, + bindingResources: {}, + geometry:{ + primitive: { cullFace: "back" }, + vertices: vertexArray.vertices, + indices: new Uint16Array(cubeVertexIndices), + draw: { __type__: "DrawIndexed", indexCount: 36 }, + } }; - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects: [ro], }; @@ -220,9 +222,9 @@ import { getShaderSource, loadImage } from "./utility"; mat4.rotateY(mvMatrix, mvMatrix, orientation[1] * Math.PI); mat4.rotateZ(mvMatrix, mvMatrix, orientation[2] * Math.PI); - ro.uniforms.mvMatrix = mvMatrix; - ro.uniforms.pMatrix = perspectiveMatrix; - ro.uniforms.diffuse = { texture, sampler }; + ro.bindingResources.mvMatrix = mvMatrix; + ro.bindingResources.pMatrix = perspectiveMatrix; + ro.bindingResources.diffuse = { texture, sampler }; webgl.submit({ commandEncoders: [{ passEncoders: [rp] }] }); diff --git a/examples/src/WebGL2Samples/texture_immutable.ts b/examples/src/WebGL2Samples/texture_immutable.ts index 9ad3d4db2bcca073e299fdd28dc91bbe5a4b570e..d9626605e0853b45249f8f2e16ee904678b86453 100644 --- a/examples/src/WebGL2Samples/texture_immutable.ts +++ b/examples/src/WebGL2Samples/texture_immutable.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, IRenderPassObject, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderPassObject, RenderObject, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { snoise } from "./third-party/noise3D"; import { getShaderSource, loadImage } from "./utility"; @@ -12,7 +12,7 @@ import { getShaderSource, loadImage } from "./utility"; canvas.height = canvas.width; document.body.appendChild(canvas); - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(rc); const Corners = { @@ -38,9 +38,9 @@ import { getShaderSource, loadImage } from "./utility"; }; // -- Init program - const program: IRenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") } }; + const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") } }; - const program3D: IRenderPipeline = { vertex: { code: getShaderSource("vs-3d") }, fragment: { code: getShaderSource("fs-3d") } }; + const program3D: RenderPipeline = { vertex: { code: getShaderSource("vs-3d") }, fragment: { code: getShaderSource("fs-3d") } }; // -- Init buffers: vec2 Position, vec2 Texcoord const positions = new Float32Array([ @@ -62,7 +62,7 @@ import { getShaderSource, loadImage } from "./utility"; ]); // -- Init VertexArray - const vertexArray: { vertices?: IVertexAttributes } = { + const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x2" }, in_texcoord: { data: texCoords, format: "float32x2" }, @@ -83,7 +83,7 @@ import { getShaderSource, loadImage } from "./utility"; ]); // -- Init 2D Texture - const texture2D: ITexture = { + const texture2D: Texture = { format: "rgba8unorm", mipLevelCount: 1, size: [512, 512], @@ -91,7 +91,7 @@ import { getShaderSource, loadImage } from "./utility"; image, flipY: false, }], }; - const sampler2D: ISampler = { + const sampler2D: Sampler = { minFilter: "nearest", magFilter: "linear", addressModeU: "clamp-to-edge", @@ -99,17 +99,19 @@ import { getShaderSource, loadImage } from "./utility"; }; // -- Render - const ro: IRenderObject = { + const ro: RenderObject = { pipeline: program, - vertices: vertexArray.vertices, - uniforms: { + bindingResources: { MVP: matrix, }, - drawVertex: { vertexCount: 6 }, + geometry:{ + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }; - const renderObjects: IRenderPassObject[] = []; - const rp: IRenderPass = { + const renderObjects: RenderPassObject[] = []; + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects }; @@ -119,8 +121,8 @@ import { getShaderSource, loadImage } from "./utility"; viewport: { x: viewports[Corners.LEFT].x, y: viewports[Corners.LEFT].y, width: viewports[Corners.LEFT].z, height: viewports[Corners.LEFT].w }, ...ro, pipeline: program, - uniforms: { - ...ro.uniforms, + bindingResources: { + ...ro.bindingResources, diffuse: { texture: texture2D, sampler: sampler2D }, }, }); @@ -131,8 +133,8 @@ import { getShaderSource, loadImage } from "./utility"; viewport: { x: viewports[Corners.RIGHT].x, y: viewports[Corners.RIGHT].y, width: viewports[Corners.RIGHT].z, height: viewports[Corners.RIGHT].w }, ...ro, pipeline: program3D, - uniforms: { - ...ro.uniforms, + bindingResources: { + ...ro.bindingResources, diffuse: { texture: texture3D, sampler: sampler3D }, }, }); @@ -166,15 +168,15 @@ import { getShaderSource, loadImage } from "./utility"; } } - const texture3D: ITexture = { + const texture3D: Texture = { dimension: "3d", format: "r8uint", generateMipmap: true, mipLevelCount: Math.log2(SIZE), size: [SIZE, SIZE, SIZE], - sources: [{ __type: "TextureDataSource", size: [SIZE, SIZE, SIZE], data }], + sources: [{ __type__: "TextureDataSource", size: [SIZE, SIZE, SIZE], data }], }; - const sampler3D: ISampler = { + const sampler3D: Sampler = { lodMinClamp: 0, lodMaxClamp: Math.log2(SIZE), minFilter: "linear", diff --git a/examples/src/WebGL2Samples/texture_integer.ts b/examples/src/WebGL2Samples/texture_integer.ts index 5fe9048bf2fde6139ae9fe3370be46d7728345bb..a771824deaa79f7f7462fbb92c9ea42b2bac73cb 100644 --- a/examples/src/WebGL2Samples/texture_integer.ts +++ b/examples/src/WebGL2Samples/texture_integer.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderObject, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource, loadImage } from "./utility"; @@ -11,11 +11,11 @@ import { getShaderSource, loadImage } from "./utility"; canvas.height = canvas.width; document.body.appendChild(canvas); - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2", antialias: false }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2", webGLContextAttributes: { antialias: false }}; const webgl = new WebGL(rc); // -- Init program - const program: IRenderPipeline = { + const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") }, }; @@ -39,7 +39,7 @@ import { getShaderSource, loadImage } from "./utility"; ]); // -- Init VertexArray - const vertexArray: { vertices?: IVertexAttributes } = { + const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x2" }, texcoord: { data: texCoords, format: "float32x2" }, @@ -49,14 +49,14 @@ import { getShaderSource, loadImage } from "./utility"; loadImage("../../assets/img/Di-3d.png", function (image) { // -- Init Texture - const texture: ITexture = { + const texture: Texture = { size: [image.width, image.height], format: "rgba8uint", sources: [{ mipLevel: 0, image, flipY: false, }], }; - const sampler: ISampler = { + const sampler: Sampler = { minFilter: "nearest", magFilter: "nearest", }; @@ -69,17 +69,19 @@ import { getShaderSource, loadImage } from "./utility"; 0.0, 0.0, 0.0, 1.0 ]); - const ro: IRenderObject = { + const ro: RenderObject = { pipeline: program, - uniforms: { + bindingResources: { MVP: matrix, diffuse: { texture, sampler }, }, - vertices: vertexArray.vertices, - drawVertex: { vertexCount: 6 }, + geometry:{ + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }; - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects: [ro], }; diff --git a/examples/src/WebGL2Samples/texture_lod.ts b/examples/src/WebGL2Samples/texture_lod.ts index a2c740a4988aed9d54f32b8c199eebec86d5cd6e..7e7d43a29cad4fe3638a22477ec8b6b6e789ddd9 100644 --- a/examples/src/WebGL2Samples/texture_lod.ts +++ b/examples/src/WebGL2Samples/texture_lod.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, IRenderPassObject, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderPassObject, RenderObject, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource, loadImage } from "./utility"; @@ -11,7 +11,7 @@ import { getShaderSource, loadImage } from "./utility"; canvas.height = canvas.width; document.body.appendChild(canvas); - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2", antialias: false }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2", webGLContextAttributes: { antialias: false }}; const webgl = new WebGL(rc); // -- Mouse Behaviour @@ -87,7 +87,7 @@ import { getShaderSource, loadImage } from "./utility"; }; // -- Initialize program - const program: IRenderPipeline = { + const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") }, }; @@ -111,7 +111,7 @@ import { getShaderSource, loadImage } from "./utility"; ]); // -- Initialize vertex array - const vertexArray: { vertices?: IVertexAttributes } = { + const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x2" }, textureCoordinates: { data: texcoords, format: "float32x2" }, @@ -120,8 +120,8 @@ import { getShaderSource, loadImage } from "./utility"; // -- Load texture then render const imageUrl = "../../assets/img/Di-3d.png"; - const textures: ITexture[] = new Array(Corners.MAX); - const samplers: ISampler[] = new Array(Corners.MAX); + const textures: Texture[] = new Array(Corners.MAX); + const samplers: Sampler[] = new Array(Corners.MAX); loadImage(imageUrl, function (image) { textures[Corners.TOP_LEFT] = { @@ -183,9 +183,9 @@ import { getShaderSource, loadImage } from "./utility"; function render() { - const renderObjects: IRenderPassObject[] = []; + const renderObjects: RenderPassObject[] = []; // Clear color buffer - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects, }; @@ -197,13 +197,15 @@ import { getShaderSource, loadImage } from "./utility"; 0.0, 0.0, 0.0, 1.0 ]); - const ro: IRenderObject = { + const ro: RenderObject = { pipeline: program, - uniforms: { + bindingResources: { mvp: matrix, }, - vertices: vertexArray.vertices, - drawVertex: { vertexCount: 6 }, + geometry:{ + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }; const lodBiasArray = [0.0, 0.0, 0.0, 0.0]; @@ -215,7 +217,7 @@ import { getShaderSource, loadImage } from "./utility"; { viewport: { x: viewport[i].x, y: viewport[i].y, width: viewport[i].z, height: viewport[i].w }, ...ro, - uniforms: { + bindingResources: { mvp: matrix, lodBias: lodBiasArray[i], diffuse: { texture: textures[i], sampler: samplers[i] }, diff --git a/examples/src/WebGL2Samples/texture_offset.ts b/examples/src/WebGL2Samples/texture_offset.ts index b423614a07d28cf66cb5a6bedcef608ad37f266b..17d708629e31c46311512950c50bcd8e824527c1 100644 --- a/examples/src/WebGL2Samples/texture_offset.ts +++ b/examples/src/WebGL2Samples/texture_offset.ts @@ -1,5 +1,5 @@ -import { IRenderPass, IRenderPassObject, IRenderPipeline, ISampler, ITexture, IVertexAttributes } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderPassObject, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { getShaderSource, loadImage } from "./utility"; (function () @@ -10,7 +10,7 @@ import { getShaderSource, loadImage } from "./utility"; canvas.height = canvas.width; document.body.appendChild(canvas); - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2", antialias: false }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2", webGLContextAttributes: { antialias: false }}; const webgl = new WebGL(rc); const Corners = { @@ -36,9 +36,9 @@ import { getShaderSource, loadImage } from "./utility"; }; // -- Init program - const programBicubic: IRenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs-bicubic") } }; + const programBicubic: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs-bicubic") } }; - const programOffsetBicubic: IRenderPipeline = { + const programOffsetBicubic: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs-offset-bicubic") }, }; @@ -62,7 +62,7 @@ import { getShaderSource, loadImage } from "./utility"; ]); // -- Init VertexArray - const vertexArray: { vertices?: IVertexAttributes } = { + const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: positions, format: "float32x2" }, texcoord: { data: texCoords, format: "float32x2" }, @@ -72,21 +72,21 @@ import { getShaderSource, loadImage } from "./utility"; loadImage("../../assets/img/Di-3d.png", function (image) { // -- Init Texture - const texture: ITexture = { + const texture: Texture = { size: [image.width, image.height], format: "rgba8unorm", sources: [{ mipLevel: 0, image, flipY: false }], }; - const sampler: ISampler = { + const sampler: Sampler = { minFilter: "nearest", magFilter: "nearest", addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge", }; - const renderObjects: IRenderPassObject[] = []; + const renderObjects: RenderPassObject[] = []; // -- Render - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects }; @@ -102,13 +102,15 @@ import { getShaderSource, loadImage } from "./utility"; renderObjects.push( { viewport: { x: viewports[Corners.RIGHT].x, y: viewports[Corners.RIGHT].y, width: viewports[Corners.RIGHT].z, height: viewports[Corners.RIGHT].w }, - vertices: vertexArray.vertices, pipeline: programBicubic, - uniforms: { + bindingResources: { MVP: matrix, diffuse: { texture, sampler }, }, - drawVertex: { vertexCount: 6 }, + geometry: { + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }); // Offset @@ -117,14 +119,16 @@ import { getShaderSource, loadImage } from "./utility"; renderObjects.push( { viewport: { x: viewports[Corners.LEFT].x, y: viewports[Corners.LEFT].y, width: viewports[Corners.LEFT].z, height: viewports[Corners.LEFT].w }, - vertices: vertexArray.vertices, pipeline: programOffsetBicubic, - uniforms: { + bindingResources: { MVP: matrix, diffuse: { texture, sampler }, offset, }, - drawVertex: { vertexCount: 6 }, + geometry: { + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }); webgl.submit({ commandEncoders: [{ passEncoders: [rp] }] }); diff --git a/examples/src/WebGL2Samples/texture_pixel_store.ts b/examples/src/WebGL2Samples/texture_pixel_store.ts index 89d05f524a67c3f59c16fa0d073a7b919d702871..957cb1c0e0fe1b65dc8c86ad50f31787511f0f07 100644 --- a/examples/src/WebGL2Samples/texture_pixel_store.ts +++ b/examples/src/WebGL2Samples/texture_pixel_store.ts @@ -1,5 +1,5 @@ -import { IIndicesDataTypes, IRenderPass, IRenderPassObject, IRenderPipeline, ISampler, ITexture, IVertexAttributes, IVertexDataTypes } from "@feng3d/render-api"; -import { getIGLBuffer, IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, IIndicesDataTypes, RenderPassObject, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes, VertexDataTypes } from "@feng3d/render-api"; +import { getIGLBuffer, WebGL } from "@feng3d/webgl"; import { getShaderSource, loadImage } from "./utility"; (function () @@ -10,11 +10,11 @@ import { getShaderSource, loadImage } from "./utility"; canvas.height = canvas.width; document.body.appendChild(canvas); - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2", antialias: false }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2", webGLContextAttributes: { antialias: false }}; const webgl = new WebGL(rc); // -- Init program - const program: IRenderPipeline = { + const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") }, }; @@ -27,7 +27,7 @@ import { getShaderSource, loadImage } from "./utility"; -1.0, 1.0, -1.0, -1.0 ]); - const vertexPosBuffer: IVertexDataTypes = positions; + const vertexPosBuffer: VertexDataTypes = positions; const texCoords = new Float32Array([ 0.0, 1.0, @@ -37,10 +37,10 @@ import { getShaderSource, loadImage } from "./utility"; 0.0, 0.0, 0.0, 1.0 ]); - const vertexTexBuffer: IVertexDataTypes = texCoords; + const vertexTexBuffer: VertexDataTypes = texCoords; // -- Init VertexArray - const vertexArray: { vertices?: IVertexAttributes, indices?: IIndicesDataTypes } = { + const vertexArray: { vertices?: VertexAttributes, indices?: IIndicesDataTypes } = { vertices: { position: { data: vertexPosBuffer, format: "float32x2" }, texcoord: { data: vertexTexBuffer, format: "float32x2" }, @@ -59,11 +59,11 @@ import { getShaderSource, loadImage } from "./utility"; const pixels = new Uint8Array(imageData.data.buffer); // -- Init Texture - const texture: ITexture = { + const texture: Texture = { size: [image.width / 2, image.height / 2], format: "rgba8unorm", sources: [{ - __type: "TextureDataSource", + __type__: "TextureDataSource", mipLevel: 0, size: [image.width / 2, image.height / 2], data: pixels, @@ -71,14 +71,14 @@ import { getShaderSource, loadImage } from "./utility"; dataImageOrigin: [image.width / 4, image.width / 4], }] }; - const sampler: ISampler = { + const sampler: Sampler = { minFilter: "nearest", magFilter: "nearest", }; - const renderObjects: IRenderPassObject[] = []; + const renderObjects: RenderPassObject[] = []; // -- Render - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects, }; @@ -92,13 +92,15 @@ import { getShaderSource, loadImage } from "./utility"; renderObjects.push({ pipeline: program, - vertices: vertexArray.vertices, - indices: vertexArray.indices, - uniforms: { + bindingResources: { MVP: matrix, diffuse: { texture, sampler }, }, - drawVertex: { vertexCount: 6 }, + geometry:{ + vertices: vertexArray.vertices, + indices: vertexArray.indices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }); webgl.submit({ commandEncoders: [{ passEncoders: [rp] }] }); diff --git a/examples/src/WebGL2Samples/texture_srgb.ts b/examples/src/WebGL2Samples/texture_srgb.ts index f5a947ec462371ea13b3f7482babc77afe399883..649e08b5a3a9d8ff12e9e64871f38414c2495733 100644 --- a/examples/src/WebGL2Samples/texture_srgb.ts +++ b/examples/src/WebGL2Samples/texture_srgb.ts @@ -1,5 +1,5 @@ -import { IRenderPass, IRenderPassObject, IRenderPipeline, ISampler, ITexture, IVertexAttributes, IVertexDataTypes } from "@feng3d/render-api"; -import { getIGLBuffer, IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderPassObject, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes, VertexDataTypes } from "@feng3d/render-api"; +import { getIGLBuffer, WebGL } from "@feng3d/webgl"; import { getShaderSource, loadImage } from "./utility"; @@ -11,12 +11,12 @@ import { getShaderSource, loadImage } from "./utility"; canvas.height = canvas.width; document.body.appendChild(canvas); - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2", antialias: false }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2", webGLContextAttributes: { antialias: false }}; const webgl = new WebGL(rc); // -- Initialize program - const program: IRenderPipeline = { + const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") }, }; @@ -30,7 +30,7 @@ import { getShaderSource, loadImage } from "./utility"; -1.0, 1.0, -1.0, -1.0 ]); - const vertexPosBuffer: IVertexDataTypes = positions; + const vertexPosBuffer: VertexDataTypes = positions; const texcoords = new Float32Array([ 0.0, 1.0, @@ -40,11 +40,11 @@ import { getShaderSource, loadImage } from "./utility"; 0.0, 0.0, 0.0, 1.0 ]); - const vertexTexBuffer: IVertexDataTypes = texcoords; + const vertexTexBuffer: VertexDataTypes = texcoords; // -- Initialize vertex array - const vertices: IVertexAttributes = { + const vertices: VertexAttributes = { position: { data: vertexPosBuffer, format: "float32x2" }, textureCoordinates: { data: vertexTexBuffer, format: "float32x2" }, }; @@ -52,8 +52,8 @@ import { getShaderSource, loadImage } from "./utility"; // -- Load texture then render const imageUrl = "../../assets/img/Di-3d.png"; - let texture: ITexture; - let sampler: ISampler; + let texture: Texture; + let sampler: Sampler; loadImage(imageUrl, function (image) { texture = { @@ -68,9 +68,9 @@ import { getShaderSource, loadImage } from "./utility"; function render() { - const renderObjects: IRenderPassObject[] = []; + const renderObjects: RenderPassObject[] = []; // Clear color buffer - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }] }, renderObjects, }; @@ -83,12 +83,14 @@ import { getShaderSource, loadImage } from "./utility"; ]); renderObjects.push({ pipeline: program, - vertices, - uniforms: { + bindingResources: { mvp: matrix, materialDiffuse: { texture, sampler }, }, - drawVertex: { vertexCount: 6 }, + geometry:{ + vertices, + draw: { __type__: "DrawVertex", vertexCount: 6 }, + } }); webgl.submit({ commandEncoders: [{ passEncoders: [rp] }] }); diff --git a/examples/src/WebGL2Samples/texture_vertex.ts b/examples/src/WebGL2Samples/texture_vertex.ts index 79edd93e89a2873300f94e80799655f3f6516cbb..e209feac6f9a1cb50f049270d5a94da79050b373 100644 --- a/examples/src/WebGL2Samples/texture_vertex.ts +++ b/examples/src/WebGL2Samples/texture_vertex.ts @@ -1,5 +1,5 @@ -import { IIndicesDataTypes, IPrimitiveTopology, IRenderObject, IRenderPass, IRenderPassObject, IRenderPipeline, ISampler, ITexture, IVertexAttributes, IVertexDataTypes } from "@feng3d/render-api"; -import { getIVertexFormat, IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, GLVertexAttributeTypes, IIndicesDataTypes, RenderPassObject, PrimitiveTopology, RenderPass, RenderPipeline, Sampler, Texture, VertexAttributes, VertexDataTypes, VertexFormat, vertexFormatMap } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { mat4, vec3 } from "gl-matrix"; import { GlTFLoader, Primitive } from "./third-party/gltf-loader"; @@ -7,7 +7,7 @@ import { getShaderSource, loadImage } from "./utility"; (function () { - const IDrawMode2Name: { [key: string]: IPrimitiveTopology } = { + const IDrawMode2Name: { [key: string]: PrimitiveTopology } = { 0: "point-list", 3: "line-strip", 2: "LINE_LOOP", @@ -36,29 +36,25 @@ import { getShaderSource, loadImage } from "./utility"; canvas.height = canvas.width; document.body.appendChild(canvas); - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2", antialias: false }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2", webGLContextAttributes: { antialias: false }}; const webgl = new WebGL(rc); // -- Init program - const program: IRenderPipeline = { + const program: RenderPipeline = { vertex: { code: getShaderSource("vs") }, fragment: { code: getShaderSource("fs") }, depthStencil: { depthCompare: "less" }, }; - const vertexArrayMaps: { [key: string]: { vertices?: IVertexAttributes, indices: IIndicesDataTypes }[] } = {}; + const vertexArrayMaps: { [key: string]: { vertices?: VertexAttributes, indices: IIndicesDataTypes }[] } = {}; // var in loop let mesh; let primitive: Primitive; - let vertexBuffer: IVertexDataTypes; + let vertexBuffer: VertexDataTypes; let indicesBuffer: IIndicesDataTypes; - let texture: ITexture; - let sampler: ISampler; - - const ro: IRenderObject = { - pipeline: program, - }; + let texture: Texture; + let sampler: Sampler; // -- Load model then render const glTFLoader = new GlTFLoader(); @@ -185,9 +181,9 @@ import { getShaderSource, loadImage } from "./utility"; const localMV = mat4.create(); function render() { - const renderObjects: IRenderPassObject[] = []; + const renderObjects: RenderPassObject[] = []; // -- Render - const rp: IRenderPass = { + const rp: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], loadOp: "clear" }], depthStencilAttachment: { depthLoadOp: "clear" } @@ -217,17 +213,19 @@ import { getShaderSource, loadImage } from "./utility"; renderObjects.push({ pipeline: { ...program, - primitive: { topology: IDrawMode2Name[primitive.mode] } }, - vertices: vertexArrayMaps[mid][i].vertices, - indices: vertexArrayMaps[mid][i].indices, - uniforms: { + bindingResources: { mvMatrix: localMV, pMatrix: perspectiveMatrix, displacementMap: { texture, sampler }, diffuse: { texture, sampler }, }, - drawIndexed: { indexCount: primitive.indices.length } + geometry:{ + primitive: { topology: IDrawMode2Name[primitive.mode] }, + vertices: vertexArrayMaps[mid][i].vertices, + indices: vertexArrayMaps[mid][i].indices, + draw: { __type__: "DrawIndexed", indexCount: primitive.indices.length } + } }); } } @@ -236,4 +234,24 @@ import { getShaderSource, loadImage } from "./utility"; requestAnimationFrame(render); } -})(); \ No newline at end of file +})(); + +function getIVertexFormat(numComponents: 1 | 2 | 3 | 4, type: GLVertexAttributeTypes = "FLOAT", normalized = false): VertexFormat +{ + for (const key in vertexFormatMap) + { + const element = vertexFormatMap[key]; + if ( + element.numComponents === numComponents + && element.type === type + && !element.normalized === !normalized + ) + { + return key as VertexFormat; + } + } + + console.error(`没有找到与 ${JSON.stringify({ numComponents, type, normalized })} 对应的顶点数据格式!`); + + return undefined; +} \ No newline at end of file diff --git a/examples/src/WebGL2Samples/transform_feedback_instanced.ts b/examples/src/WebGL2Samples/transform_feedback_instanced.ts index 0fd0b220367e8204721eb6fbbfe3fda6994bc190..fd3872927c85479a53199628f4c2623e9b88265d 100644 --- a/examples/src/WebGL2Samples/transform_feedback_instanced.ts +++ b/examples/src/WebGL2Samples/transform_feedback_instanced.ts @@ -1,5 +1,5 @@ -import { IIndicesDataTypes, IRenderObject, IRenderPipeline, ISubmit, IVertexAttributes, IVertexDataTypes } from "@feng3d/render-api"; -import { IGLCanvasContext, IGLTransformFeedback, IGLTransformFeedbackObject, IGLTransformFeedbackPipeline, WebGL } from "@feng3d/webgl"; +import { CanvasContext, IIndicesDataTypes, RenderObject, RenderPipeline, Submit, VertexAttributes, VertexDataTypes } from "@feng3d/render-api"; +import { TransformFeedback, TransformFeedbackObject, TransformFeedbackPipeline, WebGL } from "@feng3d/webgl"; import { getShaderSource } from "./utility"; (function () @@ -12,7 +12,7 @@ import { getShaderSource } from "./utility"; document.body.appendChild(canvas); // -- Init WebGL Context - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2", antialias: false }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2", webGLContextAttributes: { antialias: false }}; const webgl = new WebGL(rc); canvas.addEventListener("webglcontextlost", function (event) @@ -65,12 +65,12 @@ import { getShaderSource } from "./utility"; const COLOR_LOCATION = 3; const NUM_LOCATIONS = 4; - const vertexArrays: { vertices?: IVertexAttributes, indices?: IIndicesDataTypes }[][] = []; + const vertexArrays: { vertices?: VertexAttributes, indices?: IIndicesDataTypes }[][] = []; // Transform feedback objects track output buffer state - const transformFeedbacks: IGLTransformFeedback[] = []; + const transformFeedbacks: TransformFeedback[] = []; - const vertexBuffers: IVertexDataTypes[][] = new Array(vertexArrays.length); + const vertexBuffers: VertexDataTypes[][] = new Array(vertexArrays.length); for (let i = 0; i < 2; ++i) { @@ -107,13 +107,13 @@ import { getShaderSource } from "./utility"; function initPrograms() { - const programTransform: IGLTransformFeedbackPipeline = { + const programTransform: TransformFeedbackPipeline = { vertex: { code: getShaderSource("vs-emit") }, transformFeedbackVaryings: { varyings: ["v_offset", "v_rotation"], bufferMode: "SEPARATE_ATTRIBS" }, }; // Setup program for draw shader - const programDraw: IRenderPipeline = { + const programDraw: RenderPipeline = { vertex: { code: getShaderSource("vs-draw") }, fragment: { code: getShaderSource("fs-draw"), targets: [{ @@ -123,34 +123,36 @@ import { getShaderSource } from "./utility"; } }] }, - primitive: { topology: "triangle-list" }, }; - const programs: [IGLTransformFeedbackPipeline, IRenderPipeline] = [programTransform, programDraw]; + const programs: [TransformFeedbackPipeline, RenderPipeline] = [programTransform, programDraw]; return programs; } - const transformRO: IGLTransformFeedbackObject = { + const transformRO: TransformFeedbackObject = { pipeline: programs[PROGRAM_TRANSFORM], vertices: null, transformFeedback: null, uniforms: {}, - drawVertex: { vertexCount: NUM_INSTANCES }, + draw: { __type__: "DrawVertex", vertexCount: NUM_INSTANCES }, }; - const renderRO: IRenderObject = { + const renderRO: RenderObject = { viewport: { x: 0, y: 0, width: canvas.width, height: canvas.height - 10 }, pipeline: programs[PROGRAM_DRAW], - uniforms: {}, - drawVertex: { vertexCount: 3, instanceCount: NUM_INSTANCES }, + bindingResources: {}, + geometry:{ + primitive: { topology: "triangle-list" }, + draw: { __type__: "DrawVertex", vertexCount: 3, instanceCount: NUM_INSTANCES }, + } }; - const submit: ISubmit = { + const submit: Submit = { commandEncoders: [{ passEncoders: [ { - __type: "TransformFeedbackPass", + __type__: "TransformFeedbackPass", transformFeedbackObjects: [transformRO], }, { @@ -181,8 +183,8 @@ import { getShaderSource } from "./utility"; // Rotate triangles transform(); - renderRO.vertices = vertexArrays[currentSourceIdx][1].vertices; - renderRO.indices = vertexArrays[currentSourceIdx][1].indices; + renderRO.geometry.vertices = vertexArrays[currentSourceIdx][1].vertices; + renderRO.geometry.indices = vertexArrays[currentSourceIdx][1].indices; webgl.submit(submit); diff --git a/examples/src/WebGL2Samples/transform_feedback_interleaved.ts b/examples/src/WebGL2Samples/transform_feedback_interleaved.ts index 769a2c3b5b63af0ce3d1fb13098081f663ee11f5..5c8d459158b4dba01953a550e6d14188c4ff5fbf 100644 --- a/examples/src/WebGL2Samples/transform_feedback_interleaved.ts +++ b/examples/src/WebGL2Samples/transform_feedback_interleaved.ts @@ -1,5 +1,5 @@ -import { IIndicesDataTypes, IRenderPipeline, IVertexAttributes, IVertexDataTypes } from "@feng3d/render-api"; -import { getIGLVertexBuffer, IGLCanvasContext, IGLTransformFeedback, IGLTransformFeedbackPipeline, WebGL } from "@feng3d/webgl"; +import { CanvasContext, IIndicesDataTypes, RenderPipeline, VertexAttributes, VertexDataTypes } from "@feng3d/render-api"; +import { getIGLBuffer, TransformFeedback, TransformFeedbackPipeline, WebGL } from "@feng3d/webgl"; import { getShaderSource } from "./utility"; (function () @@ -12,7 +12,7 @@ import { getShaderSource } from "./utility"; document.body.appendChild(canvas); // -- Init WebGL Context - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2", antialias: false }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2", webGLContextAttributes: { antialias: false }}; const webgl = new WebGL(rc); // -- Init Program @@ -21,7 +21,7 @@ import { getShaderSource } from "./utility"; const programTransform = (function (vertexShaderSourceTransform, fragmentShaderSourceTransform) { - const programTransform: IGLTransformFeedbackPipeline = { + const programTransform: TransformFeedbackPipeline = { vertex: { code: vertexShaderSourceTransform }, transformFeedbackVaryings: { varyings: ["gl_Position", "v_color"], bufferMode: "INTERLEAVED_ATTRIBS" }, }; @@ -29,7 +29,7 @@ import { getShaderSource } from "./utility"; return programTransform; })(getShaderSource("vs-transform"), getShaderSource("fs-transform")); - const programFeedback: IRenderPipeline = { + const programFeedback: RenderPipeline = { vertex: { code: getShaderSource("vs-feedback") }, fragment: { code: getShaderSource("fs-feedback") }, }; @@ -45,7 +45,7 @@ import { getShaderSource } from "./utility"; -1.0, -1.0, 0.0, 1.0 ]); - const buffers: IVertexDataTypes[] = [ + const buffers: VertexDataTypes[] = [ // Transform buffer vertices, // Feedback empty buffer @@ -53,7 +53,7 @@ import { getShaderSource } from "./utility"; ]; // -- Init Vertex Array - const vertexArrays: { vertices?: IVertexAttributes, indices?: IIndicesDataTypes }[] = [ + const vertexArrays: { vertices?: VertexAttributes, indices?: IIndicesDataTypes }[] = [ { vertices: { position: { data: buffers[PROGRAM_TRANSFORM], format: "float32x4" }, @@ -68,7 +68,7 @@ import { getShaderSource } from "./utility"; ]; // -- Init TransformFeedback - const transformFeedback: IGLTransformFeedback = { + const transformFeedback: TransformFeedback = { bindBuffers: [ { index: 0, data: buffers[PROGRAM_FEEDBACK] } ] @@ -88,14 +88,14 @@ import { getShaderSource } from "./utility"; commandEncoders: [{ passEncoders: [ { - __type: "TransformFeedbackPass", + __type__: "TransformFeedbackPass", transformFeedbackObjects: [ { pipeline: programTransform, vertices: vertexArrays[PROGRAM_TRANSFORM].vertices, uniforms: { MVP: matrix }, transformFeedback, - drawVertex: { vertexCount: VERTEX_COUNT }, + draw: { __type__: "DrawVertex", vertexCount: VERTEX_COUNT }, } ], }, @@ -105,9 +105,11 @@ import { getShaderSource } from "./utility"; // Second draw, reuse captured attributes { pipeline: programFeedback, - vertices: vertexArrays[PROGRAM_FEEDBACK].vertices, - indices: vertexArrays[PROGRAM_FEEDBACK].indices, - drawVertex: { vertexCount: VERTEX_COUNT }, + geometry:{ + vertices: vertexArrays[PROGRAM_FEEDBACK].vertices, + indices: vertexArrays[PROGRAM_FEEDBACK].indices, + draw: { __type__: "DrawVertex", vertexCount: VERTEX_COUNT }, + }, } ], }] @@ -116,8 +118,8 @@ import { getShaderSource } from "./utility"; // -- Delete WebGL resources webgl.deleteTransformFeedback(transformFeedback); - webgl.deleteBuffer(getIGLVertexBuffer(buffers[PROGRAM_TRANSFORM])); - webgl.deleteBuffer(getIGLVertexBuffer(buffers[PROGRAM_FEEDBACK])); + webgl.deleteBuffer(getIGLBuffer(buffers[PROGRAM_TRANSFORM])); + webgl.deleteBuffer(getIGLBuffer(buffers[PROGRAM_FEEDBACK])); webgl.deleteProgram(programTransform); webgl.deleteProgram(programFeedback); })(); diff --git a/examples/src/WebGL2Samples/transform_feedback_separated.ts b/examples/src/WebGL2Samples/transform_feedback_separated.ts index d6126ec2c17303e4fec79b5d3f2366c0d44632bf..ea4ba53d13cec7b0426e7ecb867e310921d54fd8 100644 --- a/examples/src/WebGL2Samples/transform_feedback_separated.ts +++ b/examples/src/WebGL2Samples/transform_feedback_separated.ts @@ -1,5 +1,5 @@ -import { IIndicesDataTypes, IRenderPass, IRenderPassObject, IRenderPipeline, ISubmit, IVertexAttributes, IVertexDataTypes } from "@feng3d/render-api"; -import { IGLCanvasContext, IGLTransformFeedback, IGLTransformFeedbackPipeline, WebGL } from "@feng3d/webgl"; +import { CanvasContext, IIndicesDataTypes, VertexDataTypes, RenderPipeline, Submit, VertexAttributes } from "@feng3d/render-api"; +import { TransformFeedback, TransformFeedbackPipeline, WebGL } from "@feng3d/webgl"; import { getShaderSource } from "./utility"; @@ -13,13 +13,13 @@ import { getShaderSource } from "./utility"; document.body.appendChild(canvas); // -- Init WebGL Context - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2", antialias: false }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2", webGLContextAttributes: { antialias: false }}; const webgl = new WebGL(rc); // -- Init Program const programTransform = (function (vertexShaderSourceTransform, fragmentShaderSourceTransform) { - const transformFeedbackPipeline: IGLTransformFeedbackPipeline = { + const transformFeedbackPipeline: TransformFeedbackPipeline = { vertex: { code: vertexShaderSourceTransform }, transformFeedbackVaryings: { varyings: ["gl_Position", "v_color"], bufferMode: "SEPARATE_ATTRIBS" }, }; @@ -27,7 +27,7 @@ import { getShaderSource } from "./utility"; return transformFeedbackPipeline; })(getShaderSource("vs-transform"), getShaderSource("fs-transform")); - const programFeedback: IRenderPipeline = { + const programFeedback: RenderPipeline = { vertex: { code: getShaderSource("vs-feedback") }, fragment: { code: getShaderSource("fs-feedback") }, }; @@ -54,7 +54,7 @@ import { getShaderSource } from "./utility"; MAX: 3 }; - const buffers: IVertexDataTypes[] = [ + const buffers: VertexDataTypes[] = [ // Transform buffer positions, // Feedback empty buffers @@ -63,7 +63,7 @@ import { getShaderSource } from "./utility"; ]; // -- Init Transform Vertex Array - const vertexArrays: { vertices?: IVertexAttributes, indices?: IIndicesDataTypes }[] = [ + const vertexArrays: { vertices?: VertexAttributes, indices?: IIndicesDataTypes }[] = [ { vertices: { position: { data: buffers[BufferType.VERTEX], format: "float32x4" }, @@ -78,7 +78,7 @@ import { getShaderSource } from "./utility"; ]; // -- Init TransformFeedback - const transformFeedback: IGLTransformFeedback = { + const transformFeedback: TransformFeedback = { bindBuffers: [ { index: 0, data: buffers[BufferType.POSITION] }, { index: 1, data: buffers[BufferType.COLOR] }, @@ -95,18 +95,18 @@ import { getShaderSource } from "./utility"; 0.0, 0.0, 0.0, 1.0 ]); - const submit: ISubmit = { + const submit: Submit = { commandEncoders: [{ passEncoders: [ { - __type: "TransformFeedbackPass", + __type__: "TransformFeedbackPass", transformFeedbackObjects: [ { pipeline: programTransform, vertices: vertexArrays[PROGRAM_TRANSFORM].vertices, uniforms: { MVP: matrix }, transformFeedback, - drawVertex: { vertexCount: VERTEX_COUNT }, + draw: { __type__: "DrawVertex", vertexCount: VERTEX_COUNT }, } ] }, @@ -116,9 +116,11 @@ import { getShaderSource } from "./utility"; // Second draw, reuse captured attributes { pipeline: programs[PROGRAM_FEEDBACK], - vertices: vertexArrays[PROGRAM_FEEDBACK].vertices, - indices: vertexArrays[PROGRAM_FEEDBACK].indices, - drawVertex: { vertexCount: VERTEX_COUNT }, + geometry: { + vertices: vertexArrays[PROGRAM_FEEDBACK].vertices, + indices: vertexArrays[PROGRAM_FEEDBACK].indices, + draw: { __type__: "DrawVertex", vertexCount: VERTEX_COUNT }, + } } ], } diff --git a/examples/src/WebGL2Samples/transform_feedback_separated_2.ts b/examples/src/WebGL2Samples/transform_feedback_separated_2.ts index 055ade8dc2882ab523b1d720b6b64deb6dc0c27d..f48d3fc74b566c1ce6a7330c3b4256003ae2daa3 100644 --- a/examples/src/WebGL2Samples/transform_feedback_separated_2.ts +++ b/examples/src/WebGL2Samples/transform_feedback_separated_2.ts @@ -1,5 +1,5 @@ -import { IIndicesDataTypes, IRenderObject, IRenderPipeline, ISubmit, IVertexAttributes, IVertexDataTypes } from "@feng3d/render-api"; -import { IGLCanvasContext, IGLTransformFeedback, IGLTransformFeedbackObject, IGLTransformFeedbackPipeline, WebGL } from "@feng3d/webgl"; +import { CanvasContext, IIndicesDataTypes, RenderObject, RenderPipeline, Submit, VertexAttributes, VertexDataTypes } from "@feng3d/render-api"; +import { TransformFeedback, TransformFeedbackObject, TransformFeedbackPipeline, WebGL } from "@feng3d/webgl"; import { getShaderSource } from "./utility"; @@ -13,7 +13,7 @@ import { getShaderSource } from "./utility"; document.body.appendChild(canvas); // -- Init WebGL Context - const rc: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2", antialias: false }; + const rc: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2", webGLContextAttributes: { antialias: false } }; const webgl = new WebGL(rc); canvas.addEventListener("webglcontextlost", function (event) @@ -58,12 +58,12 @@ import { getShaderSource } from "./utility"; const NUM_LOCATIONS = 5; // -- Init Vertex Arrays and Buffers - const vertexArrays: { vertices?: IVertexAttributes, indices?: IIndicesDataTypes }[][] = []; + const vertexArrays: { vertices?: VertexAttributes, indices?: IIndicesDataTypes }[][] = []; // Transform feedback objects track output buffer state - const transformFeedbacks: IGLTransformFeedback[] = []; + const transformFeedbacks: TransformFeedback[] = []; - const vertexBuffers: IVertexDataTypes[][] = new Array(vertexArrays.length); + const vertexBuffers: VertexDataTypes[][] = new Array(vertexArrays.length); for (let i = 0; i < 2; ++i) { @@ -108,14 +108,14 @@ import { getShaderSource } from "./utility"; }; } - function initProgram(): [IGLTransformFeedbackPipeline, IRenderPipeline] + function initProgram(): [TransformFeedbackPipeline, RenderPipeline] { - const transformFeedbackPipeline: IGLTransformFeedbackPipeline = { + const transformFeedbackPipeline: TransformFeedbackPipeline = { vertex: { code: getShaderSource("vs-emit") }, transformFeedbackVaryings: { varyings: ["v_position", "v_velocity", "v_spawntime", "v_lifetime"], bufferMode: "SEPARATE_ATTRIBS" }, }; - const program: IRenderPipeline = { + const program: RenderPipeline = { vertex: { code: getShaderSource("vs-draw") }, fragment: { code: getShaderSource("fs-draw"), @@ -126,36 +126,38 @@ import { getShaderSource } from "./utility"; } }] }, - primitive: { topology: "point-list" }, }; return [transformFeedbackPipeline, program]; } - const transformRO: IGLTransformFeedbackObject = { + const transformRO: TransformFeedbackObject = { pipeline: transformFeedbackPipeline, vertices: null, transformFeedback: null, uniforms: { u_acceleration: [0.0, ACCELERATION], }, - drawVertex: { vertexCount: NUM_PARTICLES }, + draw: { __type__: "DrawVertex", vertexCount: NUM_PARTICLES }, }; - const renderRO: IRenderObject = { + const renderRO: RenderObject = { viewport: { x: 0, y: 0, width: canvas.width, height: canvas.height - 10 }, pipeline: program, - uniforms: { + bindingResources: { u_color: [0.0, 1.0, 1.0, 1.0], }, - drawVertex: { vertexCount: NUM_PARTICLES }, + geometry: { + draw: { __type__: "DrawVertex", vertexCount: NUM_PARTICLES }, + primitive: { topology: "point-list" }, + } }; - const submit: ISubmit = { + const submit: Submit = { commandEncoders: [{ passEncoders: [ { - __type: "TransformFeedbackPass", + __type__: "TransformFeedbackPass", transformFeedbackObjects: [transformRO], }, { @@ -186,8 +188,8 @@ import { getShaderSource } from "./utility"; transform(); // - renderRO.vertices = vertexArrays[currentSourceIdx][1].vertices; - renderRO.indices = vertexArrays[currentSourceIdx][1].indices; + renderRO.geometry.vertices = vertexArrays[currentSourceIdx][1].vertices; + renderRO.geometry.indices = vertexArrays[currentSourceIdx][1].indices; webgl.submit(submit); diff --git a/examples/src/regl-examples/basic.ts b/examples/src/regl-examples/basic.ts index 0e8551cba0c613571be2edd537c685353d0ccc5e..bff99361ff9f630aab2a0ecc6d565a31509f5dc4 100644 --- a/examples/src/regl-examples/basic.ts +++ b/examples/src/regl-examples/basic.ts @@ -1,4 +1,4 @@ -import { IRenderObject } from "@feng3d/render-api"; +import { RenderObject } from "@feng3d/render-api"; import { WebGL } from "@feng3d/webgl"; /** @@ -16,18 +16,21 @@ document.body.appendChild(canvas); const webgl = new WebGL({ canvasId: "glcanvas" }); -const renderObject: IRenderObject = { - vertices: { - position: { - data: new Float32Array([ - -1, 0, - 0, -1, - 1, 1 - ]), - format: "float32x2", +const renderObject: RenderObject = { + geometry: { + vertices: { + position: { + data: new Float32Array([ + -1, 0, + 0, -1, + 1, 1 + ]), + format: "float32x2", + }, }, + draw: { __type__: "DrawVertex", vertexCount: 3 }, }, - uniforms: { color: [1, 0, 0, 1] }, + bindingResources: { color: [1, 0, 0, 1] }, pipeline: { vertex: { code: ` @@ -49,7 +52,6 @@ const renderObject: IRenderObject = { }, depthStencil: {}, }, - drawVertex: { vertexCount: 3 }, }; function draw() diff --git a/examples/src/regl-examples/batch.ts b/examples/src/regl-examples/batch.ts index aa974ad8aacd6154dedd252a3cc0e73c1bdb5d6c..f46defb1cb80a3a34e35b9dceb145636105f2274 100644 --- a/examples/src/regl-examples/batch.ts +++ b/examples/src/regl-examples/batch.ts @@ -1,4 +1,4 @@ -import { IRenderObject, IRenderPipeline, ISubmit, IVertexAttributes } from "@feng3d/render-api"; +import { RenderObject, RenderPipeline, Submit, VertexAttributes } from "@feng3d/render-api"; import { WebGL } from "@feng3d/webgl"; const canvas = document.createElement("canvas"); @@ -21,7 +21,7 @@ const offsets = [{ offset: [-1, -1] }, { offset: [1, 0] }, { offset: [1, 1] }]; -const pipeline: IRenderPipeline = { +const pipeline: RenderPipeline = { vertex: { code: `precision mediump float; attribute vec2 position; @@ -41,7 +41,7 @@ const pipeline: IRenderPipeline = { depthStencil: { depthWriteEnabled: false }, }; -const vertexArray: { vertices?: IVertexAttributes } = { +const vertexArray: { vertices?: VertexAttributes } = { vertices: { position: { data: new Float32Array([ @@ -56,25 +56,27 @@ const vertexArray: { vertices?: IVertexAttributes } = { function getRenderObject(batchId: number) { - const renderObject: IRenderObject = { - vertices: vertexArray.vertices, - uniforms: { + const renderObject: RenderObject = { + geometry: { + vertices: vertexArray.vertices, + draw: { __type__: "DrawVertex", vertexCount: 3 } + }, + bindingResources: { offset: offsets[batchId].offset, }, - pipeline, - drawVertex: { vertexCount: 3 } + pipeline: pipeline, }; return renderObject; } -const renderObjects: IRenderObject[] = []; +const renderObjects: RenderObject[] = []; for (let i = 0; i < offsets.length; i++) { renderObjects.push(getRenderObject(i)); } -const submit: ISubmit = { +const submit: Submit = { commandEncoders: [{ passEncoders: [ { @@ -97,12 +99,12 @@ function draw() batchId = i; // const ro = renderObjects[i]; - ro.uniforms.color = [ + ro.bindingResources.color = [ Math.sin(0.02 * ((0.1 + Math.sin(batchId)) * tick + 3.0 * batchId)), Math.cos(0.02 * (0.02 * tick + 0.1 * batchId)), Math.sin(0.02 * ((0.3 + Math.cos(2.0 * batchId)) * tick + 0.8 * batchId)), 1]; - ro.uniforms.angle = 0.01 * tick; + ro.bindingResources.angle = 0.01 * tick; } webgl.submit(submit); diff --git a/examples/src/regl-examples/bunny.ts b/examples/src/regl-examples/bunny.ts index 388a1960add266a3624b8221e383d8c65198caa7..04e3a590dab1c168f1659d45b2d9ec8ac7c02b41 100644 --- a/examples/src/regl-examples/bunny.ts +++ b/examples/src/regl-examples/bunny.ts @@ -1,4 +1,4 @@ -import { IRenderObject, ISubmit } from "@feng3d/render-api"; +import { Submit, RenderObject } from "@feng3d/render-api"; import { WebGL } from "@feng3d/webgl"; import * as bunny from "./mikolalysenko/bunny"; @@ -10,7 +10,7 @@ canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); -const webgl = new WebGL({ canvasId: "glcanvas", antialias: true }); +const webgl = new WebGL({ canvasId: "glcanvas", webGLContextAttributes: { antialias: true } }); const positions = bunny.positions.reduce((pv: number[], cv: number[]) => { @@ -30,13 +30,15 @@ let tick = 0; let viewportWidth = canvas.clientWidth; let viewportHeight = canvas.clientHeight; -const renderObject: IRenderObject = { - vertices: { - position: { data: new Float32Array(positions), format: "float32x3" }, +const renderObject: RenderObject = { + geometry: { + vertices: { + position: { data: new Float32Array(positions), format: "float32x3" }, + }, + indices: new Uint16Array(indices), + draw: { __type__: "DrawIndexed", indexCount: indices.length }, }, - indices: new Uint16Array(indices), - drawIndexed: { indexCount: indices.length }, - uniforms: { + bindingResources: { model: mat4.identity([]), }, pipeline: { @@ -58,7 +60,7 @@ const renderObject: IRenderObject = { } }; -const submit: ISubmit = { +const submit: Submit = { commandEncoders: [{ passEncoders: [ { @@ -77,12 +79,12 @@ function draw() tick++; const t = 0.01 * tick; - renderObject.uniforms.view = mat4.lookAt([], + renderObject.bindingResources.view = mat4.lookAt([], [30 * Math.cos(t), 2.5, 30 * Math.sin(t)], [0, 2.5, 0], [0, 1, 0]); - renderObject.uniforms.projection + renderObject.bindingResources.projection = mat4.perspective([], Math.PI / 4, viewportWidth / viewportHeight, diff --git a/examples/src/regl-examples/camera.ts b/examples/src/regl-examples/camera.ts index ae5f99ab83847731f9b63e55dc09e4d7ebdb5b6a..da3e3b02456f00c561588f2fccbe6759b1d4753b 100644 --- a/examples/src/regl-examples/camera.ts +++ b/examples/src/regl-examples/camera.ts @@ -1,4 +1,4 @@ -import { IRenderObject } from "@feng3d/render-api"; +import { RenderObject } from "@feng3d/render-api"; import { WebGL } from "@feng3d/webgl"; import { angleNormals } from "./mikolalysenko/angle-normals"; @@ -11,7 +11,7 @@ canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); -const webgl = new WebGL({ canvasId: "glcanvas", antialias: true }); +const webgl = new WebGL({ canvasId: "glcanvas", webGLContextAttributes: { antialias: true } }); const camera = createCamera({ center: [0, 2.5, 0] @@ -21,14 +21,16 @@ const positions = bunny.positions.flat(); const indices = bunny.cells.flat(); const normals = angleNormals(bunny.cells, bunny.positions).flat(); -const renderObject: IRenderObject = { - vertices: { - position: { data: new Float32Array(positions), format: "float32x3" }, - normal: { data: new Float32Array(normals), format: "float32x3" }, +const renderObject: RenderObject = { + geometry: { + vertices: { + position: { data: new Float32Array(positions), format: "float32x3" }, + normal: { data: new Float32Array(normals), format: "float32x3" }, + }, + indices: new Uint16Array(indices), + draw: { __type__: "DrawIndexed", indexCount: indices.length }, }, - indices: new Uint16Array(indices), - drawIndexed: { indexCount: indices.length }, - uniforms: {}, + bindingResources: {}, pipeline: { vertex: { code: `precision mediump float; diff --git a/examples/src/regl-examples/cloth.ts b/examples/src/regl-examples/cloth.ts index b67600e519e0fe23a8847c9abc61a1f338a90d10..7682ac080e73056db2653d96c3e40f80ba764551 100644 --- a/examples/src/regl-examples/cloth.ts +++ b/examples/src/regl-examples/cloth.ts @@ -1,5 +1,5 @@ -import { IRenderObject, ISubmit } from "@feng3d/render-api"; -import { getIGLVertexBuffer, IGLSamplerTexture, WebGL } from "@feng3d/webgl"; +import { RenderObject, Submit } from "@feng3d/render-api"; +import { getIGLBuffer, SamplerTexture, WebGL } from "@feng3d/webgl"; import { fit } from "./hughsk/canvas-fit"; import { attachCamera } from "./hughsk/canvas-orbit-camera"; @@ -164,18 +164,20 @@ import * as vec3 from "./stackgl/gl-vec3"; let viewportWidth = 1; let viewportHeight = 1; - const renderObject: IRenderObject = { - vertices: { - position: { data: new Float32Array(positions), format: "float32x3" }, - normal: { data: new Float32Array(normals), format: "float32x3" }, - uv: { data: new Float32Array(uvs), format: "float32x2" }, + const renderObject: RenderObject = { + geometry:{ + vertices: { + position: { data: new Float32Array(positions), format: "float32x3" }, + normal: { data: new Float32Array(normals), format: "float32x3" }, + uv: { data: new Float32Array(uvs), format: "float32x2" }, + }, + indices: new Uint16Array(indices), + draw: { __type__: "DrawIndexed", indexCount: indices.length }, }, - indices: new Uint16Array(indices), - drawIndexed: { indexCount: indices.length }, - uniforms: {}, + bindingResources: {}, pipeline: { vertex: { - code: `precision mediump float; + code: /* wgsl */`precision mediump float; attribute vec3 position; attribute vec3 normal; @@ -192,7 +194,7 @@ import * as vec3 from "./stackgl/gl-vec3"; gl_Position = projection * view * vec4(position, 1); }` }, fragment: { - code: `precision mediump float; + code: /* wgsl */`precision mediump float; varying vec2 vUv; varying vec3 vNormal; @@ -221,7 +223,7 @@ import * as vec3 from "./stackgl/gl-vec3"; } }; - const submit: ISubmit = { + const submit: Submit = { commandEncoders: [{ passEncoders: [ { @@ -359,8 +361,8 @@ import * as vec3 from "./stackgl/gl-vec3"; return pv; }, []); - getIGLVertexBuffer(renderObject.vertices.position.data).data = new Float32Array(positions); - getIGLVertexBuffer(renderObject.vertices.normal.data).data = new Float32Array(normals); + getIGLBuffer(renderObject.geometry.vertices.position.data).data = new Float32Array(positions); + getIGLBuffer(renderObject.geometry.vertices.normal.data).data = new Float32Array(normals); tick++; @@ -369,8 +371,8 @@ import * as vec3 from "./stackgl/gl-vec3"; camera.tick(); - renderObject.uniforms.view = camera.view(); - renderObject.uniforms.projection + renderObject.bindingResources.view = camera.view(); + renderObject.bindingResources.projection = mat4.perspective([], Math.PI / 4, viewportWidth / viewportHeight, @@ -386,14 +388,14 @@ import * as vec3 from "./stackgl/gl-vec3"; img.src = "../../assets/cloth.png"; await img.decode(); - const diffuse: IGLSamplerTexture = { + const diffuse: SamplerTexture = { texture: { size: [img.width, img.height], generateMipmap: true, sources: [{ image: img }] }, sampler: { minFilter: "linear", mipmapFilter: "linear", addressModeU: "repeat", addressModeV: "repeat" } }; - renderObject.uniforms.texture = diffuse; + renderObject.bindingResources.texture = diffuse; draw(); })(); \ No newline at end of file diff --git a/examples/src/regl-examples/cube.ts b/examples/src/regl-examples/cube.ts index f1dfad842bb3d02f8dfd370a4ec7ed48466f6910..1b1e80c67483470e6ef44298826f7e9cdfb157c4 100644 --- a/examples/src/regl-examples/cube.ts +++ b/examples/src/regl-examples/cube.ts @@ -1,5 +1,5 @@ -import { IRenderObject, ISubmit } from "@feng3d/render-api"; -import { IGLSamplerTexture, WebGL } from "@feng3d/webgl"; +import { RenderObject, Submit } from "@feng3d/render-api"; +import { SamplerTexture, WebGL } from "@feng3d/webgl"; import * as mat4 from "./stackgl/gl-mat4"; (async () => @@ -64,14 +64,16 @@ import * as mat4 from "./stackgl/gl-mat4"; let viewportWidth = 1; let viewportHeight = 1; - const renderObject: IRenderObject = { - vertices: { - position: { data: new Float32Array(positions), format: "float32x3" }, - uv: { data: new Float32Array(uvs), format: "float32x2" }, + const renderObject: RenderObject = { + geometry:{ + vertices: { + position: { data: new Float32Array(positions), format: "float32x3" }, + uv: { data: new Float32Array(uvs), format: "float32x2" }, + }, + indices: new Uint16Array(indices), + draw: { __type__: "DrawIndexed", indexCount: indices.length }, }, - indices: new Uint16Array(indices), - drawIndexed: { indexCount: indices.length }, - uniforms: {}, + bindingResources: {}, pipeline: { vertex: { code: `precision mediump float; @@ -96,7 +98,7 @@ import * as mat4 from "./stackgl/gl-mat4"; } }; - const submit: ISubmit = { + const submit: Submit = { commandEncoders: [{ passEncoders: [ { @@ -114,11 +116,11 @@ import * as mat4 from "./stackgl/gl-mat4"; viewportHeight = canvas.height = canvas.clientHeight; const t = 0.01 * tick; - renderObject.uniforms.view = mat4.lookAt([], + renderObject.bindingResources.view = mat4.lookAt([], [5 * Math.cos(t), 2.5 * Math.sin(t), 5 * Math.sin(t)], [0, 0.0, 0], [0, 1, 0]); - renderObject.uniforms.projection + renderObject.bindingResources.projection = mat4.perspective([], Math.PI / 4, viewportWidth / viewportHeight, @@ -134,13 +136,13 @@ import * as mat4 from "./stackgl/gl-mat4"; img.src = "../../assets/peppers.png"; await img.decode(); - const diffuse: IGLSamplerTexture = { + const diffuse: SamplerTexture = { texture: { size: [img.width, img.height], sources: [{ image: img }] }, sampler: { minFilter: "linear" } }; - renderObject.uniforms.tex = diffuse; + renderObject.bindingResources.tex = diffuse; draw(); })(); \ No newline at end of file diff --git a/examples/src/regl-examples/util/camera.ts b/examples/src/regl-examples/util/camera.ts index c477f796089b728274880217bf1091f4c339c5e4..9564a6a8b104c1016cf016062e1842a104114fdc 100644 --- a/examples/src/regl-examples/util/camera.ts +++ b/examples/src/regl-examples/util/camera.ts @@ -1,4 +1,4 @@ -import { IRenderObject } from "@feng3d/render-api"; +import { RenderObject } from "@feng3d/render-api"; import { mouseListen as mouseChange } from "../mikolalysenko/mouse-change"; import { mouseWheelListen as mouseWheel } from "../mikolalysenko/mouse-wheel"; @@ -101,21 +101,21 @@ export function createCamera(props) lookAt(cameraState.view, eye, center, up); } - const injectContext = (renderObject: IRenderObject, viewportWidth: number, viewportHeight: number) => + const injectContext = (renderObject: RenderObject, viewportWidth: number, viewportHeight: number) => { Object.keys(cameraState).forEach(function (name) { - renderObject.uniforms[name] = setupCamera[name]; + renderObject.bindingResources[name] = setupCamera[name]; }); - renderObject.uniforms["projection"] = perspective(cameraState.projection, + renderObject.bindingResources["projection"] = perspective(cameraState.projection, Math.PI / 4.0, viewportWidth / viewportHeight, 0.01, 1000.0); }; - function setupCamera(renderObject: IRenderObject, viewportWidth: number, viewportHeight: number) + function setupCamera(renderObject: RenderObject, viewportWidth: number, viewportHeight: number) { updateCamera(); injectContext(renderObject, viewportWidth, viewportHeight); diff --git a/examples/src/test/RenderObjectChanges.html b/examples/src/test/RenderObjectChanges.html new file mode 100644 index 0000000000000000000000000000000000000000..a9750b638e93186b93bdb30ed0f23809786ff735 --- /dev/null +++ b/examples/src/test/RenderObjectChanges.html @@ -0,0 +1,17 @@ + + + + + + 测试渲染对象数据变化。 + + + + +

+ 测试渲染对象数据变化。 +

+ + + + \ No newline at end of file diff --git a/examples/src/test/RenderObjectChanges.ts b/examples/src/test/RenderObjectChanges.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9da5e74f1ef6c912626d8f21740c7a30c477830 --- /dev/null +++ b/examples/src/test/RenderObjectChanges.ts @@ -0,0 +1,105 @@ +import { Submit, RenderObject } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; + +const init = async (canvas: HTMLCanvasElement) => +{ + const devicePixelRatio = window.devicePixelRatio || 1; + canvas.width = canvas.clientWidth * devicePixelRatio; + canvas.height = canvas.clientHeight * devicePixelRatio; + + const webgl = new WebGL({ canvasId: "glcanvas", webGLcontextId: "webgl" }); // 初始化WebGL + + const renderObject: RenderObject = { // 渲染对象 + pipeline: { // 渲染管线 + vertex: { // 顶点着色器 + code: ` + attribute vec4 position; + + void main() { + gl_Position = position; + } + ` }, + fragment: { // 片段着色器 + code: ` + precision highp float; + uniform vec4 color; + void main() { + gl_FragColor = color; + } + ` }, + }, + geometry: { + vertices: { + position: { data: new Float32Array([0.0, 0.5, -0.5, -0.5, 0.5, -0.5]), format: "float32x2" }, // 顶点坐标数据 + }, + indices: new Uint16Array([0, 1, 2]), // 顶点索引数据 + draw: { __type__: "DrawIndexed", indexCount: 3 }, // 绘制命令 + }, + bindingResources: { color: [1, 0, 0, 1] }, // Uniform 颜色值。 + }; + + const submit: Submit = { // 一次GPU提交 + commandEncoders: [ // 命令编码列表 + { + passEncoders: [ // 通道编码列表 + { // 渲染通道 + descriptor: { // 渲染通道描述 + colorAttachments: [{ // 颜色附件 + clearValue: [0.0, 0.0, 0.0, 1.0], // 渲染前填充颜色 + }], + }, + renderObjects: [renderObject] + }, + ] + } + ], + }; + + function render() + { + webgl.submit(submit); // 提交GPU执行 + requestAnimationFrame(render); + } + + render(); + + window.onclick = () => + { + // 修改顶点着色器代码 + renderObject.pipeline.vertex.code = ` + attribute vec4 position; + + void main() { + vec4 pos = position; + pos.x = pos.x + 0.5; + gl_Position = pos; + } + `; + + // 修改片段着色器代码 + renderObject.pipeline.fragment.code = ` + precision highp float; + uniform vec4 color; + void main() { + vec4 col = color; + col.x = 0.5; + col.y = 0.6; + col.z = 0.7; + gl_FragColor = col; + } + `; + // + // renderObject.uniforms.color = [0, 1, 0, 1]; + }; +}; + +let webglCanvas = document.querySelector("#glcanvas") as HTMLCanvasElement; +if (!webglCanvas) +{ + webglCanvas = document.createElement("canvas"); + webglCanvas.id = "webgpu"; + webglCanvas.style.width = "400px"; + webglCanvas.style.height = "300px"; + document.body.appendChild(webglCanvas); +} +init(webglCanvas); \ No newline at end of file diff --git a/examples/src/test/fractalCube.ts b/examples/src/test/fractalCube.ts index 35e98edbdc6fb244b64830bca35876f532b0c5a9..499f776451e3bd331a2c20794a1964b0a5175d73 100644 --- a/examples/src/test/fractalCube.ts +++ b/examples/src/test/fractalCube.ts @@ -1,5 +1,5 @@ -import { IRenderObject, ISampler, ISubmit, ITexture } from "@feng3d/render-api"; -import { IGLCanvasContext, WebGL } from "@feng3d/webgl"; +import { CanvasContext, RenderObject, Sampler, Submit, Texture } from "@feng3d/render-api"; +import { WebGL } from "@feng3d/webgl"; import { mat4 } from "gl-matrix"; let cubeRotation = 0.0; @@ -13,7 +13,7 @@ async function main() { const canvas = document.querySelector("#glcanvas") as HTMLCanvasElement; - const renderingContext: IGLCanvasContext = { canvasId: "glcanvas", contextId: "webgl2" }; + const renderingContext: CanvasContext = { canvasId: "glcanvas", webGLcontextId: "webgl2" }; const webgl = new WebGL(renderingContext); @@ -22,13 +22,12 @@ async function main() const buffers = initBuffers(); const texture: { - texture: ITexture; - sampler: ISampler; + texture: Texture; + sampler: Sampler; } = { texture: { size: [canvas.width, canvas.height] }, sampler: {} }; - const renderObject: IRenderObject = { + const renderObject: RenderObject = { pipeline: { - primitive: { topology: "triangle-list" }, vertex: { code: ` attribute vec4 aVertexPosition; @@ -62,22 +61,25 @@ async function main() ` }, depthStencil: { depthCompare: "less-equal" } }, - vertices: { - aVertexPosition: { - format: "float32x3", - data: buffers.position, - }, - aTextureCoord: { - format: "float32x2", - data: buffers.textureCoord, + geometry: { + primitive: { topology: "triangle-list" }, + vertices: { + aVertexPosition: { + format: "float32x3", + data: buffers.position, + }, + aTextureCoord: { + format: "float32x2", + data: buffers.textureCoord, + }, }, + indices: buffers.indices, + draw: { __type__: "DrawIndexed", firstIndex: 0, indexCount: 36 }, }, - indices: buffers.indices, - uniforms: { uSampler: texture }, - drawIndexed: { firstIndex: 0, indexCount: 36 }, + bindingResources: { uSampler: texture }, }; - const submit: ISubmit = { + const submit: Submit = { commandEncoders: [{ passEncoders: [ // 绘制 @@ -90,7 +92,7 @@ async function main() }, // 从画布中拷贝到纹理。 { - __type: "CopyTextureToTexture", + __type__: "CopyTextureToTexture", source: { texture: null }, // 当值设置为 null或者undefined时表示当前画布。 destination: { texture: texture.texture }, copySize: [canvas.width, canvas.height], @@ -111,8 +113,8 @@ async function main() const { projectionMatrix, modelViewMatrix } = drawScene(canvas, deltaTime); - renderObject.uniforms.uProjectionMatrix = projectionMatrix; - renderObject.uniforms.uModelViewMatrix = modelViewMatrix; + renderObject.bindingResources.uProjectionMatrix = projectionMatrix; + renderObject.bindingResources.uModelViewMatrix = modelViewMatrix; webgl.submit(submit); diff --git a/examples/src/webgl-examples/sample1.ts b/examples/src/webgl-examples/sample1.ts index 9f334e70c24128ea28840ceffd10087c4f2db113..4f95e13458451448e0dc5fa3c411f66d1fd58bdb 100644 --- a/examples/src/webgl-examples/sample1.ts +++ b/examples/src/webgl-examples/sample1.ts @@ -1,4 +1,4 @@ -import { ISubmit } from "@feng3d/render-api"; +import { Submit } from "@feng3d/render-api"; import { WebGL } from "@feng3d/webgl"; const init = async (canvas: HTMLCanvasElement) => @@ -7,9 +7,9 @@ const init = async (canvas: HTMLCanvasElement) => canvas.width = canvas.clientWidth * devicePixelRatio; canvas.height = canvas.clientHeight * devicePixelRatio; - const webgl = new WebGL({ canvasId: "glcanvas", contextId: "webgl" }); // 初始化WebGL + const webgl = new WebGL({ canvasId: "glcanvas", webGLcontextId: "webgl" }); // 初始化WebGL - const submit: ISubmit = { // 一次GPU提交 + const submit: Submit = { // 一次GPU提交 commandEncoders: [ // 命令编码列表 { passEncoders: [ // 通道编码列表 @@ -39,12 +39,14 @@ const init = async (canvas: HTMLCanvasElement) => } ` }, }, - vertices: { - position: { data: new Float32Array([0.0, 0.5, -0.5, -0.5, 0.5, -0.5]), format: "float32x2" }, // 顶点坐标数据 + geometry: { + vertices: { + position: { data: new Float32Array([0.0, 0.5, -0.5, -0.5, 0.5, -0.5]), format: "float32x2" }, // 顶点坐标数据 + }, + indices: new Uint16Array([0, 1, 2]), // 顶点索引数据 + draw: { __type__: "DrawIndexed", indexCount: 3 }, // 绘制命令 }, - indices: new Uint16Array([0, 1, 2]), // 顶点索引数据 - uniforms: { color: [1, 0, 0, 1] }, // Uniform 颜色值。 - drawIndexed: { indexCount: 3 }, // 绘制命令 + bindingResources: { color: [1, 0, 0, 1] }, // Uniform 颜色值。 }] }, ] diff --git a/examples/src/webgl-examples/sample2.ts b/examples/src/webgl-examples/sample2.ts index be3e0e323351f21993b212042f8907b2d732cca8..05e340d55e61faaf62afbe5e06adfcb2868726af 100644 --- a/examples/src/webgl-examples/sample2.ts +++ b/examples/src/webgl-examples/sample2.ts @@ -1,4 +1,4 @@ -import { IRenderPass } from "@feng3d/render-api"; +import { RenderPass } from "@feng3d/render-api"; import { WebGL } from "@feng3d/webgl"; import { mat4 } from "gl-matrix"; @@ -10,9 +10,9 @@ function main() const { projectionMatrix, modelViewMatrix } = drawScene(canvas); - const webgl = new WebGL({ canvasId: "glcanvas", contextId: "webgl" }); + const webgl = new WebGL({ canvasId: "glcanvas", webGLcontextId: "webgl" }); - const renderPass: IRenderPass = { + const renderPass: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0, 0, 0, 1], @@ -25,7 +25,6 @@ function main() }, renderObjects: [{ pipeline: { - primitive: { topology: "triangle-strip" }, vertex: { code: ` attribute vec4 aVertexPosition; @@ -42,22 +41,25 @@ function main() }` }, depthStencil: { depthCompare: "less-equal" } }, - vertices: { - aVertexPosition: { - format: "float32x2", - data: new Float32Array([ - 1.0, 1.0, - -1.0, 1.0, - 1.0, -1.0, - -1.0, -1.0, - ]), - } + geometry: { + primitive: { topology: "triangle-strip" }, + vertices: { + aVertexPosition: { + format: "float32x2", + data: new Float32Array([ + 1.0, 1.0, + -1.0, 1.0, + 1.0, -1.0, + -1.0, -1.0, + ]), + } + }, + draw: { __type__: "DrawVertex", firstVertex: 0, vertexCount: 4 }, }, - uniforms: { + bindingResources: { uProjectionMatrix: projectionMatrix, uModelViewMatrix: modelViewMatrix, }, - drawVertex: { firstVertex: 0, vertexCount: 4 }, }], }; diff --git a/examples/src/webgl-examples/sample3.ts b/examples/src/webgl-examples/sample3.ts index b666ea90f45effc850ccfc70360f114250e8a562..3c9443e7e1278d7ba880b34f6c02b8584cf7897d 100644 --- a/examples/src/webgl-examples/sample3.ts +++ b/examples/src/webgl-examples/sample3.ts @@ -1,4 +1,4 @@ -import { IRenderPass } from "@feng3d/render-api"; +import { RenderPass } from "@feng3d/render-api"; import { WebGL } from "@feng3d/webgl"; import { mat4 } from "gl-matrix"; @@ -14,9 +14,9 @@ function main() // Draw the scene const { projectionMatrix, modelViewMatrix } = drawScene(canvas); - const webgl = new WebGL({ canvasId: "glcanvas", contextId: "webgl" }); + const webgl = new WebGL({ canvasId: "glcanvas", webGLcontextId: "webgl" }); - const renderPass: IRenderPass = { + const renderPass: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], @@ -29,7 +29,6 @@ function main() }, renderObjects: [{ pipeline: { - primitive: { topology: "triangle-strip" }, vertex: { code: ` attribute vec4 aVertexPosition; @@ -54,31 +53,34 @@ function main() ` }, depthStencil: { depthCompare: "less-equal" } }, - vertices: { - aVertexPosition: { - format: "float32x2", - data: new Float32Array([ - 1.0, 1.0, - -1.0, 1.0, - 1.0, -1.0, - -1.0, -1.0, - ]), - }, - aVertexColor: { - format: "float32x4", - data: new Float32Array([ - 1.0, 1.0, 1.0, 1.0, // white - 1.0, 0.0, 0.0, 1.0, // red - 0.0, 1.0, 0.0, 1.0, // green - 0.0, 0.0, 1.0, 1.0, // blue - ]), + geometry: { + primitive: { topology: "triangle-strip" }, + vertices: { + aVertexPosition: { + format: "float32x2", + data: new Float32Array([ + 1.0, 1.0, + -1.0, 1.0, + 1.0, -1.0, + -1.0, -1.0, + ]), + }, + aVertexColor: { + format: "float32x4", + data: new Float32Array([ + 1.0, 1.0, 1.0, 1.0, // white + 1.0, 0.0, 0.0, 1.0, // red + 0.0, 1.0, 0.0, 1.0, // green + 0.0, 0.0, 1.0, 1.0, // blue + ]), + }, }, + draw: { __type__: "DrawVertex", firstVertex: 0, vertexCount: 4 }, }, - uniforms: { + bindingResources: { uProjectionMatrix: projectionMatrix, uModelViewMatrix: modelViewMatrix, }, - drawVertex: { firstVertex: 0, vertexCount: 4 }, }], }; diff --git a/examples/src/webgl-examples/sample4.ts b/examples/src/webgl-examples/sample4.ts index bf89c1f6e748764bfc449eaaaed35a99fddbf8c4..63f20cc06fcfded9752fc5b991c4e0e3493f34bd 100644 --- a/examples/src/webgl-examples/sample4.ts +++ b/examples/src/webgl-examples/sample4.ts @@ -1,4 +1,4 @@ -import { IRenderObject, IRenderPass } from "@feng3d/render-api"; +import { RenderPass, RenderObject } from "@feng3d/render-api"; import { WebGL } from "@feng3d/webgl"; import { mat4 } from "gl-matrix"; @@ -13,11 +13,10 @@ function main() { const canvas = document.querySelector("#glcanvas") as HTMLCanvasElement; - const webgl = new WebGL({ canvasId: "glcanvas", contextId: "webgl" }); + const webgl = new WebGL({ canvasId: "glcanvas", webGLcontextId: "webgl" }); - const renderObject: IRenderObject = { + const renderObject: RenderObject = { pipeline: { - primitive: { topology: "triangle-strip" }, vertex: { code: ` attribute vec4 aVertexPosition; @@ -42,31 +41,34 @@ function main() ` }, depthStencil: { depthCompare: "less-equal" } }, - vertices: { - aVertexPosition: { - format: "float32x2", - data: new Float32Array([ - 1.0, 1.0, - -1.0, 1.0, - 1.0, -1.0, - -1.0, -1.0, - ]), - }, - aVertexColor: { - format: "float32x4", - data: new Float32Array([ - 1.0, 1.0, 1.0, 1.0, // white - 1.0, 0.0, 0.0, 1.0, // red - 0.0, 1.0, 0.0, 1.0, // green - 0.0, 0.0, 1.0, 1.0, // blue - ]), + geometry:{ + primitive: { topology: "triangle-strip" }, + vertices: { + aVertexPosition: { + format: "float32x2", + data: new Float32Array([ + 1.0, 1.0, + -1.0, 1.0, + 1.0, -1.0, + -1.0, -1.0, + ]), + }, + aVertexColor: { + format: "float32x4", + data: new Float32Array([ + 1.0, 1.0, 1.0, 1.0, // white + 1.0, 0.0, 0.0, 1.0, // red + 0.0, 1.0, 0.0, 1.0, // green + 0.0, 0.0, 1.0, 1.0, // blue + ]), + }, }, + draw: { __type__: "DrawVertex", firstVertex: 0, vertexCount: 4 }, }, - uniforms: {}, - drawVertex: { firstVertex: 0, vertexCount: 4 }, + bindingResources: {}, }; - const renderPass: IRenderPass = { + const renderPass: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], @@ -91,8 +93,8 @@ function main() const { projectionMatrix, modelViewMatrix } = drawScene(canvas, deltaTime); - renderObject.uniforms.uProjectionMatrix = projectionMatrix; - renderObject.uniforms.uModelViewMatrix = modelViewMatrix; + renderObject.bindingResources.uProjectionMatrix = projectionMatrix; + renderObject.bindingResources.uModelViewMatrix = modelViewMatrix; webgl.submit({ commandEncoders: [{ passEncoders: [renderPass] }] }); diff --git a/examples/src/webgl-examples/sample5.ts b/examples/src/webgl-examples/sample5.ts index b05b586c89a2d5ebb03295ff4cc90e2faf2a8f4d..c86be974a860faae1bdc682633d0d6d7a7ceb02c 100644 --- a/examples/src/webgl-examples/sample5.ts +++ b/examples/src/webgl-examples/sample5.ts @@ -1,4 +1,4 @@ -import { IRenderObject, IRenderPass } from "@feng3d/render-api"; +import { RenderPass, RenderObject } from "@feng3d/render-api"; import { WebGL } from "@feng3d/webgl"; import { mat4 } from "gl-matrix"; @@ -13,15 +13,14 @@ function main() { const canvas = document.querySelector("#glcanvas") as HTMLCanvasElement; - const webgl = new WebGL({ canvasId: "glcanvas", contextId: "webgl" }); + const webgl = new WebGL({ canvasId: "glcanvas", webGLcontextId: "webgl" }); // Here's where we call the routine that builds all the // objects we'll be drawing. const buffers = initBuffers(); - const renderObject: IRenderObject = { + const renderObject: RenderObject = { pipeline: { - primitive: { topology: "triangle-list" }, vertex: { code: ` attribute vec4 aVertexPosition; @@ -46,22 +45,25 @@ function main() ` }, depthStencil: { depthCompare: "less-equal" } }, - vertices: { - aVertexPosition: { - format: "float32x3", - data: buffers.position, - }, - aVertexColor: { - format: "float32x4", - data: buffers.color, + geometry: { + primitive: { topology: "triangle-list" }, + vertices: { + aVertexPosition: { + format: "float32x3", + data: buffers.position, + }, + aVertexColor: { + format: "float32x4", + data: buffers.color, + }, }, + indices: buffers.indices, + draw: { __type__: "DrawIndexed", firstIndex: 0, indexCount: 36 }, }, - indices: buffers.indices, - uniforms: {}, - drawIndexed: { firstIndex: 0, indexCount: 36 }, + bindingResources: {}, }; - const renderPass: IRenderPass = { + const renderPass: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], @@ -86,8 +88,8 @@ function main() const { projectionMatrix, modelViewMatrix } = drawScene(canvas, deltaTime); - renderObject.uniforms.uProjectionMatrix = projectionMatrix; - renderObject.uniforms.uModelViewMatrix = modelViewMatrix; + renderObject.bindingResources.uProjectionMatrix = projectionMatrix; + renderObject.bindingResources.uModelViewMatrix = modelViewMatrix; webgl.submit({ commandEncoders: [{ passEncoders: [renderPass] }] }); diff --git a/examples/src/webgl-examples/sample6.ts b/examples/src/webgl-examples/sample6.ts index 847c71c9b8b03f05325b2ae1b5a934fbaa793c23..ce5c132d2b103729cad23b65dbb6014767cc1dc3 100644 --- a/examples/src/webgl-examples/sample6.ts +++ b/examples/src/webgl-examples/sample6.ts @@ -1,4 +1,4 @@ -import { IRenderObject, IRenderPass, ISampler, ITexture } from "@feng3d/render-api"; +import { RenderPass, Sampler, Texture, RenderObject } from "@feng3d/render-api"; import { WebGL } from "@feng3d/webgl"; import { mat4 } from "gl-matrix"; @@ -13,7 +13,7 @@ async function main() { const canvas = document.querySelector("#glcanvas") as HTMLCanvasElement; - const webgl = new WebGL({ canvasId: "glcanvas", contextId: "webgl" }); + const webgl = new WebGL({ canvasId: "glcanvas", webGLcontextId: "webgl" }); // Here's where we call the routine that builds all the // objects we'll be drawing. @@ -21,9 +21,8 @@ async function main() const texture = await loadTexture("../../cubetexture.png"); - const renderObject: IRenderObject = { + const renderObject: RenderObject = { pipeline: { - primitive: { topology: "triangle-list" }, vertex: { code: ` attribute vec4 aVertexPosition; @@ -50,22 +49,25 @@ async function main() ` }, depthStencil: { depthCompare: "less-equal" } }, - vertices: { - aVertexPosition: { - format: "float32x3", - data: buffers.position, - }, - aTextureCoord: { - format: "float32x2", - data: buffers.textureCoord, + geometry: { + primitive: { topology: "triangle-list" }, + vertices: { + aVertexPosition: { + format: "float32x3", + data: buffers.position, + }, + aTextureCoord: { + format: "float32x2", + data: buffers.textureCoord, + }, }, + indices: buffers.indices, + draw: { __type__: "DrawIndexed", firstIndex: 0, indexCount: 36 }, }, - indices: buffers.indices, - uniforms: { uSampler: texture }, - drawIndexed: { firstIndex: 0, indexCount: 36 }, + bindingResources: { uSampler: texture }, }; - const renderPass: IRenderPass = { + const renderPass: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], @@ -90,8 +92,8 @@ async function main() const { projectionMatrix, modelViewMatrix } = drawScene(canvas, deltaTime); - renderObject.uniforms.uProjectionMatrix = projectionMatrix; - renderObject.uniforms.uModelViewMatrix = modelViewMatrix; + renderObject.bindingResources.uProjectionMatrix = projectionMatrix; + renderObject.bindingResources.uModelViewMatrix = modelViewMatrix; webgl.submit({ commandEncoders: [{ passEncoders: [renderPass] }] }); @@ -220,14 +222,14 @@ async function loadTexture(url: string) const generateMipmap = isPowerOf2(img.width) && isPowerOf2(img.height); - const texture: ITexture = { + const texture: Texture = { size: [img.width, img.height], format: "rgba8unorm", sources: [{ image: img }], generateMipmap, }; - let sampler: ISampler = {}; + let sampler: Sampler = {}; if (generateMipmap) { sampler = { addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge", minFilter: "linear" }; diff --git a/examples/src/webgl-examples/sample7.ts b/examples/src/webgl-examples/sample7.ts index a171f9c2689c80028c6dd44bdebfdf6292ec8e79..7eedfddb39770fe7787ead020b54435efe520a30 100644 --- a/examples/src/webgl-examples/sample7.ts +++ b/examples/src/webgl-examples/sample7.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, ISampler, ITexture } from "@feng3d/render-api"; -import { IGLSamplerTexture, WebGL } from "@feng3d/webgl"; +import { RenderPass, Sampler, Texture, RenderObject } from "@feng3d/render-api"; +import { SamplerTexture, WebGL } from "@feng3d/webgl"; import { mat4 } from "gl-matrix"; let cubeRotation = 0.0; @@ -13,7 +13,7 @@ async function main() { const canvas = document.querySelector("#glcanvas") as HTMLCanvasElement; - const webgl = new WebGL({ canvasId: "glcanvas", contextId: "webgl" }); + const webgl = new WebGL({ canvasId: "glcanvas", webGLcontextId: "webgl" }); // Here's where we call the routine that builds all the // objects we'll be drawing. @@ -21,9 +21,8 @@ async function main() const texture = await loadTexture("../../cubetexture.png"); - const renderObject: IRenderObject = { + const renderObject: RenderObject = { pipeline: { - primitive: { topology: "triangle-list" }, vertex: { code: ` attribute vec4 aVertexPosition; @@ -67,26 +66,29 @@ async function main() ` }, depthStencil: { depthCompare: "less-equal" } }, - vertices: { - aVertexPosition: { - format: "float32x3", - data: buffers.position, - }, - aVertexNormal: { - format: "float32x3", - data: buffers.normal, - }, - aTextureCoord: { - format: "float32x2", - data: buffers.textureCoord, + bindingResources: { uSampler: texture }, + geometry: { + primitive: { topology: "triangle-list" }, + vertices: { + aVertexPosition: { + format: "float32x3", + data: buffers.position, + }, + aVertexNormal: { + format: "float32x3", + data: buffers.normal, + }, + aTextureCoord: { + format: "float32x2", + data: buffers.textureCoord, + }, }, - }, - indices: buffers.indices, - uniforms: { uSampler: texture }, - drawIndexed: { firstIndex: 0, indexCount: 36 }, + indices: buffers.indices, + draw: { __type__: "DrawIndexed", firstIndex: 0, indexCount: 36 }, + } }; - const renderPass: IRenderPass = { + const renderPass: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], @@ -111,9 +113,9 @@ async function main() const { projectionMatrix, modelViewMatrix, normalMatrix } = drawScene(canvas, deltaTime); - renderObject.uniforms.uProjectionMatrix = projectionMatrix; - renderObject.uniforms.uModelViewMatrix = modelViewMatrix; - renderObject.uniforms.uNormalMatrix = normalMatrix; + renderObject.bindingResources.uProjectionMatrix = projectionMatrix; + renderObject.bindingResources.uModelViewMatrix = modelViewMatrix; + renderObject.bindingResources.uNormalMatrix = normalMatrix; webgl.submit({ commandEncoders: [{ passEncoders: [renderPass] }] }); @@ -288,21 +290,21 @@ async function loadTexture(url: string) const generateMipmap = isPowerOf2(img.width) && isPowerOf2(img.height); - const texture: ITexture = { + const texture: Texture = { size: [img.width, img.height], format: "rgba8unorm", sources: [{ image: img }], generateMipmap, }; - let sampler: ISampler = {}; + let sampler: Sampler = {}; if (!generateMipmap) { sampler = { addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge", minFilter: "linear" }; } - return { texture, sampler } as IGLSamplerTexture; + return { texture, sampler } as SamplerTexture; } function isPowerOf2(value: number) diff --git a/examples/src/webgl-examples/sample8.ts b/examples/src/webgl-examples/sample8.ts index 4369f56f6003eedef56279f4680b670324878743..8b1ccccb10dc0389b317098a1d0aed51bbbd6044 100644 --- a/examples/src/webgl-examples/sample8.ts +++ b/examples/src/webgl-examples/sample8.ts @@ -1,5 +1,5 @@ -import { IRenderObject, IRenderPass, ISampler, ITexture } from "@feng3d/render-api"; -import { IGLSamplerTexture, WebGL } from "@feng3d/webgl"; +import { RenderObject, RenderPass, Sampler, Texture } from "@feng3d/render-api"; +import { SamplerTexture, WebGL } from "@feng3d/webgl"; import { mat4 } from "gl-matrix"; let cubeRotation = 0.0; @@ -15,7 +15,7 @@ function main() { const canvas = document.querySelector("#glcanvas") as HTMLCanvasElement; - const webgl = new WebGL({ canvasId: "glcanvas", contextId: "webgl" }); + const webgl = new WebGL({ canvasId: "glcanvas", webGLcontextId: "webgl" }); // Here's where we call the routine that builds all the // objects we'll be drawing. @@ -25,9 +25,8 @@ function main() const video = setupVideo("../../Firefox.mp4"); - const renderObject: IRenderObject = { + const renderObject: RenderObject = { pipeline: { - primitive: { topology: "triangle-list" }, vertex: { code: ` attribute vec4 aVertexPosition; @@ -71,26 +70,29 @@ function main() ` }, depthStencil: { depthCompare: "less-equal" } }, - vertices: { - aVertexPosition: { - format: "float32x3", - data: buffers.position, - }, - aVertexNormal: { - format: "float32x3", - data: buffers.normal, - }, - aTextureCoord: { - format: "float32x2", - data: buffers.textureCoord, + geometry: { + primitive: { topology: "triangle-list" }, + vertices: { + aVertexPosition: { + format: "float32x3", + data: buffers.position, + }, + aVertexNormal: { + format: "float32x3", + data: buffers.normal, + }, + aTextureCoord: { + format: "float32x2", + data: buffers.textureCoord, + }, }, + indices: buffers.indices, + draw: { __type__: "DrawIndexed", firstIndex: 0, indexCount: 36 }, }, - indices: buffers.indices, - uniforms: { uSampler: texture }, - drawIndexed: { firstIndex: 0, indexCount: 36 }, + bindingResources: { uSampler: texture }, }; - const renderPass: IRenderPass = { + const renderPass: RenderPass = { descriptor: { colorAttachments: [{ clearValue: [0.0, 0.0, 0.0, 1.0], @@ -120,9 +122,9 @@ function main() const { projectionMatrix, modelViewMatrix, normalMatrix } = drawScene(canvas, deltaTime); - renderObject.uniforms.uProjectionMatrix = projectionMatrix; - renderObject.uniforms.uModelViewMatrix = modelViewMatrix; - renderObject.uniforms.uNormalMatrix = normalMatrix; + renderObject.bindingResources.uProjectionMatrix = projectionMatrix; + renderObject.bindingResources.uModelViewMatrix = modelViewMatrix; + renderObject.bindingResources.uNormalMatrix = normalMatrix; webgl.submit({ commandEncoders: [{ passEncoders: [renderPass] }] }); @@ -318,14 +320,14 @@ function initBuffers() // // Initialize a texture. // -function initTexture(): IGLSamplerTexture +function initTexture(): SamplerTexture { - const texture: ITexture = { + const texture: Texture = { size: [1, 1], format: "rgba8unorm", - sources: [{ __type: "TextureDataSource", size: [1, 1], data: new Uint8Array([0, 0, 255, 255]) }], + sources: [{ __type__: "TextureDataSource", size: [1, 1], data: new Uint8Array([0, 0, 255, 255]) }], }; - const sampler: ISampler = { addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge", minFilter: "linear" }; + const sampler: Sampler = { addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge", minFilter: "linear" }; return { texture, sampler }; } @@ -333,7 +335,7 @@ function initTexture(): IGLSamplerTexture // // copy the video texture // -function updateTexture(texture: ITexture, video: HTMLVideoElement) +function updateTexture(texture: Texture, video: HTMLVideoElement) { // 修改纹理尺寸 if (texture.size[0] !== video.videoWidth || texture.size[1] !== video.videoHeight) diff --git a/package.json b/package.json index 08ce72fabc4bc5d810821734fcb29e75b2e75b10..b244dc59e313f5af7eca7dad6bc8fa65f6e2aa2b 100644 --- a/package.json +++ b/package.json @@ -64,6 +64,6 @@ }, "dependencies": { "@feng3d/render-api": "0.0.2", - "@feng3d/watcher": "^0.8.8" + "@feng3d/watcher": "^0.8.12" } } \ No newline at end of file diff --git a/src/RunWebGL.ts b/src/RunWebGL.ts index fa75989995d4f285878ad5bb3c5dddb9c90801c7..979cd580d7af97de04bfa99ac90a7e470ca27bf7 100644 --- a/src/RunWebGL.ts +++ b/src/RunWebGL.ts @@ -1,56 +1,39 @@ -import { getBlendConstantColor, IBlendComponent, IBufferBinding, IColorTargetState, ICommandEncoder, ICopyBufferToBuffer, ICopyTextureToTexture, ICullFace, IDepthStencilState, IDrawIndexed, IDrawVertex, IFrontFace, IIndicesDataTypes, IPrimitiveState, IRenderObject, IRenderPass, IRenderPassColorAttachment, IRenderPassDepthStencilAttachment, IRenderPassDescriptor, IRenderPassObject, IRenderPipeline, ISampler, IScissorRect, ISubmit, ITextureView, IUniforms, IVertexAttribute, IVertexAttributes, IViewport, TypedArray, UnReadonly } from "@feng3d/render-api"; +import { BindingResources, BlendComponent, BlendState, BufferBinding, ColorTargetState, CommandEncoder, CopyBufferToBuffer, CopyTextureToTexture, CullFace, DepthStencilState, DrawIndexed, DrawVertex, FrontFace, GBuffer, IIndicesDataTypes, OcclusionQuery, PrimitiveState, RenderObject, RenderPass, RenderPassDescriptor, RenderPassObject, RenderPipeline, Sampler, ScissorRect, Submit, TextureView, TypedArray, UnReadonly, VertexAttribute, VertexAttributes, vertexFormatMap, Viewport } from "@feng3d/render-api"; +import { getGLBlitFramebuffer } from "./caches/getGLBlitFramebuffer"; import { getGLBuffer } from "./caches/getGLBuffer"; +import { getGLDrawMode, GLDrawMode } from "./caches/getGLDrawMode"; import { getGLFramebuffer } from "./caches/getGLFramebuffer"; -import { getGLProgram } from "./caches/getGLProgram"; +import { getGLProgram, UniformItemInfo } from "./caches/getGLProgram"; import { getGLRenderOcclusionQuery } from "./caches/getGLRenderOcclusionQuery"; -import { getGLSampler, getIGLTextureMagFilter, getIGLTextureMinFilter, getIGLTextureWrap } from "./caches/getGLSampler"; +import { getGLRenderPassDescriptorWithMultisample } from "./caches/getGLRenderPassDescriptorWithMultisample"; +import { getGLSampler, getIGLTextureMagFilter, getIGLTextureMinFilter, getIGLTextureWrap, GLTextureMagFilter, GLTextureMinFilter, GLTextureWrap } from "./caches/getGLSampler"; +import { getGLTextureTarget, GLTextureTarget } from "./caches/getGLTextureTarget"; import { getGLTransformFeedback } from "./caches/getGLTransformFeedback"; -import { getIGLBlitFramebuffer } from "./caches/getIGLBlitFramebuffer"; -import { getIGLDrawMode, IGLDrawMode } from "./caches/getIGLDrawMode"; -import { getIGLRenderPassDescriptorWithMultisample } from "./caches/getIGLRenderPassDescriptorWithMultisample"; -import { getIGLTextureTarget } from "./caches/getIGLTextureTarget"; import { _GL_Submit_Times } from "./const/const"; -import { IGLUniformBufferType } from "./const/IGLUniformType"; -import { IGLBlitFramebuffer } from "./data/IGLBlitFramebuffer"; -import { IGLDrawElementType, IGLUniformBuffer } from "./data/IGLBuffer"; -import { IGLCompareFunction, IGLStencilFunc, IGLStencilOp } from "./data/IGLDepthStencilState"; -import { IGLOcclusionQuery } from "./data/IGLOcclusionQuery"; -import { IGLTextureMagFilter, IGLTextureMinFilter, IGLTextureWrap } from "./data/IGLSampler"; -import { IGLSamplerTexture } from "./data/IGLSamplerTexture"; -import { IGLTextureTarget } from "./data/IGLTexture"; -import { IGLTransformFeedback } from "./data/IGLTransformFeedback"; -import { IGLTransformFeedbackObject, IGLTransformFeedbackPass, IGLTransformFeedbackPipeline } from "./data/IGLTransformFeedbackPass"; -import { IUniformItemInfo } from "./data/IGLUniformInfo"; +import { GLUniformBufferType } from "./const/GLUniformType"; +import { BlitFramebuffer } from "./data/BlitFramebuffer"; +import { DrawElementType } from "./data/polyfills/Buffer"; +import { SamplerTexture } from "./data/SamplerTexture"; +import { TransformFeedback, TransformFeedbackObject, TransformFeedbackPass, TransformFeedbackPipeline } from "./data/TransformFeedbackPass"; import { getGLTexture } from "./internal"; -import { getIGLIndexBuffer, getIGLUniformBuffer, getIGLVertexBuffer } from "./runs/getIGLBuffer"; +import { getIGLBuffer } from "./runs/getIGLBuffer"; import { getIGLBlendEquation, getIGLBlendFactor, IGLBlendEquation, IGLBlendFactor } from "./runs/runColorTargetStates"; import { getIGLCompareFunction } from "./runs/runDepthState"; import { getIGLStencilFunc, getIGLStencilOp } from "./runs/runStencilState"; -import { ChainMap } from "./utils/ChainMap"; -import { getGLRenderPassAttachmentSize } from "./utils/getGLRenderPassAttachmentSize"; -import { getIGLCullFace, IGLCullFace } from "./utils/getIGLCullFace"; -import { getIGLFrontFace, IGLFrontFace } from "./utils/getIGLFrontFace"; -import { getIGLVertexFormat } from "./utils/getIVertexFormat"; import { updateBufferBinding } from "./utils/updateBufferBinding"; -declare global -{ - interface WebGLRenderingContext - { - _vertexArrays: ChainMap<[IRenderPipeline, IVertexAttributes, IIndicesDataTypes], WebGLVertexArrayObject>; - } -} +import "./data/polyfills/OcclusionQuery"; declare global { interface WebGLTexture { - minFilter?: IGLTextureMinFilter, - magFilter?: IGLTextureMagFilter, - wrapS?: IGLTextureWrap, - wrapT?: IGLTextureWrap, - wrapR?: IGLTextureWrap, + minFilter?: GLTextureMinFilter, + magFilter?: GLTextureMagFilter, + wrapS?: GLTextureWrap, + wrapT?: GLTextureWrap, + wrapR?: GLTextureWrap, maxAnisotropy?: number, lodMinClamp?: number; lodMaxClamp?: number; @@ -59,7 +42,7 @@ declare global export class RunWebGL { - runSubmit(gl: WebGLRenderingContext, submit: ISubmit) + runSubmit(gl: WebGLRenderingContext, submit: Submit) { const commandBuffers = submit.commandEncoders.map((v) => { @@ -72,31 +55,31 @@ export class RunWebGL gl[_GL_Submit_Times] = ~~gl[_GL_Submit_Times] + 1; } - protected runCommandEncoder(gl: WebGLRenderingContext, commandEncoder: ICommandEncoder) + protected runCommandEncoder(gl: WebGLRenderingContext, commandEncoder: CommandEncoder) { commandEncoder.passEncoders.forEach((passEncoder) => { - if (!passEncoder.__type) + if (!passEncoder.__type__) { - this.runRenderPass(gl, passEncoder as IRenderPass); + this.runRenderPass(gl, passEncoder as RenderPass); } - else if (passEncoder.__type === "RenderPass") + else if (passEncoder.__type__ === "RenderPass") { this.runRenderPass(gl, passEncoder); } - else if (passEncoder.__type === "TransformFeedbackPass") + else if (passEncoder.__type__ === "TransformFeedbackPass") { this.runTransformFeedbackPass(gl, passEncoder); } - else if (passEncoder.__type === "BlitFramebuffer") + else if (passEncoder.__type__ === "BlitFramebuffer") { this.runBlitFramebuffer(gl, passEncoder); } - else if (passEncoder.__type === "CopyTextureToTexture") + else if (passEncoder.__type__ === "CopyTextureToTexture") { this.runCopyTextureToTexture(gl, passEncoder); } - else if (passEncoder.__type === "CopyBufferToBuffer") + else if (passEncoder.__type__ === "CopyBufferToBuffer") { this.runCopyBuffer(gl, passEncoder); } @@ -107,7 +90,7 @@ export class RunWebGL }); } - protected runTransformFeedbackPass(gl: WebGLRenderingContext, transformFeedbackPass: IGLTransformFeedbackPass) + protected runTransformFeedbackPass(gl: WebGLRenderingContext, transformFeedbackPass: TransformFeedbackPass) { // 执行变换反馈通道时关闭光栅化功能 if (gl instanceof WebGL2RenderingContext) @@ -124,7 +107,7 @@ export class RunWebGL } } - protected runRenderPass(gl: WebGLRenderingContext, renderPass: IRenderPass) + protected runRenderPass(gl: WebGLRenderingContext, renderPass: RenderPass) { // 获取附件尺寸 const attachmentSize = getGLRenderPassAttachmentSize(gl, renderPass.descriptor); @@ -134,9 +117,9 @@ export class RunWebGL // occlusionQuery.init(); - if (renderPass.descriptor?.sampleCount && (renderPass.descriptor.colorAttachments[0].view as ITextureView).texture) + if (renderPass.descriptor?.sampleCount && (renderPass.descriptor.colorAttachments[0].view as TextureView).texture) { - const { passDescriptor, blitFramebuffer } = getIGLRenderPassDescriptorWithMultisample(renderPass.descriptor); + const { passDescriptor, blitFramebuffer } = getGLRenderPassDescriptorWithMultisample(renderPass.descriptor); this.runRenderPassDescriptor(gl, passDescriptor); @@ -154,25 +137,30 @@ export class RunWebGL occlusionQuery.resolve(renderPass); } - private runRenderPassDescriptor(gl: WebGLRenderingContext, passDescriptor: IRenderPassDescriptor) + private runRenderPassDescriptor(gl: WebGLRenderingContext, passDescriptor: RenderPassDescriptor) { passDescriptor = passDescriptor || {}; - // - const colorAttachment = Object.assign({}, defaultRenderPassColorAttachment, passDescriptor.colorAttachments?.[0]); // const framebuffer = getGLFramebuffer(gl, passDescriptor); gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); // - const { clearValue, loadOp } = colorAttachment; + const colorAttachment = passDescriptor.colorAttachments?.[0]; + // + const clearValue = colorAttachment?.clearValue ?? [0, 0, 0, 0]; + const loadOp = colorAttachment?.loadOp ?? "clear"; gl.clearColor(clearValue[0], clearValue[1], clearValue[2], clearValue[3]); // - const depthStencilAttachment = Object.assign({}, defaultDepthStencilAttachment, passDescriptor.depthStencilAttachment); - const { depthClearValue, depthLoadOp, stencilClearValue, stencilLoadOp } = depthStencilAttachment; + const depthStencilAttachment = passDescriptor.depthStencilAttachment; + const depthClearValue = depthStencilAttachment?.depthClearValue ?? 1; + const depthLoadOp = depthStencilAttachment?.depthLoadOp ?? "load"; + const stencilClearValue = depthStencilAttachment?.stencilClearValue ?? 0; + const stencilLoadOp = depthStencilAttachment?.stencilLoadOp ?? "load"; + // gl.clearDepth(depthClearValue); gl.clearStencil(stencilClearValue); @@ -183,11 +171,11 @@ export class RunWebGL ); } - private runRenderObjects(gl: WebGLRenderingContext, attachmentSize: { width: number, height: number }, renderObjects?: readonly IRenderPassObject[]) + private runRenderObjects(gl: WebGLRenderingContext, attachmentSize: { width: number, height: number }, renderObjects?: readonly RenderPassObject[]) { renderObjects?.forEach((renderObject) => { - if (renderObject.__type === "OcclusionQuery") + if (renderObject.__type__ === "OcclusionQuery") { this.runOcclusionQuery(gl, attachmentSize, renderObject); } @@ -198,12 +186,9 @@ export class RunWebGL }); } - private runRenderObject(gl: WebGLRenderingContext, attachmentSize: { width: number, height: number }, renderObject: IRenderObject) + private runRenderObject(gl: WebGLRenderingContext, attachmentSize: { width: number, height: number }, renderObject: RenderObject) { - const { viewport, scissorRect, pipeline, vertices, indices, uniforms, drawIndexed, drawVertex } = renderObject; - - const topology = pipeline.primitive?.topology || "triangle-list"; - const drawMode = getIGLDrawMode(topology); + const { viewport, scissorRect, pipeline, geometry, bindingResources: uniforms } = renderObject; this.runViewPort(gl, attachmentSize, viewport); @@ -211,40 +196,47 @@ export class RunWebGL this.runRenderPipeline(gl, pipeline); + this.runUniforms(gl, pipeline, uniforms); + + const { vertices, indices, draw, primitive } = geometry; + this.runVertexArray(gl, pipeline, vertices, indices); - this.runUniforms(gl, pipeline, uniforms); + this.runPrimitiveState(gl, primitive); - if (drawVertex) + const topology = primitive?.topology || "triangle-list"; + const drawMode = getGLDrawMode(topology); + + if (draw.__type__ === 'DrawVertex') { - this.runDrawVertex(gl, drawMode, drawVertex); + this.runDrawVertex(gl, drawMode, draw); } - if (drawIndexed) + else { - this.runDrawIndexed(gl, drawMode, indices, drawIndexed); + this.runDrawIndexed(gl, drawMode, indices, draw); } } - private runTransformFeedbackObject(gl: WebGLRenderingContext, renderObject: IGLTransformFeedbackObject) + private runTransformFeedbackObject(gl: WebGLRenderingContext, renderObject: TransformFeedbackObject) { - const { pipeline, vertices, uniforms, transformFeedback, drawVertex } = renderObject; + const { pipeline: material, vertices, uniforms, transformFeedback, draw } = renderObject; - const drawMode = getIGLDrawMode("point-list"); + const drawMode = getGLDrawMode("point-list"); - this.runTransformFeedbackPipeline(gl, pipeline); + this.runTransformFeedbackPipeline(gl, material); - this.runVertexArray(gl, pipeline, vertices, undefined); + this.runVertexArray(gl, material, vertices, undefined); - this.runUniforms(gl, pipeline, uniforms); + this.runUniforms(gl, material, uniforms); this.runTransformFeedback(gl, transformFeedback, drawMode); - this.runDrawVertex(gl, drawMode, drawVertex); + this.runDrawVertex(gl, drawMode, draw); this.endTransformFeedback(gl, transformFeedback); } - private endTransformFeedback(gl: WebGLRenderingContext, transformFeedback: IGLTransformFeedback) + private endTransformFeedback(gl: WebGLRenderingContext, transformFeedback: TransformFeedback) { // if (transformFeedback) @@ -259,9 +251,9 @@ export class RunWebGL } } - private runDrawIndexed(gl: WebGLRenderingContext, drawMode: IGLDrawMode, indices: IIndicesDataTypes, drawIndexed: IDrawIndexed) + private runDrawIndexed(gl: WebGLRenderingContext, drawMode: GLDrawMode, indices: IIndicesDataTypes, drawIndexed: DrawIndexed) { - const type: IGLDrawElementType = indices.BYTES_PER_ELEMENT === 2 ? "UNSIGNED_SHORT" : "UNSIGNED_INT"; + const type: DrawElementType = indices.BYTES_PER_ELEMENT === 2 ? "UNSIGNED_SHORT" : "UNSIGNED_INT"; // const indexCount = drawIndexed.indexCount; const firstIndex = drawIndexed.firstIndex || 0; @@ -288,7 +280,7 @@ export class RunWebGL } } - private runDrawVertex(gl: WebGLRenderingContext, drawMode: IGLDrawMode, drawArrays: IDrawVertex) + private runDrawVertex(gl: WebGLRenderingContext, drawMode: GLDrawMode, drawArrays: DrawVertex) { // const vertexCount = drawArrays.vertexCount; @@ -316,9 +308,9 @@ export class RunWebGL /** * 激活常量 */ - private runUniforms(gl: WebGLRenderingContext, pipeline: IRenderPipeline, uniforms: IUniforms) + private runUniforms(gl: WebGLRenderingContext, material: RenderPipeline, uniforms: BindingResources) { - const webGLProgram = getGLProgram(gl, pipeline); + const webGLProgram = getGLProgram(gl, material); webGLProgram.uniforms.forEach((uniformInfo) => { @@ -341,11 +333,11 @@ export class RunWebGL if (isTexture) { - this.runSamplerTexture(gl, v, uniformData as IGLSamplerTexture); + this.runSamplerTexture(gl, v, uniformData as SamplerTexture); } else { - this.runUniform(gl, type as IGLUniformBufferType, v, uniformData); + this.runUniform(gl, type as GLUniformBufferType, v, uniformData); } }); }); @@ -355,22 +347,21 @@ export class RunWebGL webGLProgram.uniformBlocks.forEach((uniformBlock) => { const { name, index } = uniformBlock; - const uniformData = uniforms[name] as TypedArray | IBufferBinding; + const uniformData = uniforms[name] as TypedArray | BufferBinding; // - let buffer: IGLUniformBuffer; - const typedArray = uniformData as TypedArray; - if (typedArray.buffer && typedArray.BYTES_PER_ELEMENT) + let typedArray = uniformData as TypedArray; + if (!(typedArray.buffer && typedArray.BYTES_PER_ELEMENT)) { - buffer = getIGLUniformBuffer(typedArray); - } - else - { - const bufferBinding = uniforms[name] as IBufferBinding; + const bufferBinding = uniforms[name] as BufferBinding; updateBufferBinding(uniformBlock.bufferBindingInfo, bufferBinding); - buffer = getIGLUniformBuffer(bufferBinding.bufferView); + typedArray = bufferBinding.bufferView; } - (buffer as UnReadonly).label = buffer.label || (`UniformBuffer ${name}`); + const buffer = getIGLBuffer(typedArray, "UNIFORM_BUFFER", "DYNAMIC_DRAW"); + buffer.target ??= "UNIFORM_BUFFER"; + buffer.usage ??= "DYNAMIC_DRAW"; + + (buffer as UnReadonly).label = buffer.label || (`UniformBuffer ${name}`); // const webGLBuffer = getGLBuffer(gl, buffer); @@ -379,12 +370,12 @@ export class RunWebGL } } - private runSamplerTexture(gl: WebGLRenderingContext, uniformInfo: IUniformItemInfo, samplerTexture: IGLSamplerTexture) + private runSamplerTexture(gl: WebGLRenderingContext, uniformInfo: UniformItemInfo, samplerTexture: SamplerTexture) { const { texture, sampler } = samplerTexture; const { location, textureID } = uniformInfo; - const textureTarget = getIGLTextureTarget(texture.dimension); + const textureTarget = getGLTextureTarget(texture.dimension); // 设置纹理所在采样编号 gl.uniform1i(location, textureID); @@ -403,7 +394,7 @@ export class RunWebGL /** * 设置采样参数 */ - private runSampler(gl: WebGLRenderingContext, textureTarget: IGLTextureTarget, webGLTexture: WebGLTexture, sampler: ISampler, textureID: number) + private runSampler(gl: WebGLRenderingContext, textureTarget: GLTextureTarget, webGLTexture: WebGLTexture, sampler: Sampler, textureID: number) { if (gl instanceof WebGL2RenderingContext) { @@ -412,10 +403,10 @@ export class RunWebGL } else { - const minFilter: IGLTextureMinFilter = getIGLTextureMinFilter(sampler.minFilter, sampler.mipmapFilter); - const magFilter: IGLTextureMagFilter = getIGLTextureMagFilter(sampler.magFilter); - const wrapS: IGLTextureWrap = getIGLTextureWrap(sampler.addressModeU); - const wrapT: IGLTextureWrap = getIGLTextureWrap(sampler.addressModeV); + const minFilter = getIGLTextureMinFilter(sampler.minFilter, sampler.mipmapFilter); + const magFilter = getIGLTextureMagFilter(sampler.magFilter); + const wrapS = getIGLTextureWrap(sampler.addressModeU); + const wrapT = getIGLTextureWrap(sampler.addressModeV); // 设置纹理参数 if (webGLTexture.minFilter !== minFilter) @@ -456,12 +447,13 @@ export class RunWebGL /** * 设置环境Uniform数据 */ - private runUniform(gl: WebGLRenderingContext, type: IGLUniformBufferType, uniformInfo: IUniformItemInfo, data: any) + private runUniform(gl: WebGLRenderingContext, type: GLUniformBufferType, uniformInfo: UniformItemInfo, data: any) { if (typeof data === "number") { data = [data]; } + if (data.toArray) data = data.toArray(); const location = uniformInfo.location; switch (type) { @@ -540,14 +532,14 @@ export class RunWebGL /** * 执行设置或者上传渲染对象的顶点以及索引数据。 */ - private runVertexArray(gl: WebGLRenderingContext, pipeline: IRenderPipeline, vertices: IVertexAttributes, indices: IIndicesDataTypes) + private runVertexArray(gl: WebGLRenderingContext, material: RenderPipeline, vertices: VertexAttributes, indices: IIndicesDataTypes) { if (!vertices && !indices) return; let webGLVertexArrayObject: WebGLVertexArrayObject; if (gl instanceof WebGL2RenderingContext) { - webGLVertexArrayObject = gl._vertexArrays.get([pipeline, vertices, indices]); + webGLVertexArrayObject = gl._vertexArrays.get([material, vertices, indices]); if (webGLVertexArrayObject) { gl.bindVertexArray(webGLVertexArrayObject); @@ -557,10 +549,10 @@ export class RunWebGL webGLVertexArrayObject = gl.createVertexArray(); gl.bindVertexArray(webGLVertexArrayObject); - gl._vertexArrays.set([pipeline, vertices, indices], webGLVertexArrayObject); + gl._vertexArrays.set([material, vertices, indices], webGLVertexArrayObject); } - const shaderResult = getGLProgram(gl, pipeline); + const shaderResult = getGLProgram(gl, material); // shaderResult.attributes.forEach((activeInfo) => @@ -585,18 +577,20 @@ export class RunWebGL { if (!indices) return; - const indexBuffer = getIGLIndexBuffer(indices); + const indexBuffer = getIGLBuffer(indices, "ELEMENT_ARRAY_BUFFER"); + indexBuffer.target ??= "ELEMENT_ARRAY_BUFFER"; + indexBuffer.usage ??= "STATIC_DRAW"; const buffer = getGLBuffer(gl, indexBuffer); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer); } - private runVertexAttribute(gl: WebGLRenderingContext, location: number, attribute: IVertexAttribute) + private runVertexAttribute(gl: WebGLRenderingContext, location: number, attribute: VertexAttribute) { const { stepMode, format } = attribute; let { arrayStride, offset } = attribute; - const glVertexFormat = getIGLVertexFormat(format); + const glVertexFormat = vertexFormatMap[format]; const { numComponents, normalized, type } = glVertexFormat; gl.enableVertexAttribArray(location); @@ -619,7 +613,9 @@ export class RunWebGL offset = offset || 0; // - const buffer = getIGLVertexBuffer(attribute.data); + const buffer = getIGLBuffer(attribute.data, "ARRAY_BUFFER", "STATIC_DRAW"); + buffer.target ??= "ARRAY_BUFFER"; + const webGLBuffer = getGLBuffer(gl, buffer); gl.bindBuffer(gl.ARRAY_BUFFER, webGLBuffer); @@ -634,7 +630,7 @@ export class RunWebGL } } - private runTransformFeedback(gl: WebGLRenderingContext, transformFeedback: IGLTransformFeedback, topology: IGLDrawMode) + private runTransformFeedback(gl: WebGLRenderingContext, transformFeedback: TransformFeedback, topology: GLDrawMode) { if (gl instanceof WebGL2RenderingContext) { @@ -657,23 +653,21 @@ export class RunWebGL } } - private runTransformFeedbackPipeline(gl: WebGLRenderingContext, renderPipeline: IGLTransformFeedbackPipeline) + private runTransformFeedbackPipeline(gl: WebGLRenderingContext, renderPipeline: TransformFeedbackPipeline) { const program = getGLProgram(gl, renderPipeline); gl.useProgram(program); } - private runRenderPipeline(gl: WebGLRenderingContext, renderPipeline: IRenderPipeline) + private runRenderPipeline(gl: WebGLRenderingContext, renderPipeline: RenderPipeline) { this.runProgram(gl, renderPipeline); - this.runPrimitiveState(gl, renderPipeline?.primitive); - this.runDepthState(gl, renderPipeline.depthStencil); this.runStencilState(gl, renderPipeline.depthStencil); } - private runStencilState(gl: WebGLRenderingContext, depthStencil?: IDepthStencilState) + private runStencilState(gl: WebGLRenderingContext, depthStencil?: DepthStencilState) { const { stencilFront, stencilBack } = { ...depthStencil }; // @@ -687,10 +681,10 @@ export class RunWebGL if (stencilFront) { - const func: IGLStencilFunc = getIGLStencilFunc(stencilFront.compare ?? "always"); - const fail: IGLStencilOp = getIGLStencilOp(stencilFront.failOp); - const zfail: IGLStencilOp = getIGLStencilOp(stencilFront.depthFailOp); - const zpass: IGLStencilOp = getIGLStencilOp(stencilFront.passOp); + const func = getIGLStencilFunc(stencilFront.compare ?? "always"); + const fail = getIGLStencilOp(stencilFront.failOp); + const zfail = getIGLStencilOp(stencilFront.depthFailOp); + const zpass = getIGLStencilOp(stencilFront.passOp); // gl.stencilFuncSeparate(gl.FRONT, gl[func], ref, readMask); gl.stencilOpSeparate(gl.FRONT, gl[fail], gl[zfail], gl[zpass]); @@ -698,10 +692,10 @@ export class RunWebGL } if (stencilBack) { - const func: IGLStencilFunc = getIGLStencilFunc(stencilBack.compare ?? "always"); - const fail: IGLStencilOp = getIGLStencilOp(stencilBack.failOp); - const zfail: IGLStencilOp = getIGLStencilOp(stencilBack.depthFailOp); - const zpass: IGLStencilOp = getIGLStencilOp(stencilBack.passOp); + const func = getIGLStencilFunc(stencilBack.compare ?? "always"); + const fail = getIGLStencilOp(stencilBack.failOp); + const zfail = getIGLStencilOp(stencilBack.depthFailOp); + const zpass = getIGLStencilOp(stencilBack.passOp); // gl.stencilFuncSeparate(gl.BACK, gl[func], ref, readMask); gl.stencilOpSeparate(gl.BACK, gl[fail], gl[zfail], gl[zpass]); @@ -714,11 +708,11 @@ export class RunWebGL } } - private runDepthState(gl: WebGLRenderingContext, depthStencil?: IDepthStencilState) + private runDepthState(gl: WebGLRenderingContext, depthStencil?: DepthStencilState) { if (depthStencil && (depthStencil.depthWriteEnabled || depthStencil.depthCompare !== "always")) { - const depthCompare: IGLCompareFunction = getIGLCompareFunction(depthStencil.depthCompare ?? "less"); + const depthCompare = getIGLCompareFunction(depthStencil.depthCompare ?? "less"); const depthWriteEnabled = depthStencil.depthWriteEnabled ?? true; // gl.enable(gl.DEPTH_TEST); @@ -746,17 +740,21 @@ export class RunWebGL } } - private runPrimitiveState(gl: WebGLRenderingContext, primitive?: IPrimitiveState) + private runPrimitiveState(gl: WebGLRenderingContext, primitive?: PrimitiveState) { - const cullFace: ICullFace = primitive?.cullFace || "none"; - const frontFace: IFrontFace = primitive?.frontFace || "ccw"; + const cullFace: CullFace = primitive?.cullFace || "none"; + const frontFace: FrontFace = primitive?.frontFace || "ccw"; - const enableCullFace = cullFace !== "none"; - const glCullMode: IGLCullFace = getIGLCullFace(cullFace); - const glFrontFace: IGLFrontFace = getIGLFrontFace(frontFace); - if (enableCullFace) + if (cullFace !== "none") { + const glCullMode = cullFaceMap[cullFace]; + console.assert(!!glCullMode, `接收到错误值,请从 ${Object.keys(cullFaceMap).toString()} 中取值!`); + + const glFrontFace = frontFaceMap[frontFace]; + console.assert(!!glFrontFace, `接收到错误 IFrontFace 值,请从 ${Object.keys(frontFaceMap).toString()} 中取值!`); + + // gl.enable(gl.CULL_FACE); gl.cullFace(gl[glCullMode]); gl.frontFace(gl[glFrontFace]); @@ -767,16 +765,16 @@ export class RunWebGL } } - private runProgram(gl: WebGLRenderingContext, pipeline: IRenderPipeline) + private runProgram(gl: WebGLRenderingContext, material: RenderPipeline) { - const program = getGLProgram(gl, pipeline); + const program = getGLProgram(gl, material); gl.useProgram(program); // - this.runColorTargetStates(gl, pipeline.fragment.targets); + this.runColorTargetStates(gl, material.fragment.targets); } - private runColorTargetStates(gl: WebGLRenderingContext, targets?: readonly IColorTargetState[]) + private runColorTargetStates(gl: WebGLRenderingContext, targets?: readonly ColorTargetState[]) { // const colorMask = targets?.[0]?.writeMask || [true, true, true, true]; @@ -786,8 +784,8 @@ export class RunWebGL const blend = targets?.[0]?.blend; if (blend) { - const color: IBlendComponent = blend.color; - const alpha: IBlendComponent = blend.alpha; + const color: BlendComponent = blend.color; + const alpha: BlendComponent = blend.alpha; const colorOperation: IGLBlendEquation = getIGLBlendEquation(color?.operation) || "FUNC_ADD"; const colorSrcFactor: IGLBlendFactor = getIGLBlendFactor(color?.srcFactor, color?.operation) || "SRC_ALPHA"; @@ -798,7 +796,7 @@ export class RunWebGL const alphaDstFactor: IGLBlendFactor = getIGLBlendFactor(alpha?.dstFactor, color?.operation) || colorDstFactor; // 当混合系数用到了混合常量值时设置混合常量值。 - const constantColor = getBlendConstantColor(blend); + const constantColor = BlendState.getBlendConstantColor(blend); if (constantColor) { const constantColor = blend.constantColor ?? [0, 0, 0, 0]; @@ -816,7 +814,7 @@ export class RunWebGL } } - private runOcclusionQuery(gl: WebGLRenderingContext, attachmentSize: { width: number, height: number }, occlusionQuery: IGLOcclusionQuery) + private runOcclusionQuery(gl: WebGLRenderingContext, attachmentSize: { width: number, height: number }, occlusionQuery: OcclusionQuery) { // 开始查询 occlusionQuery._step.begin(); @@ -831,7 +829,7 @@ export class RunWebGL occlusionQuery._step.end(); } - private runViewPort(gl: WebGLRenderingContext, attachmentSize: { width: number, height: number }, viewport: IViewport) + private runViewPort(gl: WebGLRenderingContext, attachmentSize: { width: number, height: number }, viewport: Viewport) { if (viewport) { @@ -854,7 +852,7 @@ export class RunWebGL } } - private runScissor(gl: WebGLRenderingContext, attachmentSize: { width: number, height: number }, scissor: IScissorRect) + private runScissor(gl: WebGLRenderingContext, attachmentSize: { width: number, height: number }, scissor: ScissorRect) { if (scissor) { @@ -878,13 +876,13 @@ export class RunWebGL } } - private runCopyTextureToTexture(gl: WebGLRenderingContext, copyTextureToTexture: ICopyTextureToTexture) + private runCopyTextureToTexture(gl: WebGLRenderingContext, copyTextureToTexture: CopyTextureToTexture) { - const blitFramebuffer = getIGLBlitFramebuffer(copyTextureToTexture); + const blitFramebuffer = getGLBlitFramebuffer(copyTextureToTexture); this.runBlitFramebuffer(gl, blitFramebuffer); } - private runBlitFramebuffer(gl: WebGLRenderingContext, blitFramebuffer: IGLBlitFramebuffer) + private runBlitFramebuffer(gl: WebGLRenderingContext, blitFramebuffer: BlitFramebuffer) { const { read, draw, blitFramebuffers } = blitFramebuffer; @@ -914,7 +912,7 @@ export class RunWebGL } } - private runCopyBuffer(gl: WebGLRenderingContext, copyBuffer: ICopyBufferToBuffer) + private runCopyBuffer(gl: WebGLRenderingContext, copyBuffer: CopyBufferToBuffer) { if (gl instanceof WebGL2RenderingContext) { @@ -938,5 +936,48 @@ export class RunWebGL } } -export const defaultRenderPassColorAttachment: IRenderPassColorAttachment = { clearValue: [0, 0, 0, 0], loadOp: "clear" }; -export const defaultDepthStencilAttachment: IRenderPassDepthStencilAttachment = { depthClearValue: 1, depthLoadOp: "load", stencilClearValue: 0, stencilLoadOp: "load" }; +const cullFaceMap = Object.freeze({ + FRONT_AND_BACK: "FRONT_AND_BACK", + none: "BACK", // 不会开启剔除面功能,什么值无所谓。 + front: "FRONT", + back: "BACK", +}); + +const frontFaceMap = Object.freeze({ ccw: "CCW", cw: "CW", }); + +/** + * 获取渲染通道附件尺寸。 + * + * @param gl + * @param descriptor + */ +function getGLRenderPassAttachmentSize(gl: WebGLRenderingContext, descriptor: RenderPassDescriptor): { readonly width: number; readonly height: number; } +{ + if (!descriptor) return { width: gl.drawingBufferWidth, height: gl.drawingBufferHeight }; + + const colorAttachments = descriptor.colorAttachments; + if (colorAttachments) + { + const view = colorAttachments[0]?.view; + if (view) + { + return { width: view.texture.size[0], height: view.texture.size[1] }; + } + + return { width: gl.drawingBufferWidth, height: gl.drawingBufferHeight }; + } + + const depthStencilAttachment = descriptor.depthStencilAttachment; + if (depthStencilAttachment) + { + const view = depthStencilAttachment.view; + if (view) + { + return { width: view.texture.size[0], height: view.texture.size[1] }; + } + + return { width: gl.drawingBufferWidth, height: gl.drawingBufferHeight }; + } + + return { width: gl.drawingBufferWidth, height: gl.drawingBufferHeight }; +} \ No newline at end of file diff --git a/src/WebGL.ts b/src/WebGL.ts index 00cceefba66ca4b1cb4ab7c881e35a41f15394d4..39e47aa04586b8820b71174a52c18e8e5f2118bc 100644 --- a/src/WebGL.ts +++ b/src/WebGL.ts @@ -1,4 +1,4 @@ -import { IBuffer, IRenderPassDescriptor, IRenderPipeline, ISampler, ISubmit, ITexture } from "@feng3d/render-api"; +import { GBuffer, CanvasContext, ReadPixels, RenderPassDescriptor, RenderPipeline, Sampler, Submit, Texture } from "@feng3d/render-api"; import { RunWebGL } from "./RunWebGL"; import { deleteBuffer } from "./caches/getGLBuffer"; @@ -9,10 +9,8 @@ import { deleteRenderbuffer } from "./caches/getGLRenderbuffer"; import { deleteSampler } from "./caches/getGLSampler"; import { deleteTexture } from "./caches/getGLTexture"; import { deleteTransformFeedback } from "./caches/getGLTransformFeedback"; -import { IGLCanvasContext } from "./data/IGLCanvasContext"; -import { IGLReadPixels } from "./data/IGLReadPixels"; -import { IGLRenderbuffer } from "./data/IGLRenderbuffer"; -import { IGLTransformFeedback } from "./data/IGLTransformFeedback"; +import { Renderbuffer } from "./data/Renderbuffer"; +import { TransformFeedback } from "./data/TransformFeedbackPass"; import { readPixels } from "./utils/readPixels"; /** @@ -23,13 +21,13 @@ import { readPixels } from "./utils/readPixels"; export class WebGL { private _runWebGL: RunWebGL = new RunWebGL(); - private _renderingContext: IGLCanvasContext; + private _renderingContext: CanvasContext; private _gl: WebGLRenderingContext; - constructor(renderingContext?: IGLCanvasContext) + constructor(renderingContext?: CanvasContext) { this._renderingContext = renderingContext; - this._gl = getGLCanvasContext(this._renderingContext); + this._gl = getGLCanvasContext(this._renderingContext) as any; } /** @@ -38,47 +36,49 @@ export class WebGL * @param submit 一次 GPU 提交内容。 * */ - submit(submit: ISubmit) + submit(submit: Submit) { this._runWebGL.runSubmit(this._gl, submit); } - runReadPixels(glReadPixels: IGLReadPixels) + readPixels(glReadPixels: ReadPixels) { - readPixels(this._gl, glReadPixels); + glReadPixels.result = readPixels(this._gl, glReadPixels); + + return glReadPixels.result; } - deleteFramebuffer(passDescriptor: IRenderPassDescriptor) + deleteFramebuffer(passDescriptor: RenderPassDescriptor) { deleteFramebuffer(this._gl, passDescriptor); } - deleteRenderbuffer(renderbuffer: IGLRenderbuffer) + deleteRenderbuffer(renderbuffer: Renderbuffer) { deleteRenderbuffer(this._gl, renderbuffer); } - deleteBuffer(buffer: IBuffer) + deleteBuffer(buffer: GBuffer) { deleteBuffer(this._gl, buffer); } - deleteTexture(texture: ITexture) + deleteTexture(texture: Texture) { deleteTexture(this._gl, texture); } - deleteSampler(sampler: ISampler) + deleteSampler(sampler: Sampler) { deleteSampler(this._gl, sampler); } - deleteProgram(pipeline: IRenderPipeline) + deleteProgram(material: RenderPipeline) { - deleteProgram(this._gl, pipeline); + deleteProgram(this._gl, material); } - deleteTransformFeedback(transformFeedback: IGLTransformFeedback) + deleteTransformFeedback(transformFeedback: TransformFeedback) { deleteTransformFeedback(this._gl, transformFeedback); } diff --git a/src/caches/Capabilities.ts b/src/caches/Capabilities.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ab0c9261b718431aec47ef3f136e2946336c35e --- /dev/null +++ b/src/caches/Capabilities.ts @@ -0,0 +1,212 @@ +/** + * WEBGL支持功能 + * + * @see https://webglreport.com + * @see http://html5test.com + */ +export class Capabilities +{ + /** + * 纹理各向异性过滤最大值 + */ + get maxAnisotropy() + { + if (this._maxAnisotropy) return this._maxAnisotropy; + this._maxAnisotropy = this._gl.getExtension("EXT_texture_filter_anisotropic") ? this._gl.getParameter(this._gl.getExtension("EXT_texture_filter_anisotropic").MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0; + return this._maxAnisotropy; + } + private _maxAnisotropy: number; + + /** + * 支持最大纹理数量 + */ + get maxTextures() + { + if (this._maxTextures) return this._maxTextures; + this._maxTextures = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS); + return this._maxTextures; + } + private _maxTextures: number; + + /** + * 支持最大顶点纹理数量 + */ + get maxVertexTextures() + { + if (this._maxVertexTextures) return this._maxVertexTextures; + this._maxVertexTextures = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); + return this._maxVertexTextures; + } + private _maxVertexTextures: number; + + /** + * 支持最大纹理尺寸 + */ + get maxTextureSize() + { + if (this._maxTextureSize) return this._maxTextureSize; + this._maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE); + return this._maxTextureSize; + } + private _maxTextureSize: number; + + /** + * 支持最大立方体贴图尺寸 + */ + get maxCubemapSize() + { + if (this._maxCubemapSize) return this._maxCubemapSize; + this._maxCubemapSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE); + return this._maxCubemapSize; + } + private _maxCubemapSize: number; + + /** + * 支持属性数量 + */ + get maxAttributes() + { + if (this._maxAttributes) return this._maxAttributes; + this._maxAttributes = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS); + return this._maxAttributes; + } + private _maxAttributes: number; + + /** + * 顶点着色器支持最大 Uniform 数量 + */ + get maxVertexUniforms() + { + if (this._maxVertexUniforms) return this._maxVertexUniforms; + this._maxVertexUniforms = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS); + return this._maxVertexUniforms; + } + private _maxVertexUniforms: number; + + /** + * 支持最大shader之间传递的变量数 + */ + get maxVaryings() + { + if (this._maxVaryings) return this._maxVaryings; + this._maxVaryings = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS); + return this._maxVaryings; + } + private _maxVaryings: number; + + /** + * 片段着色器支持最大 Uniform 数量 + */ + get maxFragmentUniforms() + { + if (this._maxFragmentUniforms) return this._maxFragmentUniforms; + this._maxFragmentUniforms = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS); + return this._maxFragmentUniforms; + } + private _maxFragmentUniforms: number; + + /** + * 是否支持顶点纹理 + */ + get vertexTextures() + { + if (this._vertexTextures) return this._vertexTextures; + this._vertexTextures = this.maxVertexTextures > 0; + return this._vertexTextures; + } + private _vertexTextures: boolean; + + /** + * 是否支持浮点类型片段着色器纹理 + */ + get floatFragmentTextures() + { + if (this._floatFragmentTextures) return this._floatFragmentTextures; + this._floatFragmentTextures = this._gl instanceof WebGL2RenderingContext || !!this._gl.getExtension("OES_texture_float"); + return this._floatFragmentTextures; + } + private _floatFragmentTextures: boolean; + + /** + * 是否支持浮点类型顶点着色器纹理 + */ + get floatVertexTextures() + { + if (this._floatVertexTextures) return this._floatVertexTextures; + this._floatVertexTextures = this.vertexTextures && this.floatFragmentTextures; + return this._floatVertexTextures; + } + private _floatVertexTextures: boolean; + + /** + * Shader中支持浮点类型的最高精度 + */ + get maxPrecision() + { + if (this._maxPrecision) return this._maxPrecision; + this._maxPrecision = _getMaxPrecision(this._gl, this._precision); + return this._maxPrecision; + } + private _maxPrecision: "highp" | "mediump" | "lowp"; + + + /** + * + */ + get maxSamples() + { + if (this._maxSamples) return this._maxSamples; + this._maxSamples = this._gl instanceof WebGL2RenderingContext ? this._gl.getParameter(this._gl.MAX_SAMPLES) : 0; + return this._maxSamples; + } + private _maxSamples: number; + + /** + * 支持模板的位数 + */ + get stencilBits() + { + if (this._stencilBits) return this._stencilBits; + this._stencilBits = this._gl.getParameter(this._gl.STENCIL_BITS); + return this._stencilBits; + } + private _stencilBits: number; + + /** + * 是否支持VAO。 + */ + get vaoAvailable() + { + if (this._vaoAvailable) return this._vaoAvailable; + this._vaoAvailable = this._gl instanceof WebGL2RenderingContext || !!this._gl.getExtension("OES_vertex_array_object"); + return this._vaoAvailable; + } + private _vaoAvailable: boolean; + + constructor(private _gl: WebGLRenderingContext | WebGL2RenderingContext, private _precision: "highp" | "mediump" | "lowp" = "highp") + { + } +} + +function _getMaxPrecision(gl: WebGLRenderingContext | WebGL2RenderingContext, precision: "highp" | "mediump" | "lowp" = "highp") +{ + if (precision === "highp") + { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 + && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) + { + return "highp"; + } + precision = "mediump"; + } + if (precision === "mediump") + { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 + && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) + { + return "mediump"; + } + } + + return "lowp"; +} \ No newline at end of file diff --git a/src/caches/getCapabilities.ts b/src/caches/getCapabilities.ts deleted file mode 100644 index 7df01830af90b3150db598ef551b309b3ff79e8e..0000000000000000000000000000000000000000 --- a/src/caches/getCapabilities.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { IGLCapabilities } from "../data/IGLCapabilities"; - -export function getCapabilities(gl: WebGLRenderingContext, precision: "highp" | "mediump" | "lowp" = "highp") -{ - const capabilities: IGLCapabilities = {} as any; - gl._capabilities = capabilities; - // - capabilities.maxAnisotropy = gl.getExtension("EXT_texture_filter_anisotropic") ? gl.getParameter(gl.getExtension("EXT_texture_filter_anisotropic").MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0; - capabilities.maxPrecision = _getMaxPrecision(gl, precision); - - capabilities.maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); - capabilities.maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); - capabilities.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); - capabilities.maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE); - - capabilities.maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - capabilities.maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS); - capabilities.maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); - capabilities.maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS); - - capabilities.vertexTextures = capabilities.maxVertexTextures > 0; - capabilities.floatFragmentTextures = gl instanceof WebGL2RenderingContext || !!gl.getExtension("OES_texture_float"); - capabilities.floatVertexTextures = capabilities.vertexTextures && capabilities.floatFragmentTextures; - - capabilities.maxSamples = gl instanceof WebGL2RenderingContext ? gl.getParameter(gl.MAX_SAMPLES) : 0; - capabilities.stencilBits = gl.getParameter(gl.STENCIL_BITS); - - capabilities.vaoAvailable = gl instanceof WebGL2RenderingContext || !!gl.getExtension("OES_vertex_array_object"); - - return capabilities; -} - -function _getMaxPrecision(gl: WebGLRenderingContext, precision: "highp" | "mediump" | "lowp" = "highp") -{ - if (precision === "highp") - { - if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 - && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) - { - return "highp"; - } - precision = "mediump"; - } - if (precision === "mediump") - { - if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 - && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) - { - return "mediump"; - } - } - - return "lowp"; -} \ No newline at end of file diff --git a/src/caches/getIGLBlitFramebuffer.ts b/src/caches/getGLBlitFramebuffer.ts similarity index 56% rename from src/caches/getIGLBlitFramebuffer.ts rename to src/caches/getGLBlitFramebuffer.ts index 42755ab243b54f5c62bcaa143bec42bf2e7cc62c..7f88f836db995812a117fe521134ab206c2b4105 100644 --- a/src/caches/getIGLBlitFramebuffer.ts +++ b/src/caches/getGLBlitFramebuffer.ts @@ -1,5 +1,5 @@ -import { ICopyTextureToTexture, IImageCopyTexture, IRenderPassColorAttachment, IRenderPassDepthStencilAttachment, ITextureView } from "@feng3d/render-api"; -import { IGLBlitFramebuffer, IGLBlitFramebufferItem } from "../data/IGLBlitFramebuffer"; +import { CopyTextureToTexture, ImageCopyTexture, RenderPassColorAttachment, RenderPassDepthStencilAttachment, TextureView } from "@feng3d/render-api"; +import { BlitFramebuffer, BlitFramebufferItem } from "../data/BlitFramebuffer"; /** * 通过 IGLBlitFramebuffer 实现纹理之间拷贝并不靠谱。 @@ -7,7 +7,7 @@ import { IGLBlitFramebuffer, IGLBlitFramebufferItem } from "../data/IGLBlitFrame * @param copyTextureToTexture GL纹理之间拷贝。 * @returns */ -export function getIGLBlitFramebuffer(copyTextureToTexture: ICopyTextureToTexture) +export function getGLBlitFramebuffer(copyTextureToTexture: CopyTextureToTexture) { const { source, destination, copySize } = copyTextureToTexture; @@ -16,43 +16,43 @@ export function getIGLBlitFramebuffer(copyTextureToTexture: ICopyTextureToTextur console.assert(sourceAspect === destinationAspect, `拷贝纹理时两个纹理的 aspect 必须相同!`); - const sourceColorAttachments: IRenderPassColorAttachment[] = []; - let sourceDepthStencilAttachment: IRenderPassDepthStencilAttachment; - const destinationColorAttachments: IRenderPassColorAttachment[] = []; - let destinationDepthStencilAttachment: IRenderPassDepthStencilAttachment; + const sourceColorAttachments: RenderPassColorAttachment[] = []; + let sourceDepthStencilAttachment: RenderPassDepthStencilAttachment; + const destinationColorAttachments: RenderPassColorAttachment[] = []; + let destinationDepthStencilAttachment: RenderPassDepthStencilAttachment; // let mask: "COLOR_BUFFER_BIT" | "DEPTH_BUFFER_BIT" | "STENCIL_BUFFER_BIT"; if (sourceAspect === "all") { mask = "COLOR_BUFFER_BIT"; - sourceColorAttachments.push({ view: getIGLTextureView(source) }); - destinationColorAttachments.push({ view: getIGLTextureView(destination) }); + sourceColorAttachments.push({ view: getGLTextureView(source) }); + destinationColorAttachments.push({ view: getGLTextureView(destination) }); } else if (sourceAspect === "depth-only") { mask = "DEPTH_BUFFER_BIT"; - sourceDepthStencilAttachment = { view: getIGLTextureView(source) }; - destinationDepthStencilAttachment = { view: getIGLTextureView(destination) }; + sourceDepthStencilAttachment = { view: getGLTextureView(source) }; + destinationDepthStencilAttachment = { view: getGLTextureView(destination) }; } else if (sourceAspect === "stencil-only") { mask = "STENCIL_BUFFER_BIT"; - sourceDepthStencilAttachment = { view: getIGLTextureView(source) }; - destinationDepthStencilAttachment = { view: getIGLTextureView(destination) }; + sourceDepthStencilAttachment = { view: getGLTextureView(source) }; + destinationDepthStencilAttachment = { view: getGLTextureView(destination) }; } const sourceOrigin = source.origin || [0, 0]; const destinationOrigin = destination.origin || [0, 0]; // - const blitFramebufferItem: IGLBlitFramebufferItem = [ + const blitFramebufferItem: BlitFramebufferItem = [ sourceOrigin[0], sourceOrigin[1], sourceOrigin[0] + copySize[0], sourceOrigin[1] + copySize[1], destinationOrigin[0], destinationOrigin[1], destinationOrigin[0] + copySize[0], destinationOrigin[1] + copySize[1], mask, "NEAREST", ]; - const blitFramebuffer: IGLBlitFramebuffer = { - __type: "BlitFramebuffer", + const blitFramebuffer: BlitFramebuffer = { + __type__: "BlitFramebuffer", read: { colorAttachments: sourceColorAttachments, depthStencilAttachment: sourceDepthStencilAttachment, @@ -67,11 +67,11 @@ export function getIGLBlitFramebuffer(copyTextureToTexture: ICopyTextureToTextur return blitFramebuffer; } -function getIGLTextureView(source: IImageCopyTexture) +function getGLTextureView(source: ImageCopyTexture) { if (!source.texture) return undefined; - const textureView: ITextureView = { + const textureView: TextureView = { texture: source.texture, baseMipLevel: source.mipLevel, baseArrayLayer: source.origin?.[2], diff --git a/src/caches/getGLBuffer.ts b/src/caches/getGLBuffer.ts index 1cfd4da6c999c2c2eeb5e46059c045b3b87d35e0..d448ac34f702117d37ea14487385dca3808bceda 100644 --- a/src/caches/getGLBuffer.ts +++ b/src/caches/getGLBuffer.ts @@ -1,13 +1,8 @@ -import { IBuffer } from "@feng3d/render-api"; +import { Buffer, UnReadonly } from "@feng3d/render-api"; import { watcher } from "@feng3d/watcher"; declare global { - interface WebGLRenderingContext - { - _buffers: Map - } - interface WebGLBuffer { /** @@ -17,13 +12,13 @@ declare global } } -export function getGLBuffer(gl: WebGLRenderingContext, buffer: IBuffer) +export function getGLBuffer(gl: WebGLRenderingContext, buffer: Buffer) { - let webGLBuffer = gl._buffers.get(buffer); + let webGLBuffer = gl._bufferMap.get(buffer); if (webGLBuffer) return webGLBuffer; webGLBuffer = gl.createBuffer(); - gl._buffers.set(buffer, webGLBuffer); + gl._bufferMap.set(buffer, webGLBuffer); const target = buffer.target; @@ -66,7 +61,7 @@ export function getGLBuffer(gl: WebGLRenderingContext, buffer: IBuffer) } gl.bufferSubData(gl[target], bufferOffset, arrayBufferView); }); - buffer.writeBuffers = null; + (buffer as UnReadonly).writeBuffers = null; }; const dataChange = () => @@ -75,7 +70,7 @@ export function getGLBuffer(gl: WebGLRenderingContext, buffer: IBuffer) const writeBuffers = buffer.writeBuffers || []; writeBuffers.unshift({ data: buffer.data }); - buffer.writeBuffers = writeBuffers; + (buffer as UnReadonly).writeBuffers = writeBuffers; }; dataChange(); @@ -95,12 +90,12 @@ export function getGLBuffer(gl: WebGLRenderingContext, buffer: IBuffer) return webGLBuffer; } -export function deleteBuffer(gl: WebGLRenderingContext, buffer: IBuffer) +export function deleteBuffer(gl: WebGLRenderingContext, buffer: Buffer) { - const webGLBuffer = gl._buffers.get(buffer); + const webGLBuffer = gl._bufferMap.get(buffer); if (webGLBuffer) { - gl._buffers.delete(buffer); + gl._bufferMap.delete(buffer); webGLBuffer.destroy(); delete webGLBuffer.destroy; // diff --git a/src/caches/getGLCanvasContext.ts b/src/caches/getGLCanvasContext.ts index f2ad55ca6a0c80e59dcca4e95982c9572bc52d99..48f7347b60b8507fd8dedb966cea070333cb9f76 100644 --- a/src/caches/getGLCanvasContext.ts +++ b/src/caches/getGLCanvasContext.ts @@ -1,49 +1,61 @@ -import { IGLCanvasContext } from "../data/IGLCanvasContext"; -import { defaultCanvasContext } from "../defaults/defaults"; -import { ChainMap } from "../utils/ChainMap"; -import { getCapabilities } from "./getCapabilities"; +import { CanvasContext, ChainMap, GBuffer, IIndicesDataTypes, RenderPassDescriptor, RenderPipeline, Sampler, Texture, VertexAttributes } from "@feng3d/render-api"; +import { defaultWebGLContextAttributes } from "../data/polyfills/CanvasContext"; +import { Renderbuffer } from "../data/Renderbuffer"; +import { TransformFeedback } from "../data/TransformFeedbackPass"; +import { Capabilities } from "./Capabilities"; + +declare global +{ + interface WebGLRenderingContext + { + _capabilities: Capabilities; + // + _bufferMap: WeakMap + _textures: WeakMap + _renderbuffers: WeakMap; + _framebuffers: WeakMap; + _vertexArrays: ChainMap<[RenderPipeline, VertexAttributes, IIndicesDataTypes], WebGLVertexArrayObject>; + _samplers: WeakMap; + _transforms: WeakMap; + _programs: { [key: string]: WebGLProgram } + _shaders: { [key: string]: WebGLShader } + } +} /** * 获取WebGL上下文。 * - * @param renderingContext + * @param canvasContext * @returns */ -export function getGLCanvasContext(renderingContext: IGLCanvasContext) +export function getGLCanvasContext(canvasContext: CanvasContext) { - const key = renderingContext.canvasId; - let value = canvasContextMap.get(key); - if (!value) - { - const canvas = getCanvas(renderingContext); - value = getWebGLContext(canvas, renderingContext); - - // - getCapabilities(value); - initMap(value); - - // - canvas.addEventListener("webglcontextlost", _onContextLost, false); - canvas.addEventListener("webglcontextrestored", _onContextRestore, false); - canvas.addEventListener("webglcontextcreationerror", _onContextCreationError, false); + let gl: WebGLRenderingContext = canvasContext["_gl"]; + if (gl) return gl; - canvasContextMap.set(key, value); - } + const canvas = typeof canvasContext.canvasId === "string" ? document.getElementById(canvasContext.canvasId) as HTMLCanvasElement : canvasContext.canvasId; + gl = canvasContext["_gl"] = getWebGLContext(canvas, canvasContext); - return value; -} + canvasContext.webGLContextAttributes + // + gl._capabilities = new Capabilities(gl); -function initMap(gl: WebGLRenderingContext) -{ - gl._buffers = new Map(); - gl._textures = new Map(); - gl._renderbuffers = new Map(); - gl._framebuffers = new Map(); + gl._bufferMap = new WeakMap(); + gl._textures = new WeakMap(); + gl._renderbuffers = new WeakMap(); + gl._framebuffers = new WeakMap(); gl._vertexArrays = new ChainMap(); - gl._samplers = new Map(); - gl._transforms = new Map(); + gl._samplers = new WeakMap(); + gl._transforms = new WeakMap(); gl._programs = {}; gl._shaders = {}; + + // + canvas.addEventListener("webglcontextlost", _onContextLost, false); + canvas.addEventListener("webglcontextrestored", _onContextRestore, false); + canvas.addEventListener("webglcontextcreationerror", _onContextCreationError, false); + + return gl; } function _onContextLost(event: Event) @@ -63,46 +75,20 @@ function _onContextCreationError(event: WebGLContextEvent) console.error("WebGLRenderer: A WebGL context could not be created. Reason: ", event.statusMessage); } -function autoCreateCanvas(canvasId: string) -{ - const canvas = document.createElement("canvas"); - canvas.id = canvasId; - document.body.appendChild(canvas); - - return canvas; -} - -export function getCanvas(canvasContext: IGLCanvasContext) -{ - let canvas = document.getElementById(canvasContext.canvasId) as HTMLCanvasElement; - if (!canvas || !(canvas instanceof HTMLCanvasElement)) - { - canvas = autoCreateCanvas(canvasContext.canvasId); - } - - return canvas; -} - -function getWebGLContext(canvas: HTMLCanvasElement, canvasContext: IGLCanvasContext) +function getWebGLContext(canvas: HTMLCanvasElement | OffscreenCanvas, canvasContext: CanvasContext): WebGLRenderingContext { - const contextAttributes = Object.assign({}, defaultCanvasContext, canvasContext); + const contextAttributes = Object.assign({}, defaultWebGLContextAttributes, canvasContext.webGLContextAttributes); // 使用用户提供参数获取WebGL上下文 - let gl = canvas.getContext(contextAttributes.contextId, contextAttributes) as any; - if (gl) return gl; + let gl = canvas.getContext(canvasContext.webGLcontextId || "webgl2", contextAttributes); + gl || console.warn(`无法使用用户提供参数获取指定WebGL上下文`, contextAttributes); - gl = canvas.getContext("webgl", contextAttributes) || canvas.getContext("webgl2", contextAttributes); - gl && console.warn(`无法使用用户提供参数获取指定WebGL上下文,${canvasContext}`); - if (gl) return gl; - - // 使用默认参数获取WebGL上下文 - gl = canvas.getContext("webgl") || canvas.getContext("webgl2"); - gl && console.warn(`无法使用用户提供参数获取WebGL上下文,${canvasContext}`); - if (gl) return gl; + gl = canvas.getContext("webgl2", contextAttributes) + || canvas.getContext("webgl2") + || canvas.getContext("webgl", contextAttributes) + || canvas.getContext("webgl"); - console.error(`无法获取WebGL上下文。`); + gl || console.error(`无法获取WebGL上下文。`); - return null; + return gl as any; } - -const canvasContextMap = new Map(); diff --git a/src/caches/getIGLDrawMode.ts b/src/caches/getGLDrawMode.ts similarity index 81% rename from src/caches/getIGLDrawMode.ts rename to src/caches/getGLDrawMode.ts index 77980f0d323d1d75aa5ecfb6ea389ac4223c6cbe..58e4e6359390fe819bdf3e652c424a94a2b8dd6e 100644 --- a/src/caches/getIGLDrawMode.ts +++ b/src/caches/getGLDrawMode.ts @@ -1,6 +1,6 @@ -import { IPrimitiveTopology } from "@feng3d/render-api"; +import { PrimitiveTopology } from "@feng3d/render-api"; -export function getIGLDrawMode(topology: IPrimitiveTopology): IGLDrawMode +export function getGLDrawMode(topology: PrimitiveTopology): GLDrawMode { let drawMode = drawModeMap[topology]; @@ -11,7 +11,7 @@ export function getIGLDrawMode(topology: IPrimitiveTopology): IGLDrawMode return drawMode; } -const drawModeMap: { [key: string]: IGLDrawMode } = { +const drawModeMap: { [key: string]: GLDrawMode } = { "point-list": "POINTS", "line-list": "LINES", "line-strip": "LINE_STRIP", @@ -44,4 +44,4 @@ const drawModeMap: { [key: string]: IGLDrawMode } = { * * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/drawElements */ -export type IGLDrawMode = "POINTS" | "LINE_STRIP" | "LINE_LOOP" | "LINES" | "TRIANGLE_STRIP" | "TRIANGLE_FAN" | "TRIANGLES"; +export type GLDrawMode = "POINTS" | "LINE_STRIP" | "LINE_LOOP" | "LINES" | "TRIANGLE_STRIP" | "TRIANGLE_FAN" | "TRIANGLES"; diff --git a/src/caches/getGLFramebuffer.ts b/src/caches/getGLFramebuffer.ts index 57983ea101cda4416d0373773b710154bea6ba4c..89723b8f759866e662bb7e4b8cce15c8c806d128 100644 --- a/src/caches/getGLFramebuffer.ts +++ b/src/caches/getGLFramebuffer.ts @@ -1,22 +1,14 @@ -import { IRenderPassDescriptor, ITextureView } from "@feng3d/render-api"; -import { IGLRenderbuffer } from "../data/IGLRenderbuffer"; +import { RenderPassDescriptor, TextureView } from "@feng3d/render-api"; +import { Renderbuffer } from "../data/Renderbuffer"; import { deleteRenderbuffer, getGLRenderbuffer } from "./getGLRenderbuffer"; +import { _IGLRenderPassDescriptorWithMultisample, GLRenderPassDescriptorWithMultisample } from "./getGLRenderPassDescriptorWithMultisample"; import { getGLTexture } from "./getGLTexture"; -import { _IGLRenderPassDescriptorWithMultisample, IGLRenderPassDescriptorWithMultisample } from "./getIGLRenderPassDescriptorWithMultisample"; -import { getIGLTextureTarget } from "./getIGLTextureTarget"; - -declare global -{ - interface WebGLRenderingContext - { - _framebuffers: Map; - } -} +import { getGLTextureTarget } from "./getGLTextureTarget"; /** * 获取帧缓冲区 */ -export function getGLFramebuffer(gl: WebGLRenderingContext, passDescriptor: IRenderPassDescriptor) +export function getGLFramebuffer(gl: WebGLRenderingContext, passDescriptor: RenderPassDescriptor) { const view = passDescriptor?.colorAttachments?.[0]?.view || passDescriptor?.depthStencilAttachment?.view; if (!view) return null; @@ -34,7 +26,7 @@ export function getGLFramebuffer(gl: WebGLRenderingContext, passDescriptor: IRen const drawBuffers: number[] = []; passDescriptor.colorAttachments?.forEach((item, i) => { - const view = item.view as (ITextureView | IGLRenderbuffer); + const view = item.view as (TextureView | Renderbuffer); const attachment = gl[`COLOR_ATTACHMENT${i}`]; drawBuffers.push(attachment); if ("texture" in view) @@ -44,7 +36,7 @@ export function getGLFramebuffer(gl: WebGLRenderingContext, passDescriptor: IRen const baseArrayLayer = view.baseArrayLayer || 0; const webGLTexture = getGLTexture(gl, texture); - const textureTarget = getIGLTextureTarget(texture.dimension); + const textureTarget = getGLTextureTarget(texture.dimension); if (textureTarget === "TEXTURE_2D") { @@ -88,7 +80,7 @@ export function getGLFramebuffer(gl: WebGLRenderingContext, passDescriptor: IRen const baseArrayLayer = view.baseArrayLayer || 0; const webGLTexture = getGLTexture(gl, texture); - const textureTarget = getIGLTextureTarget(texture.dimension); + const textureTarget = getGLTextureTarget(texture.dimension); if (textureTarget === "TEXTURE_2D") { @@ -117,13 +109,13 @@ export function getGLFramebuffer(gl: WebGLRenderingContext, passDescriptor: IRen * @param handleMultisample 处理存在多重采样的渲染通道描述。 * @returns */ -export function deleteFramebuffer(gl: WebGLRenderingContext, passDescriptor: IRenderPassDescriptor, handleMultisample = true) +export function deleteFramebuffer(gl: WebGLRenderingContext, passDescriptor: RenderPassDescriptor, handleMultisample = true) { if (handleMultisample && passDescriptor?.[_IGLRenderPassDescriptorWithMultisample]) { deleteRenderPassDescriptorWithMultisample(gl, passDescriptor[_IGLRenderPassDescriptorWithMultisample]); -return; + return; } const webGLFramebuffer = gl._framebuffers.get(passDescriptor); @@ -132,7 +124,7 @@ return; gl.deleteFramebuffer(webGLFramebuffer); } -function deleteRenderPassDescriptorWithMultisample(gl: WebGLRenderingContext, renderPassDescriptorWithMultisample: IGLRenderPassDescriptorWithMultisample) +function deleteRenderPassDescriptorWithMultisample(gl: WebGLRenderingContext, renderPassDescriptorWithMultisample: GLRenderPassDescriptorWithMultisample) { deleteFramebuffer(gl, renderPassDescriptorWithMultisample.blitFramebuffer.read, false); deleteFramebuffer(gl, renderPassDescriptorWithMultisample.blitFramebuffer.draw, false); diff --git a/src/caches/getGLProgram.ts b/src/caches/getGLProgram.ts index 5c38125adca3ee76197c32e8808258116fc1ec1f..af7bba06e97a863640aa3545239b6c387f2863ce 100644 --- a/src/caches/getGLProgram.ts +++ b/src/caches/getGLProgram.ts @@ -1,18 +1,9 @@ -import { IRenderPipeline } from "@feng3d/render-api"; -import { getWebGLUniformType, IGLUniformBufferType, isWebGLUniformTextureType } from "../const/IGLUniformType"; -import { IGLAttributeInfo } from "../data/IGLAttributeInfo"; -import { IGLTransformFeedbackPipeline, IGLTransformFeedbackVaryings } from "../data/IGLTransformFeedbackPass"; -import { IGLUniformInfo, IUniformItemInfo } from "../data/IGLUniformInfo"; -import { getIGLAttributeType } from "./getIGLAttributeType"; +import { BufferBindingInfo, GLVertexAttributeTypes, RenderPipeline } from "@feng3d/render-api"; +import { getWebGLUniformType, GLUniformBufferType, GLUniformType, isWebGLUniformTextureType } from "../const/GLUniformType"; +import { TransformFeedbackPipeline, TransformFeedbackVaryings } from "../data/TransformFeedbackPass"; declare global { - interface WebGLRenderingContext - { - _programs: { [key: string]: WebGLProgram } - _shaders: { [key: string]: WebGLShader } - } - export interface WebGLProgram { vertex: string; @@ -24,28 +15,52 @@ declare global /** * uniform信息列表 */ - uniforms: IGLUniformInfo[]; + uniforms: GLUniformInfo[]; /** * 统一变量块信息列表。 * * 仅 WebGL2 中存在。 */ - uniformBlocks: IUniformBlockInfo[]; + uniformBlocks: UniformBlockInfo[]; } } +export interface IGLAttributeInfo +{ + /** + * 名称。 + */ + name: string; + + /** + * 顶点尺寸。 + */ + size: number; + + /** + * 属性缓冲数据类型 + */ + type?: GLVertexAttributeTypes; + + /** + * 属性地址 + */ + location: number; +} + + /** * 激活渲染程序 */ -export function getGLProgram(gl: WebGLRenderingContext, pipeline: IRenderPipeline | IGLTransformFeedbackPipeline) +export function getGLProgram(gl: WebGLRenderingContext, material: RenderPipeline | TransformFeedbackPipeline) { - const shaderKey = getKey(pipeline); + const shaderKey = getKey(material); let result = gl._programs[shaderKey]; if (result) return result; - const vertex = pipeline.vertex.code; - const fragment = (pipeline as IRenderPipeline).fragment?.code || `#version 300 es + const vertex = material.vertex.code; + const fragment = (material as RenderPipeline).fragment?.code || `#version 300 es precision highp float; precision highp int; @@ -53,7 +68,7 @@ export function getGLProgram(gl: WebGLRenderingContext, pipeline: IRenderPipelin { } `; - const transformFeedbackVaryings = (pipeline as IGLTransformFeedbackPipeline).transformFeedbackVaryings; + const transformFeedbackVaryings = (material as TransformFeedbackPipeline).transformFeedbackVaryings; result = getWebGLProgram(gl, vertex, fragment, transformFeedbackVaryings); gl._programs[shaderKey] = result; @@ -61,9 +76,9 @@ export function getGLProgram(gl: WebGLRenderingContext, pipeline: IRenderPipelin return result; } -export function deleteProgram(gl: WebGLRenderingContext, pipeline: IRenderPipeline) +export function deleteProgram(gl: WebGLRenderingContext, material: RenderPipeline) { - const shaderKey = getKey(pipeline); + const shaderKey = getKey(material); const result = gl._programs[shaderKey]; if (result) { @@ -72,16 +87,16 @@ export function deleteProgram(gl: WebGLRenderingContext, pipeline: IRenderPipeli } } -function getKey(pipeline: IRenderPipeline | IGLTransformFeedbackPipeline) +function getKey(material: RenderPipeline | TransformFeedbackPipeline) { - const vertex = pipeline.vertex.code; - const fragment = (pipeline as IRenderPipeline).fragment?.code; - const transformFeedbackVaryings = (pipeline as IGLTransformFeedbackPipeline).transformFeedbackVaryings; + const vertex = material.vertex.code; + const fragment = (material as RenderPipeline).fragment?.code; + const transformFeedbackVaryings = (material as TransformFeedbackPipeline).transformFeedbackVaryings; return `---vertexShader---\n${vertex}\n---fragment---\n${fragment}\n---feedback---${transformFeedbackVaryings?.varyings.toString()} ${transformFeedbackVaryings?.bufferMode}`; } -function getWebGLProgram(gl: WebGLRenderingContext, vshader: string, fshader: string, transformFeedbackVaryings: IGLTransformFeedbackVaryings) +function getWebGLProgram(gl: WebGLRenderingContext, vshader: string, fshader: string, transformFeedbackVaryings: TransformFeedbackVaryings) { // 编译顶点着色器 const vertexShader = getWebGLShader(gl, "VERTEX_SHADER", vshader); @@ -100,12 +115,12 @@ function getWebGLProgram(gl: WebGLRenderingContext, vshader: string, fshader: st const activeInfo = gl.getActiveAttrib(program, i); const { name, size, type } = activeInfo; const location = gl.getAttribLocation(program, name); - const typeString = getIGLAttributeType(type as any); + const typeString = getGLAttributeType(type as any); attributes.push({ name, size, type: typeString, location }); } // 获取uniform信息 const numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - const uniforms: IGLUniformInfo[] = []; + const uniforms: GLUniformInfo[] = []; let textureID = 0; for (let i = 0; i < numUniforms; i++) { @@ -127,7 +142,7 @@ function getWebGLProgram(gl: WebGLRenderingContext, vshader: string, fshader: st } } - const items: IUniformItemInfo[] = []; + const items: UniformItemInfo[] = []; for (let j = 0; j < names.length; j++) { const name = names[j]; @@ -161,7 +176,7 @@ function getWebGLProgram(gl: WebGLRenderingContext, vshader: string, fshader: st gl.uniformBlockBinding(program, i, i); // 获取包含的统一变量列表。 const uniformIndices: Uint32Array = gl.getActiveUniformBlockParameter(program, i, gl.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES); - const uniformList: IGLUniformInfo[] = []; + const uniformList: GLUniformInfo[] = []; for (let i = 0; i < uniformIndices.length; i++) { const unifrom = uniforms[uniformIndices[i]]; @@ -170,7 +185,7 @@ function getWebGLProgram(gl: WebGLRenderingContext, vshader: string, fshader: st } const name = gl.getActiveUniformBlockName(program, i); // - const info: IUniformBlockInfo = { + const info: UniformBlockInfo = { name, index: i, dataSize: gl.getActiveUniformBlockParameter(program, i, gl.UNIFORM_BLOCK_DATA_SIZE), @@ -198,7 +213,7 @@ function getWebGLProgram(gl: WebGLRenderingContext, vshader: string, fshader: st /** * 统一变量块信息。 */ -export interface IUniformBlockInfo +export interface UniformBlockInfo { /** * 名称。 @@ -218,12 +233,12 @@ export interface IUniformBlockInfo /** * 包含的统一变量列表。 */ - uniforms: IGLUniformInfo[]; + uniforms: GLUniformInfo[]; /** * 缓冲区绑定信息。 */ - bufferBindingInfo: IBufferBindingInfo; + bufferBindingInfo: BufferBindingInfo; } /** @@ -256,7 +271,7 @@ function getWebGLShader(gl: WebGLRenderingContext, type: ShaderType, code: strin return shader; } -function createLinkProgram(gl: WebGLRenderingContext, vertexShader: WebGLShader, fragmentShader: WebGLShader, transformFeedbackVaryings: IGLTransformFeedbackVaryings) +function createLinkProgram(gl: WebGLRenderingContext, vertexShader: WebGLShader, fragmentShader: WebGLShader, transformFeedbackVaryings: TransformFeedbackVaryings) { // 创建程序对象 const program = gl.createProgram(); @@ -301,21 +316,7 @@ function createLinkProgram(gl: WebGLRenderingContext, vertexShader: WebGLShader, */ export type ShaderType = "FRAGMENT_SHADER" | "VERTEX_SHADER"; -/** - * 缓冲区绑定信息。 - */ -export interface IBufferBindingInfo -{ - size: number; - items: { - paths: string[]; - offset: number; - size: number; - Cls: Float32ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor; - }[] -} - -function getBufferBindingInfo(uniformBlock: IUniformBlockInfo): IBufferBindingInfo +function getBufferBindingInfo(uniformBlock: UniformBlockInfo): BufferBindingInfo { const size = uniformBlock.dataSize; // @@ -325,7 +326,7 @@ function getBufferBindingInfo(uniformBlock: IUniformBlockInfo): IBufferBindingIn const items: { paths: string[], offset: number, size: number, Cls: Float32ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor }[] = []; uniformBlock.uniforms.forEach((uniformInfo) => { - const uniformBufferType = uniformInfo.type as IGLUniformBufferType; + const uniformBufferType = uniformInfo.type as GLUniformBufferType; const alignSize = uniformBufferTypeAlignSizeMap[uniformBufferType]; console.assert(alignSize, `没有找到 ${uniformBufferType} 统一缓冲类型对应的对齐与尺寸。`); @@ -356,7 +357,7 @@ function getBufferBindingInfo(uniformBlock: IUniformBlockInfo): IBufferBindingIn console.assert(size === currentSize, `uniformBlock映射尺寸出现错误( ${size} ${currentSize} )!`); - const bufferBindingInfo: IBufferBindingInfo = { + const bufferBindingInfo: BufferBindingInfo = { size: uniformBlock.dataSize, items, }; @@ -406,4 +407,73 @@ const uniformBufferTypeAlignSizeMap: { FLOAT_MAT3x4: { align: 16, size: 48, clsType: Float32Array }, FLOAT_MAT4x2: { align: 8, size: 32, clsType: Float32Array }, FLOAT_MAT4x3: { align: 16, size: 64, clsType: Float32Array }, -}; \ No newline at end of file +}; + + +/** + * WebGL统一变量 + */ +export interface GLUniformInfo +{ + /** + * 名称。 + */ + name: string; + + type: GLUniformType; + + /** + * 是否纹理。 + */ + isTexture: boolean; + + /** + * 子项信息列表。 + */ + items: UniformItemInfo[] + + /** + * 是否在Block中。 + */ + inBlock?: boolean; +} + +/** + * WebGL统一变量 + */ +export interface UniformItemInfo +{ + /** + * uniform地址 + */ + location: WebGLUniformLocation; + + /** + * texture索引 + */ + textureID: number; + + /** + * Uniform数组索引,当Uniform数据为数组数据时生效 + */ + paths: string[]; +} + +/** + * WebGL 属性类型。 + */ +export type GLAttributeType = keyof typeof webglAttributeTypeValue; + +/** + * 获取顶点数据类型名称。 + * + * @param gl + * @param value + */ +export function getGLAttributeType(value: keyof typeof webglAttributeValueType): GLAttributeType +{ + return webglAttributeValueType[value]; +} + +const webglAttributeTypeValue = Object.freeze({ FLOAT: 5126, BYTE: 5120, SHORT: 5122, UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, HALF_FLOAT: 5131, INT: 5124, UNSIGNED_INT: 5125 }); +const webglAttributeValueType = Object.freeze({ 5120: "BYTE", 5121: "UNSIGNED_BYTE", 5122: "SHORT", 5123: "UNSIGNED_SHORT", 5124: "INT", 5125: "UNSIGNED_INT", 5126: "FLOAT", 5131: "HALF_FLOAT" }); diff --git a/src/caches/getGLRenderOcclusionQuery.ts b/src/caches/getGLRenderOcclusionQuery.ts index 36fba8b710f46446b09c791f96c2d02ea3d0b6e1..799cdbdb0658f843a2ed8a9a899fb690cacaffd3 100644 --- a/src/caches/getGLRenderOcclusionQuery.ts +++ b/src/caches/getGLRenderOcclusionQuery.ts @@ -1,14 +1,15 @@ -import { IRenderPass, IRenderPassObject } from "@feng3d/render-api"; -import { IGLOcclusionQuery, IGLQuery } from "../data/IGLOcclusionQuery"; +import { RenderPassObject, OcclusionQuery, RenderPass } from "@feng3d/render-api"; -export function getGLRenderOcclusionQuery(gl: WebGLRenderingContext, renderObjects?: readonly IRenderPassObject[]) +import "../data/polyfills/OcclusionQuery"; + +export function getGLRenderOcclusionQuery(gl: WebGLRenderingContext, renderObjects?: readonly RenderPassObject[]) { if (!renderObjects) return defautRenderOcclusionQuery; if (!(gl instanceof WebGL2RenderingContext)) return defautRenderOcclusionQuery; let renderOcclusionQuery: GLRenderOcclusionQuery = renderObjects["_GLRenderOcclusionQuery"]; if (renderOcclusionQuery) return renderOcclusionQuery; - const occlusionQueryObjects: IGLOcclusionQuery[] = renderObjects.filter((cv) => cv.__type === "OcclusionQuery") as any; + const occlusionQueryObjects: OcclusionQuery[] = renderObjects.filter((cv) => cv.__type__ === "OcclusionQuery") as any; if (occlusionQueryObjects.length === 0) { renderObjects["_GLRenderOcclusionQuery"] = defautRenderOcclusionQuery; @@ -30,13 +31,13 @@ export function getGLRenderOcclusionQuery(gl: WebGLRenderingContext, renderObjec /** * 查询结果。 */ - const resolve = (renderPass: IRenderPass) => + const resolve = (renderPass: RenderPass) => { const results = occlusionQueryObjects.map((v) => v._step.resolve()); Promise.all(results).then((v) => { - renderPass.occlusionQueryResults = v; + renderPass.onOcclusionQuery?.(occlusionQueryObjects, v); }); }; @@ -48,14 +49,14 @@ export function getGLRenderOcclusionQuery(gl: WebGLRenderingContext, renderObjec interface GLRenderOcclusionQuery { init: () => void - resolve: (renderPass: IRenderPass) => void + resolve: (renderPass: RenderPass) => void } const defautRenderOcclusionQuery = { init: () => { }, resolve: () => { } }; -export function getGLOcclusionQueryStep(gl: WebGL2RenderingContext, occlusionQuery: IGLOcclusionQuery) +export function getGLOcclusionQueryStep(gl: WebGL2RenderingContext, occlusionQuery: OcclusionQuery) { - const query: IGLQuery = {} as any; + const query: { result?: number } = {}; let webGLQuery: WebGLQuery; // 开始查询 @@ -77,11 +78,11 @@ export function getGLOcclusionQueryStep(gl: WebGL2RenderingContext, occlusionQue */ const resolve = async () => { - if (query.result !== undefined) return occlusionQuery; + if (query.result !== undefined) return query.result; if (gl instanceof WebGL2RenderingContext) { - const result: IGLOcclusionQuery = await new Promise((resolve, reject) => + const result: number = await new Promise((resolve, reject) => { (function tick() { @@ -94,11 +95,11 @@ export function getGLOcclusionQueryStep(gl: WebGL2RenderingContext, occlusionQue return; } - query.result = gl.getQueryParameter(webGLQuery, gl.QUERY_RESULT); + const result = query.result = gl.getQueryParameter(webGLQuery, gl.QUERY_RESULT) as number; - occlusionQuery.result = query; + occlusionQuery.onQuery(result); - resolve(occlusionQuery); + resolve(result); gl.deleteQuery(webGLQuery); })(); @@ -110,13 +111,13 @@ export function getGLOcclusionQueryStep(gl: WebGL2RenderingContext, occlusionQue return undefined; }; - return { begin, end, resolve } as IGLOcclusionQueryStep; + return { begin, end, resolve } as GLOcclusionQueryStep; } /** * 不被遮挡查询步骤。 */ -export interface IGLOcclusionQueryStep +export interface GLOcclusionQueryStep { /** * 开始查询 @@ -131,5 +132,5 @@ export interface IGLOcclusionQueryStep /** * 获取查询结果,将获取被赋值新结果的遮挡查询对象。 */ - resolve: () => Promise + resolve: () => Promise } \ No newline at end of file diff --git a/src/caches/getIGLRenderPassDescriptorWithMultisample.ts b/src/caches/getGLRenderPassDescriptorWithMultisample.ts similarity index 62% rename from src/caches/getIGLRenderPassDescriptorWithMultisample.ts rename to src/caches/getGLRenderPassDescriptorWithMultisample.ts index d5022c55944db8a4a6d1b3e9a3819b6c20b66bc2..d9652f35777abfbeabe778a7f260d59e8b2b7aad 100644 --- a/src/caches/getIGLRenderPassDescriptorWithMultisample.ts +++ b/src/caches/getGLRenderPassDescriptorWithMultisample.ts @@ -1,7 +1,7 @@ -import { IRenderPassColorAttachment, IRenderPassDescriptor, ITextureFormat, ITextureView } from "@feng3d/render-api"; -import { IGLBlitFramebuffer } from "../data/IGLBlitFramebuffer"; -import { GLRenderbufferInternalformat, IGLRenderbuffer } from "../data/IGLRenderbuffer"; -import { getIGLTextureFormats } from "./getIGLTextureFormats"; +import { RenderPassColorAttachment, RenderPassDescriptor, TextureFormat, TextureView } from "@feng3d/render-api"; +import { BlitFramebuffer } from "../data/BlitFramebuffer"; +import { RenderbufferInternalformat, Renderbuffer } from "../data/Renderbuffer"; +import { getGLTextureFormats } from "./getGLTextureFormats"; /** * @@ -11,43 +11,43 @@ import { getIGLTextureFormats } from "./getIGLTextureFormats"; * * @param sourcePassDescriptor 需要渲染到纹理并且开启多重采样的渲染通道描述。 */ -export function getIGLRenderPassDescriptorWithMultisample(sourcePassDescriptor: IRenderPassDescriptor): IGLRenderPassDescriptorWithMultisample +export function getGLRenderPassDescriptorWithMultisample(sourcePassDescriptor: RenderPassDescriptor): GLRenderPassDescriptorWithMultisample { if (sourcePassDescriptor[_IGLRenderPassDescriptorWithMultisample]) return sourcePassDescriptor[_IGLRenderPassDescriptorWithMultisample]; - const texture = (sourcePassDescriptor.colorAttachments[0].view as ITextureView).texture; + const texture = (sourcePassDescriptor.colorAttachments[0].view as TextureView).texture; const textureSize = texture.size; - const renderbuffers: IGLRenderbuffer[] = []; + const renderbuffers: Renderbuffer[] = []; // 创建支持 多重采样的 渲染通道 - const passDescriptor: IRenderPassDescriptor = { + const passDescriptor: RenderPassDescriptor = { colorAttachments: sourcePassDescriptor.colorAttachments.map((v) => { const texture = v.view.texture; - const renderbuffer: IGLRenderbuffer = { + const renderbuffer: Renderbuffer = { internalformat: getGLRenderbufferInternalformat(texture.format), width: textureSize[0], height: textureSize[1], }; renderbuffers.push(renderbuffer); - const colorAttachment: IRenderPassColorAttachment = { + const colorAttachment: RenderPassColorAttachment = { ...v, view: renderbuffer as any, }; -return colorAttachment; + return colorAttachment; }), depthStencilAttachment: sourcePassDescriptor.depthStencilAttachment, sampleCount: sourcePassDescriptor.sampleCount, }; // 拷贝 渲染缓冲区到 IGLTexture - const blitFramebuffer: IGLBlitFramebuffer = { - __type: "BlitFramebuffer", + const blitFramebuffer: BlitFramebuffer = { + __type__: "BlitFramebuffer", read: passDescriptor, draw: sourcePassDescriptor, blitFramebuffers: [[0, 0, textureSize[0], textureSize[1], @@ -55,16 +55,16 @@ return colorAttachment; "COLOR_BUFFER_BIT", "NEAREST"]], }; - sourcePassDescriptor[_IGLRenderPassDescriptorWithMultisample] = { passDescriptor, blitFramebuffer, renderbuffers } as IGLRenderPassDescriptorWithMultisample; + sourcePassDescriptor[_IGLRenderPassDescriptorWithMultisample] = { passDescriptor, blitFramebuffer, renderbuffers } as GLRenderPassDescriptorWithMultisample; return sourcePassDescriptor[_IGLRenderPassDescriptorWithMultisample]; } -function getGLRenderbufferInternalformat(format?: ITextureFormat) +function getGLRenderbufferInternalformat(format?: TextureFormat) { - const { internalformat } = getIGLTextureFormats(format); + const { internalformat } = getGLTextureFormats(format); - return internalformat as GLRenderbufferInternalformat; + return internalformat as RenderbufferInternalformat; } export const _IGLRenderPassDescriptorWithMultisample = "_IGLRenderPassDescriptorWithMultisample"; @@ -72,18 +72,18 @@ export const _IGLRenderPassDescriptorWithMultisample = "_IGLRenderPassDescriptor /** * 由`passDescriptor.multisample`值存在的IGLRenderPassDescriptor生成。 */ -export interface IGLRenderPassDescriptorWithMultisample +export interface GLRenderPassDescriptorWithMultisample { /** * 渲染到渲染缓冲区上。 */ - passDescriptor: IRenderPassDescriptor; + passDescriptor: RenderPassDescriptor; /** * 拷贝渲染缓冲区到目标纹理中。 */ - blitFramebuffer: IGLBlitFramebuffer; + blitFramebuffer: BlitFramebuffer; /** * 需要销毁的临时渲染缓冲区。 */ - renderbuffers: IGLRenderbuffer[]; + renderbuffers: Renderbuffer[]; } \ No newline at end of file diff --git a/src/caches/getGLRenderbuffer.ts b/src/caches/getGLRenderbuffer.ts index 3fe8b023977f96e1fa143d767b019fc273ee6362..ceca182f727016a4fe925f25807e5e7128b75c6c 100644 --- a/src/caches/getGLRenderbuffer.ts +++ b/src/caches/getGLRenderbuffer.ts @@ -1,14 +1,6 @@ -import { IGLRenderbuffer } from "../data/IGLRenderbuffer"; +import { Renderbuffer } from "../data/Renderbuffer"; -declare global -{ - interface WebGLRenderingContext - { - _renderbuffers: Map; - } -} - -export function getGLRenderbuffer(gl: WebGLRenderingContext, renderbuffer: IGLRenderbuffer, sampleCount?: 4) +export function getGLRenderbuffer(gl: WebGLRenderingContext, renderbuffer: Renderbuffer, sampleCount?: 4) { let webGLRenderbuffer = gl._renderbuffers.get(renderbuffer); if (webGLRenderbuffer) return webGLRenderbuffer; @@ -31,7 +23,7 @@ export function getGLRenderbuffer(gl: WebGLRenderingContext, renderbuffer: IGLRe return webGLRenderbuffer; } -export function deleteRenderbuffer(gl: WebGLRenderingContext, renderbuffer: IGLRenderbuffer) +export function deleteRenderbuffer(gl: WebGLRenderingContext, renderbuffer: Renderbuffer) { const webGLRenderbuffer = gl._renderbuffers.get(renderbuffer); gl._renderbuffers.delete(renderbuffer); diff --git a/src/caches/getGLSampler.ts b/src/caches/getGLSampler.ts index 9fe3d6bcbaab3d0d0b0e692a528c249261076e09..cd275a8c6a97106107aa437eb31ebfab74ce0e49 100644 --- a/src/caches/getGLSampler.ts +++ b/src/caches/getGLSampler.ts @@ -1,17 +1,9 @@ -import { IAddressMode, IFilterMode, ISampler } from "@feng3d/render-api"; -import { IGLCompareFunction } from "../data/IGLDepthStencilState"; -import { IGLSamplerCompareMode, IGLTextureMagFilter, IGLTextureMinFilter, IGLTextureWrap } from "../data/IGLSampler"; +import { IAddressMode, IFilterMode, Sampler } from "@feng3d/render-api"; import { getIGLCompareFunction } from "../runs/runDepthState"; -declare global -{ - interface WebGLRenderingContext - { - _samplers: Map; - } -} +export type GLSamplerCompareMode = "NONE" | "COMPARE_REF_TO_TEXTURE"; -export function getGLSampler(gl: WebGLRenderingContext, sampler?: ISampler) +export function getGLSampler(gl: WebGLRenderingContext, sampler?: Sampler) { let webGLSampler = gl._samplers.get(sampler); if (webGLSampler) return webGLSampler; @@ -21,15 +13,15 @@ export function getGLSampler(gl: WebGLRenderingContext, sampler?: ISampler) webGLSampler = gl.createSampler(); gl._samplers.set(sampler, webGLSampler); - const minFilter: IGLTextureMinFilter = getIGLTextureMinFilter(sampler.minFilter, sampler.mipmapFilter); - const magFilter: IGLTextureMagFilter = getIGLTextureMagFilter(sampler.magFilter); - const wrapS: IGLTextureWrap = getIGLTextureWrap(sampler.addressModeU); - const wrapT: IGLTextureWrap = getIGLTextureWrap(sampler.addressModeV); - const wrapR: IGLTextureWrap = getIGLTextureWrap(sampler.addressModeW); + const minFilter: GLTextureMinFilter = getIGLTextureMinFilter(sampler.minFilter, sampler.mipmapFilter); + const magFilter: GLTextureMagFilter = getIGLTextureMagFilter(sampler.magFilter); + const wrapS: GLTextureWrap = getIGLTextureWrap(sampler.addressModeU); + const wrapT: GLTextureWrap = getIGLTextureWrap(sampler.addressModeV); + const wrapR: GLTextureWrap = getIGLTextureWrap(sampler.addressModeW); const lodMinClamp = sampler.lodMinClamp || 0; const lodMaxClamp = sampler.lodMaxClamp || 16; - const compareMode: IGLSamplerCompareMode = sampler.compare ? "COMPARE_REF_TO_TEXTURE" : "NONE"; - const compare: IGLCompareFunction = getIGLCompareFunction(sampler.compare ?? "less-equal"); + const compareMode: GLSamplerCompareMode = sampler.compare ? "COMPARE_REF_TO_TEXTURE" : "NONE"; + const compare = getIGLCompareFunction(sampler.compare ?? "less-equal"); // gl.samplerParameteri(webGLSampler, gl.TEXTURE_MIN_FILTER, gl[minFilter]); @@ -46,7 +38,7 @@ export function getGLSampler(gl: WebGLRenderingContext, sampler?: ISampler) return webGLSampler; } -export function deleteSampler(gl: WebGLRenderingContext, sampler?: ISampler) +export function deleteSampler(gl: WebGLRenderingContext, sampler?: Sampler) { if (gl instanceof WebGL2RenderingContext) { @@ -56,24 +48,51 @@ export function deleteSampler(gl: WebGLRenderingContext, sampler?: ISampler) } } +/** + * 纹理坐标s包装函数枚举 + * Wrapping function for texture coordinate s + * + * * `REPEAT` + * * `CLAMP_TO_EDGE` + * * `MIRRORED_REPEAT` + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texParameter + */ +export type GLTextureWrap = "REPEAT" | "CLAMP_TO_EDGE" | "MIRRORED_REPEAT"; + export function getIGLTextureWrap(addressMode: IAddressMode = "repeat") { - const textureWrap: IGLTextureWrap = addressModeMap[addressMode]; + const textureWrap: GLTextureWrap = addressModeMap[addressMode]; console.assert(!!textureWrap, `接收到错误值,请从 ${Object.keys(addressModeMap).toString()} 中取值!`); return textureWrap; } -const addressModeMap: { [key: string]: IGLTextureWrap } = { +const addressModeMap: { [key: string]: GLTextureWrap } = { "clamp-to-edge": "CLAMP_TO_EDGE", repeat: "REPEAT", "mirror-repeat": "MIRRORED_REPEAT", }; -export function getIGLTextureMinFilter(minFilter: IFilterMode = "nearest", mipmapFilter?: IFilterMode): IGLTextureMinFilter +/** + * 纹理缩小过滤器 + * Texture minification filter + * + * * `LINEAR` + * * `NEAREST` + * * `NEAREST_MIPMAP_NEAREST` + * * `LINEAR_MIPMAP_NEAREST` + * * `NEAREST_MIPMAP_LINEAR` + * * `LINEAR_MIPMAP_LINEAR` + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texParameter + */ +export type GLTextureMinFilter = "LINEAR" | "NEAREST" | "NEAREST_MIPMAP_NEAREST" | "LINEAR_MIPMAP_NEAREST" | "NEAREST_MIPMAP_LINEAR" | "LINEAR_MIPMAP_LINEAR"; + +export function getIGLTextureMinFilter(minFilter: IFilterMode = "nearest", mipmapFilter?: IFilterMode): GLTextureMinFilter { - let glMinFilter: IGLTextureMinFilter; + let glMinFilter: GLTextureMinFilter; if (minFilter === "linear") { if (mipmapFilter === "linear") @@ -107,17 +126,27 @@ export function getIGLTextureMinFilter(minFilter: IFilterMode = "nearest", mipma return glMinFilter; } +/** + * 纹理放大滤波器 + * Texture magnification filter + * + * * `LINEAR` + * * `NEAREST` + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texParameter + */ +export type GLTextureMagFilter = "LINEAR" | "NEAREST"; export function getIGLTextureMagFilter(magFilter: IFilterMode = "nearest") { - const glMagFilter: IGLTextureMagFilter = magFilterMap[magFilter]; + const glMagFilter: GLTextureMagFilter = magFilterMap[magFilter]; console.assert(!!glMagFilter, `接收到错误值,请从 ${Object.keys(magFilterMap).toString()} 中取值!`); return glMagFilter; } -const magFilterMap: { [key: string]: IGLTextureMagFilter } = { +const magFilterMap: { [key: string]: GLTextureMagFilter } = { nearest: "NEAREST", linear: "LINEAR", }; \ No newline at end of file diff --git a/src/caches/getGLTexture.ts b/src/caches/getGLTexture.ts index c8cce70d9c975fb36e1920e0a579f6c3cb0a5a99..174b9b0c033dce143c663bd481e6fa69aa78ec01 100644 --- a/src/caches/getGLTexture.ts +++ b/src/caches/getGLTexture.ts @@ -1,17 +1,10 @@ -import { ITexture, ITextureDataSource, ITextureImageSource, ITextureSize } from "@feng3d/render-api"; +import { Texture, TextureDataSource, TextureImageSource, TextureSize } from "@feng3d/render-api"; import { watcher } from "@feng3d/watcher"; -import { IGLTexturePixelStore } from "../data/IGLTexturePixelStore"; -import { getTextureCubeMapTarget } from "../utils/getTextureCubeMapTarget"; -import { getIGLTextureFormats } from "./getIGLTextureFormats"; -import { getIGLTextureTarget } from "./getIGLTextureTarget"; +import { getGLTextureFormats } from "./getGLTextureFormats"; +import { getGLTextureTarget } from "./getGLTextureTarget"; declare global { - interface WebGLRenderingContext - { - _textures: Map - } - interface WebGLTexture { /** @@ -21,7 +14,7 @@ declare global } } -export const defaultTexturePixelStore: IGLTexturePixelStore = { +export const defaultTexturePixelStore: GLTexturePixelStore = { packAlignment: 4, unpackAlignment: 4, unpackFlipY: false, @@ -37,7 +30,7 @@ export const defaultTexturePixelStore: IGLTexturePixelStore = { unpackSkipImages: 0, }; -export function getGLTexture(gl: WebGLRenderingContext, texture: ITexture) +export function getGLTexture(gl: WebGLRenderingContext, texture: Texture) { let webGLTexture = gl._textures.get(texture); if (webGLTexture) return webGLTexture; @@ -45,8 +38,8 @@ export function getGLTexture(gl: WebGLRenderingContext, texture: ITexture) // 创建纹理 const createTexture = () => { - const target = getIGLTextureTarget(texture.dimension); - const { internalformat, format, type } = getIGLTextureFormats(texture.format); + const target = getGLTextureTarget(texture.dimension); + const { internalformat, format, type } = getGLTextureFormats(texture.format); webGLTexture = gl.createTexture(); // Create a texture object gl._textures.set(texture, webGLTexture); @@ -75,13 +68,13 @@ export function getGLTexture(gl: WebGLRenderingContext, texture: ITexture) const zoffset = textureOrigin?.[2]; if (gl instanceof WebGL2RenderingContext) { - const imageSource = v as ITextureImageSource; + const imageSource = v as TextureImageSource; if (imageSource.image) { const { image, imageOrigin, flipY, premultipliedAlpha } = imageSource; // - const pixelStore: IGLTexturePixelStore = {}; + const pixelStore: GLTexturePixelStore = {}; pixelStore.unpackSkipPixels = imageOrigin?.[0] || 0; pixelStore.unpackSkipRows = imageOrigin?.[1] || 0; pixelStore.unpackFlipY = flipY || false; @@ -91,7 +84,7 @@ export function getGLTexture(gl: WebGLRenderingContext, texture: ITexture) if (target === "TEXTURE_2D" || target === "TEXTURE_CUBE_MAP") { - const bindTarget = target === "TEXTURE_CUBE_MAP" ? getTextureCubeMapTarget(depthOrArrayLayers) : target; + const bindTarget = target === "TEXTURE_CUBE_MAP" ? getTextureCubeMapTarget(zoffset) : target; if (width && height) { gl.texImage2D(gl[bindTarget], mipLevel, gl[internalformat], width, height, 0, gl[format], gl[type], image); @@ -112,14 +105,14 @@ export function getGLTexture(gl: WebGLRenderingContext, texture: ITexture) } else { - const bufferSource = v as ITextureDataSource; + const bufferSource = v as TextureDataSource; const { data, dataLayout, dataImageOrigin } = bufferSource; // const offset = dataLayout?.offset || 0; // - const pixelStore: IGLTexturePixelStore = {}; + const pixelStore: GLTexturePixelStore = {}; pixelStore.unpackSkipPixels = dataImageOrigin?.[0] || 0; pixelStore.unpackSkipRows = dataImageOrigin?.[1] || 0; pixelStore.unpackSkipImages = dataImageOrigin?.[2] || 0; @@ -130,7 +123,7 @@ export function getGLTexture(gl: WebGLRenderingContext, texture: ITexture) if (target === "TEXTURE_2D" || target === "TEXTURE_CUBE_MAP") { - const bindTarget = target === "TEXTURE_CUBE_MAP" ? getTextureCubeMapTarget(depthOrArrayLayers) : target; + const bindTarget = target === "TEXTURE_CUBE_MAP" ? getTextureCubeMapTarget(zoffset) : target; gl.texImage2D(gl[bindTarget], mipLevel, gl[internalformat], width, height, 0, gl[format], gl[type], data, offset); } else if (target === "TEXTURE_3D" || target === "TEXTURE_2D_ARRAY") @@ -145,13 +138,13 @@ export function getGLTexture(gl: WebGLRenderingContext, texture: ITexture) } else { - const imageSource = v as ITextureImageSource; + const imageSource = v as TextureImageSource; if (imageSource.image) { const { image, imageOrigin, flipY, premultipliedAlpha } = imageSource; // - const pixelStore: IGLTexturePixelStore = {}; + const pixelStore: GLTexturePixelStore = {}; pixelStore.unpackSkipPixels = imageOrigin?.[0] || 0; pixelStore.unpackSkipRows = imageOrigin?.[1] || 0; pixelStore.unpackFlipY = flipY || false; @@ -161,7 +154,7 @@ export function getGLTexture(gl: WebGLRenderingContext, texture: ITexture) if (target === "TEXTURE_2D" || target === "TEXTURE_CUBE_MAP") { - const bindTarget = target === "TEXTURE_CUBE_MAP" ? getTextureCubeMapTarget(depthOrArrayLayers) : target; + const bindTarget = target === "TEXTURE_CUBE_MAP" ? getTextureCubeMapTarget(zoffset) : target; gl.texImage2D(gl[bindTarget], mipLevel, gl[format], gl[format], gl[type], image); } else @@ -171,14 +164,14 @@ export function getGLTexture(gl: WebGLRenderingContext, texture: ITexture) } else { - const bufferSource = v as ITextureDataSource; + const bufferSource = v as TextureDataSource; const { data, dataLayout, dataImageOrigin } = bufferSource; // const offset = dataLayout?.offset || 0; // - const pixelStore: IGLTexturePixelStore = {}; + const pixelStore: GLTexturePixelStore = {}; pixelStore.unpackSkipPixels = dataImageOrigin?.[0] || 0; pixelStore.unpackSkipRows = dataImageOrigin?.[1] || 0; pixelStore.unpackSkipImages = dataImageOrigin?.[2] || 0; @@ -189,7 +182,7 @@ export function getGLTexture(gl: WebGLRenderingContext, texture: ITexture) if (target === "TEXTURE_2D" || target === "TEXTURE_CUBE_MAP") { - const bindTarget = target === "TEXTURE_CUBE_MAP" ? getTextureCubeMapTarget(depthOrArrayLayers) : target; + const bindTarget = target === "TEXTURE_CUBE_MAP" ? getTextureCubeMapTarget(zoffset) : target; console.assert(offset === 0, `WebGL1中ITextureDataLayout.offset必须为0`); gl.texImage2D(gl[bindTarget], mipLevel, gl[format], width, height, 0, gl[format], gl[type], data); } @@ -255,8 +248,8 @@ export function getGLTexture(gl: WebGLRenderingContext, texture: ITexture) const { writeTextures } = texture; if (!writeTextures || writeTextures.length === 0) return; - const target = getIGLTextureTarget(texture.dimension); - const { format, type } = getIGLTextureFormats(texture.format); + const target = getGLTextureTarget(texture.dimension); + const { format, type } = getGLTextureFormats(texture.format); gl.bindTexture(gl[target], webGLTexture); @@ -272,13 +265,13 @@ export function getGLTexture(gl: WebGLRenderingContext, texture: ITexture) const zoffset = textureOrigin?.[2]; // 处理图片资源 - const imageSource = v as ITextureImageSource; + const imageSource = v as TextureImageSource; if (imageSource.image) { const { image, imageOrigin, flipY, premultipliedAlpha } = imageSource; // - const pixelStore: IGLTexturePixelStore = {}; + const pixelStore: GLTexturePixelStore = {}; pixelStore.unpackSkipPixels = imageOrigin?.[0] || 0; pixelStore.unpackSkipRows = imageOrigin?.[1] || 0; pixelStore.unpackFlipY = flipY || false; @@ -326,18 +319,18 @@ export function getGLTexture(gl: WebGLRenderingContext, texture: ITexture) } } -return; + return; } // 处理数据资源 - const bufferSource = v as ITextureDataSource; + const bufferSource = v as TextureDataSource; const { data, dataLayout, dataImageOrigin } = bufferSource; // const offset = dataLayout?.offset || 0; // - const pixelStore: IGLTexturePixelStore = {}; + const pixelStore: GLTexturePixelStore = {}; pixelStore.unpackSkipPixels = dataImageOrigin?.[0] || 0; pixelStore.unpackSkipRows = dataImageOrigin?.[1] || 0; pixelStore.unpackSkipImages = dataImageOrigin?.[2] || 0; @@ -389,7 +382,7 @@ return; watcher.watch(texture, "writeTextures", updateTexture); // 监听纹理尺寸发生变化 - const resize = (newValue: ITextureSize, oldValue: ITextureSize) => + const resize = (newValue: TextureSize, oldValue: TextureSize) => { if (!!newValue && !!oldValue) { @@ -423,7 +416,7 @@ return; return webGLTexture; } -export function deleteTexture(gl: WebGLRenderingContext, texture: ITexture) +export function deleteTexture(gl: WebGLRenderingContext, texture: Texture) { const webGLTexture = gl._textures.get(texture); if (!webGLTexture) return; @@ -437,7 +430,7 @@ export function deleteTexture(gl: WebGLRenderingContext, texture: ITexture) * @param gl * @param pixelStore 像素解包打包时参数。 */ -function setTexturePixelStore(gl: WebGLRenderingContext, pixelStore: IGLTexturePixelStore) +function setTexturePixelStore(gl: WebGLRenderingContext, pixelStore: GLTexturePixelStore) { const { packAlignment, @@ -473,4 +466,190 @@ function setTexturePixelStore(gl: WebGLRenderingContext, pixelStore: IGLTextureP gl.pixelStorei(gl.UNPACK_SKIP_ROWS, unpackSkipRows); gl.pixelStorei(gl.UNPACK_SKIP_IMAGES, unpackSkipImages); } -} \ No newline at end of file +} + +/** + * 像素解包打包时参数。 + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/pixelStorei + */ +interface GLTexturePixelStore +{ + /** + * Packing of pixel data into memory + * + * gl.PACK_ALIGNMENT + * + * 默认值为 4 。 + */ + packAlignment?: 1 | 2 | 4 | 8; + + /** + * Unpacking of pixel data from memory. + * + * gl.UNPACK_ALIGNMENT + * + * 默认值为 4 。 + */ + unpackAlignment?: 1 | 2 | 4 | 8; + + /** + * 解包图像数据时进行Y轴反转。 + * + * Flips the source data along its vertical axis if true. + * + * gl.UNPACK_FLIP_Y_WEBGL + * + * 默认为 false。 + */ + unpackFlipY?: boolean; + + /** + * 将图像RGB颜色值得每一个分量乘以A。 + * + * Multiplies the alpha channel into the other color channels + * + * gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL + * + * 默认为 false。 + */ + unpackPremulAlpha?: boolean; + + /** + * Default color space conversion or no color space conversion. + * + * gl.UNPACK_COLORSPACE_CONVERSION_WEBGL + * + * 默认为 "BROWSER_DEFAULT_WEBGL" 。 + */ + unpackColorSpaceConversion?: "BROWSER_DEFAULT_WEBGL" | "NONE"; + + /** + * Number of pixels in a row. + * + * gl.PACK_ROW_LENGTH + * + * 默认值为 0 。 + * + * 仅 WebGL2。 + */ + packRowLength?: number; + + /** + * Number of pixel locations skipped before the first pixel is written into memory. + * + * gl.PACK_SKIP_PIXELS + * + * 默认值为 0 。 + * + * 仅 WebGL2。 + */ + packSkipPixels?: number; + + /** + * Number of rows of pixel locations skipped before the first pixel is written into memory + * + * gl.PACK_SKIP_ROWS + * + * 默认值为 0 。 + * + * 仅 WebGL2。 + */ + packSkipRows?: number; + + /** + * Number of pixels in a row. + * + * gl.UNPACK_ROW_LENGTH + * + * 默认值为 0 。 + * + * 仅 WebGL2。 + */ + unpackRowLength?: number; + + /** + * Image height used for reading pixel data from memory + * + * gl.UNPACK_IMAGE_HEIGHT + * + * 默认值为 0 。 + * + * 仅 WebGL2。 + */ + unpackImageHeight?: number; + + /** + * + * Number of pixel images skipped before the first pixel is read from memory + * + * gl.UNPACK_SKIP_PIXELS + * + * 默认值为 0 。 + * + * 仅 WebGL2。 + */ + unpackSkipPixels?: number; + + /** + * + * Number of rows of pixel locations skipped before the first pixel is read from memory + * + * gl.UNPACK_SKIP_ROWS + * + * 默认值为 0 。 + * + * 仅 WebGL2。 + */ + unpackSkipRows?: number; + + /** + * + * Number of pixel images skipped before the first pixel is read from memory + * + * gl.UNPACK_SKIP_IMAGES + * + * 默认值为 0 。 + * + * 仅 WebGL2。 + */ + unpackSkipImages?: number; +} + +function getTextureCubeMapTarget(depthOrArrayLayers: number) +{ + const textureCubeMapTarget: GLTextureCubeMapTarget = textureCubeMapTargetMap[depthOrArrayLayers]; + + console.assert(!!textureCubeMapTarget, `CubeMap的depthOrArrayLayers值应在[0-5]之间!`); + + return textureCubeMapTarget; +} + +const textureCubeMapTargetMap: GLTextureCubeMapTarget[] = [ + "TEXTURE_CUBE_MAP_POSITIVE_X", + "TEXTURE_CUBE_MAP_NEGATIVE_X", + "TEXTURE_CUBE_MAP_POSITIVE_Y", + "TEXTURE_CUBE_MAP_NEGATIVE_Y", + "TEXTURE_CUBE_MAP_POSITIVE_Z", + "TEXTURE_CUBE_MAP_NEGATIVE_Z", +]; + +/** + * A GLenum specifying the texture target. + * + * gl.TEXTURE_CUBE_MAP_POSITIVE_X: Positive X face for a cube-mapped texture. + * gl.TEXTURE_CUBE_MAP_NEGATIVE_X: Negative X face for a cube-mapped texture. + * gl.TEXTURE_CUBE_MAP_POSITIVE_Y: Positive Y face for a cube-mapped texture. + * gl.TEXTURE_CUBE_MAP_NEGATIVE_Y: Negative Y face for a cube-mapped texture. + * gl.TEXTURE_CUBE_MAP_POSITIVE_Z: Positive Z face for a cube-mapped texture. + * gl.TEXTURE_CUBE_MAP_NEGATIVE_Z: Negative Z face for a cube-mapped texture. + * + * https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texImage2D + */ +type GLTextureCubeMapTarget = + | "TEXTURE_CUBE_MAP_POSITIVE_X" + | "TEXTURE_CUBE_MAP_NEGATIVE_X" + | "TEXTURE_CUBE_MAP_POSITIVE_Y" + | "TEXTURE_CUBE_MAP_NEGATIVE_Y" + | "TEXTURE_CUBE_MAP_POSITIVE_Z" + | "TEXTURE_CUBE_MAP_NEGATIVE_Z"; \ No newline at end of file diff --git a/src/caches/getIGLTextureFormats.ts b/src/caches/getGLTextureFormats.ts similarity index 51% rename from src/caches/getIGLTextureFormats.ts rename to src/caches/getGLTextureFormats.ts index f688e6c98eacc5184b718efc2a44b3b223c052f4..d0a9b8cfe88c5e9e95ac33f9345cf4db12644678 100644 --- a/src/caches/getIGLTextureFormats.ts +++ b/src/caches/getGLTextureFormats.ts @@ -1,16 +1,39 @@ -import { ITextureFormat } from "@feng3d/render-api"; -import { IGLTextureFormats } from "../data/IGLTextureFormats"; +import { TextureFormat } from "@feng3d/render-api"; -export function getIGLTextureFormats(format: ITextureFormat = "rgba8unorm") +export function getGLTextureFormats(format: TextureFormat = "rgba8unorm") { - const glTextureFormat: IGLTextureFormats = formatMap[format]; + const glTextureFormat: GLTextureFormats = formatMap[format]; console.assert(!!glTextureFormat, `未处理格式 ${format};或者WebGL不支持纹理, 该格式只在WebGPU中支持!`); return glTextureFormat; } -const formatMap: { [key: string]: IGLTextureFormats } = { +export interface GLTextureFormats +{ + /** + * 内部纹理格式。 + * + * 默认 "RGBA"。 + */ + readonly internalformat?: GLTextureInternalFormat, + + /** + * 纹理格式。 + * + * 默认 "RGBA"。 + */ + readonly format?: GLTextureFormat; + + /** + * 数据类型。 + * + * 默认 "UNSIGNED_BYTE"。 + */ + readonly type?: GLTextureDataType; +} + +const formatMap: { [key: string]: GLTextureFormats } = { r8unorm: { internalformat: "R8", format: "RED", type: "UNSIGNED_BYTE" }, r8snorm: undefined, r8uint: { internalformat: "R8", format: "RED", type: "UNSIGNED_BYTE" }, @@ -106,4 +129,47 @@ const formatMap: { [key: string]: IGLTextureFormats } = { "astc-12x10-unorm-srgb": undefined, "astc-12x12-unorm": undefined, "astc-12x12-unorm-srgb": undefined, -}; \ No newline at end of file +}; + +/** + * internalformat format type + * + * @see https://registry.khronos.org/webgl/specs/latest/2.0/#TEXTURE_TYPES_FORMATS_FROM_DOM_ELEMENTS_TABLE + */ +type GLTextureTypes = + | { internalformat: "RGB", format: "RGB", type: "UNSIGNED_BYTE" | "UNSIGNED_SHORT_5_6_5" } + | { internalformat: "RGBA", format: "RGBA", type: "UNSIGNED_BYTE" | "UNSIGNED_SHORT_4_4_4_4" | "UNSIGNED_SHORT_5_5_5_1" } + | { internalformat: "LUMINANCE_ALPHA", format: "LUMINANCE_ALPHA", type: "UNSIGNED_BYTE" } + | { internalformat: "LUMINANCE", format: "LUMINANCE", type: "UNSIGNED_BYTE" } + | { internalformat: "ALPHA", format: "ALPHA", type: "UNSIGNED_BYTE" } + | { internalformat: "R8", format: "RED", type: "UNSIGNED_BYTE" } + | { internalformat: "R16F", format: "RED", type: "HALF_FLOAT" | " FLOAT" } + | { internalformat: "R32F", format: "RED", type: "FLOAT" } + | { internalformat: "R8UI", format: "RED_INTEGER", type: "UNSIGNED_BYTE" } + | { internalformat: "RG8", format: "RG", type: "UNSIGNED_BYTE" } + | { internalformat: "RG16F", format: "RG", type: "HALF_FLOAT" | "FLOAT" } + | { internalformat: "RG32F", format: "RG", type: "FLOAT" } + | { internalformat: "RG8UI", format: "RG_INTEGER", type: "UNSIGNED_BYTE" } + | { internalformat: "RGB8", format: "RGB", type: "UNSIGNED_BYTE" } + | { internalformat: "SRGB8", format: "RGB", type: "UNSIGNED_BYTE" } + | { internalformat: "RGB565", format: "RGB", type: "UNSIGNED_BYTE" | "UNSIGNED_SHORT_5_6_5" } + | { internalformat: "R11F_G11F_B10F", format: "RGB", type: "UNSIGNED_INT_10F_11F_11F_REV" | "HALF_FLOAT" | "FLOAT" } + | { internalformat: "RGB9_E5", format: "RGB", type: "HALF_FLOAT" | "FLOAT" } + | { internalformat: "RGB16F", format: "RGB", type: "HALF_FLOAT" | "FLOAT" } + | { internalformat: "RGB32F", format: "RGB", type: "FLOAT" } + | { internalformat: "RGB8UI", format: "RGB_INTEGER", type: "UNSIGNED_BYTE" } + | { internalformat: "RGBA8", format: "RGBA", type: "UNSIGNED_BYTE" } + | { internalformat: "SRGB8_ALPHA8", format: "RGBA", type: "UNSIGNED_BYTE" } + | { internalformat: "RGB5_A1", format: "RGBA", type: "UNSIGNED_BYTE" | "UNSIGNED_SHORT_5_5_5_1" } + | { internalformat: "RGB10_A2", format: "RGBA", type: "UNSIGNED_INT_2_10_10_10_REV" } + | { internalformat: "RGBA4", format: "RGBA", type: "UNSIGNED_BYTE" | "UNSIGNED_SHORT_4_4_4_4" } + | { internalformat: "RGBA16F", format: "RGBA", type: "HALF_FLOAT" | "FLOAT" } + | { internalformat: "RGBA32F", format: "RGBA", type: "FLOAT" } + | { internalformat: "RGBA8UI", format: "RGBA_INTEGER", type: "UNSIGNED_BYTE" } + // 深度纹理 + | { internalformat: "DEPTH_COMPONENT16", format: "DEPTH_COMPONENT", type: "UNSIGNED_SHORT", } + ; + +export type GLTextureInternalFormat = GLTextureTypes["internalformat"]; +export type GLTextureFormat = GLTextureTypes["format"]; +export type GLTextureDataType = GLTextureTypes["type"]; diff --git a/src/caches/getGLTextureTarget.ts b/src/caches/getGLTextureTarget.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e27203c0a5d107c6b9013f4ca768d4dcc75cf66 --- /dev/null +++ b/src/caches/getGLTextureTarget.ts @@ -0,0 +1,35 @@ +import { TextureDimension } from "@feng3d/render-api"; + +/** + * 纹理绑定点。 + * + * * gl.TEXTURE_2D: A two-dimensional texture. + * * gl.TEXTURE_CUBE_MAP: A cube-mapped texture. + * + * When using a WebGL 2 context, the following values are available additionally: + * + * * gl.TEXTURE_3D: A three-dimensional texture. + * * gl.TEXTURE_2D_ARRAY: A two-dimensional array texture. + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindTexture + */ +export type GLTextureTarget = "TEXTURE_2D" | "TEXTURE_CUBE_MAP" | "TEXTURE_3D" | "TEXTURE_2D_ARRAY"; + + +export function getGLTextureTarget(dimension: TextureDimension = "2d") +{ + const target: GLTextureTarget = dimensionMap[dimension]; + + console.assert(!!target, `WebGL 不支持纹理维度 ${dimension} , 该维度只在WebGPU中支持!`); + + return target; +} + +const dimensionMap: { [key: string]: GLTextureTarget } = { + "1d": undefined, + "2d": "TEXTURE_2D", + "2d-array": "TEXTURE_2D_ARRAY", + cube: "TEXTURE_CUBE_MAP", + "cube-array": undefined, + "3d": "TEXTURE_3D", +}; \ No newline at end of file diff --git a/src/caches/getGLTransformFeedback.ts b/src/caches/getGLTransformFeedback.ts index d18e3ad93ccd131fd2cc5f5e712004ce4c28bd59..2d322b78f29c1b7969b5882651e7908be31597e1 100644 --- a/src/caches/getGLTransformFeedback.ts +++ b/src/caches/getGLTransformFeedback.ts @@ -1,16 +1,8 @@ -import { IGLTransformFeedback } from "../data/IGLTransformFeedback"; -import { getIGLVertexBuffer } from "../runs/getIGLBuffer"; +import { TransformFeedback } from "../data/TransformFeedbackPass"; +import { getIGLBuffer } from "../runs/getIGLBuffer"; import { getGLBuffer } from "./getGLBuffer"; -declare global -{ - interface WebGLRenderingContext - { - _transforms: Map; - } -} - -export function getGLTransformFeedback(gl: WebGLRenderingContext, transformFeedback: IGLTransformFeedback) +export function getGLTransformFeedback(gl: WebGLRenderingContext, transformFeedback: TransformFeedback) { let webGLTransformFeedback = gl._transforms.get(transformFeedback); if (webGLTransformFeedback) return webGLTransformFeedback; @@ -24,7 +16,8 @@ export function getGLTransformFeedback(gl: WebGLRenderingContext, transformFeedb transformFeedback.bindBuffers.forEach((v) => { const { index, data } = v; - const buffer = getIGLVertexBuffer(data, "STREAM_COPY"); + const buffer = getIGLBuffer(data, "ARRAY_BUFFER", "STREAM_COPY"); + const webGLBuffer = getGLBuffer(gl, buffer); gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, index, webGLBuffer); }); @@ -36,7 +29,7 @@ export function getGLTransformFeedback(gl: WebGLRenderingContext, transformFeedb return webGLTransformFeedback; } -export function deleteTransformFeedback(gl: WebGLRenderingContext, transformFeedback: IGLTransformFeedback) +export function deleteTransformFeedback(gl: WebGLRenderingContext, transformFeedback: TransformFeedback) { const webGLTransformFeedback = gl._transforms.get(transformFeedback); if (!webGLTransformFeedback) return; diff --git a/src/caches/getIGLAttributeType.ts b/src/caches/getIGLAttributeType.ts deleted file mode 100644 index d2d18ce8cdb0ea2b84c6f67a098abd8d1b8615fa..0000000000000000000000000000000000000000 --- a/src/caches/getIGLAttributeType.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * WebGL 属性类型。 - */ -export type IGLAttributeType = keyof typeof webglAttributeTypeValue; - -/** - * 获取顶点数据类型名称。 - * - * @param gl - * @param value - */ -export function getIGLAttributeType(value: keyof typeof webglAttributeValueType): IGLAttributeType -{ - return webglAttributeValueType[value]; -} - -const webglAttributeTypeValue = Object.freeze({ FLOAT: 5126, BYTE: 5120, SHORT: 5122, UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, HALF_FLOAT: 5131, INT: 5124, UNSIGNED_INT: 5125 }); -const webglAttributeValueType = Object.freeze({ 5120: "BYTE", 5121: "UNSIGNED_BYTE", 5122: "SHORT", 5123: "UNSIGNED_SHORT", 5124: "INT", 5125: "UNSIGNED_INT", 5126: "FLOAT", 5131: "HALF_FLOAT" }); diff --git a/src/caches/getIGLTextureTarget.ts b/src/caches/getIGLTextureTarget.ts deleted file mode 100644 index 77e7f47f7580ca61bda6f4042be478d3673aba98..0000000000000000000000000000000000000000 --- a/src/caches/getIGLTextureTarget.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { ITextureDimension } from "@feng3d/render-api"; -import { IGLTextureTarget } from "../data/IGLTexture"; - -export function getIGLTextureTarget(dimension: ITextureDimension = "2d") -{ - const target: IGLTextureTarget = dimensionMap[dimension]; - - console.assert(!!target, `WebGL 不支持纹理维度 ${dimension} , 该维度只在WebGPU中支持!`); - - return target; -} -const dimensionMap: { [key: string]: IGLTextureTarget } = { - "1d": undefined, - "2d": "TEXTURE_2D", - "2d-array": "TEXTURE_2D_ARRAY", - cube: "TEXTURE_CUBE_MAP", - "cube-array": undefined, - "3d": "TEXTURE_3D", -}; \ No newline at end of file diff --git a/src/const/IGLUniformType.ts b/src/const/GLUniformType.ts similarity index 87% rename from src/const/IGLUniformType.ts rename to src/const/GLUniformType.ts index 488c4a9d5903b0dbea7b32cd92d8066839f0b6f5..90d0b4b21b94afee5a05a64019364967e5085b23 100644 --- a/src/const/IGLUniformType.ts +++ b/src/const/GLUniformType.ts @@ -1,17 +1,17 @@ /** * WebGL中Uniform类型 */ -export type IGLUniformType = keyof typeof webGLUniformTypeValue; +export type GLUniformType = keyof typeof webGLUniformTypeValue; /** * WebGL中Uniform纹理类型 */ -export type IGLUniformTextureType = keyof typeof webGLUniformTextureTypeValue; +export type GLUniformTextureType = keyof typeof webGLUniformTextureTypeValue; /** * WebGL中Uniform缓冲区类型 */ -export type IGLUniformBufferType = keyof typeof webGLUniformBufferTypeValue; +export type GLUniformBufferType = keyof typeof webGLUniformBufferTypeValue; /** * 获取Unifrom类型名称 @@ -19,7 +19,7 @@ export type IGLUniformBufferType = keyof typeof webGLUniformBufferTypeValue; * @param value WebGL中Unifrom类型对应的值。 * @returns Unifrom类型名称 */ -export function getWebGLUniformType(value: number): IGLUniformType +export function getWebGLUniformType(value: number): GLUniformType { const result = webGLUniformValueType[value]; console.assert(!!result); @@ -33,7 +33,7 @@ export function getWebGLUniformType(value: number): IGLUniformType * @param type Unifrom类型名称 * @returns 是否为纹理Unifrom类型。 */ -export function isWebGLUniformTextureType(type: IGLUniformType): boolean +export function isWebGLUniformTextureType(type: GLUniformType): boolean { return webGLUniformTextureTypeValue[type] !== undefined; } diff --git a/src/data/IGLBlitFramebuffer.ts b/src/data/BlitFramebuffer.ts similarity index 53% rename from src/data/IGLBlitFramebuffer.ts rename to src/data/BlitFramebuffer.ts index 2bd6b55712bc4b0e12ce558fba27c93618d1122c..47fb97952a5f57749e73cb9e85c9a00bd87766b5 100644 --- a/src/data/IGLBlitFramebuffer.ts +++ b/src/data/BlitFramebuffer.ts @@ -1,21 +1,21 @@ -import { IRenderPassDescriptor } from "@feng3d/render-api"; +import { RenderPassDescriptor } from "@feng3d/render-api"; /** * 拷贝渲染缓冲与纹理直接拷贝数据。 */ -export interface IGLBlitFramebuffer +export interface BlitFramebuffer { /** * 数据类型。 */ - readonly __type: "BlitFramebuffer"; + readonly __type__: "BlitFramebuffer"; - read: IRenderPassDescriptor; - draw: IRenderPassDescriptor; - blitFramebuffers: IGLBlitFramebufferItem[]; + read: RenderPassDescriptor; + draw: RenderPassDescriptor; + blitFramebuffers: BlitFramebufferItem[]; } -export type IGLBlitFramebufferItem = [ +export type BlitFramebufferItem = [ srcX0: number, srcY0: number, srcX1: number, srcY1: number, dstX0: number, dstY0: number, dstX1: number, dstY1: number, mask: "COLOR_BUFFER_BIT" | "DEPTH_BUFFER_BIT" | "STENCIL_BUFFER_BIT", filter: "NEAREST" | "LINEAR"]; \ No newline at end of file diff --git a/src/data/Capabilities.ts b/src/data/Capabilities.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/data/IGLAttributeInfo.ts b/src/data/IGLAttributeInfo.ts deleted file mode 100644 index 38fc6c339682be214a4a1b1694eeebe14805c758..0000000000000000000000000000000000000000 --- a/src/data/IGLAttributeInfo.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { IGLVertexAttributeTypes } from "../utils/getIVertexFormat"; - -export interface IGLAttributeInfo -{ - /** - * 名称。 - */ - name: string; - - /** - * 顶点尺寸。 - */ - size: number; - - /** - * 属性缓冲数据类型 - */ - type?: IGLVertexAttributeTypes; - - /** - * 属性地址 - */ - location: number; -} diff --git a/src/data/IGLCanvasContext.ts b/src/data/IGLCanvasContext.ts deleted file mode 100644 index 0c0a8e6117446b26aed391d0bb0c3a779f5355fe..0000000000000000000000000000000000000000 --- a/src/data/IGLCanvasContext.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * 画布(WebGL)上下文信息。 - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext - */ -export interface IGLCanvasContext extends WebGLContextAttributes -{ - /** - * 画布编号。 - */ - canvasId?: string - - /** - * WebGL上下文类型 - */ - contextId?: "webgl" | "webgl2" -} \ No newline at end of file diff --git a/src/data/IGLCanvasTexture.ts b/src/data/IGLCanvasTexture.ts deleted file mode 100644 index f18c25fc4cf2d8428c337c004c31bb6f3753954c..0000000000000000000000000000000000000000 --- a/src/data/IGLCanvasTexture.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { IGLCanvasContext } from "./IGLCanvasContext"; - -/** - * 画布纹理,从画布的WebGPU上下文获取纹理 - */ -export interface IGLCanvasTexture -{ - context: IGLCanvasContext; -} \ No newline at end of file diff --git a/src/data/IGLCapabilities.ts b/src/data/IGLCapabilities.ts deleted file mode 100644 index 630abf61fc3f6a28f5123959f31ad89e477bc68b..0000000000000000000000000000000000000000 --- a/src/data/IGLCapabilities.ts +++ /dev/null @@ -1,99 +0,0 @@ -declare global -{ - interface WebGLRenderingContext - { - /** - * WEBGL支持功能 - */ - _capabilities: IGLCapabilities; - } -} - -/** - * WEBGL支持功能 - * - * @see https://webglreport.com - * @see http://html5test.com - */ -export interface IGLCapabilities -{ - /** - * 纹理各向异性过滤最大值 - */ - maxAnisotropy: number; - - /** - * 支持最大纹理数量 - */ - maxTextures: number; - - /** - * 支持最大顶点纹理数量 - */ - maxVertexTextures: number; - - /** - * 支持最大纹理尺寸 - */ - maxTextureSize: number; - - /** - * 支持最大立方体贴图尺寸 - */ - maxCubemapSize: number; - - /** - * 支持属性数量 - */ - maxAttributes: number; - - /** - * 顶点着色器支持最大 Uniform 数量 - */ - maxVertexUniforms: number; - - /** - * 支持最大shader之间传递的变量数 - */ - maxVaryings: number; - - /** - * 片段着色器支持最大 Uniform 数量 - */ - maxFragmentUniforms: number; - - /** - * 是否支持顶点纹理 - */ - vertexTextures: boolean; - - /** - * 是否支持浮点类型片段着色器纹理 - */ - floatFragmentTextures: boolean; - - /** - * 是否支持浮点类型顶点着色器纹理 - */ - floatVertexTextures: boolean; - - /** - * Shader中支持浮点类型的最高精度 - */ - maxPrecision: "highp" | "mediump" | "lowp"; - - /** - * - */ - maxSamples: number; - - /** - * 支持模板的位数 - */ - stencilBits: number; - - /** - * 是否支持VAO。 - */ - vaoAvailable: boolean; -} diff --git a/src/data/IGLDepthStencilState.ts b/src/data/IGLDepthStencilState.ts deleted file mode 100644 index 6e4f1dbbac6accee1f7930a61c1951eb4ca88cf5..0000000000000000000000000000000000000000 --- a/src/data/IGLDepthStencilState.ts +++ /dev/null @@ -1,208 +0,0 @@ -/** - * 深度状态。 - */ -export interface IGLDepthState -{ - /** - * 是否开启深度检查,默认 true,开启深度检测。 - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/depthFunc - */ - depthtest?: boolean; - - /** - * 是否写入深度。 - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/depthMask - */ - depthWriteEnabled?: boolean; - - /** - * 指定深度比较函数的枚举,该函数设置绘制像素的条件。 - * - * 默认 LESS,如果传入值小于深度缓冲区值则通过。 - * - * A GLenum specifying the depth comparison function, which sets the conditions under which the pixel will be drawn. The default value is gl.LESS. - * - * @see IGLCompareFunction - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/depthFunc - */ - depthCompare?: IGLCompareFunction; - - /** - * 深度偏移。 - * - * 用于在深度测试中提供偏移量,以避免Z-fighting和其他深度相关的渲染问题。 - */ - depthBias?: IDepthBias; -} - -/** - * 深度偏移。 - * - * 用于在深度测试中提供偏移量,以避免Z-fighting和其他深度相关的渲染问题。 - */ -export interface IDepthBias -{ - /** - * 它设置特定于实现的值乘以的乘数,以创建恒定的深度偏移量。缺省值为0。 - * - * 对应WebGPU中的 GPUDepthStencilState.depthBias 。 - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/polygonOffset - */ - units: number; - - /** - * 为每个多边形设置可变深度偏移的比例因子。缺省值为0。 - * - * 对应WebGPU中的 GPUDepthStencilState.depthBiasSlopeScale 。 - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/polygonOffset - */ - factor: number; -} - -/** - * 模板状态。 - */ -export interface IGLStencilState -{ - /** - * 是否开启模板测试与更新模板缓冲。 - * - * Activates stencil testing and updates to the stencil buffer. - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/stencilFunc - */ - useStencil?: boolean; - - /** - * 模板正面状态。 - */ - stencilFront?: IStencilFaceState; - - /** - * 模板正面状态。 - */ - stencilBack?: IStencilFaceState; -} - -/** - * 模板单面状态。定义如何比较与运算模板值。 - */ -export interface IStencilFaceState -{ - /** - * 一个为模板测试指定参考值。这个值被限制在0到2^n -1的范围内,其中n是模板缓冲区中的位数。默认0。 - * - * A GLint specifying the reference value for the stencil test. This value is clamped to the range 0 to 2^n -1 where n is the number of bitplanes in the stencil buffer. The default value is 0. - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/stencilFunc - */ - stencilFuncRef?: number; - - /** - * 模板测试时使用的mask值,默认全为1(0xFFFFFFFF)。 - * - * A GLuint specifying a bit-wise mask that is used to AND the reference value and the stored stencil value when the test is done. The default value is all 1. - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/stencilFunc - */ - stencilFuncMask?: number; - - /** - * 指定位掩码以启用或禁用在模板平面中写入单个位的正整数。默认全为1(0xFFFFFFFF)。 - * - * A GLuint specifying a bit mask to enable or disable writing of individual bits in the stencil planes. By default, the mask is all 1. - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/stencilMask - */ - stencilMask?: number; - - /** - * 描述模板测试的方法。默认ALWAYS,总是通过。 - * - * A GLenum specifying the test function. The default function is gl.ALWAYS. - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/stencilFunc - */ - stencilFunc?: IGLStencilFunc; - - /** - * 指定模板测试失败时使用的函数的枚举。默认KEEP,保持当前值。 - * - * A GLenum specifying the function to use when the stencil test fails. The default value is gl.KEEP. - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/stencilOp - */ - stencilOpFail?: IGLStencilOp; - - /** - * 指定在模板测试通过但深度测试失败时使用的函数枚举。默认KEEP,保持当前值。 - * - * A GLenum specifying the function to use when the stencil test passes, but the depth test fails. The default value is gl.KEEP. - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/stencilOp - */ - stencilOpZFail?: IGLStencilOp; - - /** - * 指定在模板测试和深度测试通过时使用的函数枚举,或在模板测试通过且没有深度缓冲或禁用深度测试时使用的函数枚举。默认KEEP,保持当前值。 - * - * A GLenum specifying the function to use when both the stencil test and the depth test pass, or when the stencil test passes and there is no depth buffer or depth testing is disabled. The default value is gl.KEEP. - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/stencilOp - */ - stencilOpZPass?: IGLStencilOp; -} - -/** - * 指定深度比较函数的枚举,该函数设置绘制像素的条件,默认 LESS,如果传入值小于深度缓冲区值则通过。 - * - * A GLenum specifying the depth comparison function, which sets the conditions under which the pixel will be drawn. The default value is gl.LESS. - * - * * `NEVER` 总是不通过。 - * * `LESS` 如果传入值小于深度缓冲区值则通过。 - * * `EQUAL` 如果传入值等于深度缓冲区值则通过。 - * * `LEQUAL` 如果传入值小于或等于深度缓冲区值则通过。 - * * `GREATER` 如果传入值大于深度缓冲区值则通过。 - * * `NOTEQUAL` 如果传入值不等于深度缓冲区值则通过。 - * * `GEQUAL` 如果传入值大于或等于深度缓冲区值则通过。 - * * `ALWAYS` 总是通过。 - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/depthFunc - */ -export type IGLCompareFunction = "NEVER" | "LESS" | "EQUAL" | "LEQUAL" | "GREATER" | "NOTEQUAL" | "GEQUAL" | "ALWAYS"; - -/** - * A GLenum specifying the test function. The default function is gl.ALWAYS. - * - * * `NEVER` 总是不通过。 - * * `LESS` 如果 (ref & mask) < (stencil & mask) 则通过。 - * * `EQUAL` 如果 (ref & mask) = (stencil & mask) 则通过。 - * * `LEQUAL` 如果 (ref & mask) <= (stencil & mask) 则通过。 - * * `GREATER` 如果 (ref & mask) > (stencil & mask) 则通过。 - * * `NOTEQUAL` 如果 (ref & mask) != (stencil & mask) 则通过。 - * * `GEQUAL` 如果 (ref & mask) >= (stencil & mask) 则通过。 - * * `ALWAYS` 总是通过。 - * - * https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/stencilFunc - */ -export type IGLStencilFunc = "NEVER" | "LESS" | "EQUAL" | "LEQUAL" | "GREATER" | "NOTEQUAL" | "GEQUAL" | "ALWAYS"; - -/** - * The WebGLRenderingContext.stencilOp() method of the WebGL API sets both the front and back-facing stencil test actions. - * - * * `KEEP` 保持当前值。 - * * `ZERO` 设置模板缓冲值为0 - * * `REPLACE` 将模板缓冲区的值设置为WebGLRenderingContext.stencilFunc()指定的参考值。 - * * `INCR` 增加当前模板缓冲区的值。最大到可表示的无符号值的最大值。 - * * `INCR_WRAP` 增加当前模板缓冲区的值。当增加最大的可表示无符号值时,将模板缓冲区值包装为零。 - * * `DECR` 递减当前模板缓冲区的值。最小为0。 - * * `DECR_WRAP` 递减当前模板缓冲区的值。当模板缓冲区值减为0时,将模板缓冲区值包装为可表示的最大无符号值。 - * * `INVERT` 按位反转当前模板缓冲区值。 - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/stencilOp - */ -export type IGLStencilOp = "KEEP" | "ZERO" | "REPLACE" | "INCR" | "INCR_WRAP" | "DECR" | "DECR_WRAP" | "INVERT"; diff --git a/src/data/IGLOcclusionQuery.ts b/src/data/IGLOcclusionQuery.ts deleted file mode 100644 index 778c7770603ede9280ea0cae030e5e6573c4978f..0000000000000000000000000000000000000000 --- a/src/data/IGLOcclusionQuery.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { IRenderObject } from "@feng3d/render-api"; -import { IGLOcclusionQueryStep } from "../caches/getGLRenderOcclusionQuery"; - -export interface IGLOcclusionQuery -{ - /** - * 数据类型。 - */ - readonly __type: "OcclusionQuery"; - /** - * 渲染对象列表。 - */ - renderObjects: IRenderObject[]; - - /** - * 临时变量, 执行过程中由引擎自动填充。 - * - * @internal - */ - _step?: IGLOcclusionQueryStep; - - /** - * 渲染完成后由引擎自动填充。 - */ - result?: IGLQuery; -} - -/** - * 查询对象。 - * - * 一次查询周期。 - * - * 仅 WebGL2 支持。 - */ -export interface IGLQuery -{ - /** - * 查询结果。 - */ - result: number; -} \ No newline at end of file diff --git a/src/data/IGLPrimitiveState.ts b/src/data/IGLPrimitiveState.ts deleted file mode 100644 index 2b408972f2d288017d436e78d907b637c593cd6e..0000000000000000000000000000000000000000 --- a/src/data/IGLPrimitiveState.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { ICullFace, IFrontFace, IPrimitiveTopology } from "@feng3d/render-api"; - -declare module "@feng3d/render-api" -{ - export interface IPrimitiveTopologyMap - { - /** - * 绘制循环连线。 - */ - "LINE_LOOP": "LINE_LOOP", - - /** - * 绘制三角扇形。 - */ - "TRIANGLE_FAN": "TRIANGLE_FAN", - } - - export interface ICullFaceMap - { - "FRONT_AND_BACK": "FRONT_AND_BACK"; - } - - export interface IPrimitiveState - { - /** - * 图形拓扑结构。 - * - * 以下仅在WebGL生效 - * * LINE_LOOP 绘制循环连线。 - * * TRIANGLE_FAN 绘制三角扇形。 - */ - readonly topology?: IPrimitiveTopology; - - /** - * * `FRONT_AND_BACK` 剔除正面与背面,仅在WebGL中生效! - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/cullFace - */ - readonly cullFace?: ICullFace; - - /** - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/frontFace - */ - readonly frontFace?: IFrontFace; - } -} diff --git a/src/data/IGLReadPixels.ts b/src/data/IGLReadPixels.ts deleted file mode 100644 index e697deb6487a831aa105986e01b18f07213da850..0000000000000000000000000000000000000000 --- a/src/data/IGLReadPixels.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { IRenderPassDescriptor } from "@feng3d/render-api"; -import { GLAttachmentPoint } from "../gl/WebGLEnums"; -import { IGLTextureDataType, IGLTextureFormat } from "./IGLTexture"; - -/** - * 读取渲染缓冲区或者纹理视图中的像素值。 - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/readPixels - */ -export interface IGLReadPixels -{ - frameBuffer: IRenderPassDescriptor; - - /** - * 读取那个附件。 - */ - attachmentPoint: GLAttachmentPoint; - - x: number, - y: number, - width: number, - height: number, - - /** - * 纹理格式。 - * - * 默认 "RGBA"。 - */ - format?: IGLTextureFormat; - - /** - * 数据类型。 - * - * 默认 "UNSIGNED_BYTE"。 - */ - type?: IGLTextureDataType; - - dstData: ArrayBufferView, - dstOffset: number -} diff --git a/src/data/IGLRenderPass.ts b/src/data/IGLRenderPass.ts deleted file mode 100644 index f115ef8c58fa433557a1abf17c65a4fadf712fd0..0000000000000000000000000000000000000000 --- a/src/data/IGLRenderPass.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { IRenderPass, IRenderPassObject } from "@feng3d/render-api"; -import { IGLOcclusionQuery } from "./IGLOcclusionQuery"; - -declare module "@feng3d/render-api" -{ - /** - * WebGL渲染通道 - * - * 包含渲染通道描述以及需要渲染的对象列表。 - */ - export interface IRenderPass - { - /** - * 渲染不被遮挡查询结果。具体数据保存在各子项的"result"属性中。 - * - * 当提交WebGL后自动获取结果后填充该属性。 - */ - occlusionQueryResults?: IGLOcclusionQuery[]; - } - - export interface IRenderPassObjectMap - { - IGLOcclusionQuery: IGLOcclusionQuery - } -} diff --git a/src/data/IGLSampler.ts b/src/data/IGLSampler.ts deleted file mode 100644 index 681070da45ad78b86d83a183586a7147ca679179..0000000000000000000000000000000000000000 --- a/src/data/IGLSampler.ts +++ /dev/null @@ -1,39 +0,0 @@ -export type IGLSamplerCompareMode = "NONE" | "COMPARE_REF_TO_TEXTURE"; - -/** - * 纹理放大滤波器 - * Texture magnification filter - * - * * `LINEAR` - * * `NEAREST` - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texParameter - */ -export type IGLTextureMagFilter = "LINEAR" | "NEAREST"; - -/** - * 纹理缩小过滤器 - * Texture minification filter - * - * * `LINEAR` - * * `NEAREST` - * * `NEAREST_MIPMAP_NEAREST` - * * `LINEAR_MIPMAP_NEAREST` - * * `NEAREST_MIPMAP_LINEAR` - * * `LINEAR_MIPMAP_LINEAR` - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texParameter - */ -export type IGLTextureMinFilter = "LINEAR" | "NEAREST" | "NEAREST_MIPMAP_NEAREST" | "LINEAR_MIPMAP_NEAREST" | "NEAREST_MIPMAP_LINEAR" | "LINEAR_MIPMAP_LINEAR"; - -/** - * 纹理坐标s包装函数枚举 - * Wrapping function for texture coordinate s - * - * * `REPEAT` - * * `CLAMP_TO_EDGE` - * * `MIRRORED_REPEAT` - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texParameter - */ -export type IGLTextureWrap = "REPEAT" | "CLAMP_TO_EDGE" | "MIRRORED_REPEAT"; \ No newline at end of file diff --git a/src/data/IGLTexture.ts b/src/data/IGLTexture.ts deleted file mode 100644 index bd1c0c203be78835a9474ccabe86222358e75888..0000000000000000000000000000000000000000 --- a/src/data/IGLTexture.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { ITexture } from "@feng3d/render-api"; -import { IGLCanvasTexture } from "./IGLCanvasTexture"; - -/** - * 类似纹理,包含画布纹理以及正常纹理。 - */ -export type IGLTextureLike = IGLCanvasTexture | ITexture; - -/** - * 纹理绑定点。 - * - * * gl.TEXTURE_2D: A two-dimensional texture. - * * gl.TEXTURE_CUBE_MAP: A cube-mapped texture. - * - * When using a WebGL 2 context, the following values are available additionally: - * - * * gl.TEXTURE_3D: A three-dimensional texture. - * * gl.TEXTURE_2D_ARRAY: A two-dimensional array texture. - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindTexture - */ -export type IGLTextureTarget = "TEXTURE_2D" | "TEXTURE_CUBE_MAP" | "TEXTURE_3D" | "TEXTURE_2D_ARRAY"; - -/** - * internalformat format type - * - * @see https://registry.khronos.org/webgl/specs/latest/2.0/#TEXTURE_TYPES_FORMATS_FROM_DOM_ELEMENTS_TABLE - */ -export type IGLTextureTypes = - | { internalformat: "RGB", format: "RGB", type: "UNSIGNED_BYTE" | "UNSIGNED_SHORT_5_6_5" } - | { internalformat: "RGBA", format: "RGBA", type: "UNSIGNED_BYTE" | "UNSIGNED_SHORT_4_4_4_4" | "UNSIGNED_SHORT_5_5_5_1" } - | { internalformat: "LUMINANCE_ALPHA", format: "LUMINANCE_ALPHA", type: "UNSIGNED_BYTE" } - | { internalformat: "LUMINANCE", format: "LUMINANCE", type: "UNSIGNED_BYTE" } - | { internalformat: "ALPHA", format: "ALPHA", type: "UNSIGNED_BYTE" } - | { internalformat: "R8", format: "RED", type: "UNSIGNED_BYTE" } - | { internalformat: "R16F", format: "RED", type: "HALF_FLOAT" | " FLOAT" } - | { internalformat: "R32F", format: "RED", type: "FLOAT" } - | { internalformat: "R8UI", format: "RED_INTEGER", type: "UNSIGNED_BYTE" } - | { internalformat: "RG8", format: "RG", type: "UNSIGNED_BYTE" } - | { internalformat: "RG16F", format: "RG", type: "HALF_FLOAT" | "FLOAT" } - | { internalformat: "RG32F", format: "RG", type: "FLOAT" } - | { internalformat: "RG8UI", format: "RG_INTEGER", type: "UNSIGNED_BYTE" } - | { internalformat: "RGB8", format: "RGB", type: "UNSIGNED_BYTE" } - | { internalformat: "SRGB8", format: "RGB", type: "UNSIGNED_BYTE" } - | { internalformat: "RGB565", format: "RGB", type: "UNSIGNED_BYTE" | "UNSIGNED_SHORT_5_6_5" } - | { internalformat: "R11F_G11F_B10F", format: "RGB", type: "UNSIGNED_INT_10F_11F_11F_REV" | "HALF_FLOAT" | "FLOAT" } - | { internalformat: "RGB9_E5", format: "RGB", type: "HALF_FLOAT" | "FLOAT" } - | { internalformat: "RGB16F", format: "RGB", type: "HALF_FLOAT" | "FLOAT" } - | { internalformat: "RGB32F", format: "RGB", type: "FLOAT" } - | { internalformat: "RGB8UI", format: "RGB_INTEGER", type: "UNSIGNED_BYTE" } - | { internalformat: "RGBA8", format: "RGBA", type: "UNSIGNED_BYTE" } - | { internalformat: "SRGB8_ALPHA8", format: "RGBA", type: "UNSIGNED_BYTE" } - | { internalformat: "RGB5_A1", format: "RGBA", type: "UNSIGNED_BYTE" | "UNSIGNED_SHORT_5_5_5_1" } - | { internalformat: "RGB10_A2", format: "RGBA", type: "UNSIGNED_INT_2_10_10_10_REV" } - | { internalformat: "RGBA4", format: "RGBA", type: "UNSIGNED_BYTE" | "UNSIGNED_SHORT_4_4_4_4" } - | { internalformat: "RGBA16F", format: "RGBA", type: "HALF_FLOAT" | "FLOAT" } - | { internalformat: "RGBA32F", format: "RGBA", type: "FLOAT" } - | { internalformat: "RGBA8UI", format: "RGBA_INTEGER", type: "UNSIGNED_BYTE" } - // 深度纹理 - | { internalformat: "DEPTH_COMPONENT16", format: "DEPTH_COMPONENT", type: "UNSIGNED_SHORT", } - ; - -export type IGLTextureInternalFormat = IGLTextureTypes["internalformat"]; -export type IGLTextureFormat = IGLTextureTypes["format"]; -export type IGLTextureDataType = IGLTextureTypes["type"]; diff --git a/src/data/IGLTextureFormats.ts b/src/data/IGLTextureFormats.ts deleted file mode 100644 index 5c2dc144110d14fdf1ff67e0c1dfc45f9e50c0ca..0000000000000000000000000000000000000000 --- a/src/data/IGLTextureFormats.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { IGLTextureDataType, IGLTextureFormat, IGLTextureInternalFormat } from "./IGLTexture"; - -export interface IGLTextureFormats -{ - /** - * 内部纹理格式。 - * - * 默认 "RGBA"。 - */ - readonly internalformat?: IGLTextureInternalFormat, - - /** - * 纹理格式。 - * - * 默认 "RGBA"。 - */ - readonly format?: IGLTextureFormat; - - /** - * 数据类型。 - * - * 默认 "UNSIGNED_BYTE"。 - */ - readonly type?: IGLTextureDataType; -} \ No newline at end of file diff --git a/src/data/IGLTexturePixelStore.ts b/src/data/IGLTexturePixelStore.ts deleted file mode 100644 index 381a7bb04d7cfbcd0e8418555446daa832617630..0000000000000000000000000000000000000000 --- a/src/data/IGLTexturePixelStore.ts +++ /dev/null @@ -1,249 +0,0 @@ -/** - * 像素解包打包时参数。 - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/pixelStorei - */ -export interface IGLTexturePixelStore1 -{ - /** - * Packing of pixel data into memory - * - * gl.PACK_ALIGNMENT - * - * 默认值为 4 。 - */ - packAlignment?: 1 | 2 | 4 | 8; - - /** - * Unpacking of pixel data from memory. - * - * gl.UNPACK_ALIGNMENT - * - * 默认值为 4 。 - */ - unpackAlignment?: 1 | 2 | 4 | 8; - - /** - * Default color space conversion or no color space conversion. - * - * gl.UNPACK_COLORSPACE_CONVERSION_WEBGL - * - * 默认为 "BROWSER_DEFAULT_WEBGL" 。 - */ - unpackColorSpaceConversion?: "BROWSER_DEFAULT_WEBGL" | "NONE"; - - /** - * Number of pixels in a row. - * - * gl.PACK_ROW_LENGTH - * - * 默认值为 0 。 - * - * 仅 WebGL2。 - */ - packRowLength?: number; - - /** - * Number of pixel locations skipped before the first pixel is written into memory. - * - * gl.PACK_SKIP_PIXELS - * - * 默认值为 0 。 - * - * 仅 WebGL2。 - */ - packSkipPixels?: number; - - /** - * Number of rows of pixel locations skipped before the first pixel is written into memory - * - * gl.PACK_SKIP_ROWS - * - * 默认值为 0 。 - * - * 仅 WebGL2。 - */ - packSkipRows?: number; - - /** - * Number of pixels in a row. - * - * gl.UNPACK_ROW_LENGTH - * - * 默认值为 0 。 - * - * 仅 WebGL2。 - */ - unpackRowLength?: number; - - /** - * Image height used for reading pixel data from memory - * - * gl.UNPACK_IMAGE_HEIGHT - * - * 默认值为 0 。 - * - * 仅 WebGL2。 - */ - unpackImageHeight?: number; - - /** - * - * Number of pixel images skipped before the first pixel is read from memory - * - * gl.UNPACK_SKIP_IMAGES - * - * 默认值为 0 。 - * - * 仅 WebGL2。 - */ - unpackSkipImages?: number; -} - -/** - * 像素解包打包时参数。 - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/pixelStorei - */ -export interface IGLTexturePixelStore -{ - /** - * Packing of pixel data into memory - * - * gl.PACK_ALIGNMENT - * - * 默认值为 4 。 - */ - packAlignment?: 1 | 2 | 4 | 8; - - /** - * Unpacking of pixel data from memory. - * - * gl.UNPACK_ALIGNMENT - * - * 默认值为 4 。 - */ - unpackAlignment?: 1 | 2 | 4 | 8; - - /** - * 解包图像数据时进行Y轴反转。 - * - * Flips the source data along its vertical axis if true. - * - * gl.UNPACK_FLIP_Y_WEBGL - * - * 默认为 false。 - */ - unpackFlipY?: boolean; - - /** - * 将图像RGB颜色值得每一个分量乘以A。 - * - * Multiplies the alpha channel into the other color channels - * - * gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL - * - * 默认为 false。 - */ - unpackPremulAlpha?: boolean; - - /** - * Default color space conversion or no color space conversion. - * - * gl.UNPACK_COLORSPACE_CONVERSION_WEBGL - * - * 默认为 "BROWSER_DEFAULT_WEBGL" 。 - */ - unpackColorSpaceConversion?: "BROWSER_DEFAULT_WEBGL" | "NONE"; - - /** - * Number of pixels in a row. - * - * gl.PACK_ROW_LENGTH - * - * 默认值为 0 。 - * - * 仅 WebGL2。 - */ - packRowLength?: number; - - /** - * Number of pixel locations skipped before the first pixel is written into memory. - * - * gl.PACK_SKIP_PIXELS - * - * 默认值为 0 。 - * - * 仅 WebGL2。 - */ - packSkipPixels?: number; - - /** - * Number of rows of pixel locations skipped before the first pixel is written into memory - * - * gl.PACK_SKIP_ROWS - * - * 默认值为 0 。 - * - * 仅 WebGL2。 - */ - packSkipRows?: number; - - /** - * Number of pixels in a row. - * - * gl.UNPACK_ROW_LENGTH - * - * 默认值为 0 。 - * - * 仅 WebGL2。 - */ - unpackRowLength?: number; - - /** - * Image height used for reading pixel data from memory - * - * gl.UNPACK_IMAGE_HEIGHT - * - * 默认值为 0 。 - * - * 仅 WebGL2。 - */ - unpackImageHeight?: number; - - /** - * - * Number of pixel images skipped before the first pixel is read from memory - * - * gl.UNPACK_SKIP_PIXELS - * - * 默认值为 0 。 - * - * 仅 WebGL2。 - */ - unpackSkipPixels?: number; - - /** - * - * Number of rows of pixel locations skipped before the first pixel is read from memory - * - * gl.UNPACK_SKIP_ROWS - * - * 默认值为 0 。 - * - * 仅 WebGL2。 - */ - unpackSkipRows?: number; - - /** - * - * Number of pixel images skipped before the first pixel is read from memory - * - * gl.UNPACK_SKIP_IMAGES - * - * 默认值为 0 。 - * - * 仅 WebGL2。 - */ - unpackSkipImages?: number; -} diff --git a/src/data/IGLTransformFeedback.ts b/src/data/IGLTransformFeedback.ts deleted file mode 100644 index 8ad75046ab3ecb6e24c429790964b3d0dd8c415a..0000000000000000000000000000000000000000 --- a/src/data/IGLTransformFeedback.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { IVertexDataTypes } from "@feng3d/render-api"; - -/** - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext/createTransformFeedback - */ -export interface IGLTransformFeedback -{ - /** - * 绑定缓冲区列表。 - */ - bindBuffers: IGLTransformFeedbacBindBuffer[]; -} - -export interface IGLTransformFeedbacBindBuffer -{ - index: number; - - data: IVertexDataTypes; -} \ No newline at end of file diff --git a/src/data/IGLUniformInfo.ts b/src/data/IGLUniformInfo.ts deleted file mode 100644 index 45c6883727ac81f6f8bdf37949413da69ed9f29c..0000000000000000000000000000000000000000 --- a/src/data/IGLUniformInfo.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { IGLUniformType } from "../const/IGLUniformType"; - -/** - * WebGL统一变量 - */ -export interface IGLUniformInfo -{ - /** - * 名称。 - */ - name: string; - - type: IGLUniformType; - - /** - * 是否纹理。 - */ - isTexture: boolean; - - /** - * 子项信息列表。 - */ - items: IUniformItemInfo[] - - /** - * 是否在Block中。 - */ - inBlock?: boolean; -} - -/** - * WebGL统一变量 - */ -export interface IUniformItemInfo -{ - /** - * uniform地址 - */ - location: WebGLUniformLocation; - - /** - * texture索引 - */ - textureID: number; - - /** - * Uniform数组索引,当Uniform数据为数组数据时生效 - */ - paths: string[]; -} \ No newline at end of file diff --git a/src/data/IGLUniforms.ts b/src/data/IGLUniforms.ts deleted file mode 100644 index a1bf151bd7f33e72e2147280c30cbd777cfc84ee..0000000000000000000000000000000000000000 --- a/src/data/IGLUniforms.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { IUniformDataItem } from "@feng3d/render-api"; -import { IGLSamplerTexture } from "./IGLSamplerTexture"; - -declare module "@feng3d/render-api" -{ - export interface IUniformTypeMap - { - IGLSamplerTexture: IGLSamplerTexture; - IUniformDataItem: IUniformDataItem; - } -} diff --git a/src/data/IGLRenderbuffer.ts b/src/data/Renderbuffer.ts similarity index 88% rename from src/data/IGLRenderbuffer.ts rename to src/data/Renderbuffer.ts index ddc6f190000854adb5ba9cdb4ceaf7a4d24a4b4c..cccfb641255eec32b0fa1f8b8155b1ffaef0fbae 100644 --- a/src/data/IGLRenderbuffer.ts +++ b/src/data/Renderbuffer.ts @@ -1,15 +1,15 @@ /** - * 渲染缓冲区。 + * WebGL渲染缓冲区。 * * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/renderbufferStorage * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext/renderbufferStorageMultisample */ -export interface IGLRenderbuffer +export interface Renderbuffer { /** - * 渲染缓冲区内部格式。 + * WebGL渲染缓冲区内部格式。 */ - readonly internalformat: GLRenderbufferInternalformat, + readonly internalformat: RenderbufferInternalformat, /** * 宽度。 @@ -23,6 +23,8 @@ export interface IGLRenderbuffer } /** + * WebGL渲染缓冲区内部格式。 + * * A GLenum specifying the internal format of the renderbuffer. Possible values: * * * gl.RGBA4: 4 red bits, 4 green bits, 4 blue bits 4 alpha bits. @@ -85,7 +87,7 @@ export interface IGLRenderbuffer * * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/renderbufferStorage */ -export type GLRenderbufferInternalformat = "RGBA4" | "RGB565" | "RGB5_A1" | "DEPTH_COMPONENT16" | "STENCIL_INDEX8" | "DEPTH_STENCIL" // WebGL1 +export type RenderbufferInternalformat = "RGBA4" | "RGB565" | "RGB5_A1" | "DEPTH_COMPONENT16" | "STENCIL_INDEX8" | "DEPTH_STENCIL" // WebGL1 | "R8" | "R8UI" | "R8I" | "R16UI" | "R16I" | "R32UI" | "R32I" | "RG8" | "RG8UI" | "RG8I" // WebGL2 | "RG16UI" | "RG16I" | "RG32UI" | "RG32I" | "RGB8" | "RGBA8" | "SRGB8_ALPHA8" | "RGB10_A2" // WebGL2 | "RGBA8UI" | "RGBA8I" | "RGB10_A2UI" | "RGBA16UI" | "RGBA16I" | "RGBA32I" | "RGBA32UI" // WebGL2 diff --git a/src/data/IGLSamplerTexture.ts b/src/data/SamplerTexture.ts similarity index 48% rename from src/data/IGLSamplerTexture.ts rename to src/data/SamplerTexture.ts index 2a1bb572b0e117f453ecb7cfe3ae02dac38cca72..f5ed8223b2ba68910e2f6feb4f13bcecb5f50dd3 100644 --- a/src/data/IGLSamplerTexture.ts +++ b/src/data/SamplerTexture.ts @@ -1,19 +1,19 @@ -import { ISampler, ITexture } from "@feng3d/render-api"; +import { Sampler, Texture } from "@feng3d/render-api"; /** * 采样纹理。 * * 采样器与纹理。 */ -export interface IGLSamplerTexture +export interface SamplerTexture { /** * 纹理。 */ - texture: ITexture; + texture: Texture; /** * 采样器。 */ - sampler?: ISampler; + sampler?: Sampler; } diff --git a/src/data/IGLTransformFeedbackPass.ts b/src/data/TransformFeedbackPass.ts similarity index 48% rename from src/data/IGLTransformFeedbackPass.ts rename to src/data/TransformFeedbackPass.ts index 2e9228e39c62f2a760ac59c5b1bfba99e16261ad..ca3ad1f578dbadd4acf6558a8cd1f00d8958c13f 100644 --- a/src/data/IGLTransformFeedbackPass.ts +++ b/src/data/TransformFeedbackPass.ts @@ -1,75 +1,74 @@ -import { IDrawVertex, IUniforms, IVertexAttributes, IVertexState } from "@feng3d/render-api"; -import { IGLTransformFeedback } from "./IGLTransformFeedback"; +import { BindingResources, DrawVertex, VertexAttributes, VertexDataTypes, VertexState } from "@feng3d/render-api"; declare module "@feng3d/render-api" { - export interface IPassEncoderMap + export interface PassEncoderMap { - IGLTransformFeedbackPass: IGLTransformFeedbackPass, + TransformFeedbackPass: TransformFeedbackPass, } } -export interface IGLTransformFeedbackPass +export interface TransformFeedbackPass { /** * 数据类型。 */ - readonly __type: "TransformFeedbackPass"; + readonly __type__: "TransformFeedbackPass"; /** * 变换反馈对象列表。 */ - transformFeedbackObjects: IGLTransformFeedbackObject[]; + transformFeedbackObjects: TransformFeedbackObject[]; } -export interface IGLTransformFeedbackObject +export interface TransformFeedbackObject { /** * 渲染管线描述。 */ - readonly pipeline: IGLTransformFeedbackPipeline; + readonly pipeline: TransformFeedbackPipeline; /** * 顶点属性数据映射。 */ - vertices: IVertexAttributes; + vertices: VertexAttributes; /** * 根据顶点数据绘制图元。 * * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/drawVertex */ - readonly drawVertex: IDrawVertex; + readonly draw: DrawVertex; /** * Uniform渲染数据 */ - uniforms?: IUniforms; + uniforms?: BindingResources; /** * 回写顶点着色器中输出到缓冲区。 * * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext/bindTransformFeedback */ - transformFeedback: IGLTransformFeedback; + transformFeedback: TransformFeedback; } -export interface IGLTransformFeedbackPipeline +export interface TransformFeedbackPipeline { /** * 顶点着色器阶段描述。 */ - readonly vertex: IVertexState; + readonly vertex: VertexState; /** * 回写变量。 * * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext/transformFeedbackVaryings */ - transformFeedbackVaryings: IGLTransformFeedbackVaryings; + transformFeedbackVaryings: TransformFeedbackVaryings; } -export interface IGLTransformFeedbackVaryings +export interface TransformFeedbackVaryings { /** * 回写变量列表。 @@ -81,3 +80,21 @@ export interface IGLTransformFeedbackVaryings */ bufferMode: "INTERLEAVED_ATTRIBS" | "SEPARATE_ATTRIBS"; } + +/** + * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext/createTransformFeedback + */ +export interface TransformFeedback +{ + /** + * 绑定缓冲区列表。 + */ + bindBuffers: TransformFeedbacBindBuffer[]; +} + +export interface TransformFeedbacBindBuffer +{ + index: number; + + data: VertexDataTypes; +} \ No newline at end of file diff --git a/src/data/IGLBuffer.ts b/src/data/polyfills/Buffer.ts similarity index 77% rename from src/data/IGLBuffer.ts rename to src/data/polyfills/Buffer.ts index 46a93367ca1af63a60213300063584142bae9792..9b087781aaa50e93974bdc17007e431685597963 100644 --- a/src/data/IGLBuffer.ts +++ b/src/data/polyfills/Buffer.ts @@ -1,4 +1,4 @@ -import { IBuffer, IIndicesDataTypes, IVertexDataTypes } from "@feng3d/render-api"; +import { } from "@feng3d/render-api"; declare module "@feng3d/render-api" { @@ -7,54 +7,24 @@ declare module "@feng3d/render-api" * * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bufferData */ - export interface IBuffer + export interface Buffer { - target: IGLBufferTarget; + /** + * WebGL缓冲区目标。 + */ + target: BufferTarget; /** * 为优化目的指定数据存储的预期使用模式的GLenum。 * * 默认为 "STATIC_DRAW"。 */ - usage?: IGLBufferUsage; + usage?: BufferUsage; } } -export interface IGLVertexBuffer extends IBuffer -{ - target: "ARRAY_BUFFER"; - - /** - * 缓冲区数据。 - */ - data?: IVertexDataTypes; -} - -/** - * WebGL元素缓冲,顶点索引缓冲。 - * - * 使用 gl.ELEMENT_ARRAY_BUFFER 进行绑定数据。 - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindBuffer - * - */ -export interface IGLIndexBuffer extends IBuffer -{ - target: "ELEMENT_ARRAY_BUFFER"; - - /** - * 顶点索引数据。 - */ - data: IIndicesDataTypes; -} - -export interface IGLUniformBuffer extends IBuffer -{ - target: "UNIFORM_BUFFER"; -} - /** - * 元素缓冲数据类型。 + * WebGL元素缓冲数据类型。 * * A GLenum specifying the type of the values in the element array buffer. Possible values are: * @@ -67,9 +37,11 @@ export interface IGLUniformBuffer extends IBuffer * * @see https://developer.mozilla.org/zh-CN/docs/Web/API/WebGLRenderingContext/drawElements */ -export type IGLDrawElementType = "UNSIGNED_BYTE" | "UNSIGNED_SHORT" | "UNSIGNED_INT"; +export type DrawElementType = "UNSIGNED_BYTE" | "UNSIGNED_SHORT" | "UNSIGNED_INT"; /** + * WebGL缓冲区使用模式。 + * * A GLenum specifying the intended usage pattern of the data store for optimization purposes. Possible values: * * * gl.STATIC_DRAW: The contents are intended to be specified once by the application, and used many times as the source for WebGL drawing and image specification commands. @@ -87,11 +59,13 @@ export type IGLDrawElementType = "UNSIGNED_BYTE" | "UNSIGNED_SHORT" | "UNSIGNED_ * * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bufferData */ -export type IGLBufferUsage = "STATIC_DRAW" | "DYNAMIC_DRAW" | "STREAM_DRAW" // WebGL1 +export type BufferUsage = "STATIC_DRAW" | "DYNAMIC_DRAW" | "STREAM_DRAW" // WebGL1 | "STATIC_READ" | "DYNAMIC_READ" | "STREAM_READ" | "STATIC_COPY" | "DYNAMIC_COPY" | "STREAM_COPY" // WebGL2 ; /** + * WebGL缓冲区目标。 + * * A GLenum specifying the binding point (target). Possible values: * * * gl.ARRAY_BUFFER: Buffer containing vertex attributes, such as vertex coordinates, texture coordinate data, or vertex color data. @@ -106,6 +80,6 @@ export type IGLBufferUsage = "STATIC_DRAW" | "DYNAMIC_DRAW" | "STREAM_DRAW" // W * * gl.PIXEL_UNPACK_BUFFER: Buffer used for pixel transfer operations. * */ -export type IGLBufferTarget = "ARRAY_BUFFER" | "ELEMENT_ARRAY_BUFFER" // WebGL1 +export type BufferTarget = "ARRAY_BUFFER" | "ELEMENT_ARRAY_BUFFER" // WebGL1 | "COPY_READ_BUFFER" | "COPY_WRITE_BUFFER" | "TRANSFORM_FEEDBACK_BUFFER"// WebGL2 | "UNIFORM_BUFFER" | "PIXEL_PACK_BUFFER" | "PIXEL_UNPACK_BUFFER"; // WebGL2 diff --git a/src/data/polyfills/CanvasContext.ts b/src/data/polyfills/CanvasContext.ts new file mode 100644 index 0000000000000000000000000000000000000000..4252e6461cdc943d7d369137e7fb0aac206afef7 --- /dev/null +++ b/src/data/polyfills/CanvasContext.ts @@ -0,0 +1,34 @@ +import { CanvasContext } from "@feng3d/render-api"; + +declare module "@feng3d/render-api" +{ + /** + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext + */ + export interface CanvasContext + { + /** + * WebGL上下文类型 + */ + webGLcontextId?: "webgl" | "webgl2"; + + /** + * WebGL上下文属性。 + */ + webGLContextAttributes?: WebGLContextAttributes; + } +} + +/** + * 默认画布(WebGL)上下文信息。 + */ +export const defaultWebGLContextAttributes: WebGLContextAttributes = { + depth: true, + stencil: true, + antialias: false, + premultipliedAlpha: true, + preserveDrawingBuffer: false, + powerPreference: "default", + failIfMajorPerformanceCaveat: false, +} diff --git a/src/data/IGLCommandEncoder.ts b/src/data/polyfills/CommandEncoder.ts similarity index 55% rename from src/data/IGLCommandEncoder.ts rename to src/data/polyfills/CommandEncoder.ts index 32bff98d0943e19c48fdcbb6d8f558e0103bf355..45fd1af3c0e2f729d516dc37570cbf321ae0a8a4 100644 --- a/src/data/IGLCommandEncoder.ts +++ b/src/data/polyfills/CommandEncoder.ts @@ -1,11 +1,11 @@ -import { ITextureLike } from "@feng3d/render-api"; -import { IGLBlitFramebuffer } from "./IGLBlitFramebuffer"; +import { TextureLike } from "@feng3d/render-api"; +import { BlitFramebuffer } from "../BlitFramebuffer"; declare module "@feng3d/render-api" { - export interface IPassEncoderMap + export interface PassEncoderMap { - IGLBlitFramebuffer: IGLBlitFramebuffer; + GLBlitFramebuffer: BlitFramebuffer; } /** @@ -14,12 +14,12 @@ declare module "@feng3d/render-api" * {@link GPUCommandEncoder.copyTextureToTexture} * {@link GPUImageCopyTexture} */ - export interface IImageCopyTexture + export interface ImageCopyTexture { /** * * 注:当值设置为 null或者undefined时表示当前画布。 */ - texture: ITextureLike; + texture: TextureLike; } } diff --git a/src/data/polyfills/OcclusionQuery.ts b/src/data/polyfills/OcclusionQuery.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e21592ce5d675f35c3ff663da4203a46bee35fd --- /dev/null +++ b/src/data/polyfills/OcclusionQuery.ts @@ -0,0 +1,16 @@ +import { } from "@feng3d/render-api"; +import { GLOcclusionQueryStep } from "../../caches/getGLRenderOcclusionQuery"; + +declare module "@feng3d/render-api" +{ + export interface OcclusionQuery + { + /** + * 临时变量, 执行过程中由引擎自动填充。 + * + * @internal + */ + _step?: GLOcclusionQueryStep; + } + +} diff --git a/src/data/polyfills/PrimitiveState.ts b/src/data/polyfills/PrimitiveState.ts new file mode 100644 index 0000000000000000000000000000000000000000..9433058bf1404b03c6fc6066dc5f9bc98ce7ffdd --- /dev/null +++ b/src/data/polyfills/PrimitiveState.ts @@ -0,0 +1,27 @@ +import { CullFace, FrontFace, PrimitiveTopology } from "@feng3d/render-api"; + +declare module "@feng3d/render-api" +{ + export interface PrimitiveTopologyMap + { + /** + * 绘制循环连线。 + * + * 仅在WebGL生效。 + */ + "LINE_LOOP": "LINE_LOOP", + + /** + * 绘制三角扇形。 + * + * 仅在WebGL生效。 + */ + "TRIANGLE_FAN": "TRIANGLE_FAN", + } + + export interface CullFaceMap + { + "FRONT_AND_BACK": "FRONT_AND_BACK"; + } + +} diff --git a/src/data/polyfills/Uniforms.ts b/src/data/polyfills/Uniforms.ts new file mode 100644 index 0000000000000000000000000000000000000000..b2b0aec9b32638919ec1082d2bce56ceac1500a7 --- /dev/null +++ b/src/data/polyfills/Uniforms.ts @@ -0,0 +1,11 @@ +import { UniformDataItem } from "@feng3d/render-api"; +import { SamplerTexture } from "../SamplerTexture"; + +declare module "@feng3d/render-api" +{ + export interface BindingResourceTypeMap + { + GLSamplerTexture: SamplerTexture; + UniformDataItem: UniformDataItem; + } +} diff --git a/src/defaults/defaults.ts b/src/defaults/defaults.ts deleted file mode 100644 index 158527760a22f3626d288fe5b0b5c986c294e72e..0000000000000000000000000000000000000000 --- a/src/defaults/defaults.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { IGLCanvasContext } from "../data/IGLCanvasContext"; - -/** - * 默认WebGL上下文信息。 - */ -export const defaultCanvasContext: IGLCanvasContext = Object.freeze({ - contextId: "webgl2", - depth: true, - stencil: true, - antialias: false, - premultipliedAlpha: true, - preserveDrawingBuffer: false, - powerPreference: "default", - failIfMajorPerformanceCaveat: false, -}); diff --git a/src/gl/WebGLEnums.ts b/src/gl/WebGLEnums.ts index 52d94500a2e72ab80c5434ba1725e213eb7860c3..73d55f2bb0084ef792096b2e81a1215e88e9752f 100644 --- a/src/gl/WebGLEnums.ts +++ b/src/gl/WebGLEnums.ts @@ -1,117 +1,5 @@ -import { IGLTextureMagFilter, IGLTextureMinFilter, IGLTextureWrap } from "../data/IGLSampler"; +import { GLTextureWrap } from "../caches/getGLSampler"; -/** - * A GLenum specifying which WebGL capability to enable. Possible values: - * - * gl.BLEND Activates blending of the computed fragment color values. See WebGLRenderingContext.blendFunc(). - * gl.CULL_FACE Activates culling of polygons. See WebGLRenderingContext.cullFace(). - * gl.DEPTH_TEST Activates depth comparisons and updates to the depth buffer. See WebGLRenderingContext.depthFunc(). - * gl.DITHER Activates dithering of color components before they get written to the color buffer. - * gl.POLYGON_OFFSET_FILL Activates adding an offset to depth values of polygon's fragments. See WebGLRenderingContext.polygonOffset(). - * gl.SAMPLE_ALPHA_TO_COVERAGE Activates the computation of a temporary coverage value determined by the alpha value. - * gl.SAMPLE_COVERAGE Activates ANDing the fragment's coverage with the temporary coverage value. See WebGLRenderingContext.sampleCoverage(). - * gl.SCISSOR_TEST Activates the scissor test that discards fragments that are outside of the scissor rectangle. See WebGLRenderingContext.scissor(). - * gl.STENCIL_TEST Activates stencil testing and updates to the stencil buffer. See WebGLRenderingContext.stencilFunc(). - * - * When using a WebGL 2 context, the following values are available additionally: - * - * gl.RASTERIZER_DISCARD Primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage. gl.clear() commands are ignored. - */ -export type Capability = - "BLEND" | "CULL_FACE" | "DEPTH_TEST" | "DITHER" - | "POLYGON_OFFSET_FILL" | "SAMPLE_ALPHA_TO_COVERAGE" | "SAMPLE_COVERAGE" - | "SCISSOR_TEST" - | "STENCIL_TEST" - | "RASTERIZER_DISCARD" - ; - -/** - * A GLenum specifying the format of the pixel data. Possible values: - * - * * gl.ALPHA Discards the red, green and blue components and reads the alpha component. - * * gl.RGB Discards the alpha components and reads the red, green and blue components. - * * gl.RGBA Red, green, blue and alpha components are read from the color buffer. - * - * WebGL2 adds - * - * * gl.RED - * * gl.RG - * * gl.RED_INTEGER - * * gl.RG_INTEGER - * * gl.RGB_INTEGER - * * gl.RGBA_INTEGER - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/readPixels - */ -export type ReadPixelsFormat = "ALPHA" | "RGB" | "RGBA" // WebGL1 - | "RED" | "RG" | "RED_INTEGER" | "RG_INTEGER" | "RGB_INTEGER" | "RGBA_INTEGER" // WebGL2 - ; - -/** - * A GLenum specifying the data type of the pixel data. Possible values: - * * gl.UNSIGNED_BYTE - * * gl.UNSIGNED_SHORT_5_6_5 - * * gl.UNSIGNED_SHORT_4_4_4_4 - * * gl.UNSIGNED_SHORT_5_5_5_1 - * * gl.FLOAT - * - * WebGL2 adds - * * gl.BYTE - * * gl.UNSIGNED_INT_2_10_10_10_REV - * * gl.HALF_FLOAT - * * gl.SHORT - * * gl.UNSIGNED_SHORT - * * gl.INT - * * gl.UNSIGNED_INT - * * gl.UNSIGNED_INT_10F_11F_11F_REV - * * gl.UNSIGNED_INT_5_9_9_9_REV - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/readPixels - */ -export type ReadPixelsType = - | "UNSIGNED_BYTE" - | "UNSIGNED_SHORT_5_6_5" - | "UNSIGNED_SHORT_4_4_4_4" - | "UNSIGNED_SHORT_5_5_5_1" - | "FLOAT" - | "BYTE" - | "UNSIGNED_INT_2_10_10_10_REV" - | "HALF_FLOAT" - | "SHORT" - | "UNSIGNED_SHORT" - | "INT" - | "UNSIGNED_INT" - | "UNSIGNED_INT_10F_11F_11F_REV" - | "UNSIGNED_INT_5_9_9_9_REV" - ; - -/** - * The pname parameter is a GLenum specifying the texture parameter to set. - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texParameter - */ -export interface TexParameteri extends TexParameteri_WebGL2 -{ - /** - * Texture magnification filter - */ - TEXTURE_MAG_FILTER: IGLTextureMagFilter; - - /** - * Texture minification filter - */ - TEXTURE_MIN_FILTER: IGLTextureMinFilter; - - /** - * Wrapping function for texture coordinate s - */ - TEXTURE_WRAP_S: IGLTextureWrap; - - /** - * Wrapping function for texture coordinate t - */ - TEXTURE_WRAP_T: IGLTextureWrap; -} /** * The pname parameter is a GLenum specifying the texture parameter to set. @@ -163,7 +51,7 @@ export interface TexParameteri_WebGL2 /** * Wrapping function for texture coordinate r */ - TEXTURE_WRAP_R: IGLTextureWrap; + TEXTURE_WRAP_R: GLTextureWrap; } /** @@ -323,22 +211,3 @@ export interface ProgramParameter * A precision type value. Either gl.LOW_FLOAT, gl.MEDIUM_FLOAT, gl.HIGH_FLOAT, gl.LOW_INT, gl.MEDIUM_INT, or gl.HIGH_INT. */ export type PrecisionType = "LOW_FLOAT" | "MEDIUM_FLOAT" | "HIGH_FLOAT" | "LOW_INT" | "MEDIUM_INT" | "HIGH_INT"; - -/** - * A GLenum specifying the attachment point for the texture. Possible values: - * - * gl.COLOR_ATTACHMENT0: Attaches the texture to the framebuffer's color buffer. - * gl.DEPTH_ATTACHMENT: Attaches the texture to the framebuffer's depth buffer. - * gl.STENCIL_ATTACHMENT: Attaches the texture to the framebuffer's stencil buffer. - * - * When using a WebGL 2 context, the following values are available additionally: - * - * gl.DEPTH_STENCIL_ATTACHMENT: depth and stencil buffer. - * gl.COLOR_ATTACHMENT1 gl.COLOR_ATTACHMENT2 gl.COLOR_ATTACHMENT3 gl.COLOR_ATTACHMENT4 gl.COLOR_ATTACHMENT5 gl.COLOR_ATTACHMENT6 gl.COLOR_ATTACHMENT7 gl.COLOR_ATTACHMENT8 gl.COLOR_ATTACHMENT9 gl.COLOR_ATTACHMENT10 gl.COLOR_ATTACHMENT11 gl.COLOR_ATTACHMENT12 gl.COLOR_ATTACHMENT13 gl.COLOR_ATTACHMENT14 gl.COLOR_ATTACHMENT15 - */ -export type GLAttachmentPoint = "COLOR_ATTACHMENT0" | "DEPTH_ATTACHMENT" | "STENCIL_ATTACHMENT" - | "DEPTH_STENCIL_ATTACHMENT" - | "COLOR_ATTACHMENT1" | "COLOR_ATTACHMENT2" | "COLOR_ATTACHMENT3" | "COLOR_ATTACHMENT4" | "COLOR_ATTACHMENT5" - | "COLOR_ATTACHMENT6" | "COLOR_ATTACHMENT7" | "COLOR_ATTACHMENT8" | "COLOR_ATTACHMENT9" | "COLOR_ATTACHMENT10" - | "COLOR_ATTACHMENT11" | "COLOR_ATTACHMENT12" | "COLOR_ATTACHMENT13" | "COLOR_ATTACHMENT14" | "COLOR_ATTACHMENT15" - ; diff --git a/src/index.ts b/src/index.ts index fc06b9c5ff4de6eb6830d320a4de6391e8f82882..5f15cbc967aed41f943feec71bf834038bf3554b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,30 +1,18 @@ -export * from "./data/IGLBlitFramebuffer"; -export * from "./data/IGLBuffer"; -export * from "./data/IGLCanvasContext"; -export * from "./data/IGLCapabilities"; -export * from "./data/IGLCommandEncoder"; -export * from "./data/IGLDepthStencilState"; -export * from "./data/IGLOcclusionQuery"; -export * from "./data/IGLPrimitiveState"; -export * from "./data/IGLReadPixels"; -export * from "./data/IGLRenderbuffer"; -export * from "./data/IGLRenderPass"; -export * from "./data/IGLSampler"; -export * from "./data/IGLSamplerTexture"; -export * from "./data/IGLTexture"; -export * from "./data/IGLTexturePixelStore"; -export * from "./data/IGLTransformFeedback"; -export * from "./data/IGLTransformFeedbackPass"; -export * from "./data/IGLUniforms"; +export * from "./data/BlitFramebuffer"; +export * from "./data/Renderbuffer"; +export * from "./data/SamplerTexture"; +export * from "./data/TransformFeedbackPass"; + +export * from "./data/polyfills/CanvasContext"; +export * from "./data/polyfills/Buffer"; +export * from "./data/polyfills/CommandEncoder"; +export * from "./data/polyfills/PrimitiveState"; +export * from "./data/polyfills/Uniforms"; export * from "./runs/getIGLBuffer"; export * from "./runs/runColorTargetStates"; export * from "./RunWebGL"; -export * from "./defaults/defaults"; - -export * from "./gl/WebGLEnums"; - export * from "./shader/Macro"; export * from "./shader/ShaderLib"; export * from "./shader/ShaderMacroUtils"; @@ -34,6 +22,3 @@ export * from "./WebGL"; export * as internal from "./internal"; export * from "./caches/getGLBuffer"; - -export * from "./utils/getIVertexFormat"; - diff --git a/src/runs/getIGLBuffer.ts b/src/runs/getIGLBuffer.ts index 8ac96942781ac53a47cc17c73d930f25f79e0037..e1c7f1636d4f327b48006ce780c79b832d812323 100644 --- a/src/runs/getIGLBuffer.ts +++ b/src/runs/getIGLBuffer.ts @@ -1,11 +1,11 @@ -import { IBuffer, IIndicesDataTypes, IVertexDataTypes, TypedArray } from "@feng3d/render-api"; -import { IGLBufferTarget, IGLBufferUsage, IGLIndexBuffer, IGLUniformBuffer, IGLVertexBuffer } from "../data/IGLBuffer"; +import { Buffer, TypedArray } from "@feng3d/render-api"; +import { BufferTarget, BufferUsage } from "../data/polyfills/Buffer"; -export function getIGLBuffer(data: TypedArray, target?: IGLBufferTarget, usage: IGLBufferUsage = "STATIC_DRAW"): IBuffer +export function getIGLBuffer(data: TypedArray, target?: BufferTarget, usage: BufferUsage = "STATIC_DRAW"): Buffer { if (data[_IGLBuffer]) return data[_IGLBuffer]; - const buffer: IBuffer = { + const buffer: Buffer = { size: Math.ceil(data.byteLength / 4) * 4, target, usage, @@ -16,26 +16,4 @@ export function getIGLBuffer(data: TypedArray, target?: IGLBufferTarget, usage: return buffer; } -export function getIGLUniformBuffer(data: TypedArray, usage?: "DYNAMIC_DRAW") -{ - const vertexBuffer: IGLUniformBuffer = data[_IGLBuffer] = data[_IGLBuffer] || getIGLBuffer(data, "UNIFORM_BUFFER", usage); - vertexBuffer.target = vertexBuffer.target || "UNIFORM_BUFFER"; - - return vertexBuffer; -} - -export function getIGLVertexBuffer(data: IVertexDataTypes, usage?: "STREAM_COPY") -{ - const vertexBuffer: IGLVertexBuffer = data[_IGLBuffer] = data[_IGLBuffer] || getIGLBuffer(data, "ARRAY_BUFFER", usage); - - return vertexBuffer; -} - -export function getIGLIndexBuffer(indices: IIndicesDataTypes) -{ - const indexBuffer: IGLIndexBuffer = indices[_IGLBuffer] = indices[_IGLBuffer] || getIGLBuffer(indices, "ELEMENT_ARRAY_BUFFER"); - - return indexBuffer; -} - -const _IGLBuffer = "IGLBuffer"; \ No newline at end of file +const _IGLBuffer = "_IGLBuffer"; \ No newline at end of file diff --git a/src/runs/runDepthState.ts b/src/runs/runDepthState.ts index b4d5ca0d362069a65fe2ccfb3905cc576d052114..286b16e1e9d9d6f5f654d61311f06b5abe7b67e0 100644 --- a/src/runs/runDepthState.ts +++ b/src/runs/runDepthState.ts @@ -1,16 +1,15 @@ -import { ICompareFunction, IDepthStencilState } from "@feng3d/render-api"; -import { IGLCompareFunction } from "../data/IGLDepthStencilState"; +import { ICompareFunction, DepthStencilState } from "@feng3d/render-api"; export function getIGLCompareFunction(depthCompare: ICompareFunction) { - const glDepthCompare: IGLCompareFunction = depthCompareMap[depthCompare]; + const glDepthCompare: GLCompareFunction = depthCompareMap[depthCompare]; console.assert(!!glDepthCompare, `接收到错误值,请从 ${Object.keys(depthCompareMap).toString()} 中取值!`); return glDepthCompare; } -const depthCompareMap: { [key: string]: IGLCompareFunction } = { +const depthCompareMap: { [key: string]: GLCompareFunction } = { never: "NEVER", less: "LESS", equal: "EQUAL", @@ -19,4 +18,22 @@ const depthCompareMap: { [key: string]: IGLCompareFunction } = { "not-equal": "NOTEQUAL", "greater-equal": "GEQUAL", always: "ALWAYS", -}; \ No newline at end of file +}; + +/** + * 指定深度比较函数的枚举,该函数设置绘制像素的条件,默认 LESS,如果传入值小于深度缓冲区值则通过。 + * + * A GLenum specifying the depth comparison function, which sets the conditions under which the pixel will be drawn. The default value is gl.LESS. + * + * * `NEVER` 总是不通过。 + * * `LESS` 如果传入值小于深度缓冲区值则通过。 + * * `EQUAL` 如果传入值等于深度缓冲区值则通过。 + * * `LEQUAL` 如果传入值小于或等于深度缓冲区值则通过。 + * * `GREATER` 如果传入值大于深度缓冲区值则通过。 + * * `NOTEQUAL` 如果传入值不等于深度缓冲区值则通过。 + * * `GEQUAL` 如果传入值大于或等于深度缓冲区值则通过。 + * * `ALWAYS` 总是通过。 + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/depthFunc + */ +export type GLCompareFunction = "NEVER" | "LESS" | "EQUAL" | "LEQUAL" | "GREATER" | "NOTEQUAL" | "GEQUAL" | "ALWAYS"; diff --git a/src/runs/runStencilState.ts b/src/runs/runStencilState.ts index d4a114b52627ae357aa0c0d57d5e5dc55ed7c41f..728760019fb5759a6402c0b9ec5821f38b366fb1 100644 --- a/src/runs/runStencilState.ts +++ b/src/runs/runStencilState.ts @@ -1,13 +1,13 @@ -import { ICompareFunction, IDepthStencilState, IStencilOperation } from "@feng3d/render-api"; -import { IGLStencilFunc, IGLStencilOp } from "../data/IGLDepthStencilState"; +import { ICompareFunction, IStencilOperation } from "@feng3d/render-api"; export function getIGLStencilFunc(compare: ICompareFunction) { - const stencilFunc: IGLStencilFunc = compareMap[compare]; + const stencilFunc: GLStencilFunc = compareMap[compare]; return stencilFunc; } -const compareMap: { [key: string]: IGLStencilFunc } = { + +const compareMap: { [key: string]: GLStencilFunc } = { never: "NEVER", less: "LESS", equal: "EQUAL", @@ -18,13 +18,30 @@ const compareMap: { [key: string]: IGLStencilFunc } = { always: "ALWAYS", }; +/** + * A GLenum specifying the test function. The default function is gl.ALWAYS. + * + * * `NEVER` 总是不通过。 + * * `LESS` 如果 (ref & mask) < (stencil & mask) 则通过。 + * * `EQUAL` 如果 (ref & mask) = (stencil & mask) 则通过。 + * * `LEQUAL` 如果 (ref & mask) <= (stencil & mask) 则通过。 + * * `GREATER` 如果 (ref & mask) > (stencil & mask) 则通过。 + * * `NOTEQUAL` 如果 (ref & mask) != (stencil & mask) 则通过。 + * * `GEQUAL` 如果 (ref & mask) >= (stencil & mask) 则通过。 + * * `ALWAYS` 总是通过。 + * + * https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/stencilFunc + */ +export type GLStencilFunc = "NEVER" | "LESS" | "EQUAL" | "LEQUAL" | "GREATER" | "NOTEQUAL" | "GEQUAL" | "ALWAYS"; + + export function getIGLStencilOp(stencilOperation?: IStencilOperation) { - const glStencilOp: IGLStencilOp = stencilOperationMap[stencilOperation]; + const glStencilOp: GLStencilOp = stencilOperationMap[stencilOperation]; return glStencilOp; } -const stencilOperationMap: { [key: string]: IGLStencilOp } = { +const stencilOperationMap: { [key: string]: GLStencilOp } = { keep: "KEEP", zero: "ZERO", replace: "REPLACE", @@ -33,4 +50,20 @@ const stencilOperationMap: { [key: string]: IGLStencilOp } = { "decrement-clamp": "DECR", "increment-wrap": "INCR_WRAP", "decrement-wrap": "DECR_WRAP", -}; \ No newline at end of file +}; + +/** + * The WebGLRenderingContext.stencilOp() method of the WebGL API sets both the front and back-facing stencil test actions. + * + * * `KEEP` 保持当前值。 + * * `ZERO` 设置模板缓冲值为0 + * * `REPLACE` 将模板缓冲区的值设置为WebGLRenderingContext.stencilFunc()指定的参考值。 + * * `INCR` 增加当前模板缓冲区的值。最大到可表示的无符号值的最大值。 + * * `INCR_WRAP` 增加当前模板缓冲区的值。当增加最大的可表示无符号值时,将模板缓冲区值包装为零。 + * * `DECR` 递减当前模板缓冲区的值。最小为0。 + * * `DECR_WRAP` 递减当前模板缓冲区的值。当模板缓冲区值减为0时,将模板缓冲区值包装为可表示的最大无符号值。 + * * `INVERT` 按位反转当前模板缓冲区值。 + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/stencilOp + */ +export type GLStencilOp = "KEEP" | "ZERO" | "REPLACE" | "INCR" | "INCR_WRAP" | "DECR" | "DECR_WRAP" | "INVERT"; diff --git a/src/shader/ShaderLib.ts b/src/shader/ShaderLib.ts index 84ba3af9f62fb3b8569d2be0bbc3570cad4fd7bf..d0a1e0f190ea58c93502f5020dd0baaf6a919c91 100644 --- a/src/shader/ShaderLib.ts +++ b/src/shader/ShaderLib.ts @@ -127,7 +127,7 @@ export class ShaderLib this._shaderCache = {}; } - private getMacroCode(variables: string[], valueObj: Object) + getMacroCode(variables: string[], valueObj: Object) { let macroHeader = ""; variables.forEach((macroName) => diff --git a/src/utils/ChainMap.ts b/src/utils/ChainMap.ts deleted file mode 100644 index 14e069d664f642d2d84c2c604fbdb892f2947c59..0000000000000000000000000000000000000000 --- a/src/utils/ChainMap.ts +++ /dev/null @@ -1,74 +0,0 @@ -/** - * 链式Map。 - * - * 多个key数组对应一个值。 - * - * 由于键值可能是字面值也可能是对象,因此无法使用 {@link WeakMap} 来构建{@link ChainMap},只能使用 {@link Map}。 - */ -export class ChainMap, V> -{ - private _map = new Map(); - - /** - * 获取键对应的值。 - * - * @param keys 键。 - * @returns 值。 - */ - get(keys: K): V - { - let map = this._map; - - for (let i = 0, n = keys.length - 1; i < n; i++) - { - map = map.get(keys[i]); - - if (map === undefined) return undefined; - } - - return map.get(keys[keys.length - 1]); - } - - /** - * 设置映射。 - * - * @param keys 键。 - * @param value 值。 - */ - set(keys: K, value: V) - { - let map = this._map; - - for (let i = 0; i < keys.length - 1; i++) - { - const key = keys[i]; - - if (map.has(key) === false) map.set(key, new Map()); - - map = map.get(key); - } - - map.set(keys[keys.length - 1], value); - } - - /** - * 删除映射。 - * - * @param keys 键。 - * @returns 如果找到目标值且被删除返回 `true` ,否则返回 `false` 。 - */ - delete(keys: K): boolean - { - let map = this._map; - - for (let i = 0; i < keys.length - 1; i++) - { - map = map.get(keys[i]); - - if (map === undefined) return false; - } - - return map.delete(keys[keys.length - 1]); - } -} - diff --git a/src/utils/getGLRenderPassAttachmentSize.ts b/src/utils/getGLRenderPassAttachmentSize.ts deleted file mode 100644 index 3cb7a0bfb253f561c427b468caae144bd1c266f4..0000000000000000000000000000000000000000 --- a/src/utils/getGLRenderPassAttachmentSize.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { IRenderPassDescriptor } from "@feng3d/render-api"; - -/** - * 获取渲染通道附件尺寸。 - * - * @param gl - * @param descriptor - */ -export function getGLRenderPassAttachmentSize(gl: WebGLRenderingContext, descriptor: IRenderPassDescriptor): { readonly width: number; readonly height: number; } -{ - if (!descriptor) return { width: gl.drawingBufferWidth, height: gl.drawingBufferHeight }; - - const colorAttachments = descriptor.colorAttachments; - if (colorAttachments) - { - for (let i = 0; i < colorAttachments.length; i++) - { - const view = colorAttachments[i].view; - if (view) - { - return { width: view.texture.size[0], height: view.texture.size[1] }; - } - - return { width: gl.drawingBufferWidth, height: gl.drawingBufferHeight }; - } - } - - const depthStencilAttachment = descriptor.depthStencilAttachment; - if (depthStencilAttachment) - { - const view = depthStencilAttachment.view; - if (view) - { - return { width: view.texture.size[0], height: view.texture.size[1] }; - } - - return { width: gl.drawingBufferWidth, height: gl.drawingBufferHeight }; - } - - return { width: gl.drawingBufferWidth, height: gl.drawingBufferHeight }; -} \ No newline at end of file diff --git a/src/utils/getIGLCullFace.ts b/src/utils/getIGLCullFace.ts deleted file mode 100644 index fb670de43ea3d9dc7a92b842aa02ccfc1277db83..0000000000000000000000000000000000000000 --- a/src/utils/getIGLCullFace.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { ICullFace } from "@feng3d/render-api"; - -export function getIGLCullFace(cullFace: ICullFace) -{ - const glCullMode: IGLCullFace = cullFaceMap[cullFace]; - - console.assert(!!glCullMode, `接收到错误值,请从 ${Object.keys(cullFaceMap).toString()} 中取值!`); - - return glCullMode; -} - -const cullFaceMap: { [key: string]: IGLCullFace } = { - FRONT_AND_BACK: "FRONT_AND_BACK", - none: "BACK", // 不会开启剔除面功能,什么值无所谓。 - front: "FRONT", - back: "BACK", -}; - -/** - * 剔除面,默认 BACK,剔除背面。 - * - * 默认情况下,逆时针的顶点连接顺序被定义为三角形的正面。 - * 使用gl.frontFace(gl.CW);调整顺时针为正面 - * - * * FRONT 正面 - * * BACK 背面 - * * FRONT_AND_BACK 正面与背面 - * - * @see http://www.jianshu.com/p/ee04165f2a02 - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/cullFace - */ -export type IGLCullFace = "FRONT" | "BACK" | "FRONT_AND_BACK"; \ No newline at end of file diff --git a/src/utils/getIGLFrontFace.ts b/src/utils/getIGLFrontFace.ts deleted file mode 100644 index de4c9262e6f9db382b4d820cf890d67de7c93aef..0000000000000000000000000000000000000000 --- a/src/utils/getIGLFrontFace.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { IFrontFace } from "@feng3d/render-api"; - -export function getIGLFrontFace(frontFace: IFrontFace) -{ - const glFrontFace: IGLFrontFace = frontFaceMap[frontFace]; - - console.assert(!!glFrontFace, `接收到错误 IFrontFace 值,请从 ${Object.keys(frontFaceMap).toString()} 中取值!`); - - return glFrontFace; -} -const frontFaceMap: { [key: string]: IGLFrontFace } = { - ccw: "CCW", - cw: "CW", -}; - -/** - * 正面方向枚举 - * - * * CW 顺时钟方向 - * * CCW 逆时钟方向 - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/frontFace - */ -export type IGLFrontFace = "CW" | "CCW"; diff --git a/src/utils/getIVertexFormat.ts b/src/utils/getIVertexFormat.ts deleted file mode 100644 index b0161e7db246b96079126247ad5e76df15bd06c2..0000000000000000000000000000000000000000 --- a/src/utils/getIVertexFormat.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { IVertexFormat } from "@feng3d/render-api"; - -export function getIVertexFormat(numComponents: 1 | 2 | 3 | 4, type: IGLVertexAttributeTypes = "FLOAT", normalized = false): IVertexFormat -{ - for (const key in formatMap) - { - const element = formatMap[key]; - if ( - element.numComponents === numComponents - && element.type === type - && !element.normalized === !normalized - ) - { - return key as IVertexFormat; - } - } - - console.error(`没有找到与 ${JSON.stringify({ numComponents, type, normalized })} 对应的顶点数据格式!`); - - return undefined; -} - -export function getIGLVertexFormat(format: IVertexFormat): IGLVertexFormat -{ - const glVertexFormat = formatMap[format]; - - console.assert(!!glVertexFormat, `接收到错误值,请从 ${Object.keys(formatMap).toString()} 中取值!`); - - return glVertexFormat; -} - -export const formatMap: { [key: string]: IGLVertexFormat } = { - - uint8x2: { numComponents: 2, type: "UNSIGNED_BYTE", normalized: false }, - uint8x4: { numComponents: 4, type: "UNSIGNED_BYTE", normalized: false }, - sint8x2: { numComponents: 2, type: "BYTE", normalized: false }, - sint8x4: { numComponents: 4, type: "BYTE", normalized: false }, - unorm8x2: { numComponents: 2, type: "UNSIGNED_BYTE", normalized: true }, - unorm8x4: { numComponents: 4, type: "UNSIGNED_BYTE", normalized: true }, - snorm8x2: { numComponents: 2, type: "BYTE", normalized: true }, - snorm8x4: { numComponents: 4, type: "BYTE", normalized: true }, - uint16x2: { numComponents: 2, type: "UNSIGNED_SHORT", normalized: false }, - uint16x4: { numComponents: 4, type: "UNSIGNED_SHORT", normalized: false }, - sint16x2: { numComponents: 2, type: "SHORT", normalized: false }, - sint16x4: { numComponents: 4, type: "SHORT", normalized: false }, - unorm16x2: { numComponents: 2, type: "UNSIGNED_SHORT", normalized: true }, - unorm16x4: { numComponents: 4, type: "UNSIGNED_SHORT", normalized: true }, - snorm16x2: { numComponents: 2, type: "SHORT", normalized: true }, - snorm16x4: { numComponents: 4, type: "SHORT", normalized: true }, - float16x2: { numComponents: 2, type: "HALF_FLOAT", normalized: false }, - float16x4: { numComponents: 4, type: "HALF_FLOAT", normalized: false }, - float32: { numComponents: 1, type: "FLOAT", normalized: false }, - float32x2: { numComponents: 2, type: "FLOAT", normalized: false }, - float32x3: { numComponents: 3, type: "FLOAT", normalized: false }, - float32x4: { numComponents: 4, type: "FLOAT", normalized: false }, - uint32: { numComponents: 1, type: "UNSIGNED_INT", normalized: false }, - uint32x2: { numComponents: 2, type: "UNSIGNED_INT", normalized: false }, - uint32x3: { numComponents: 3, type: "UNSIGNED_INT", normalized: false }, - uint32x4: { numComponents: 4, type: "UNSIGNED_INT", normalized: false }, - sint32: { numComponents: 1, type: "INT", normalized: false }, - sint32x2: { numComponents: 2, type: "INT", normalized: false }, - sint32x3: { numComponents: 3, type: "INT", normalized: false }, - sint32x4: { numComponents: 4, type: "INT", normalized: false }, - "unorm10-10-10-2": { numComponents: 4, type: "UNSIGNED_INT_2_10_10_10_REV", normalized: true }, -}; - -interface IGLVertexFormat -{ - /** - * 顶点数据元素数量。 - */ - numComponents: 1 | 2 | 3 | 4; - - /** - * 属性缓冲数据类型 - * - * 默认从Buffer数据中获取,如果未取到则默认为 "FLOAT" 。 - */ - type: IGLVertexAttributeTypes; - - /** - * 是否标准化。 - */ - normalized: boolean; -} - -/** - * 属性缓冲数据类型 - * - * A GLenum specifying the data type of each component in the array. Possible values: - * - * * gl.BYTE: signed 8-bit integer, with values in [-128, 127] - * * gl.SHORT: signed 16-bit integer, with values in [-32768, 32767] - * * gl.UNSIGNED_BYTE: unsigned 8-bit integer, with values in [0, 255] - * * gl.UNSIGNED_SHORT: unsigned 16-bit integer, with values in [0,65535] - * * gl.FLOAT: 32-bit IEEE floating point number - * - * When using a WebGL 2 context, the following values are available additionally: - * - * * gl.HALF_FLOAT: 16-bit IEEE floating point number - * * gl.INT: 32-bit signed binary integer - * * gl.UNSIGNED_INT: 32-bit unsigned binary integer - * * gl.INT_2_10_10_10_REV: 32-bit signed integer with values in [-512, 511] - * * gl.UNSIGNED_INT_2_10_10_10_REV: 32-bit unsigned integer with values in [0, 1023] - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer - */ -export type IGLVertexAttributeTypes = "FLOAT" | "BYTE" | "SHORT" | "UNSIGNED_BYTE" | "UNSIGNED_SHORT" // WebGL1 - | "HALF_FLOAT" | "INT" | "UNSIGNED_INT" | "INT_2_10_10_10_REV" | "UNSIGNED_INT_2_10_10_10_REV"; // WebGL2 - -/** - * A GLenum specifying the data type of each component in the array. Must be one of: - * * gl.BYTE - * * gl.UNSIGNED_BYTE - * * gl.SHORT - * * gl.UNSIGNED_SHORT - * * gl.INT - * * gl.UNSIGNED_INT. - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext/vertexAttribIPointer - */ -export type IGLVertexAttributeIntegerTypes = "BYTE" | "UNSIGNED_BYTE" | "SHORT" | "UNSIGNED_SHORT" | "INT" | "UNSIGNED_INT"; \ No newline at end of file diff --git a/src/utils/getTextureCubeMapTarget.ts b/src/utils/getTextureCubeMapTarget.ts deleted file mode 100644 index fbdd30653d4cef5cd743b89c82242b021a2236b5..0000000000000000000000000000000000000000 --- a/src/utils/getTextureCubeMapTarget.ts +++ /dev/null @@ -1,37 +0,0 @@ -export function getTextureCubeMapTarget(depthOrArrayLayers: number) -{ - const textureCubeMapTarget: IGLTextureCubeMapTarget = textureCubeMapTargetMap[depthOrArrayLayers]; - - console.assert(!!textureCubeMapTarget, `CubeMap的depthOrArrayLayers值应在[0-5]之间!`); - - return textureCubeMapTarget; -} - -const textureCubeMapTargetMap: IGLTextureCubeMapTarget[] = [ - "TEXTURE_CUBE_MAP_POSITIVE_X", - "TEXTURE_CUBE_MAP_NEGATIVE_X", - "TEXTURE_CUBE_MAP_POSITIVE_Y", - "TEXTURE_CUBE_MAP_NEGATIVE_Y", - "TEXTURE_CUBE_MAP_POSITIVE_Z", - "TEXTURE_CUBE_MAP_NEGATIVE_Z", -]; - -/** - * A GLenum specifying the texture target. - * - * gl.TEXTURE_CUBE_MAP_POSITIVE_X: Positive X face for a cube-mapped texture. - * gl.TEXTURE_CUBE_MAP_NEGATIVE_X: Negative X face for a cube-mapped texture. - * gl.TEXTURE_CUBE_MAP_POSITIVE_Y: Positive Y face for a cube-mapped texture. - * gl.TEXTURE_CUBE_MAP_NEGATIVE_Y: Negative Y face for a cube-mapped texture. - * gl.TEXTURE_CUBE_MAP_POSITIVE_Z: Positive Z face for a cube-mapped texture. - * gl.TEXTURE_CUBE_MAP_NEGATIVE_Z: Negative Z face for a cube-mapped texture. - * - * https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texImage2D - */ -export type IGLTextureCubeMapTarget = - | "TEXTURE_CUBE_MAP_POSITIVE_X" - | "TEXTURE_CUBE_MAP_NEGATIVE_X" - | "TEXTURE_CUBE_MAP_POSITIVE_Y" - | "TEXTURE_CUBE_MAP_NEGATIVE_Y" - | "TEXTURE_CUBE_MAP_POSITIVE_Z" - | "TEXTURE_CUBE_MAP_NEGATIVE_Z"; diff --git a/src/utils/readPixels.ts b/src/utils/readPixels.ts index 058272dd365a63e4e77ea8b10bd952578495cc25..6ce477abbeef6b5b0d9af89a9f6812bb84815c4c 100644 --- a/src/utils/readPixels.ts +++ b/src/utils/readPixels.ts @@ -1,20 +1,64 @@ -import { getGLFramebuffer } from "../caches/getGLFramebuffer"; -import { IGLReadPixels } from "../data/IGLReadPixels"; +import { ReadPixels, RenderPassDescriptor, Texture } from "@feng3d/render-api"; +import { deleteFramebuffer, getGLFramebuffer } from "../caches/getGLFramebuffer"; +import { getGLTextureFormats } from "../caches/getGLTextureFormats"; -export function readPixels(gl: WebGLRenderingContext, readPixels: IGLReadPixels) +export function readPixels(gl: WebGLRenderingContext, readPixels: ReadPixels) { + let bufferData:ArrayBufferView; + if (gl instanceof WebGL2RenderingContext) { - const { frameBuffer, attachmentPoint, x, y, width, height, format, type, dstData, dstOffset } = readPixels; - + const { textureView, origin, copySize } = readPixels; + const attachmentPoint: GLAttachmentPoint = "COLOR_ATTACHMENT0"; + const [width, height] = copySize; + // + const { format, type } = getGLTextureFormats(textureView.texture.format); + const bytesPerPixel = Texture.getTextureBytesPerPixel(textureView.texture.format); + const dataConstructor = Texture.getTextureDataConstructor(textureView.texture.format); + // + const bytesPerRow = width * bytesPerPixel; + const bufferSize = bytesPerRow * height; + bufferData = new dataConstructor(bufferSize / dataConstructor.BYTES_PER_ELEMENT); + // + const frameBuffer: RenderPassDescriptor = { + colorAttachments: [ + { view: textureView }, + ] + }; + // const webGLFramebuffer = getGLFramebuffer(gl, frameBuffer); gl.bindFramebuffer(gl.FRAMEBUFFER, webGLFramebuffer); + // gl.readBuffer(gl[attachmentPoint]); - gl.readPixels(x, y, width, height, gl[format], gl[type], dstData, dstOffset); + gl.readPixels(origin[0], origin[1], width, height, gl[format], gl[type], bufferData, 0); + + // 释放 + deleteFramebuffer(gl, frameBuffer); } else { console.error(`WebGL1 不支持 readBuffer/readPixels !`); } + + return bufferData; } + +/** + * A GLenum specifying the attachment point for the texture. Possible values: + * + * gl.COLOR_ATTACHMENT0: Attaches the texture to the framebuffer's color buffer. + * gl.DEPTH_ATTACHMENT: Attaches the texture to the framebuffer's depth buffer. + * gl.STENCIL_ATTACHMENT: Attaches the texture to the framebuffer's stencil buffer. + * + * When using a WebGL 2 context, the following values are available additionally: + * + * gl.DEPTH_STENCIL_ATTACHMENT: depth and stencil buffer. + * gl.COLOR_ATTACHMENT1 gl.COLOR_ATTACHMENT2 gl.COLOR_ATTACHMENT3 gl.COLOR_ATTACHMENT4 gl.COLOR_ATTACHMENT5 gl.COLOR_ATTACHMENT6 gl.COLOR_ATTACHMENT7 gl.COLOR_ATTACHMENT8 gl.COLOR_ATTACHMENT9 gl.COLOR_ATTACHMENT10 gl.COLOR_ATTACHMENT11 gl.COLOR_ATTACHMENT12 gl.COLOR_ATTACHMENT13 gl.COLOR_ATTACHMENT14 gl.COLOR_ATTACHMENT15 + */ +export type GLAttachmentPoint = "COLOR_ATTACHMENT0" | "DEPTH_ATTACHMENT" | "STENCIL_ATTACHMENT" + | "DEPTH_STENCIL_ATTACHMENT" + | "COLOR_ATTACHMENT1" | "COLOR_ATTACHMENT2" | "COLOR_ATTACHMENT3" | "COLOR_ATTACHMENT4" | "COLOR_ATTACHMENT5" + | "COLOR_ATTACHMENT6" | "COLOR_ATTACHMENT7" | "COLOR_ATTACHMENT8" | "COLOR_ATTACHMENT9" | "COLOR_ATTACHMENT10" + | "COLOR_ATTACHMENT11" | "COLOR_ATTACHMENT12" | "COLOR_ATTACHMENT13" | "COLOR_ATTACHMENT14" | "COLOR_ATTACHMENT15" + ; diff --git a/src/utils/updateBufferBinding.ts b/src/utils/updateBufferBinding.ts index 032e6c6b9d129377f4044393c5a7a824ea8b7651..1469ee5a0445c73994c9426fb67f0373854f46ab 100644 --- a/src/utils/updateBufferBinding.ts +++ b/src/utils/updateBufferBinding.ts @@ -1,6 +1,5 @@ -import { IBufferBinding, UnReadonly } from "@feng3d/render-api"; +import { BufferBinding, BufferBindingInfo, UnReadonly, GBuffer } from "@feng3d/render-api"; import { watcher } from "@feng3d/watcher"; -import { IBufferBindingInfo } from "../caches/getGLProgram"; import { getIGLBuffer } from "../runs/getIGLBuffer"; /** @@ -10,11 +9,11 @@ import { getIGLBuffer } from "../runs/getIGLBuffer"; * * @see https://learnopengl-cn.readthedocs.io/zh/latest/04%20Advanced%20OpenGL/08%20Advanced%20GLSL/#uniform_1 */ -export function updateBufferBinding(bufferBindingInfo: IBufferBindingInfo, uniformData: IBufferBinding) +export function updateBufferBinding(bufferBindingInfo: BufferBindingInfo, uniformData: BufferBinding) { if (uniformData["_bufferBindingInfo"] !== undefined) { - const preVariableInfo = uniformData["_bufferBindingInfo"] as any as IBufferBindingInfo; + const preVariableInfo = uniformData["_bufferBindingInfo"] as any as BufferBindingInfo; if (preVariableInfo.size !== bufferBindingInfo.size) { console.warn(`updateBufferBinding 出现一份数据对应多个 variableInfo`, { uniformData, bufferBindingInfo, preVariableInfo }); @@ -30,7 +29,7 @@ export function updateBufferBinding(bufferBindingInfo: IBufferBindingInfo, unifo const hasDefautValue = !!uniformData.bufferView; if (!hasDefautValue) { - (uniformData as UnReadonly).bufferView = new Uint8Array(size); + (uniformData as UnReadonly).bufferView = new Uint8Array(size); } else { @@ -62,7 +61,7 @@ export function updateBufferBinding(bufferBindingInfo: IBufferBindingInfo, unifo } } - let data: Float32Array | Int32Array | Uint32Array; + let data: Int16Array | Int32Array | Uint32Array | Float32Array; if (typeof value === "number") { data = new Cls([value]); @@ -78,7 +77,7 @@ export function updateBufferBinding(bufferBindingInfo: IBufferBindingInfo, unifo const writeBuffers = buffer.writeBuffers ?? []; writeBuffers.push({ data: data.buffer, bufferOffset: offset + itemInfoOffset, size: Math.min(itemInfoSize, data.byteLength) }); - buffer.writeBuffers = writeBuffers; + (buffer as UnReadonly).writeBuffers = writeBuffers; }; update();