Logo de Blender Core Gpu

Blender Core Gpu

Organização
Impertio-Studio
blender-core-gpu

Use when drawing custom overlays, viewport visualizations, or offscreen renders in Blender Python. Prevents the critical mistake of using the deprecated bgl module (removed in Blender 5.0) instead of the gpu module. Covers gpu.shader, gpu.batch, gpu.state, SpaceView3D draw handlers, built-in shaders, and BGL-to-gpu migration. Keywords: gpu module, bgl, draw handler, viewport overlay, offscreen rendering, SpaceView3D, shader, UNIFORM_COLOR, Blender Python drawing, draw on viewport, custom overlay, draw lines in 3D view.

Visão geral

Publicado porImpertio-Studio
RepositórioBlender-Bonsai-ifcOpenshell-Sverchok-Claude-Skill-Package
Nome da habilidadeblender-core-gpu
Estrelas
44
Forks
5
Arquivos incluídos
3
LicençaMIT
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    Habilidades de IA são Markdown simples, não código específico de um provedor, por isso funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • 3 arquivos incluídos

    Scripts, modelos de documentos e referências que o modelo pode ler enquanto trabalha. Os arquivos são somente leitura e nunca são executados.

  • Código aberto

    Publicada por Impertio-Studio no GitHub. Leia o conteúdo-fonte antes de instalar.

Instalação

Instale a habilidade de IA Blender Core Gpu no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL da pasta da habilidade exibida abaixo e confirme.
    https://github.com/Impertio-Studio/Blender-Bonsai-ifcOpenshell-Sverchok-Claude-Skill-Package/tree/main/skills/blender/core/blender-core-gpu
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Nova habilidade → Via URL GitHub, depois cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Impertio-Studio/Blender-Bonsai-ifcOpenshell-Sverchok-Claude-Skill-Package.git /tmp/Blender-Bonsai-ifcOpenshell-Sverchok-Claude-Skill-Package
mkdir -p .claude/skills
cp -r /tmp/Blender-Bonsai-ifcOpenshell-Sverchok-Claude-Skill-Package/skills/blender/core/blender-core-gpu .claude/skills/blender-core-gpu
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Blender Core Gpu em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Blender Core Gpu automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Blender Core Gpu não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

blender-core-gpu

Quick Reference

Critical Warnings

NEVER use the bgl module — it is deprecated since Blender 3.5 and completely removed in Blender 5.0. ALL drawing code MUST use the gpu module.

NEVER use shader name 3D_UNIFORM_COLOR or 3D_FLAT_COLOR in Blender 4.0+ — the 3D_ prefix was removed. Use UNIFORM_COLOR, POLYLINE_UNIFORM_COLOR, etc.

NEVER forget to restore gpu.state to defaults at the end of draw callbacks — failing to restore state corrupts rendering for ALL subsequent draw handlers and Blender's own UI.

NEVER create gpu.types.GPUOffScreen outside a valid OpenGL/GPU context — offscreen buffers require a graphics context (viewport draw callback or bpy.types.SpaceView3D).

NEVER call gpu.shader.from_builtin() or create batches from a background thread — ALL GPU operations MUST execute on the main thread.

ALWAYS remove draw handlers in addon unregister() — leaked handlers cause crashes or persistent ghost overlays.

ALWAYS set viewportSize and lineWidth uniforms when using POLYLINE_* shaders — these are REQUIRED uniforms (Blender 4.0+).

ALWAYS call offscreen.free() when done with offscreen buffers to prevent GPU memory leaks.

Module Overview

ModulePurpose
gpuCore GPU module — shader creation, state management
gpu.shaderShader compilation, built-in shader access
gpu.typesGPU types: GPUShader, GPUBatch, GPUOffScreen, GPUTexture
gpu.stateOpenGL-like state: blend, depth, line width, viewport
gpu.textureTexture creation from images
gpu.matrixModel-view-projection matrix stack
gpu.selectGPU-based selection utilities
gpu.platformGPU backend info (vendor, renderer, version)
gpu_extras.batchbatch_for_shader() helper
gpu_extras.presetsdraw_circle_2d(), draw_texture_2d()

Built-in Shaders (Blender 4.0+)

Shader NameGeometryUse Case
'UNIFORM_COLOR'Triangles, pointsFlat colored filled geometry
'POLYLINE_UNIFORM_COLOR'LinesLines with configurable width
'FLAT_COLOR'TrianglesPer-vertex colored (flat shaded)
'POLYLINE_FLAT_COLOR'LinesPer-vertex colored lines
'SMOOTH_COLOR'TrianglesPer-vertex colored (smooth shaded)
'POLYLINE_SMOOTH_COLOR'LinesSmooth per-vertex colored lines
'IMAGE'TrianglesTextured quads/geometry
'IMAGE_COLOR'TrianglesTextured with color tint
Shader Name Version Map
Blender 3.x NameBlender 4.0+ Name
'3D_UNIFORM_COLOR''UNIFORM_COLOR'
'3D_FLAT_COLOR''FLAT_COLOR'
'3D_SMOOTH_COLOR''SMOOTH_COLOR'
'3D_IMAGE''IMAGE'
'2D_UNIFORM_COLOR''UNIFORM_COLOR'
'2D_FLAT_COLOR''FLAT_COLOR'
'2D_SMOOTH_COLOR''SMOOTH_COLOR'
'2D_IMAGE''IMAGE'

In Blender 4.0+, the 2D_/3D_ distinction is removed. A single 'UNIFORM_COLOR' works in both 2D and 3D contexts.


Essential Patterns

Pattern 1: Basic Line Drawing with POLYLINE Shader

python
# Blender 4.0+/5.x: Draw colored lines in 3D viewport
import bpy
import gpu
from gpu_extras.batch import batch_for_shader

def draw_lines():
    coords = [(0, 0, 0), (5, 0, 0), (5, 5, 0), (0, 5, 0), (0, 0, 0)]
    shader = gpu.shader.from_builtin('POLYLINE_UNIFORM_COLOR')
    batch = batch_for_shader(shader, 'LINE_STRIP', {"pos": coords})

    gpu.state.blend_set('ALPHA')
    gpu.state.line_width_set(2.0)

    shader.bind()
    region = bpy.context.region
    shader.uniform_float("viewportSize", (region.width, region.height))
    shader.uniform_float("lineWidth", 2.0)
    shader.uniform_float("color", (1.0, 0.0, 0.0, 0.8))
    batch.draw(shader)

    # ALWAYS restore state
    gpu.state.blend_set('NONE')
    gpu.state.line_width_set(1.0)

_handle = bpy.types.SpaceView3D.draw_handler_add(draw_lines, (), 'WINDOW', 'POST_VIEW')
# Remove: bpy.types.SpaceView3D.draw_handler_remove(_handle, 'WINDOW')

Pattern 2: Filled Triangles with UNIFORM_COLOR

python
# Blender 4.0+/5.x: Draw a filled quad (two triangles)
import gpu
from gpu_extras.batch import batch_for_shader

def draw_filled():
    verts = [(0, 0, 0), (5, 0, 0), (5, 5, 0), (0, 5, 0)]
    indices = ((0, 1, 2), (2, 3, 0))
    shader = gpu.shader.from_builtin('UNIFORM_COLOR')
    batch = batch_for_shader(shader, 'TRIS', {"pos": verts}, indices=indices)

    gpu.state.blend_set('ALPHA')
    shader.bind()
    shader.uniform_float("color", (0.0, 0.5, 1.0, 0.3))
    batch.draw(shader)
    gpu.state.blend_set('NONE')

Pattern 3: Draw Handler Registration/Removal

python
# Blender 3.x/4.x/5.x: Proper handler lifecycle in an addon
import bpy

_draw_handle = None

def register():
    global _draw_handle
    _draw_handle = bpy.types.SpaceView3D.draw_handler_add(
        draw_callback, (), 'WINDOW', 'POST_VIEW'
    )

def unregister():
    global _draw_handle
    if _draw_handle is not None:
        bpy.types.SpaceView3D.draw_handler_remove(_draw_handle, 'WINDOW')
        _draw_handle = None
Draw Handler Layer Options
LayerWhenCoordinate Space
'PRE_VIEW'Before 3D scene3D world space
'POST_VIEW'After 3D scene, before gizmos3D world space
'POST_PIXEL'After everything, on top2D pixel space

Pattern 4: Version-Compatible Shader Selection

python
# Blender 3.x/4.x/5.x: Version-safe shader selection
import bpy
import gpu

def get_line_shader():
    if bpy.app.version >= (4, 0, 0):
        return gpu.shader.from_builtin('POLYLINE_UNIFORM_COLOR')
    else:
        return gpu.shader.from_builtin('3D_UNIFORM_COLOR')

def get_flat_shader():
    if bpy.app.version >= (4, 0, 0):
        return gpu.shader.from_builtin('UNIFORM_COLOR')
    else:
        return gpu.shader.from_builtin('3D_UNIFORM_COLOR')

Pattern 5: Offscreen Rendering

python
# Blender 4.x/5.x: Render to offscreen buffer
import gpu

offscreen = gpu.types.GPUOffScreen(512, 512)
with offscreen.bind():
    fb = gpu.state.active_framebuffer_get()
    fb.clear(color=(0.0, 0.0, 0.0, 0.0))
    # Draw operations here (shaders, batches)

texture = offscreen.texture_color  # GPUTexture
offscreen.free()  # ALWAYS free when done

Pattern 6: GPU State Management

python
# Blender 3.5+/4.x/5.x: Full state management pattern
import gpu

def draw_with_state():
    # Save implicit state by setting explicitly
    gpu.state.blend_set('ALPHA')
    gpu.state.depth_test_set('LESS_EQUAL')
    gpu.state.depth_mask_set(True)
    gpu.state.line_width_set(2.0)
    gpu.state.point_size_set(5.0)
    gpu.state.face_culling_set('BACK')

    # ... draw calls ...

    # ALWAYS restore defaults
    gpu.state.blend_set('NONE')
    gpu.state.depth_test_set('NONE')
    gpu.state.depth_mask_set(False)
    gpu.state.line_width_set(1.0)
    gpu.state.point_size_set(1.0)
    gpu.state.face_culling_set('NONE')

Common Operations

Drawing 2D Overlays (POST_PIXEL)

python
# Blender 4.0+/5.x: 2D HUD overlay in pixel coordinates
import bpy
import gpu
from gpu_extras.batch import batch_for_shader

def draw_2d_overlay():
    verts = [(10, 10), (200, 10), (200, 50), (10, 50)]
    indices = ((0, 1, 2), (2, 3, 0))
    shader = gpu.shader.from_builtin('UNIFORM_COLOR')
    batch = batch_for_shader(shader, 'TRIS', {"pos": verts}, indices=indices)

    gpu.state.blend_set('ALPHA')
    shader.bind()
    shader.uniform_float("color", (0.0, 0.0, 0.0, 0.5))
    batch.draw(shader)
    gpu.state.blend_set('NONE')

# POST_PIXEL = 2D pixel space overlay
_handle = bpy.types.SpaceView3D.draw_handler_add(
    draw_2d_overlay, (), 'WINDOW', 'POST_PIXEL'
)

Drawing Textured Quads

python
# Blender 4.0+/5.x: Draw image texture in viewport
import gpu
from gpu_extras.batch import batch_for_shader

def draw_image(texture):
    shader = gpu.shader.from_builtin('IMAGE')
    batch = batch_for_shader(
        shader, 'TRI_FAN',
        {
            "pos": ((0, 0), (200, 0), (200, 200), (0, 200)),
            "texCoord": ((0, 0), (1, 0), (1, 1), (0, 1)),
        },
    )
    shader.bind()
    shader.uniform_sampler("image", texture)
    batch.draw(shader)

Per-Vertex Colored Geometry

python
# Blender 4.0+/5.x: Smooth colored triangle
import gpu
from gpu_extras.batch import batch_for_shader

shader = gpu.shader.from_builtin('SMOOTH_COLOR')
batch = batch_for_shader(shader, 'TRIS', {
    "pos": [(0, 0, 0), (5, 0, 0), (2.5, 5, 0)],
    "color": [(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1)],
})
shader.bind()
batch.draw(shader)

Loading Image as GPU Texture

python
# Blender 4.0+/5.x: Load image to GPU texture (replaces bgl texture binding)
import bpy
import gpu

image = bpy.data.images.load("/path/to/image.png")
texture = gpu.texture.from_image(image)
# Use texture with IMAGE shader via shader.uniform_sampler("image", texture)

BGL-to-gpu Migration Checklist

When migrating code from bgl to gpu:

  1. Remove ALL import bgl statements
  2. Replace bgl.glEnable(bgl.GL_BLEND) → gpu.state.blend_set('ALPHA')
  3. Replace bgl.glDisable(bgl.GL_BLEND) → gpu.state.blend_set('NONE')
  4. Replace bgl.glLineWidth(w) → gpu.state.line_width_set(w)
  5. Replace bgl.glEnable(bgl.GL_DEPTH_TEST) → gpu.state.depth_test_set('LESS_EQUAL')
  6. Replace bgl.glDisable(bgl.GL_DEPTH_TEST) → gpu.state.depth_test_set('NONE')
  7. Replace bgl.glDepthMask(GL_TRUE) → gpu.state.depth_mask_set(True)
  8. Replace bgl.glPointSize(s) → gpu.state.point_size_set(s)
  9. Replace bgl.glEnable(bgl.GL_LINE_SMOOTH) → use POLYLINE_* shaders (no direct replacement)
  10. Replace image.gl_load() / bgl.glBindTexture() → gpu.texture.from_image(image)
  11. Replace 3D_UNIFORM_COLOR → POLYLINE_UNIFORM_COLOR (for lines) or UNIFORM_COLOR (for triangles)
  12. Replace 3D_FLAT_COLOR → POLYLINE_FLAT_COLOR (for lines) or FLAT_COLOR (for triangles)
  13. Add viewportSize and lineWidth uniforms for ALL POLYLINE_* shaders
  14. Add state restoration at end of every draw callback
  15. Test on Apple Silicon (Metal backend) — bgl was already non-functional there

BGL-to-gpu API Mapping

bgl (REMOVED in 5.0)gpu replacement (3.5+)Notes
bgl.glEnable(bgl.GL_BLEND)gpu.state.blend_set('ALPHA')Options: 'ALPHA', 'ADDITIVE', 'ADDITIVE_PREMUL', 'MULTIPLY'
bgl.glDisable(bgl.GL_BLEND)gpu.state.blend_set('NONE')
bgl.glLineWidth(w)gpu.state.line_width_set(w)Also set lineWidth uniform for POLYLINE shaders
bgl.glEnable(bgl.GL_DEPTH_TEST)gpu.state.depth_test_set('LESS_EQUAL')Options: 'NONE', 'LESS', 'LESS_EQUAL', 'EQUAL', 'GREATER'
bgl.glDisable(bgl.GL_DEPTH_TEST)gpu.state.depth_test_set('NONE')
bgl.glDepthMask(GL_TRUE)gpu.state.depth_mask_set(True)
bgl.glPointSize(s)gpu.state.point_size_set(s)
bgl.glEnable(bgl.GL_LINE_SMOOTH)(no direct replacement)Use POLYLINE_* shaders for antialiased lines
image.gl_load() / bgl.glBindTexture()gpu.texture.from_image(image)Completely different API

Version Timeline

VersionChange
Blender 3.0gpu module stable, gpu_extras.batch available
Blender 3.5bgl module officially deprecated
Blender 4.03D_/2D_ shader name prefixes removed; POLYLINE_* shaders added
Blender 5.0bgl module completely removed; gpu is the ONLY drawing API

Reference Links

Cross-References

  • blender-core-api — bpy.context, draw handler registration, restricted contexts

Official Sources

Arquivos incluídos

O modelo lê esses arquivos sob demanda enquanto a habilidade está carregada. Eles são disponibilizados para leitura e nunca são executados.

Perguntas frequentes

O que a habilidade de IA Blender Core Gpu faz?

Use when drawing custom overlays, viewport visualizations, or offscreen renders in Blender Python. Prevents the critical mistake of using the deprecated bgl module (removed in Blender 5.0) instead of the gpu module. Covers gpu.shader, gpu.batch, gpu.state, SpaceView3D draw handlers, built-in shaders, and BGL-to-gpu migration. Keywords: gpu module, bgl, draw handler, viewport overlay, offscreen rendering, SpaceView3D, shader, UNIFORM_COLOR, Blender Python drawing, draw on viewport, custom overlay, draw lines in 3D view.

Por que usar Blender Core Gpu no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. Blender Core Gpu é escrito em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. O TypingMind usa suas próprias chaves de API, então o pagamento é feito diretamente aos provedores, em vez de uma assinatura por licença de usuário, e suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Blender Core Gpu no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/Impertio-Studio/Blender-Bonsai-ifcOpenshell-Sverchok-Claude-Skill-Package/tree/main/skills/blender/core/blender-core-gpu. O TypingMind lê o arquivo SKILL.md, reúne os arquivos da habilidade e a instala para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Blender Core Gpu?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Blender Core Gpu?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Blender Core Gpu com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Blender Core Gpu é gratuita?

Sim. A habilidade é publicada no GitHub por Impertio-Studio sob a licença MIT. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, modelos de documento ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas para chamar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA fornece conhecimento e um processo ao modelo: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver todos

Crie seu próprio espaço de IA agora

Inscreva-se na nossa newsletter para receber novidades sobre recursos e futuros sorteios 👇