### WebGPU Device and Context Setup Source: https://github.com/maptalks/maptalks.js/blob/master/debug/webgpu/cube-texture.html Requests a WebGPU adapter and device, then gets the rendering context from the canvas element. ```javascript const adapter = await navigator.gpu?.requestAdapter(); const gpuDevice = await adapter?.requestDevice(); const canvas = document.getElementById('canvas'); const context = canvas.getContext('webgpu'); ``` -------------------------------- ### WebGPU Initialization and Setup Source: https://github.com/maptalks/maptalks.js/blob/master/debug/webgpu/cube-instance.html Initializes the WebGPU device, context, and reshader.gl components including GraphicsDevice, Renderer, MeshShader, and Geometry. This setup is required before rendering. ```javascript const adapter = await navigator.gpu?.requestAdapter(); const gpuDevice = await adapter?.requestDevice(); const canvas = document.getElementById('canvas'); const context = canvas.getContext('webgpu'); const device = new GraphicsDevice(gpuDevice, context) const renderer = new Renderer(device); const shader = new MeshShader({ wgslVert, wgslFrag, name: 'cube-instance', extraCommandProps: { cull: { enable: true } } }); const geometry = new Geometry({ position: cubeVertexArray }, cubeVertexCount, 0, { positionAttribute: 'position', positionSize: 4 }); geometry.generateBuffers(device); ``` -------------------------------- ### WebGPU Initialization and Setup Source: https://github.com/maptalks/maptalks.js/blob/master/debug/webgpu/wgsl-include.html Initializes the WebGPU device, context, and resource loader. Sets up the canvas and context for rendering. ```javascript const adapter = await navigator.gpu?.requestAdapter(); const gpuDevice = await adapter?.requestDevice(); const canvas = document.getElementById('canvas'); const context = canvas.getContext('webgpu'); const resourceLoader = new ResourceLoader(new Uint8Array(4)); const device = new GraphicsDevice(gpuDevice, context) ``` -------------------------------- ### Scene and Material Setup Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/pbr-sketchfab.html Creates a scene with a sphere mesh and applies PBR material properties. ```javascript function getScene() { const meshes = []; //创建纹理 const material = new reshader.pbr.StandardMaterial(MatUNIFORMS); const { data, indices } = generateSphereData(); delete data.aTangent; ``` -------------------------------- ### Material and Texture Setup Source: https://github.com/maptalks/maptalks.js/blob/master/debug/webgpu/wgsl-include.html Creates a material and loads a texture for the cube. The texture is specified by its URL and associated with the material. ```javascript const material = new Material({ myTexture: new Texture2D({ url: './Di-3d.png', }, resourceLoader) }); ``` -------------------------------- ### Scene and Camera Setup Source: https://github.com/maptalks/maptalks.js/blob/master/debug/webgpu/phong.html Initializes the scene and sets up the perspective projection and view matrices for the camera. Uses gl-matrix for transformations. ```javascript const scene = new Scene(); const aspect = canvas.width / canvas.height; const projectionMatrix = perspectiveZO([], (2 * Math.PI) / 5, aspect, 1, 100.0); const modelViewProjectionMatrix = mat4.create(); const viewMatrix = mat4.identity([]); const translation = [0, 0, -4] const axis = [] const upVector = vec3.set([], 0, 1, 0); const origin = vec3.set([], 0, 0, 0); const eyePosition = [4, -4, 4]; const cameraViewProjMatrix = mat4.create(); ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/maptalks/maptalks.js/blob/master/README.md Use this command to install all project dependencies. Ensure you have pnpm@9.x installed. ```shell pnpm i ``` -------------------------------- ### Main rendering function setup Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/pbr-pbrglossiness.html The main function initializes PBR helper data, sets up uniforms, and initiates the rendering loop. ```javascript function main() { const dfgLUT = reshader.pbr.PBRHelper.generateDFGLUT(regl); UNIFORMS = { 'uGlobalTexSize': [canvas.width, canvas.height], 'uEnvironmentExposure': 2, 'sIntegrateBRDF': dfgLUT, 'uDiffuseSPH': iblMaps.sh, 'uAmbientColor': [0.3, 0.3, 0.3], 'uSketchfabLight0_diffuse': [1.4192, 1.3973, 1.4269, 1], 'uSketchfabLight0_viewDirection': [0.6170, 0.6895, -0.3793] }; render(); } main(); ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/maptalks/maptalks.js/wiki/Begin-Plugin-Develop Installs all necessary project dependencies using npm. ```shell npm install ``` -------------------------------- ### WebGPU Initialization and Rendering Setup Source: https://github.com/maptalks/maptalks.js/blob/master/debug/webgpu/shadowmapping.html Initializes the WebGPU device, context, and renderer. Sets up shaders, geometry, and meshes for rendering the scene and shadow map. ```javascript const adapter = await navigator.gpu?.requestAdapter(); const gpuDevice = await adapter?.requestDevice(); const canvas = document.getElementById('canvas'); const context = canvas.getContext('webgpu'); const device = new GraphicsDevice(gpuDevice, context, adapter); const renderer = new Renderer(device); const shadowShader = new MeshShader({ wgslVert: vertShadow, // frag: fragShadow, name: 'shadow', extraCommandProps: { depth: { enable: true, func: '<' }, cull: { enable: true } } }); const shader = new MeshShader({ wgslVert: vert, wgslFrag: frag, name: 'cube', extraCommandProps: { depth: { enable: true, func: '<=' }, cull: { enable: true } } }); const geometry = new Geometry({ position: cubeVertexArray }, cubeVertexCount, 0, { positionAttribute: 'position' }); geometry.generateBuffers(device); const mesh = new Mesh(geometry); const groundGeometry = new Geometry({ position: getGroundVertexes() }, 6, 0, { positionAttribute: 'position' }); groundGeometry.generateBuffers(device); const groundMesh = new Mesh(groundGeometry); const scene = new Scene(); const depthTexture = new GraphicsTexture(device, { width: 1024, height: 1024, format: 'depth', compare: 'less' }); const shadowFBO = device.framebuffer({ color: null, depth: depthTexture, width: 1024, height: 1024 }); function render() { device.clear({ color: [0, 0, 0, 0], depth: 1 }); const cameraViewProjMatrix = getCameraViewProjMatrix(); const { lightViewProjMatrix, lightPos } = getLightMatrix(); scene.setMeshes([mesh, groundMesh]); const uniforms = { cameraViewProjMatrix, lightViewProjMatrix, lightPos }; renderer.render(shadowShader, uniforms, scene, shadowFBO); renderer.render(shader, { cameraViewProjMatrix, lightViewProjMatrix, lightPos, shadowMap: shadowFBO.depthTexture }, scene); device.sub ``` -------------------------------- ### Initialize REGL and Reshader Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/picking.html Sets up the REGL context and imports necessary modules from maptalksgl. This is the initial setup for rendering and picking. ```javascript import cubeData from './common/cube.js'; const { createREGL, mat4, reshader } = maptalksgl; const regl = createREGL({ canvas : canvas }); ``` -------------------------------- ### Instance Data and Transformation Setup Source: https://github.com/maptalks/maptalks.js/blob/master/debug/webgpu/cube-instance.html Prepares the instance data arrays and calculates initial model matrices for each cube instance. This includes setting up projection and view matrices. ```javascript const xCount = 4; const yCount = 4; const numInstances = xCount * yCount; const instanceData = { 'instance_vectorA': new Float32Array(numInstances * 4), 'instance_vectorB': new Float32Array(numInstances * 4), 'instance_vectorC': new Float32Array(numInstances * 4) }; const aspect = canvas.width / canvas.height; const projectionMatrix = perspectiveZO([], (2 * Math.PI) / 5, aspect, 1, 100.0); const viewMatrix = mat4.fromTranslation([], [0, 0, -12]); const projViewMatrix = mat4.multiply([], projectionMatrix, viewMatrix); const modelMatrices = new Array(numInstances); const translation = []; const step = 4.0; // Initialize the matrix data for every instance. let m = 0; for (let x = 0; x < xCount; x++) { for (let y = 0; y < yCount; y++) { const translate = vec3.set(translation, step * (x - xCount / 2 + 0.5), step * (y - yCount / 2 + 0.5), 0); modelMatrices[m] = mat4.fromTranslation([], translate); m++; } } const tmpMat4 = []; updateTransformationMatrix(instanceData); ``` -------------------------------- ### WebGPU Cube Rendering Setup Source: https://github.com/maptalks/maptalks.js/blob/master/debug/webgpu/cube.html Initializes the WebGPU device, context, and reshader components for rendering. Requires a canvas element with id 'canvas'. ```javascript const adapter = await navigator.gpu?.requestAdapter(); const gpuDevice = await adapter?.requestDevice(); const canvas = document.getElementById('canvas'); const context = canvas.getContext('webgpu'); const device = new GraphicsDevice(gpuDevice, context) ``` -------------------------------- ### Start Rendering Source: https://github.com/maptalks/maptalks.js/blob/master/debug/webgpu/cube.html Initiates the rendering process by calling the render function once to begin the animation loop. ```javascript render(); ``` -------------------------------- ### Scene Setup Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/picking.html Creates two scenes, each containing a mesh. This is used for rendering and picking different objects. ```javascript function getScene() { const mesh1 = getMesh(0, [0,0,0]); const mesh2 = getMesh(1, [3,0,0]); //const scene = new reshader.Scene([mesh1, mesh2]); //return scene; const scene1 = new reshader.Scene([mesh1]); const scene2 = new reshader.Scene([mesh2]); return { scene1, scene2 }; } ``` -------------------------------- ### Install maptalks-gl using npm Source: https://github.com/maptalks/maptalks.js/blob/master/README.md Use npm to install the maptalks-gl package. ```shell npm i maptalks-gl ``` -------------------------------- ### Install maptalks.gltf Layer Source: https://github.com/maptalks/maptalks.js/blob/master/packages/layer-gltf/README.md Install the glTF layer package using npm or include it via a CDN. ```bash npm install @maptalks/gltf-layer ``` ```html ``` -------------------------------- ### Initialize PBR Shaders and Passes Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/pbr-sketchfab-model.html Initializes the Jitter, TaaPass, and FxaaShader for rendering. This setup is typically done once before the main rendering loop. ```javascript function drawGLTFModel() { const viewport = { x: 0, y: 0, width: canvas.width, height: canvas.height }; jitter = new reshader.Jitter(0.8); taaPass = new reshader.TaaPass(renderer, viewport, jitter); fxaaShader = new reshader.FxaaShader(viewport); SHADER = new reshader.pbr.StandardShader({ positionAttribute : 'POSITION', normalAttribute : 'NORMAL', tangentAttribute : 'TANGENT', colorAttribute : 'COLOR_0', uv0Attribute : 'TEXCOORD_0', uv1Attribute : 'TEXCOORD_1', extraCommandProps: { cull: { enable: true, face: 'back' } }, defines: { 'HAS_IBL_LIGHTING': 1 } }); const scenePromise = getGLTFScene(); scenePromise.then(scene => { SCENE = scene; drawScene(); }); } ``` -------------------------------- ### Main Scene Setup and Texture Loading Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/pbr-sketchfab.html Loads skybox and PBR textures, then initializes IBL maps and PBR textures for rendering. ```javascript function main() { const skyboxTextures = [ // "./ibl/resources/skybox/right.jpg", // "./ibl/resources/skybox/left.jpg", // "./ibl/resources/skybox/top.jpg", // "./ibl/resources/skybox/bottom.jpg", // "./ibl/resources/skybox/back.jpg", // "./ibl/resources/skybox/front.jpg", "./ibl/resources/color_box/right.jpg", "./ibl/resources/color_box/left.jpg", "./ibl/resources/color_box/top.jpg", "./ibl/resources/color_box/bottom.jpg", "./ibl/resources/color_box/back.jpg", "./ibl/resources/color_box/front.jpg" ]; //载入天空盒纹理图片 const promises = skyboxTextures.map(url => new Promise(function (resolve, reject) { const img = new Image(); img.onload = function () { resolve(img); }; img.src = url; })); const textures = [ // "./ibl/resources/rusted_iron/normal.png", "./ibl/resources/rusted_iron/609-normal.jpg", "./ibl/resources/rusted_iron/occulusionRoughnessMetallicMap-1024.png", "./ibl/resources/rusted_iron/albedo.png", // "./ibl/resources/rusted_iron/normal.png", ]; promises.push(...textures.map(url => new Promise(function (resolve, reject) { const img = new Image(); img.onload = function () { resolve(img); }; img.src = url; }))); Promise.all(promises).then(images => { iblMaps = createMaps(images.slice(0, 6)); NORMAL_TEXTURE = new reshader.Texture2D(regl.texture(images[6])); ROUGHNESS_METALLIC_TEXTURE = new reshader.Texture2D(regl.texture(images[7])); BASE_COLOR_TEXTURE = new reshader.Texture2D(regl.texture(images[8])); // CLEAR_COAT_NORMAL_TEXTURE = new reshader.Texture2D(regl.texture(images[9])); const mipLevel = Math.log(PREFILTER_CUBE_SIZE) / Math.log(2); UNIFORMS = { 'uGlobalTexSize': [canvas.width, canvas.height], 'uHalton': [0, 0], 'uSketchfabLight0_diffuse': [0.1747, 0.1375, 0.1065, 1], 'sIntegrateBRDF': iblMaps.dfgLUT, 'sSpecularPBR': iblMaps.prefilterMap, 'uDiffuseSPH': iblMaps.sh, 'uTextureEnvironmentSpecularPBRLodRange': [mipLevel, mipLevel], 'uTextureEnvironmentSpecularPBRTextureSize': [PREFILTER_CUBE_SIZE, PREFILTER_CUBE_SIZE], 'lightColorIntensity': [1, 1, 1, 30000], 'sun': [1, 1, 1, -1], 'uSketchfabLight0_viewDirection': [1, 0, -1], 'uEnvironmentExposure': 1, }; MatUNIFORMS = { 'uAlbedo': [10 / 255, 10 / 255, 10 / 255, 1], 'uRoughnessPBRFactor': 0.3, 'uAnisotropyFactor': 0, 'uClearCoatFactor': 0, 'uMetalnessPBRFactor': 1 }; initGUI(); render(); }); } main(); ``` -------------------------------- ### Install maptalks-gl using pnpm Source: https://github.com/maptalks/maptalks.js/blob/master/README.md Use pnpm to install the maptalks-gl package. ```shell pnpm i maptalks-gl ``` -------------------------------- ### Camera and Light Matrix Setup Source: https://github.com/maptalks/maptalks.js/blob/master/debug/webgpu/shadowmapping.html Initializes vectors and matrices for camera and light transformations. This includes setting up perspective and orthographic projections, view matrices, and combining them for shadow mapping. ```javascript const upVector = vec3.set([], 0, 1, 0); const origin = vec3.set([], 0, 0, 0); const aspect = canvas.width / canvas.height; const projectionMatrix = perspectiveZO([], (2 * Math.PI) / 5, aspect, 1, 100.0); const cameraViewProjMatrix = mat4.create(); const viewMatrix = mat4.identity([]); const axis = []; const eyePosition = [4, -4, 4]; function getCameraViewProjMatrix() { mat4.identity(viewMatrix); mat4.lookAt(viewMatrix, eyePosition, origin, upVector); mat4.multiply(cameraViewProjMatrix, projectionMatrix, viewMatrix); return cameraViewProjMatrix; } // light related matrices const lightPosition = vec3.set([], -7, -4, 5); const lightViewMatrix = mat4.lookAt([], lightPosition, origin, upVector); const lightProjectionMatrix = []; { const left = -10; const right = 10; const bottom = -10; const top = 10; const near = 1; const far = 20; mat4.ortho(lightProjectionMatrix, left, right, bottom, top, near, far); } const lightViewProjMatrix = mat4.multiply([], lightProjectionMatrix, lightViewMatrix); function getLightMatrix() { return { lightViewProjMatrix, lightPos: lightPosition }; } ``` -------------------------------- ### Projection Matrix Setup Source: https://github.com/maptalks/maptalks.js/blob/master/debug/webgpu/cube-texture.html Calculates the perspective projection matrix for the scene. ```javascript const aspect = canvas.width / canvas.height; const projectionMatrix = perspectiveZO([], (2 * Math.PI) / 5, aspect, 1, 100.0); ``` -------------------------------- ### Get Scene Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/bloom.html Constructs the scene graph, including meshes with PBR materials and geometry. Sets up transformations and defines. ```javascript function getScene() { const meshes = []; //创建纹理 const material = new reshader.pbr.StandardMaterial(MatUNIFORMS); const { data, indices } = generateSphereData(); delete data.aTangent; const modelMatrix = mat4.identity([]); mat4.scale(modelMatrix, modelMatrix, [0.4, 0.4, 0.4]); const geometry = new reshader.Geometry(data, indices, 0, { uv0Attribute: 'aTexCoord0' }); geometry.createTangent('aTangent'); const defines = getGeometryDefines(geometry); const mesh = new reshader.Mesh(geometry, material); mesh.setLocalTransform(modelMatrix); mesh.setDefines(defines); meshes.push(mesh); return new reshader.Scene(meshes); } ``` -------------------------------- ### Publish Plugin to npm Source: https://github.com/maptalks/maptalks.js/wiki/Begin-Plugin-Develop Execute this command to publish your plugin to the npm registry, making it available for installation by others. ```shell npm publish ``` -------------------------------- ### Compile Project with pnpm Source: https://github.com/maptalks/maptalks.js/blob/master/README.md Run this command to compile the project. This is typically done after installing dependencies or making code changes. ```shell pnpm build ``` -------------------------------- ### Configure Baidu Tile Layer in Maptalks Source: https://github.com/maptalks/maptalks.js/wiki/Tile-System Example of setting up a Baidu map tile layer. The tileSystem is specified as [1,1,0,0]. ```javascript //baidu tile service new maptalks.TileLayer("baidu",{ tileSystem:[1,1,0,0], urlTemplate:'http://online{s}.map.bdimg.com/onlinelabel/?qt=tile&x={x}&y={y}&z={z}&styles=pl&scaler=1&p=1', subdomains:[0,1,2,3,4,5,6,7,8,9] }); ``` -------------------------------- ### Configure OSM Tile Layer in Maptalks Source: https://github.com/maptalks/maptalks.js/wiki/Tile-System Example of setting up an OpenStreetMap tile layer. The default tileSystem can be used, so it doesn't need to be explicitly specified. ```javascript //osm's tile service with default tileSystem, so we don't need to specify in options new maptalks.TileLayer("osm",{ //tileSystem : [1, -1, -20037508.34, 20037508.34], urlTemplate : 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', subdomains : ['a','b','c'] }); ``` -------------------------------- ### Create a Simple PBR Scene with a Sphere Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/pbr-standard.html Constructs a basic scene containing a single sphere mesh with a standard PBR material. This is a minimal example for setting up a PBR scene. ```javascript function getScene() { const meshes = []; //创建纹理 const material = new reshader.pbr.StandardMaterial(MatUNIFORMS); const { data, indices } = generateSphereData(); const modelMatrix = mat4.identity([]); mat4.scale(modelMatrix, modelMatrix, [0.4, 0.4, 0.4]); const geometry = new reshader.Geometry(data, indices, 0, { uv0Attribute: 'aTexCoord0' }); geometry.createTangent('aTangent'); const defines = getGeometryDefines(geometry); mesh = new reshader.Mesh(geometry, material); mesh.setLocalTransform(modelMatrix); mesh.setDefines(defines); meshes.push(mesh); return new reshader.Scene(meshes); } ``` -------------------------------- ### Matrix Transformation Example Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/bloom.html Demonstrates the creation of a model matrix and its conversion to a normal matrix using maptalksgl.mat3.fromMat4. This is useful for understanding 3D transformations. ```javascript function myTest() { const modelMatrix = [1, -0.0000, 0.0000, 0, 0.0000, 0, 1, 0, 0.0000, -1, -0.0000, 0, -34.5294, 143.0380, -523.5370, 1]; const modelNormalMatrix = maptalksgl.mat3.fromMat4([], modelMatrix); console.log(modelNormalMatrix); } myTest(); ``` -------------------------------- ### Matrix and Camera Setup Source: https://github.com/maptalks/maptalks.js/blob/master/debug/webgpu/cube.html Defines projection and view matrices, including a perspective projection and a camera lookAt function, for transforming cube vertices. ```javascript const aspect = canvas.width / canvas.height; const projectionMatrix = perspectiveZO([], (2 * Math.PI) / 5, aspect, 1, 100.0); const modelViewProjectionMatrix = mat4.create(); const viewMatrix = mat4.identity([]); const translation = [0, 0, -4]; const axis = []; const upVector = vec3.set([], 0, 1, 0); const origin = vec3.set([], 0, 0, 0); const eyePosition = [4, -4, 4]; const cameraViewProjMatrix = mat4.create(); function getTransformationMatrix() { mat4.identity(viewMatrix); mat4.lookAt(viewMatrix, eyePosition, origin, upVector); mat4.multiply(cameraViewProjMatrix, projectionMatrix, viewMatrix); return cameraViewProjMatrix; } function perspectiveZO(out, fovy, aspect, near, far) { const f = 1.0 / Math.tan(fovy / 2); out[0] = f / aspect; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = f; out[6] = 0; out[7] = 0; out[8] = 0; out[9] = 0; out[11] = -1; out[12] = 0; out[13] = 0; out[15] = 0; if (far != null && far !== Infinity) { const nf = 1 / (near - far); out[10] = far * nf; out[14] = far * near * nf; } else { out[10] = -1; out[14] = -near; } return out; } ``` -------------------------------- ### Initial Render Call Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/skyline.html Initiates the rendering process by calling the render function, which in turn fetches scene data and starts the animation loop. ```javascript function render() { const scenePromise = getScene(); scenePromise.then(meshes => { scene.addMesh(meshes); }); drawAll(); } render(); ``` -------------------------------- ### Setup PBR Shader with Uniforms and Defines Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/gltf.html Configures a PBR mesh shader with standard vertex and fragment shaders. It defines uniforms, including matrices and lighting properties, and sets up shader compilation defines. ```javascript const shader = new reshader.MeshShader({ vert : reshader.pbr.StandardVert, frag : reshader.pbr.StandardFrag, uniforms : [ 'camPos', 'dirLightDirections[1]', 'dirLightColors[1]', 'ambientColor', 'ambientIntensity', 'irradianceMap', 'prefilterMap', 'brdfLUT', { name : 'projViewModelMatrix', type : 'function', fn : function (context, props) { const projViewModelMatrix = []; mat4.multiply(projViewModelMatrix, props['viewMatrix'], props['modelMatrix']); mat4.multiply(projViewModelMatrix, props['projMatrix'], projViewModelMatrix); return projViewModelMatrix; } }, { name : 'viewModelMatrix', type : 'function', fn : function (context, props) { const viewModelMatrix = []; mat4.multiply(viewModelMatrix, props['viewMatrix'], props['modelMatrix']); return viewModelMatrix; } } ], defines : { // 'NUM_OF_SPOT_LIGHTS' : '(4' ``` -------------------------------- ### Define Global Uniforms and Scene Setup Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/phong-glossiness.html Initializes global uniforms for lighting and scene properties, and sets up the rendering pipeline. This includes defining the Phong shader and loading GLTF scenes. ```javascript UNIFORMS = { 'globalTexSize': [canvas.width, canvas.height], 'lightAmbient': [0.1, 0.1, 0.1], 'lightSpecular': [1, 1, 1], 'lightDiffuse': [1.4192, 1.3973, 1.4269], 'lightDirection': [0.6170, 0.6895, -0.3793] }; SHADER = new reshader.PhongShader({ positionAttribute : 'POSITION', normalAttribute : 'NORMAL', tangentAttribute : 'TANGENT', colorAttribute : 'COLOR_0', uv0Attribute : 'TEXCOORD_0', uv1Attribute : 'TEXCOORD_1', extraCommandProps: { cull: { enable: true, face: 'back' } }, defines: { // 'HAS_IBL_LIGHTING': 1 } }); const scenePromise = getGLTFScene(); scenePromise.then(scene => { SCENE = scene; drawScene(); }); ``` -------------------------------- ### Main Function: Load Skybox and Initialize PBR Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/pbr-model.html Loads skybox textures, creates IBL maps (including prefiltered specular and diffuse LUTs), computes EV100 for lighting, and initializes the GUI. This function orchestrates the setup for PBR rendering. ```javascript function main() { const skyboxTextures = [ "./ibl/resources/skybox_bridge/posx.jpg", "./ibl/resources/skybox_bridge/negx.jpg", "./ibl/resources/skybox_bridge/posy.jpg", "./ibl/resources/skybox_bridge/negy.jpg", "./ibl/resources/skybox_bridge/posz.jpg", "./ibl/resources/skybox_bridge/negz.jpg" ]; const promises = skyboxTextures.map(url => new Promise(function (resolve, reject) { const img = new Image(); img.onload = function () { resolve(img); }; img.src = url; })); Promise.all(promises).then(images => { iblMaps = createMaps(images.slice(0, 6)); const aperture = 16; const speed = 1 / 125; const iso = 100; const ev100 = computeEV100(aperture, speed, iso); UNIFORMS = { 'light_iblDFG': iblMaps.dfgLUT, 'light_iblSpecular': iblMaps.prefilterMap, 'resolution': [canvas.width, canvas.height, 1 / canvas.width, 1 / canvas.height], 'cameraPosition': camPos, 'iblSH': iblMaps.sh, 'lightColorIntensity': [0.98, 0.92, 0.89, 30000], 'sun': [1, 1, 1, -1], 'lightDirection': [1, 1, -1], 'iblLuminance': 8000, 'exposure': EV100toExposure(ev100), 'ev100': ev100, }; MatUNIFORMS = { 'baseColorFactor': [0.660, 0.609, 0.526, 1], 'metallicFactor': 1, 'roughnessFactor': 0.65, 'reflectance': 0.47, 'clearCoat': 0, 'clearCoatRoughness': 0.3, }; initGUI(); render(); }); } main(); ``` -------------------------------- ### Initialize WebGPU and Renderer Source: https://github.com/maptalks/maptalks.js/blob/master/debug/webgpu/phong.html Sets up the WebGPU device, context, and the reshader.gl renderer. Requires a canvas element with id 'canvas'. ```javascript const adapter = await navigator.gpu?.requestAdapter(); const gpuDevice = await adapter?.requestDevice(); const canvas = document.getElementById('canvas'); const context = canvas.getContext('webgpu'); const device = new GraphicsDevice(gpuDevice, context) const renderer = new Renderer(device); ``` -------------------------------- ### Install Maptalks.js via NPM Source: https://github.com/maptalks/maptalks.js/wiki/Home Install Maptalks.js as a project dependency using npm. ```shell npm install maptalks --save ``` -------------------------------- ### Install maptalks-gl using yarn Source: https://github.com/maptalks/maptalks.js/blob/master/README.md Use yarn to add the maptalks-gl package. ```shell yarn add maptalks-gl ``` -------------------------------- ### Run Tests with Karma Source: https://github.com/maptalks/maptalks.js/wiki/Begin-Plugin-Develop Starts Karma test runner to execute the project's tests. ```shell $ gulp test ``` -------------------------------- ### Initialize REGL and Load Resources Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/ibl/ibl.html Sets up the REGL context with necessary extensions and initializes the resource loader. This is the entry point for rendering. ```javascript import cubeData from '../common/cube.js'; import sphereData from '../common/sphere.js'; const { createREGL, mat4, reshader } = maptalksgl; const regl = createREGL({ canvas : canvas, extensions : [ 'OES_texture_float', 'OES_element_index_uint', 'OES_standard_derivatives', 'EXT_shader_texture_lod' ] }); const lightPositions = [ [0.7, 0.2, 2.0], [2.3, -3.0, 2.0], [0.0, 5.0, 2.0], [0.0, 0.0, 2.0] ]; const lightColors = [ [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0] ]; let iblMaps; let shader, meshes, scene; const loader = new reshader.ResourceLoader(regl.texture(2)); const renderer = new reshader.Renderer(regl); const camPos = [0, 0, 6]; main(); ``` -------------------------------- ### Initialize GUI Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/bloom.html Sets up a dat.GUI interface for controlling material properties like roughness and metalness. Updates uniforms on change. ```javascript function initGUI() { var gui = new dat.GUI( { width: 600 } ); const config = { roughness: 0.3, metalness: 1 }; var metallicFactorController = gui.add(config, 'metalness', 0, 1, 0.001); metallicFactorController.onChange(function(value){ MatUNIFORMS['uMetalnessPBRFactor'] = value; }); var roughnessFactorController = gui.add(config, "roughness", 0, 1, 0.001); roughnessFactorController.onChange(function(value){ MatUNIFORMS['uRoughnessPBRFactor'] = value; }); } ``` -------------------------------- ### Initialize GUI with dat.GUI Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/ViewShed.html Sets up a graphical user interface using dat.GUI for controlling camera parameters like look point, eye position, and viewing angles. Allows real-time adjustments to scene perspective. ```javascript function initGUI() { var gui = new dat.GUI( { width: 300 } ); const config = { lookPointX: lookPoint[0], lookPointY: lookPoint[1], lookPointZ: lookPoint[2], eyePosX: eyePos[0], eyePosY: eyePos[1], eyePosZ: eyePos[2], verticalAngle: 60, horizontalAngle: 90 }; var verticalController = gui.add(config, "verticalAngle", 0, 180); verticalController.onChange(function (value) { verticalAngle = value; }); var horizonController = gui.add(config, "horizontalAngle", 0, 180); horizonController.onChange(function (value) { horizontalAngle = value; }); var lookPos = gui.addFolder('lookPoint'); var lookPosX = lookPos.add(config, 'lookPointX'); lookPosX.onFinishChange(function (value) { lookPoint[0] = value; }); var lookPosY = lookPos.add(config, 'lookPointX'); lookPosY.onFinishChange(function (value) { lookPoint[1] = value; }); var lookPosZ = lookPos.add(config, 'lookPointZ'); lookPosZ.onFinishChange(function (value) { lookPoint[2] = value; }); //// var eyePosition = gui.addFolder('eyePosition'); var eyePosX = eyePosition.add(config, 'eyePosX'); eyePosX.onFinishChange(function (value) { eyePos[0] = value; }); var eyePosY = eyePosition.add(config, 'eyePosX'); eyePosY.onFinishChange(function (value) { eyePos[1] = value; }); var eyePosZ = eyePosition.add(config, 'eyePosZ'); eyePosZ.onFinishChange(function (value) { eyePos[2] = value; }); } ``` -------------------------------- ### Initialize GUI for Map Controls Source: https://github.com/maptalks/maptalks.js/blob/master/debug/vt/buildings.html Sets up a dat.GUI interface for controlling various map and lighting parameters. This includes directional light, ambient light, SSAO, and sharpen effects. ```javascript function initGUI() { var gui = new dat.GUI( { width: 250 } ); // ... (rest of the GUI initialization code) ``` -------------------------------- ### Initialize dat.GUI for PBR Material Properties Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/pbr-sketchfab.html Sets up a dat.GUI interface to control PBR material properties like metalness and roughness. Changes made in the GUI update the corresponding shader uniforms. ```javascript function initGUI() { var gui = new dat.GUI( { width: 600 } ); const config = { roughness: 0.3, metalness: 1 }; var metallicFactorController = gui.add(config, 'metalness', 0, 1, 0.001); metallicFactorController.onChange(function(value){ MatUNIFORMS['uMetalnessPBRFactor'] = value; }); var roughnessFactorController = gui.add(config, "roughness", 0, 1, 0.001); roughnessFactorController.onChange(function(value){ MatUNIFORMS['uRoughnessPBRFactor'] = value; }); } ``` -------------------------------- ### TDD Mode with Karma Source: https://github.com/maptalks/maptalks.js/wiki/Begin-Plugin-Develop Starts Karma, watches for source changes, and re-runs tests, useful for Test-Driven Development. ```shell $ gulp tdd ``` -------------------------------- ### Get Excavated Volume Source: https://github.com/maptalks/maptalks.js/blob/master/packages/analysis/demo/excavateAnalysis.html Retrieves the calculated volume of the excavated area from the ExcavateAnalysis instance. The volume is logged to the console. ```javascript document.getElementById('volume').onclick = function() { const volume = excavateAnalysis.getVolume(); console.log(volume); } ``` -------------------------------- ### Initialize GUI Controls Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/pbr-sketchfab-skybox.html Sets up a dat.GUI interface to control rendering parameters like blur and brightness. Changes made in the GUI update the corresponding global variables. ```javascript function initGUI() { var gui = new dat.GUI( { width: 300 } ); const config = { blur: 0.125, brightness: 1.0 }; var blurController = gui.add(config, "blur", 0.01, 1.0); blurController.onChange(function (value) { blur = value; }); var brightnessController = gui.add(config, "brightness", 0, 2.0); brightnessController.onCh ``` -------------------------------- ### Get Geometry Shader Defines Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/pbr-sketchfab-hdr.html Retrieves shader defines for a given geometry, including enabling directional lighting. ```javascript function getGeometryDefines(geometry) { const defines = SHADER.getGeometryDefines(geometry); defines['HAS_DIRECTIONAL_LIGHTING'] = 1; return defines; } ``` -------------------------------- ### Initialize GraphicsDevice and Renderer Source: https://github.com/maptalks/maptalks.js/blob/master/debug/webgpu/cube-texture.html Initializes the GraphicsDevice with the WebGPU device and context, and creates a Renderer instance. ```javascript const device = new GraphicsDevice(gpuDevice, context) const renderer = new Renderer(device); ``` -------------------------------- ### Initialize REGL Renderer and Scene Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/skyline.html Sets up the REGL context and initializes the reshader scene and renderer. Includes necessary extensions for advanced rendering. ```javascript const regl = createREGL({ canvas : canvas, extensions : [ 'OES_texture_float', 'OES_element_index_uint', 'OES_standard_derivatives', 'EXT_shader_texture_lod' ] }); // let iblMaps; let scene = new reshader.Scene([]); const renderer = new reshader.Renderer(regl); ``` -------------------------------- ### MeshShader and Geometry Setup Source: https://github.com/maptalks/maptalks.js/blob/master/debug/webgpu/cube.html Configures the MeshShader with WGSL code and creates a Geometry object for the cube, including buffer generation. ```javascript const shader = new MeshShader({ wgslVert: vert, wgslFrag: frag, name: 'cube', extraCommandProps: { cull: { enable: true } } }); const geometry = new Geometry({ position: cubeVertexArray }, cubeVertexCount, 0, { positionSize: 4, positionAttribute: 'position' }); geometry.generateBuffers(device); ``` -------------------------------- ### Initialize REGL and Renderer Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/pbr-sketchfab-skybox.html Sets up the REGL context with necessary extensions and initializes the reshader Renderer. Ensure the canvas element is available. ```javascript const { createREGL, mat4, reshader, vec2 } = maptalksgl; const regl = createREGL({ attributes: { alpha: true, stencil: true, depth: true, antialias: true, }, canvas : canvas, extensions : [ 'OES_texture_float', 'OES_texture_float_linear', 'OES_texture_half_float', 'OES_texture_half_float_linear', 'OES_element_index_uint', 'OES_standard_derivatives', 'EXT_shader_texture_lod', 'WEBGL_depth_texture' ] }); let iblMaps; let mouseDown = false; let roll = 3.1315926535897955; let pitch = 1.35; let translate = 4.0; var wheelSpeed = 1.04; let lastMouseX = null; let lastMouseY = null; const renderer = new reshader.Renderer(regl); ``` -------------------------------- ### Initialize Scene and Render Loop Source: https://github.com/maptalks/maptalks.js/blob/master/debug/webgpu/cube-texture.html Sets up the Scene and defines the render function which updates the mesh's transform, renders the scene, and requests the next frame. ```javascript const scene = new Scene(); function render() { const matrix = getTransformationMatrix(); mesh.setLocalTransform(matrix); scene.setMeshes([mesh]); renderer.render(shader, null, scene); device.submit(); requestAnimationFrame(render); } ``` -------------------------------- ### Camera View Projection Matrix Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/pbr-pbrglossiness.html Calculates view and projection matrices for camera setup. Use when defining camera perspective. ```javascript function getViewProjection(cameraPos, aspect) { const projMatrix = mat4.perspective([], 60 * Math.PI / 180, aspect, 0.1, 200); const viewMatrix = mat4.lookAt([], cameraPos, [0, 0, 0], [0, 1, 0]); return { viewMatrix, projMatrix }; } ``` -------------------------------- ### Initialize Maptalks GL and Scene Source: https://github.com/maptalks/maptalks.js/blob/master/debug/reshader/floodAnalyse.html Sets up the REGL context, defines shader uniforms, and initializes the scene and renderer. Includes extensions for floating-point textures and LOD. ```javascript const { createREGL, mat4, reshader } = maptalksgl; const MODES = ['points', 'lines', 'line strip', 'line loop', 'triangles', 'triangle strip', 'triangle fan']; let camPos = [0, 7, 11]; const cameraNearFar = [0.1, 1000]; let mouseDown = false; let roll = 0; let pitch = 0; let translate = 11; var wheelSpeed = 1.04; let lastMouseX = null; let lastMouseY = null; let viewpoint = []; let currentAngle = 0; let waterHeight = 0.2; initGUI(); const TEXTURE_SAMPLER = { '9728' : 'nearest', '9729' : 'linear', '9984' : 'nearest mipmap nearest', '9985' : 'linear mipmap nearest', '9986' : 'nearest mipmap linear', '9987' : 'linear mipmap linear', '33071' : 'clamp ro edge', '33684' : 'mirrored repeat', '10497' : 'repeat' }; const regl = createREGL({ canvas: canvas, extensions: [ 'OES_texture_float', 'OES_element_index_uint', 'OES_standard_derivatives', 'EXT_shader_texture_lod' ] }); // let iblMaps; let scene = new reshader.Scene([]); const renderer = new reshader.Renderer(regl); const viewport = { x: 0, y: 0, width: () => { return canvas.width; }, height: () => { return canvas.height; } }; const uniforms = { halton: [0.2107, -0.0202], globalTexSize: [canvas.width, canvas.height], lightAmbient: [0.8, 0.8, 0.8], lightDiffuse: [1.0, 1.0, 1.0], lightSpecular: [1.0, 1.0, 1.0], lightDirection: [-1, -1, 1] }; ``` -------------------------------- ### Canvas Creation and Update Source: https://github.com/maptalks/maptalks.js/wiki/创建新图层 Use `createCanvas()` to initialize a new canvas and `onCanvasCreate()` as a callback after canvas creation for any post-creation setup. ```javascript createCanvas() onCanvasCreate() ```