1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;
namespace LightTest
{
internal static class Program
{
static void Main()
{
using (var app = new RenderEngine())
{
app.Run();
}
}
}
internal class RenderEngine : GameWindow
{
private readonly int _width = 800;
private readonly int _height = 600;
private readonly List<Light> _lights = new List<Light>();
private readonly List<Block> _blocks = new List<Block>();
private int _fragmentShader;
private int _shaderProgram;
private Random r = new Random();
public RenderEngine() : base(800, 600, GraphicsMode.Default, "2D lighting test", GameWindowFlags.FixedWindow) { }
protected override void OnLoad(EventArgs e)
{
SetUpObjects();
Initialize();
}
protected override void OnClosing(CancelEventArgs cancelEventArgs)
{
Cleanup();
}
protected override void OnRenderFrame(FrameEventArgs e)
{
GL.Clear(ClearBufferMask.ColorBufferBit);
foreach (var light in _lights) // Для каждого источника света подрубаем stencil буфер
{
GL.ColorMask(false, false, false, false);
GL.StencilFunc(StencilFunction.Always, 1, 1);
GL.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Replace);
foreach (var block in _blocks) // Тут мы должны рассчитать и отрисовать тень для stencil буфера
{
Vector2[] vertices = block.GetVertices();
for (int i = 0; i < vertices.Length; i++)
{
Vector2 currentVertex = vertices[i];
Vector2 nextVertex = vertices[(i + 1) % vertices.Length];
Vector2 edge = Vector2.Subtract(nextVertex, currentVertex);
Vector2 normal = new Vector2(edge.Y, -edge.X);
Vector2 lightToCurrent = Vector2.Subtract(currentVertex, light.Location);
if (Vector2.Dot(normal, lightToCurrent) > 0)
{
Vector2 tmp1;
Vector2.Subtract(ref nextVertex, ref light.Location, out tmp1);
Vector2 point1 = Vector2.Add(currentVertex, Vector2.Multiply(tmp1, 500));
Vector2 tmp2;
Vector2.Subtract(ref nextVertex, ref light.Location, out tmp2);
Vector2 point2 = Vector2.Add(nextVertex, Vector2.Multiply(tmp2, 500));
GL.Begin(PrimitiveType.Quads);
GL.Vertex2(currentVertex.X, currentVertex.Y);
GL.Vertex2(point1.X, point1.Y);
GL.Vertex2(point2.X, point2.Y);
GL.Vertex2(nextVertex.X, nextVertex.Y);
GL.End();
}
}
}
GL.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Keep); // Отрубаем stencil буфер
GL.StencilFunc(StencilFunction.Equal, 0, 1);
GL.ColorMask(true, true, true, true);
GL.UseProgram(_shaderProgram); // И отрисовываем свет через шейдер там, где буфер пуст
GL.Uniform2(GL.GetUniformLocation(_shaderProgram, "lightLocation"), light.Location.X, _height - light.Location.Y);
GL.Uniform3(GL.GetUniformLocation(_shaderProgram, "lightColor"), light.Red, light.Green, light.Blue);
GL.Enable(EnableCap.Blend);
GL.BlendFunc(BlendingFactor.One, BlendingFactor.One);
GL.Begin(PrimitiveType.Quads);
GL.Vertex2(0, 0);
GL.Vertex2(0, _height);
GL.Vertex2(_width, _height);
GL.Vertex2(_width, 0);
GL.End();
GL.Disable(EnableCap.Blend);
GL.UseProgram(0);
GL.Clear(ClearBufferMask.StencilBufferBit);
}
GL.Color3(0, 0, 0);
foreach (var block in _blocks) // Тут рисуем блоки
{
GL.Begin(PrimitiveType.Quads);
foreach (var vertex in block.GetVertices())
{
GL.Vertex2(vertex.X, vertex.Y);
}
GL.End();
}
SwapBuffers();
base.OnRenderFrame(e);
}
protected override void OnKeyDown(KeyboardKeyEventArgs e)
{
if (e.Key == Key.Escape) Close();
}
protected override void OnMouseWheel(MouseWheelEventArgs mouseWheelEventArgs)
{
if (mouseWheelEventArgs.Delta > 1) // Крутится вперёд
{
_lights[0].Red++;
_lights[0].Green++;
_lights[0].Blue++;
}
if (mouseWheelEventArgs.Delta < 1) // Крутится назад
{
_lights[0].Red--;
_lights[0].Green--;
_lights[0].Blue--;
}
}
protected override void OnMouseMove(MouseMoveEventArgs mouseMoveEventArgs)
{
_lights[0].Location.X = mouseMoveEventArgs.Position.X;
_lights[0].Location.Y = mouseMoveEventArgs.Position.Y - 40; // Погрешность на заголовок окна (WindowBorder.Fixed)
}
private void SetUpObjects() // Тут накидывем свет и блоки на сцену
{
int lightCount = 1 + r.Next(5);
int blockCount = 1 + r.Next(10);
for (int i = 1; i <= lightCount; i++)
{
Vector2 location = new Vector2(r.Next(_width), r.Next(_height));
_lights.Add(new Light(location, r.Next(10), r.Next(10), r.Next(10)));
}
for (int i = 1; i <= blockCount; i++)
{
int lwidth = 50;
int lheight = 50;
int x = r.Next(_width - lwidth);
int y = r.Next(_height - lheight);
_blocks.Add(new Block(x, y, lwidth, lheight));
}
}
private void Initialize() // Тут вся инициализация
{
_shaderProgram = GL.CreateProgram();
_fragmentShader = GL.CreateShader(ShaderType.FragmentShader);
const string fragmentShaderSource =
@"#version 420 core
uniform vec2 lightLocation;
uniform vec3 lightColor;
void main()
{
float distance = length(lightLocation - gl_FragCoord.xy);
float attenuation = 1.0 / distance;
vec4 color = vec4(attenuation, attenuation, attenuation, pow(attenuation, 3)) * vec4(lightColor, 1);
gl_FragColor = color;
}";
GL.ShaderSource(_fragmentShader, fragmentShaderSource);
GL.CompileShader(_fragmentShader);
int res;
GL.GetShader(_fragmentShader, ShaderParameter.CompileStatus, out res);
if (res == 0)
Console.WriteLine("Чекай шейдер, он не компилится.");
GL.AttachShader(_shaderProgram, _fragmentShader);
GL.LinkProgram(_shaderProgram);
GL.ValidateProgram(_shaderProgram);
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Ortho(0, _width, _height, 0, 1, -1);
GL.MatrixMode(MatrixMode.Modelview);
GL.Enable(EnableCap.StencilTest);
GL.ClearColor(0.0f, 0.0f, 0.0f, 0.0f);
}
private void Cleanup()
{
GL.DeleteShader(_fragmentShader);
GL.DeleteProgram(_shaderProgram);
}
}
} |