util.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. import { WebGLContext } from '../../mol-gl/webgl/context';
  7. import { Texture } from '../../mol-gl/webgl/texture';
  8. import { printTextureImage } from '../../mol-gl/renderable/util';
  9. import { defaults, ValueCell } from '../../mol-util';
  10. import { ValueSpec, AttributeSpec, UniformSpec, Values } from '../../mol-gl/renderable/schema';
  11. import { Vec2 } from '../../mol-math/linear-algebra';
  12. import { GLRenderingContext } from '../../mol-gl/webgl/compat';
  13. export const QuadPositions = new Float32Array([
  14. 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, // First triangle
  15. -1.0, -1.0, 1.0, -1.0, 1.0, 1.0 // Second triangle
  16. ]);
  17. export const QuadSchema = {
  18. drawCount: ValueSpec('number'),
  19. instanceCount: ValueSpec('number'),
  20. aPosition: AttributeSpec('float32', 2, 0),
  21. uQuadScale: UniformSpec('v2'),
  22. };
  23. export const QuadValues: Values<typeof QuadSchema> = {
  24. drawCount: ValueCell.create(6),
  25. instanceCount: ValueCell.create(1),
  26. aPosition: ValueCell.create(QuadPositions),
  27. uQuadScale: ValueCell.create(Vec2.create(1, 1)),
  28. };
  29. //
  30. function getArrayForTexture(gl: GLRenderingContext, texture: Texture, size: number) {
  31. switch (texture.type) {
  32. case gl.UNSIGNED_BYTE: return new Uint8Array(size);
  33. case gl.FLOAT: return new Float32Array(size);
  34. }
  35. throw new Error('unknown/unsupported texture type');
  36. }
  37. export function readTexture(ctx: WebGLContext, texture: Texture, width?: number, height?: number) {
  38. const { gl, resources } = ctx;
  39. width = defaults(width, texture.getWidth());
  40. height = defaults(height, texture.getHeight());
  41. const size = width * height * 4;
  42. const framebuffer = resources.framebuffer();
  43. const array = getArrayForTexture(gl, texture, size);
  44. framebuffer.bind();
  45. texture.attachFramebuffer(framebuffer, 0);
  46. ctx.readPixels(0, 0, width, height, array);
  47. return { array, width, height };
  48. }
  49. export function printTexture(ctx: WebGLContext, texture: Texture, scale: number) {
  50. printTextureImage(readTexture(ctx, texture), scale);
  51. }