Логотип Shader Basics

Shader Basics

Сообщество
jame581
shader-basics

Используйте при реализации шейдеров — язык шейдеров Godot, визуальные шейдеры, распространённые визуальные приёмы и эффекты постобработки

Обзор

Издательjame581
РепозиторийGodotPrompter
Название навыкаshader-basics
Звёзды
808
Форки
47
Файлы в комплекте
6
ЛицензияMIT
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Файлы в комплекте: 6

    Скрипты, шаблоны и справочные материалы, которые модель может читать во время работы. Файлы доступны только для чтения и никогда не выполняются.

  • Открытый исходный код

    Издатель навыка на GitHub — jame581. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Shader Basics в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/jame581/GodotPrompter/tree/master/skills/shader-basics
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/jame581/GodotPrompter.git /tmp/GodotPrompter
mkdir -p .claude/skills
cp -r /tmp/GodotPrompter/skills/shader-basics .claude/skills/shader-basics
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Shader Basics в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Shader Basics, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Shader Basics не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Shaders in Godot 4.3+

All examples target Godot 4.3+ with no deprecated APIs.

Related skills: animation-system for shader-driven effects like hit flash, godot-optimization for shader performance considerations, camera-system for post-processing camera effects, 2d-essentials for 2D lighting, pixel-art shaders, and CanvasTexture normal maps, 3d-essentials for spatial shaders and environment materials, particles-vfx for custom particle shaders, tween-animation for animating shader parameters at runtime.


1. Core Concepts

Shader Types

Shader TypeApplied ToUse For
canvas_item2D nodes (Sprite2D, Control, etc.)2D effects — outlines, dissolve, color swap
spatial3D meshes (MeshInstance3D)3D materials — water, terrain, toon shading
particlesGPUParticles2D/3DCustom particle behavior
skyWorldEnvironmentProcedural sky rendering
fogFogVolumeVolumetric fog effects

Shader vs ShaderMaterial

Shader (.gdshader)        → The code (GLSL-like language)
ShaderMaterial            → Instance of a shader with specific uniform values
CanvasItemMaterial / StandardMaterial3D → Built-in materials (no code needed)

Multiple nodes can share the same Shader but have different ShaderMaterial instances with different uniform values (e.g., same dissolve shader but different dissolve progress per enemy).

Creating a Shader

  1. Select a node (e.g., Sprite2D)
  2. In Inspector → Material → New ShaderMaterial
  3. On the ShaderMaterial → Shader → New Shader
  4. Edit the .gdshader file in the built-in editor

Or create a .gdshader file directly in the FileSystem dock.


2. Godot Shader Language Basics

Godot uses a GLSL ES 3.0-like language with Godot-specific additions.

Minimal Canvas Item Shader

glsl
shader_type canvas_item;

void fragment() {
    // COLOR is the output pixel color
    // TEXTURE is the sprite's texture
    // UV is the texture coordinate (0,0 top-left to 1,1 bottom-right)
    vec4 tex = texture(TEXTURE, UV);
    COLOR = tex;
}

Minimal Spatial Shader

glsl
shader_type spatial;

void fragment() {
    // ALBEDO is the base color (vec3)
    ALBEDO = vec3(0.8, 0.2, 0.2);
}

Built-in Variables (canvas_item)

VariableTypeDescription
UVvec2Texture coordinates
COLORvec4Output color (set this in fragment())
TEXTUREsampler2DThe node's texture
VERTEXvec2Vertex position (in vertex())
TIMEfloatElapsed time in seconds
SCREEN_UVvec2Screen-space UV (for screen effects)

SCREEN_TEXTURE was removed in Godot 4.0. To read the screen, declare a uniform: uniform sampler2D screen_texture : hint_screen_texture, filter_linear_mipmap;

Built-in Variables (spatial)

VariableTypeDescription
ALBEDOvec3Base surface color
METALLICfloatMetallic value (0.0–1.0)
ROUGHNESSfloatRoughness value (0.0–1.0)
NORMALvec3Surface normal (for normal mapping)
EMISSIONvec3Emissive color
ALPHAfloatTransparency (enable in render mode)
VERTEXvec3Vertex position (in vertex())

Uniforms (Shader Parameters)

Uniforms expose shader values to the Inspector and code.

glsl
shader_type canvas_item;

uniform float speed : hint_range(0.0, 10.0, 0.1) = 1.0;
uniform vec4 tint_color : source_color = vec4(1.0, 1.0, 1.0, 1.0);
uniform sampler2D noise_texture : filter_linear_mipmap;

void fragment() {
    vec4 tex = texture(TEXTURE, UV);
    COLOR = tex * tint_color;
}

Common Uniform Hints

HintTypeDescription
hint_range(min, max, step)float/intSlider in Inspector
source_colorvec4Color picker in Inspector
filter_linear_mipmapsampler2DTexture filtering mode
repeat_enablesampler2DAllow texture tiling
hint_normalsampler2DTreat as normal map

Setting Uniforms from Code

GDScript
gdscript
var mat: ShaderMaterial = $Sprite2D.material
mat.set_shader_parameter("speed", 2.0)
mat.set_shader_parameter("tint_color", Color.RED)
C#
csharp
var mat = GetNode<Sprite2D>("Sprite2D").Material as ShaderMaterial;
mat.SetShaderParameter("speed", 2.0f);
mat.SetShaderParameter("tint_color", Colors.Red);

3. Common 2D Shader Recipes

The canvas_item recipes most projects need: dissolve (noise + edge glow), outline (sample neighbors, expand alpha), flash-white (uniform-driven hit effect), color swap (palette shift), scrolling UV (water/lava/clouds), wave distortion.

See references/2d-shader-recipes.md for complete shader code for all six recipes.


4. Common 3D Shader Recipes

Spatial-shader recipes: toon/cel shading (banded NdotL), rim lighting / Fresnel (1 - NdotV), simple water surface (UV scroll + normal-map blend + Fresnel).

See references/3d-shader-recipes.md for the full shader source for each recipe.


5. Visual Shaders

Visual shaders provide a node-based graph editor — no code required.

When to Use Visual Shaders

Use Visual Shaders WhenUse Code Shaders When
Prototyping effects quicklyComplex math or branching logic
Artists need to tweak valuesNeed precise control over every line
Learning shader conceptsPerformance-critical shaders
Simple effects (color adjust, UV scroll)Loops or advanced techniques

Creating a Visual Shader

  1. Select node → Inspector → Material → New ShaderMaterial
  2. Shader → New VisualShader
  3. Click the shader to open the Visual Shader editor
  4. Add nodes from the palette, connect pins
  5. Output nodes (Output, FragmentOutput) are pre-placed

Key Visual Shader Nodes

NodePurpose
Texture2DSample a texture
ColorConstantSolid color value
VectorOpMath operations on vectors
ScalarOpMath operations on floats
MixLerp between two values
Step / SmoothStepThreshold / smooth threshold
TimeCurrent time (for animation)
UVTexture coordinates
Input (custom)Expose a uniform to Inspector

Visual shaders compile to the same GPU code as written shaders. There is no performance difference.

Godot 4.7+: Two new spatial Input nodes — in_shadow_pass (vertex/fragment; maps to the IN_SHADOW_PASS built-in, true when the shader is being rendered in a shadow mapping pass — render objects differently in shadow maps than in the regular pass) and specular_amount (light(); maps to SPECULAR_AMOUNT — 2.0 × light_specular for OmniLight3D/SpotLight3D, 1.0 for DirectionalLight3D).

⚠️ Changed in Godot 4.7: The LinearToSRGB visual shader node no longer clamps its output to [0.0, 1.0] when using the Forward+ or Mobile renderer — HDR values above 1.0 now pass through. Graphs that relied on the implicit clamp produce different output; add an explicit Clamp node to restore the old behavior. See the 4.7 migration guide.


6. Post-Processing Effects

The standard pattern: full-rect ColorRect with a canvas_item shader on top of the gameplay canvas. For 3D, use a WorldEnvironment Adjustment, Glow, or custom shader. For chained effects, render the world to a SubViewport then sample its texture in a final shader pass.

See references/post-processing.md for the ColorRect overlay pattern, vignette + CRT/scanline shader source, the SubViewport pipeline, and WorldEnvironment 3D post-processing notes.


7. Compositor Effects (Godot 4.3+)

CompositorEffect runs custom render passes within Godot's render pipeline (post-tonemap or pre-tonemap). Use when ColorRect overlays aren't enough — multi-pass effects, depth-aware effects, custom AO/SSR variants. Heavier setup than a screen-space shader; reach for it only when needed.

See references/compositor-effects.md for setup, a custom CompositorEffect GDScript example, and built-in Compositor use cases.


8. Render Modes

Render modes go on the first line after shader_type and control how the shader interacts with the rendering pipeline.

Canvas Item Render Modes

glsl
shader_type canvas_item;
render_mode unshaded;           // Ignore all lighting
render_mode light_only;         // Only visible where lit
render_mode blend_add;          // Additive blending (glow, fire)
render_mode blend_mix;          // Standard alpha blending (default)
render_mode blend_premul_alpha; // Pre-multiplied alpha

Spatial Render Modes

glsl
shader_type spatial;
render_mode unshaded;              // No lighting calculations
render_mode cull_disabled;         // Render both sides of faces
render_mode depth_draw_always;     // Always write to depth buffer
render_mode specular_toon;         // Toon specular model
render_mode diffuse_toon;          // Toon diffuse model
render_mode blend_add;             // Additive blending

9. Stencil Buffer Effects (Godot 4.5+)

Godot 4.5 exposes stencil write/read in spatial and canvas_item shaders via stencil_write_mode, stencil_read_mode, stencil_value, etc. across all rendering backends. Enables portals, X-ray vision, outline masks, and holes-in-geometry effects that previously required compositor-level work.

See references/stencil-buffer.md for render-mode reference and the X-ray vision portal worked example.


10. SMAA Antialiasing (Godot 4.5+)

Sub-pixel Morphological Antialiasing (SMAA 1x) is a built-in post-processing AA mode added in Godot 4.5. It produces sharper, more temporally stable results than FXAA and is less costly than MSAA for deferred-heavy scenes.

Enabling SMAA

  1. Open Project Settings
  2. Navigate to Rendering → Anti Aliasing → Quality
  3. Set Screen Space AA to SMAA

SMAA can be combined with MSAA (for geometry edge aliasing) or used standalone. It does not require any shader code changes.

AA ModeSharpnessGPU costGhosting
DisabledN/ANoneNone
FXAALow (blurry)Very lowLow
SMAAHighLowVery low
TAAMedium (slight blur)MediumPossible
MSAA 4xHighHighNone

When to use SMAA: Prefer SMAA over FXAA for most desktop projects — it delivers noticeably sharper text and thin edges with a similar performance profile. Combine SMAA + MSAA 2x for best quality at moderate cost.

This is an editor/export setting only — no runtime API is needed.


11. Shader Baker — Export-time Pre-compilation (Godot 4.5+)

The Shader Baker pre-compiles all project shaders for the target platform at export time, eliminating the stutter players experience the first time a new material renders in-game — especially severe on macOS/Apple Silicon (Metal) and Windows (D3D12), where shader translation is expensive. Enable it per export preset for release builds; leave it off for development builds to keep exports fast. It operates at the Godot export pipeline level — see the export-pipeline skill for export preset configuration.

See references/shader-baker.md for enabling steps and the with/without comparison.


12. Common Pitfalls

SymptomCauseFix
Shader has no visible effectMaterial not assigned or shader not savedCheck node's Material property in Inspector
Transparent parts render as blackAlpha not handled in shaderSet COLOR.a = tex.a; and use appropriate blend mode
Uniform doesn't appear in InspectorTypo in uniform name or wrong typeRe-save the shader; check for compilation errors
Texture appears stretched/tiledMissing repeat_enable or wrong UV scaleAdd repeat_enable hint to sampler2D uniform
Shader works in editor but not in gameScreen texture uniform needs backbufferUse hint_screen_texture on a sampler2D uniform (Godot 4.x)
Performance drops with many shadersEach unique shader = draw call breakShare ShaderMaterial instances; use uniforms for variation
Screen-space UV is wrongSCREEN_UV not available in some contextsEnsure the node is rendered in the correct viewport
Visual shader node missingNode was renamed or removed in newer Godot versionCheck Godot docs for the current node name

⚠️ Changed in Godot 4.7: textureQueryLod() is available only in the fragment shader, and Godot 4.7 enforces this with a compile error — shaders calling it from vertex() stop compiling after upgrading. Move the call into fragment(). See GH-118962.


13. Implementation Checklist

  • Shader type matches the node type (canvas_item for 2D, spatial for 3D)
  • Uniforms use appropriate hints (hint_range, source_color, filter_linear_mipmap)
  • Shared visual effects use the same Shader resource with separate ShaderMaterial instances
  • Post-processing shaders are on a CanvasLayer (2D) or WorldEnvironment (3D), not on game objects
  • TEXTURE is sampled in canvas_item shaders (otherwise sprite content is lost)
  • Alpha-transparent shaders set COLOR.a correctly and use blend_mix render mode
  • Animated shader parameters (dissolve, flash) are driven by Tweens or AnimationPlayer, not _process
  • Screen-reading shaders use hint_screen_texture on a sampler2D uniform (Godot 4.x approach)
  • Complex shaders are profiled with the Godot profiler to check GPU frame time
  • Stencil effects use two-pass materials (write pass first, read pass second) with correct render priority (Godot 4.5+)
  • SMAA is preferred over FXAA for desktop builds (sharper edges, similar cost) — set in Project Settings → Rendering → Anti Aliasing (Godot 4.5+)
  • Shader Baker is enabled in all release export presets to eliminate first-use compilation stutters (Godot 4.5+)

Файлы в комплекте

Модель читает эти файлы по мере необходимости, пока навык загружен. Они доступны только для чтения и никогда не выполняются.

Часто задаваемые вопросы

Что делает навык ИИ Shader Basics?

Используйте при реализации шейдеров — язык шейдеров Godot, визуальные шейдеры, распространённые визуальные приёмы и эффекты постобработки

Зачем использовать Shader Basics в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Shader Basics — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Shader Basics в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/jame581/GodotPrompter/tree/master/skills/shader-basics. TypingMind прочитает файл SKILL.md, включит сопутствующие файлы в пакет и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Shader Basics?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Shader Basics?

С любым количеством. В TypingMind вы можете использовать Shader Basics с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Shader Basics?

Да. Навык опубликован на GitHub по лицензии MIT. Издатель — jame581. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все
Логотип affaan-m

Plan Canvas

affaan-m
СообществоПопулярный

Open plans and HTML artifacts in a local browser canvas where the human annotates elements, chats, and approves or requests changes without leaving the page. Use when presenting a plan for review, or…

40.4K
270.2K
Файлы: 1
Открыть
Логотип mattpocock

Improve Codebase Architecture

mattpocock
СообществоПопулярный

Просканируйте кодовую базу в поисках возможностей для дальнейшего развития, представьте их в виде наглядного HTML-отчёта, а затем тщательно разберите выбранный вами вариант.

22.3K
264.4K
Файлы: 2
Открыть
Логотип mattpocock

Grilling

mattpocock
СообществоПопулярный

Неустанно расспрашивайте пользователя о плане, решении или идее, подвергая их жесткой проверке. Используйте, если пользователь хочет проверить свои рассуждения на прочность или использует любую из фраз-триггеров со словом «grill».

22.3K
264.4K
Файлы: 1
Открыть
Логотип mattpocock

Teach

mattpocock
СообществоПопулярный

Научите пользователя новому навыку или концепции в рамках этого рабочего пространства.

22.3K
264.4K
Файлы: 5
Открыть

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇