使用着色器绘制 2d 灯光?

The*_*ado 1 java opengl glsl lwjgl

我想知道如何创建像这样的 2D 灯光:

https://www.youtube.com/watch?v=mVlYsGOkkyM

和这里:

https://www.youtube.com/watch?v=nSf1MpsWKig

目前我对阴影不感兴趣。我尝试了一些东西,但它们似乎不起作用。所以我目前拥有的只是片段和顶点着色器,里面几乎没有任何东西。

小智 7

光照几乎是计算机图形学的主要问题,有几种常用的实现光照的方法:

更简单但有限的方法称为“前向着色”,总体思路是,将有关照明的所有信息(环境光、灯光位置和颜色等)提供给渲染几何体的着色器,并直接在每个几何体上计算照明您渲染的表面。限制是您只能将固定数量的灯光传递给着色器。

另一种方式称为“延迟着色”,常用于现代游戏引擎中。渲染几何体时,无需照亮几何体,只需收集几何体每个像素的相关数据(位置、颜色、法线等)并将其存储在帧缓冲区中。然后您可以使用这些数据来渲染任意数量的灯光。OGLdev 有一个关于延迟着色的很好的教程,但如果您是初学者,您可能想避免使用它,因为它很难设置并且在旧硬件上速度很慢。http://ogldev.atspace.co.uk/www/tutorial35/tutorial35.html

GLSL 中的一般光照公式为:

// Vector from the current pixel to the light
vec3 toLight = (lightpos - pixelpos);

// This computes how much is the pixel lit based on where it faces
float brightness = clamp(dot(normalize(toLight), pixelnormal), 0.0, 1.0);

// If it faces towards the light it is lit fully, if it is perpendicular
// to the direction towards the light then it is not lit at all.

// This reduces the brightness based on the distance form the light and the light's radius
brightness *= clamp(1.0 - (length(toLight) / lightradius), 0.0, 1.0);
// The final color of the pixel.
vec3 finalcolor = pixelcolor * lightcolor * brightness;
// If you have multiple lights multiply the pixel's color by the combined color of all lights
// like:
finalcolor = pixelcolor * (lightcolor1 * brightness1 + lightcolor2 * brightness2);

// Note that some things are clamped to avoid going into negative values
Run Code Online (Sandbox Code Playgroud)