The goal of the script is to live-capture the scene from a camera POV but only have certain collections be visible in the texture.
Some things I have tried - hiding objects before drawing and restoring them after (crashes blender), setting the object display type before and after (crashes), setting the view layer (almost works but doesn’t update properly and crashes). I assume the crashes are due to the draw handler, but I need the real time updates that it provides.
Any help would be appreciated!
import bpy, gpu, numpy as np
####### VARIBLES #######
# User Defined Variables
TEXTURE_NAME = 'LiveTexture'
CAMERA_NAME = '3D_Camera'
CAMERA = bpy.data.objects.get(CAMERA_NAME)
####### DATA SETUP #######
# Create Texture
if not TEXTURE_NAME in bpy.data.images:
bpy.data.images.new(TEXTURE_NAME, 32, 32)
#bpy.data.images[TEXTURE_NAME].colorspace_settings.name = "AgX Base sRGB" # Very slow viewport playback
TEXTURE = bpy.data.images[TEXTURE_NAME]
####### STARTUP #######
# Set Texture Resolution
bpy.data.images[TEXTURE_NAME].scale(1024, 1024)
# Set Offscreen Buffer Resolution
offscreen = gpu.types.GPUOffScreen(1024, 1024)
####### DRAW FUNCTION #######
# Define draw function for viewport updates
def draw():
context = bpy.context
scene = context.scene
view_layer = bpy.context.scene.view_layers.get("Preview")
#view_layer = bpy.context.scene.view_layers.get("Shader_Ball.005")
# Hide Overlays
original_overlays = context.space_data.overlay.show_overlays
context.space_data.overlay.show_overlays = False
# Get Camera Matrices
view_matrix = CAMERA.matrix_world.inverted()
projection_matrix = CAMERA.calc_matrix_camera(context.evaluated_depsgraph_get(), x=1024, y=1024)
# Disable Writing To The Depth Buffer
gpu.state.depth_mask_set(False)
# Draw 3D view into offscreen buffer
offscreen.draw_view3d(scene, view_layer, context.space_data, context.region, view_matrix, projection_matrix, draw_background=False, do_color_management=True)
# Flatten buffer and set pixels of LiveTexture
buffer = np.array(offscreen.texture_color.read(), dtype='float32').flatten(order='F')
buffer /= 255
bpy.data.images[TEXTURE_NAME].pixels.foreach_set(buffer)
# Restore overlays
context.space_data.overlay.show_overlays = original_overlays
# Add draw handler
bpy.types.SpaceView3D.draw_handler_add(draw, (), 'WINDOW', 'POST_PIXEL')
Sorry, I cannot post images as I’m a new user.