util.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 { PrintImageOptions, 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. import { PixelData } from '../../mol-util/image';
  14. export const QuadPositions = new Float32Array([
  15. 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, // First triangle
  16. -1.0, -1.0, 1.0, -1.0, 1.0, 1.0 // Second triangle
  17. ]);
  18. export const QuadSchema = {
  19. drawCount: ValueSpec('number'),
  20. instanceCount: ValueSpec('number'),
  21. aPosition: AttributeSpec('float32', 2, 0),
  22. uQuadScale: UniformSpec('v2'),
  23. };
  24. export const QuadValues: Values<typeof QuadSchema> = {
  25. drawCount: ValueCell.create(6),
  26. instanceCount: ValueCell.create(1),
  27. aPosition: ValueCell.create(QuadPositions),
  28. uQuadScale: ValueCell.create(Vec2.create(1, 1)),
  29. };
  30. //
  31. function getArrayForTexture(gl: GLRenderingContext, texture: Texture, size: number) {
  32. switch (texture.type) {
  33. case gl.UNSIGNED_BYTE: return new Uint8Array(size);
  34. case gl.FLOAT: return new Float32Array(size);
  35. }
  36. throw new Error('unknown/unsupported texture type');
  37. }
  38. export function readTexture(ctx: WebGLContext, texture: Texture, width?: number, height?: number): PixelData {
  39. const { gl, resources } = ctx;
  40. width = defaults(width, texture.getWidth());
  41. height = defaults(height, texture.getHeight());
  42. const size = width * height * 4;
  43. const framebuffer = resources.framebuffer();
  44. const array = getArrayForTexture(gl, texture, size);
  45. framebuffer.bind();
  46. texture.attachFramebuffer(framebuffer, 0);
  47. ctx.readPixels(0, 0, width, height, array);
  48. return { array, width, height };
  49. }
  50. export function printTexture(ctx: WebGLContext, texture: Texture, options: Partial<PrintImageOptions> = {}) {
  51. const pixelData = readTexture(ctx, texture);
  52. PixelData.flipY(pixelData);
  53. printTextureImage(pixelData, options);
  54. }