/
lensflares.cpp
565 lines (466 loc) · 16.8 KB
/
lensflares.cpp
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
/** @file lensflares.cpp
*
* @authors Copyright (c) 2013-2017 Jaakko Keränen <jaakko.keranen@iki.fi>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, see:
* http://www.gnu.org/licenses</small>
*/
#include "render/fx/lensflares.h"
#include "render/ilightsource.h"
#include "render/viewports.h"
#include "render/rend_main.h"
#include "world/clientserverworld.h"
#include "world/p_players.h"
#include "gl/gl_main.h"
#include "clientapp.h"
#include <de/concurrency.h>
#include <doomsday/console/cmd.h>
#include <de/Drawable>
#include <de/FileSystem>
#include <de/KdTreeAtlasAllocator>
#include <de/LogBuffer>
#include <de/Range>
#include <de/Shared>
#include <QHash>
#include <cmath>
//#define FX_TEST_LIGHT // draw a test light (positioned for Doom E1M1)
using namespace de;
namespace fx {
/**
* Shared GL resources for rendering lens flares.
*/
struct FlareData
{
ImageBank images;
AtlasTexture atlas;
enum FlareId {
Burst,
Circle,
Exponent,
Halo,
Ring,
Star,
MAX_FLARES
};
enum Corner {
TopLeft,
TopRight,
BottomRight,
BottomLeft
};
NoneId flare[MAX_FLARES];
FlareData()
: atlas(Atlas::BackingStore, Atlas::Size(1024, 1024))
{
try
{
DENG_ASSERT_IN_MAIN_THREAD();
DENG_ASSERT_GL_CONTEXT_ACTIVE();
images.addFromInfo(App::rootFolder().locate<File>("/packs/feature.lensflares/images.dei"));
atlas.setAllocator(new KdTreeAtlasAllocator);
flare[Exponent] = atlas.alloc(flareImage("exponent"));
flare[Star] = atlas.alloc(flareImage("star"));
flare[Halo] = atlas.alloc(flareImage("halo"));
flare[Circle] = atlas.alloc(flareImage("circle"));
flare[Ring] = atlas.alloc(flareImage("ring"));
flare[Burst] = atlas.alloc(flareImage("burst"));
}
catch (Error const &er)
{
LOG_GL_ERROR("Failed to initialize shared lens flare resources: %s")
<< er.asText();
}
}
~FlareData()
{
DENG_ASSERT_IN_MAIN_THREAD();
DENG_ASSERT_GL_CONTEXT_ACTIVE();
LOGDEV_GL_XVERBOSE("Releasing shared data", "");
}
Image const &flareImage(String const &name)
{
return images.image("fx.lensflares." + name);
}
Rectanglef uvRect(FlareId id) const
{
return atlas.imageRectf(flare[id]);
}
Vector2f flareCorner(FlareId id, Corner corner) const
{
Vector2f p;
switch (corner)
{
case TopLeft: p = Vector2f(-1, -1); break;
case TopRight: p = Vector2f( 1, -1); break;
case BottomRight: p = Vector2f( 1, 1); break;
case BottomLeft: p = Vector2f(-1, 1); break;
}
if (id == Burst)
{
// Non-square.
p *= Vector2f(4, .25f);
}
return p;
}
};
#ifdef FX_TEST_LIGHT
struct TestLight : public IPointLightSource
{
public:
float radius;
Colorf color;
float intensity;
TestLight() : radius(1), color(1, 1, 1), intensity(1)
{}
LightId lightSourceId() const {
return 1;
}
Origin lightSourceOrigin() const {
//return Origin(0, 0, 0);
return Origin(782, -3227, 30);
}
dfloat lightSourceRadius() const {
return radius;
}
Colorf lightSourceColorf() const {
return color;
}
dfloat lightSourceIntensity(de::Vector3d const &) const {
return intensity;
}
};
static TestLight testLight;
D_CMD(TestLight)
{
String prop = argv[1];
float value = String(argv[2]).toFloat();
if (!prop.compareWithoutCase("rd"))
{
fx::testLight.radius = value;
}
else if (!prop.compareWithoutCase("in"))
{
fx::testLight.intensity = value;
}
else if (!prop.compareWithoutCase("cl") && argc >= 5)
{
fx::testLight.color = ILightSource::Colorf(value, String(argv[3]).toFloat(), String(argv[4]).toFloat());
}
else
{
return false;
}
return true;
}
#endif
static float linearRangeFactor(float value, Rangef const &low, Rangef const &high)
{
if (low.size() > 0)
{
if (value < low.start)
{
return 0;
}
if (low.contains(value))
{
return (value - low.start) / low.size();
}
}
if (high.size() > 0)
{
if (value > high.end)
{
return 0;
}
if (high.contains(value))
{
return 1 - (value - high.start) / high.size();
}
}
return 1;
}
DENG2_PIMPL(LensFlares)
{
typedef Shared<FlareData> SharedFlareData;
SharedFlareData *res;
/**
* Current state of a potentially visible light.
*/
struct PVLight
{
IPointLightSource const *light;
int seenFrame; // R_FrameCount()
PVLight() : light(0), seenFrame(0)
{}
};
typedef QHash<IPointLightSource::LightId, PVLight *> PVSet;
PVSet pvs;
Vector3f eyeFront;
typedef GLBufferT<Vertex3Tex3Rgba> VBuf;
VBuf *buffer;
Drawable drawable;
GLUniform uMvpMatrix;
GLUniform uViewUnit;
GLUniform uPixelAsUv;
GLUniform uActiveRect;
GLUniform uAtlas;
GLUniform uDepthBuf;
Impl(Public *i)
: Base(i)
, res(0)
, buffer(0)
, uMvpMatrix ("uMvpMatrix", GLUniform::Mat4)
, uViewUnit ("uViewUnit", GLUniform::Vec2)
, uPixelAsUv ("uPixelAsUv", GLUniform::Vec2)
, uActiveRect("uActiveRect", GLUniform::Vec4)
, uAtlas ("uTex", GLUniform::Sampler2D)
, uDepthBuf ("uDepthBuf", GLUniform::Sampler2D)
{}
~Impl()
{
DENG2_ASSERT(res == 0); // should have been deinited
releaseRef(res);
clearPvs();
}
void glInit()
{
// Acquire a reference to the shared flare data.
res = SharedFlareData::hold();
buffer = new VBuf;
drawable.addBuffer(buffer);
self().shaders().build(drawable.program(), "fx.lensflares")
<< uMvpMatrix
<< uViewUnit << uPixelAsUv << uActiveRect
<< uAtlas << uDepthBuf;
uAtlas = res->atlas;
}
void glDeinit()
{
drawable.clear();
buffer = 0;
clearPvs();
releaseRef(res);
}
void clearPvs()
{
qDeleteAll(pvs);
pvs.clear();
}
void addToPvs(IPointLightSource const *light)
{
PVSet::iterator found = pvs.find(light->lightSourceId());
if (found == pvs.end())
{
found = pvs.insert(light->lightSourceId(), new PVLight);
}
PVLight *pvl = found.value();
pvl->light = light;
pvl->seenFrame = R_FrameCount();
}
void makeFlare(VBuf::Vertices & verts,
VBuf::Indices & idx,
FlareData::FlareId id,
float axisPos,
float radius,
Vector4f color,
PVLight const * pvl)
{
Rectanglef const uvRect = res->uvRect(id);
int const firstIdx = verts.size();
VBuf::Type vtx;
vtx.pos = pvl->light->lightSourceOrigin().xzy();
vtx.rgba = Vector4f(pvl->light->lightSourceColorf(), 1.f) * color;
vtx.texCoord[2] = Vector2f(axisPos, 0);
vtx.texCoord[0] = uvRect.topLeft;
vtx.texCoord[1] = res->flareCorner(id, FlareData::TopLeft) * radius;
verts << vtx;
vtx.texCoord[0] = uvRect.topRight();
vtx.texCoord[1] = res->flareCorner(id, FlareData::TopRight) * radius;
verts << vtx;
vtx.texCoord[0] = uvRect.bottomRight;
vtx.texCoord[1] = res->flareCorner(id, FlareData::BottomRight) * radius;
verts << vtx;
vtx.texCoord[0] = uvRect.bottomLeft();
vtx.texCoord[1] = res->flareCorner(id, FlareData::BottomLeft) * radius;
verts << vtx;
// Make two triangles.
idx << firstIdx << firstIdx + 1 << firstIdx + 2
<< firstIdx << firstIdx + 2 << firstIdx + 3;
}
void makeVerticesForPVS()
{
int const thisFrame = R_FrameCount();
// The vertex buffer will contain a number of quads.
VBuf::Vertices verts;
VBuf::Indices idx;
VBuf::Type vtx;
for (PVSet::const_iterator i = pvs.constBegin(); i != pvs.constEnd(); ++i)
{
PVLight const *pvl = i.value();
// Skip lights that are not visible right now.
/// @todo If so, it might be time to purge it from the PVS.
if (pvl->seenFrame != thisFrame) continue;
coord_t const distanceSquared = (Rend_EyeOrigin() - pvl->light->lightSourceOrigin().xzy()).lengthSquared();
coord_t const distance = std::sqrt(distanceSquared);
// Light intensity is always quadratic per distance.
float intensity = pvl->light->lightSourceIntensity(Rend_EyeOrigin()) / distanceSquared;
// Projected radius of the light.
float const RADIUS_FACTOR = 128; // Light radius of 1 at this distance produces a visible radius of 1.
/// @todo The factor should be FOV-dependent.
float radius = pvl->light->lightSourceRadius() / distance * RADIUS_FACTOR;
float const dot = (pvl->light->lightSourceOrigin().xzy() - Rend_EyeOrigin()).normalize().dot(eyeFront);
float const angle = radianToDegree(std::acos(dot));
//qDebug() << "i:" << intensity << "r:" << radius << "IR:" << radius*intensity;
/*
* The main flare.
* - small + bright => burst
* - big + bright => star
* - small + dim => exponent
* - big + dim => exponent
*/
struct Spec {
float axisPos;
FlareData::FlareId id;
Vector4f color;
float size;
Rangef minIntensity;
Rangef maxIntensity;
Rangef minRadius;
Rangef maxRadius;
Rangef minAngle;
Rangef maxAngle;
};
typedef Rangef Rgf;
static Spec const specs[] = {
// axisPos id color size intensity min/max radius min/max angle min/max
{ 1, FlareData::Burst, Vector4f(1, 1, 1, 1), 1, Rgf(1.0e-8f, 1.0e-6f), Rgf(), Rgf(), Rgf(.5f, .8f), Rgf(), Rgf() },
{ 1, FlareData::Star, Vector4f(1, 1, 1, 1), 1, Rgf(1.0e-6f, 1.0e-5f), Rgf(), Rgf(.5f, .7f), Rgf(), Rgf(), Rgf() },
{ 1, FlareData::Exponent, Vector4f(1, 1, 1, 1), 2.5f, Rgf(1.0e-6f, 1.0e-5f), Rgf(), Rgf(.1f, .2f), Rgf(), Rgf(), Rgf() },
{ .8f, FlareData::Halo, Vector4f(1, 1, 1, .5f), 1, Rgf(5.0e-6f, 5.0e-5f), Rgf(), Rgf(.5f, .7f), Rgf(), Rgf(), Rgf(30, 60) },
{ -.8f, FlareData::Ring, Vector4f(.4f, 1, .4f, .26f), .4f, Rgf(1.0e-5f, 1.0e-4f), Rgf(), Rgf(.1f, .5f), Rgf(), Rgf(5, 20), Rgf(40, 50) },
{ -1, FlareData::Circle, Vector4f(.4f, .4f, 1, .30f), .5f, Rgf(4.0e-6f, 4.0e-5f), Rgf(), Rgf(.08f, .45f), Rgf(), Rgf(0, 23), Rgf(30, 60) },
{ -1.2f , FlareData::Ring, Vector4f(1, .4f, .4f, .26f), .56f, Rgf(1.0e-5f, 1.0e-4f), Rgf(), Rgf(.1f, .5f), Rgf(), Rgf(10, 25), Rgf(35, 50) },
{ 1.333f, FlareData::Ring, Vector4f(.5f, .5f, 1, .1f), 1.2f, Rgf(1.0e-8f, 1.0e-7f), Rgf(), Rgf(.1f, .5f), Rgf(), Rgf(10, 25), Rgf(25, 45) },
{ 1.45f, FlareData::Ring, Vector4f(1, .5f, .5f, .15f), 1.15f, Rgf(1.0e-8f, 1.0e-7f), Rgf(), Rgf(.1f, .5f), Rgf(), Rgf(10, 25), Rgf(25, 45) },
{ -1.45f, FlareData::Ring, Vector4f(1, 1, .9f, .25f), .2f, Rgf(1.0e-5f, 1.0e-4f), Rgf(), Rgf(.1f, .4f), Rgf(), Rgf(5, 10), Rgf(15, 30) },
{ -.2f, FlareData::Circle, Vector4f(1, 1, .9f, .2f), .23f, Rgf(1.0e-5f, 1.0e-4f), Rgf(), Rgf(.1f, .4f), Rgf(), Rgf(5, 10), Rgf(15, 30) },
};
for (uint i = 0; i < sizeof(specs)/sizeof(specs[0]); ++i)
{
Spec const &spec = specs[i];
float size = radius * spec.size;
Vector4f color = spec.color;
// Apply limits.
color.w *= linearRangeFactor(intensity, spec.minIntensity, spec.maxIntensity);
color.w *= linearRangeFactor(radius, spec.minRadius, spec.maxRadius);
color.w *= linearRangeFactor(angle, spec.minAngle, spec.maxAngle);
//qDebug() << linearRangeFactor(intensity, spec.minIntensity, spec.maxIntensity);
//qDebug() << linearRangeFactor(radius, spec.minRadius, spec.maxRadius);
makeFlare(verts, idx, spec.id, spec.axisPos, size, color, pvl);
}
//makeFlare(verts, idx, FlareData::Halo, -1, size, pvl);
/*
// Project viewtocenter vector onto viewSideVec.
Vector3f const eyeToFlare = pvl->lightSourceOrigin() - eyePos;
// Calculate the 'mirror' vector.
float const scale = viewToCenter.dot(viewData->frontVec)
/ Vector3f(viewData->frontVec).dot(viewData->frontVec);
Vector3f const mirror =
(Vector3f(viewData->frontVec) * scale - viewToCenter) * 2;
*/
}
buffer->setVertices(verts, gl::Dynamic);
buffer->setIndices(gl::Triangles, idx, gl::Dynamic);
}
};
LensFlares::LensFlares(int console) : ConsoleEffect(console), d(new Impl(this))
{}
void LensFlares::clearLights()
{
d->clearPvs();
}
void LensFlares::markLightPotentiallyVisibleForCurrentFrame(IPointLightSource const *lightSource)
{
d->addToPvs(lightSource);
}
void LensFlares::glInit()
{
LOG_AS("fx::LensFlares");
ConsoleEffect::glInit();
d->glInit();
}
void LensFlares::glDeinit()
{
LOG_AS("fx::LensFlares");
d->glDeinit();
ConsoleEffect::glDeinit();
}
void fx::LensFlares::beginFrame()
{
#ifdef FX_TEST_LIGHT
markLightPotentiallyVisibleForCurrentFrame(&testLight); // testing
#endif
d->makeVerticesForPVS();
}
void LensFlares::draw()
{
if (!ClientApp::world().hasMap())
{
// Flares are not visbile unless a map is loaded.
return;
}
if (!viewPlayer) return; /// @todo How'd we get here? -ds
viewdata_t const *viewData = &DD_Player(console())->viewport();
d->eyeFront = Vector3f(viewData->frontVec);
Rectanglef const rect = viewRect();
float const aspect = rect.height() / rect.width();
GLWindow &window = ClientWindow::main();
d->uViewUnit = Vector2f(aspect, 1.f);
d->uPixelAsUv = Vector2f(1.f / window.pixelWidth(), 1.f / window.pixelHeight());
d->uMvpMatrix = Viewer_Matrix(); //Rend_GetProjectionMatrix() * Rend_GetModelViewMatrix(console());
DENG2_ASSERT(console() == displayPlayer);
//DENG2_ASSERT(viewPlayer - ddPlayers == displayPlayer);
if (DoomsdayApp::players().indexOf(viewPlayer) != displayPlayer)
{
qDebug() << "LensFrames::draw: viewPlayer != displayPlayer";
return;
}
// Depth information is required for occlusion.
GLFramebuffer &target = GLState::current().target();
GLTexture *depthTex = target.attachedTexture(GLFramebuffer::Depth);
/**
* @todo Handle the situation when depth information is not available in the target.
*/
d->uDepthBuf = depthTex;
// The active rectangle is specified with top/left coordinates, but the shader
// works with bottom/left ones.
Vector4f active(target.activeRectScale(), target.activeRectNormalizedOffset());
active.w = 1 - (active.w + active.y); // flip y
d->uActiveRect = active;
GLState::push()
.setCull(gl::None)
.setDepthTest(false)
.setDepthWrite(false)
.setBlend(true)
.setBlendFunc(gl::SrcAlpha, gl::One);
d->drawable.draw();
GLState::pop();
}
void LensFlares::consoleRegister()
{
#ifdef FX_TEST_LIGHT
C_CMD("testlight", "sf*", TestLight)
#endif
}
} // namespace fx
DENG2_SHARED_INSTANCE(fx::FlareData)