gpu.5.py 907 B

12345678910111213141516171819202122232425262728293031323334353637
  1. """
  2. Mesh with Random Vertex Colors
  3. ------------------------------
  4. """
  5. import bpy
  6. import gpu
  7. import numpy as np
  8. from random import random
  9. from gpu_extras.batch import batch_for_shader
  10. mesh = bpy.context.active_object.data
  11. mesh.calc_loop_triangles()
  12. vertices = np.empty((len(mesh.vertices), 3), 'f')
  13. indices = np.empty((len(mesh.loop_triangles), 3), 'i')
  14. mesh.vertices.foreach_get(
  15. "co", np.reshape(vertices, len(mesh.vertices) * 3))
  16. mesh.loop_triangles.foreach_get(
  17. "vertices", np.reshape(indices, len(mesh.loop_triangles) * 3))
  18. vertex_colors = [(random(), random(), random(), 1) for _ in range(len(mesh.vertices))]
  19. shader = gpu.shader.from_builtin('3D_SMOOTH_COLOR')
  20. batch = batch_for_shader(
  21. shader, 'TRIS',
  22. {"pos": vertices, "color": vertex_colors},
  23. indices=indices,
  24. )
  25. def draw():
  26. batch.draw(shader)
  27. bpy.types.SpaceView3D.draw_handler_add(draw, (), 'WINDOW', 'POST_VIEW')