UNPKG

@animech-public/playcanvas

Version:
2 lines (1 loc) 2.34 kB
import{createShaderFromCode as e}from"../../scene/shader-lib/utils.js";import{Texture as t}from"../../platform/graphics/texture.js";import{BlendState as r}from"../../platform/graphics/blend-state.js";import{drawQuadWithShader as a}from"../../scene/graphics/quad-render-utils.js";import{RenderTarget as i}from"../../platform/graphics/render-target.js";import{FILTER_LINEAR as n,ADDRESS_CLAMP_TO_EDGE as o}from"../../platform/graphics/constants.js";class s{constructor(){}textureToCanvas(s,m={}){const c=s.getSource();if("undefined"!=typeof HTMLImageElement&&c instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&c instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&c instanceof OffscreenCanvas||"undefined"!=typeof ImageBitmap&&c instanceof ImageBitmap){const{width:e,height:t}=this.calcTextureSize(c.width,c.height,m.maxTextureSize),r=document.createElement("canvas");r.width=e,r.height=t;const a=r.getContext("2d");if(null===a)return Promise.resolve(void 0);if(a.drawImage(c,0,0,r.width,r.height),m.color){const{r:r,g:i,b:n}=m.color,o=a.getImageData(0,0,e,t),s=o.data;for(let e=0;e<s.length;e+=4)s[e+0]=s[e+0]*r,s[e+1]=s[e+1]*i,s[e+2]=s[e+2]*n;a.putImageData(o,0,0)}return Promise.resolve(r)}const d=s.device,{width:l,height:h}=this.calcTextureSize(s.width,s.height,m.maxTextureSize),u=new t(d,{name:"ExtractedTexture",width:l,height:h,format:s.format,cubemap:!1,mipmaps:!1,minFilter:n,magFilter:n,addressU:o,addressV:o}),f=new i({colorBuffer:u,depth:!1}),g=e(d,"\n\tattribute vec2 vertex_position;\n\tvarying vec2 uv0;\n\tvoid main(void) {\n\t\tgl_Position = vec4(vertex_position, 0.5, 1.0);\n\t\tuv0 = vertex_position.xy * 0.5 + 0.5;\n\t}","\n\tvarying vec2 uv0;\n\tuniform sampler2D blitTexture;\n\tvoid main(void) {\n\t\tgl_FragColor = texture2D(blitTexture, uv0);\n\t}","ShaderCoreExporterBlit");d.scope.resolve("blitTexture").setValue(s),d.setBlendState(r.NOBLEND),a(d,f,g);const p=new Uint8ClampedArray(l*h*4);d.readPixels(0,0,l,h,p),u.destroy(),f.destroy();const v=new ImageData(p,l,h),x=document.createElement("canvas");x.width=l,x.height=h;const w=x.getContext("2d");return w?(w.putImageData(v,0,0),Promise.resolve(x)):Promise.resolve(void 0)}calcTextureSize(e,t,r){if(r){const a=Math.min(r/Math.max(e,t),1);e=Math.round(e*a),t=Math.round(t*a)}return{width:e,height:t}}}export{s as CoreExporter};