gpu.9.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """
  2. Copy Offscreen Rendering result back to RAM
  3. -------------------------------------------
  4. This will create a new image with the given name.
  5. If it already exists, it will override the existing one.
  6. Currently almost all of the execution time is spent in the last line.
  7. In the future this will hopefully be solved by implementing the Python buffer protocol
  8. for :class:`bgl.Buffer` and :class:`bpy.types.Image.pixels` (aka ``bpy_prop_array``).
  9. """
  10. import bpy
  11. import gpu
  12. import bgl
  13. import random
  14. from mathutils import Matrix
  15. from gpu_extras.presets import draw_circle_2d
  16. IMAGE_NAME = "Generated Image"
  17. WIDTH = 512
  18. HEIGHT = 512
  19. RING_AMOUNT = 10
  20. offscreen = gpu.types.GPUOffScreen(WIDTH, HEIGHT)
  21. with offscreen.bind():
  22. bgl.glClear(bgl.GL_COLOR_BUFFER_BIT)
  23. with gpu.matrix.push_pop():
  24. # reset matrices -> use normalized device coordinates [-1, 1]
  25. gpu.matrix.load_matrix(Matrix.Identity(4))
  26. gpu.matrix.load_projection_matrix(Matrix.Identity(4))
  27. for i in range(RING_AMOUNT):
  28. draw_circle_2d(
  29. (random.uniform(-1, 1), random.uniform(-1, 1)),
  30. (1, 1, 1, 1), random.uniform(0.1, 1), 20)
  31. buffer = bgl.Buffer(bgl.GL_BYTE, WIDTH * HEIGHT * 4)
  32. bgl.glReadBuffer(bgl.GL_BACK)
  33. bgl.glReadPixels(0, 0, WIDTH, HEIGHT, bgl.GL_RGBA, bgl.GL_UNSIGNED_BYTE, buffer)
  34. offscreen.free()
  35. if not IMAGE_NAME in bpy.data.images:
  36. bpy.data.images.new(IMAGE_NAME, WIDTH, HEIGHT)
  37. image = bpy.data.images[IMAGE_NAME]
  38. image.scale(WIDTH, HEIGHT)
  39. image.pixels = [v / 255 for v in buffer]