Логотип Forge Basic Lighting

Forge Basic Lighting

Спільнота
Nebulavenus
forge-basic-lighting

Add Blinn-Phong lighting (ambient + diffuse + specular) to a 3D scene with world-space normals, light direction, and camera position uniforms. Use when someone needs to light a mesh, add shading, or implement basic real-time lighting in SDL3 GPU.

Огляд

ВидавецьNebulavenus
Репозиторійforge-gpu
Назва навичкиforge-basic-lighting
Зірки
46
Форки
7
Файли в пакеті
Лише інструкції
ЛіцензіяZlib
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Усе необхідне — в інструкціях

    Усе потрібне моделі міститься в інструкціях — жодних додаткових файлів для синхронізації.

  • Відкритий вихідний код

    Опубліковано на GitHub користувачем Nebulavenus. Перегляньте вихідний вміст перед установленням.

Встановлення

Установіть навичку ШІ Forge Basic Lighting у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до Плагіни → Навички.
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/Nebulavenus/forge-gpu/tree/main/.claude/skills/forge-basic-lighting
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Нова навичка → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Nebulavenus/forge-gpu.git /tmp/forge-gpu
mkdir -p .claude/skills
cp -r /tmp/forge-gpu/.claude/skills/forge-basic-lighting .claude/skills/forge-basic-lighting
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Forge Basic Lighting в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Forge Basic Lighting, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції Markdown, а не код для певного постачальника, тому навичка Forge Basic Lighting не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож невикористана навичка нічого не коштує.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

Basic Lighting — Blinn-Phong Shading

This skill teaches how to add Blinn-Phong lighting to a rendered 3D scene. It builds on scene-loading (Lesson 09) and adds world-space lighting calculations in the fragment shader.

When to use

  • Adding lighting/shading to a 3D model or scene
  • Implementing ambient, diffuse, or specular shading
  • Passing light direction and camera position as shader uniforms
  • Transforming normals from object space to world space
  • Setting up a fragment shader with per-pixel lighting

Key API calls (ordered)

  1. forge_gltf_load(path, &scene) — parse glTF (provides normals)
  2. Upload vertex + index buffers to GPU (same as scene-loading skill)
  3. SDL_CreateGPUGraphicsPipeline — 3 vertex attributes (pos, normal, uv)
  4. SDL_PushGPUVertexUniformData — push MVP matrix + Model matrix (128 bytes)
  5. SDL_PushGPUFragmentUniformData — push lighting params (64 bytes)
  6. SDL_DrawGPUIndexedPrimitives — draw with lighting

Uniform layouts

Vertex uniforms (128 bytes)

Both matrices must be column_major in HLSL to match C mat4 layout.

c
typedef struct VertUniforms {
    mat4 mvp;     /* combined Model-View-Projection for clip space */
    mat4 model;   /* model (world) matrix for lighting calculations */
} VertUniforms;
hlsl
cbuffer VertUniforms : register(b0, space1)
{
    column_major float4x4 mvp;
    column_major float4x4 model;
};

Fragment uniforms (64 bytes)

Use float4 (not float3) for vectors to avoid HLSL cbuffer packing issues.

c
typedef struct FragUniforms {
    float base_color[4];   /* material color (RGBA)              */
    float light_dir[4];    /* normalized, toward light (xyz)     */
    float eye_pos[4];      /* camera world position (xyz)        */
    Uint32 has_texture;    /* 0 = solid color, 1 = sample tex    */
    float shininess;       /* specular exponent (32, 64, 128...) */
    float ambient;         /* ambient intensity [0..1]           */
    float specular_str;    /* specular intensity [0..1]          */
} FragUniforms;
hlsl
cbuffer FragUniforms : register(b0, space3)
{
    float4 base_color;
    float4 light_dir;
    float4 eye_pos;
    uint   has_texture;
    float  shininess;
    float  ambient;
    float  specular_str;
};

Code template

Vertex shader — normal transformation (adjugate transpose)

hlsl
/* World-space position for view direction calculation */
float4 wp = mul(model, float4(input.position, 1.0));
output.world_pos = wp.xyz;

/* Transform normal by the ADJUGATE TRANSPOSE of the model matrix's
 * upper-left 3x3.  Unlike (float3x3)model, this preserves
 * perpendicularity even under non-uniform scale.  The rows of the
 * adjugate transpose are cross products of pairs of model matrix rows.
 * Do NOT normalize here — the rasterizer will interpolate, and we
 * normalize per-pixel in the fragment shader. */
float3x3 m = (float3x3)model;
float3x3 adj_t;
adj_t[0] = cross(m[1], m[2]);
adj_t[1] = cross(m[2], m[0]);
adj_t[2] = cross(m[0], m[1]);
output.world_norm = mul(adj_t, input.normal);

Fragment shader — Blinn-Phong

hlsl
/* MUST normalize after interpolation — interpolated normals aren't unit length */
float3 N = normalize(input.world_norm);
float3 L = normalize(light_dir.xyz);          /* toward light */
float3 V = normalize(eye_pos.xyz - input.world_pos);  /* toward camera */

/* Ambient: constant minimum brightness */
float3 ambient_term = ambient * surface_color.rgb;

/* Diffuse: Lambert's cosine law */
float NdotL = max(dot(N, L), 0.0);
float3 diffuse_term = NdotL * surface_color.rgb;

/* Specular: Blinn half-vector */
float3 H = normalize(L + V);
float NdotH = max(dot(N, H), 0.0);
float3 specular_term = specular_str * pow(NdotH, shininess) * float3(1, 1, 1);

float3 final = ambient_term + diffuse_term + specular_term;

C side — pushing lighting uniforms

c
/* Vertex: MVP + model matrix */
VertUniforms vu;
vu.mvp   = mat4_multiply(vp, node->world_transform);
vu.model = node->world_transform;
SDL_PushGPUVertexUniformData(cmd, 0, &vu, sizeof(vu));

/* Fragment: material + lighting */
FragUniforms fu;
fu.base_color[0] = mat->base_color[0]; /* ... etc */
fu.light_dir[0] = light_dir.x;
fu.light_dir[1] = light_dir.y;
fu.light_dir[2] = light_dir.z;
fu.light_dir[3] = 0.0f;
fu.eye_pos[0] = cam_pos.x;
fu.eye_pos[1] = cam_pos.y;
fu.eye_pos[2] = cam_pos.z;
fu.eye_pos[3] = 0.0f;
fu.shininess    = 64.0f;
fu.ambient      = 0.15f;
fu.specular_str = 0.5f;
SDL_PushGPUFragmentUniformData(cmd, 0, &fu, sizeof(fu));

Common mistakes

  1. Forgetting to normalize interpolated normals — The rasterizer interpolates vertex shader outputs linearly. Even if every vertex normal is unit length, the interpolated result won't be. Always normalize() in the fragment shader.

  2. Missing column_major on both matrices — If you add the model matrix but forget column_major, the multiplication will be wrong. Both mvp and model must have it.

  3. Using float3 in the cbuffer — HLSL packs float3 to 16 bytes with 4 bytes of padding, which silently misaligns subsequent fields. Use float4 and explicitly pad the w component to 0.

  4. Light direction convention — Our convention: light_dir points FROM the surface TOWARD the light. Some tutorials use the opposite. If your model looks like the dark side is lit, negate the direction.

  5. Normalizing in the vertex shader — Don't normalize normals in the vertex shader. The rasterizer will interpolate them anyway, making the normalization pointless. Save it for the fragment shader.

  6. Normal transformation with non-uniform scale — (float3x3)model only works correctly for rotation + uniform scale. Always use the adjugate transpose instead — three cross products of the matrix rows: adj_t[0] = cross(m[1], m[2]) etc. This is correct for ALL matrices (including singular ones) and cheaper than inverse-transpose.

Typical parameter values

ParameterValueEffect
shininess8-16Rough, matte surface
shininess32-64Typical plastic / painted
shininess128-256Polished, metallic
ambient0.05-0.15Subtle fill light
ambient0.2-0.3Bright ambient (indoor)
specular_str0.3-0.5Moderate shine
specular_str0.8-1.0Very shiny / wet

References

  • GPU Lesson 10 — Basic Lighting (full implementation)
  • Math Lesson 01 — Vectors (dot product, normalize)
  • Math Lesson 02 — Coordinate Spaces (object, world, view)
  • Math Lesson 05 — Matrices (model matrix transformation)

Поширені запитання

Що робить навичка ШІ Forge Basic Lighting?

Add Blinn-Phong lighting (ambient + diffuse + specular) to a 3D scene with world-space normals, light direction, and camera position uniforms. Use when someone needs to light a mesh, add shading, or implement basic real-time lighting in SDL3 GPU.

Навіщо використовувати Forge Basic Lighting у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Forge Basic Lighting — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Forge Basic Lighting у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/Nebulavenus/forge-gpu/tree/main/.claude/skills/forge-basic-lighting. TypingMind прочитає файл SKILL.md і встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Forge Basic Lighting?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Forge Basic Lighting?

Зі скількома забажаєте. Якщо модель підтримує навички, ви можете використовувати з нею Forge Basic Lighting — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama та інші — усе в TypingMind із власними ключами API.

Чи безкоштовна навичка ШІ Forge Basic Lighting?

Так. Навичку опубліковано на GitHub: Nebulavenus, за ліцензією Zlib. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це багаторазовий набір інструкцій, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти для виклику — код, який десь виконується й повертає результат. Натомість навичка ШІ надає моделі знання та порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний ШІ-простір уже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇