util.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. uQuadShift: 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. uQuadShift: ValueCell.create(Vec2.create(0, 0)),
  30. };
  31. //
  32. function getArrayForTexture(gl: GLRenderingContext, texture: Texture, size: number) {
  33. switch (texture.type) {
  34. case gl.UNSIGNED_BYTE: return new Uint8Array(size);
  35. case gl.FLOAT: return new Float32Array(size);
  36. }
  37. throw new Error('unknown/unsupported texture type');
  38. }
  39. export function readTexture(ctx: WebGLContext, texture: Texture, width?: number, height?: number) {
  40. const { gl, resources } = ctx;
  41. width = defaults(width, texture.getWidth());
  42. height = defaults(height, texture.getHeight());
  43. const size = width * height * 4;
  44. const framebuffer = resources.framebuffer();
  45. const array = getArrayForTexture(gl, texture, size);
  46. framebuffer.bind();
  47. texture.attachFramebuffer(framebuffer, 0);
  48. ctx.readPixels(0, 0, width, height, array);
  49. return { array, width, height };
  50. }
  51. export function printTexture(ctx: WebGLContext, texture: Texture, scale: number) {
  52. printTextureImage(readTexture(ctx, texture), scale);
  53. }