forked from projectM-visualizer/projectm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMilkdropSprite.cpp
More file actions
430 lines (362 loc) · 12.9 KB
/
MilkdropSprite.cpp
File metadata and controls
430 lines (362 loc) · 12.9 KB
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
#include "UserSprites/MilkdropSprite.hpp"
#include "SpriteShaders.hpp"
#include <Preset.hpp>
#include <PresetFileParser.hpp>
#include <Renderer/ShaderCache.hpp>
#include <Renderer/TextureManager.hpp>
#include <Utils.hpp>
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <locale>
#include <sstream>
#include <string>
#define REG_VAR(var) \
var = projectm_eval_context_register_variable(spriteCodeContext, #var);
namespace libprojectM {
namespace UserSprites {
MilkdropSprite::MilkdropSprite()
{
RenderItem::Init();
}
void MilkdropSprite::InitVertexAttrib()
{
glEnableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(TexturedPoint), reinterpret_cast<void*>(offsetof(TexturedPoint, x))); // Position
// Color (index 1) is passed as a 4-float constant vertex attribute.
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(TexturedPoint), reinterpret_cast<void*>(offsetof(TexturedPoint, u))); // Texture coordinate
}
void MilkdropSprite::Init(const std::string& spriteData, const Renderer::RenderContext& renderContext)
{
PresetFileParser parser;
std::stringstream spriteDataStream(spriteData);
if (!parser.Read(spriteDataStream))
{
throw SpriteException("Error reading sprite data.");
}
// Load/compile shader
auto spriteShader = renderContext.shaderCache->Get("milkdrop_user_sprite");
if (!spriteShader)
{
// ToDo: Better handle this in the shader class to reduce duplicate code.
#ifdef USE_GLES
// GLES also requires a precision specifier for variables and 3D samplers
constexpr char versionHeader[] = "#version 300 es\n\nprecision mediump float;\nprecision mediump sampler3D;\n";
#else
constexpr char versionHeader[] = "#version 330\n\n";
#endif
spriteShader = std::make_shared<Renderer::Shader>();
spriteShader->CompileProgram(static_cast<const char*>(versionHeader) + kMilkdropSpriteVertexGlsl330,
static_cast<const char*>(versionHeader) + kMilkdropSpriteFragmentGlsl330);
renderContext.shaderCache->Insert("milkdrop_user_sprite", spriteShader);
}
m_spriteShader = spriteShader;
// We ignore the color key value here because OpenGL doesn't support those (DirectX has a specific texture
// render state for this, which replaces the given color value with transparent texels).
// Since sprites are user-supplied, we can just make blend mode 4 based on the texture's alpha channel,
// which gives way better results and users can easily convert any image to PNG.
// Load and compile code
auto initCode = parser.GetCode("init_");
m_codeContext.RunInitCode(initCode, renderContext);
auto perFrameCode = parser.GetCode("code_");
if (!perFrameCode.empty())
{
m_codeContext.perFrameCodeHandle = projectm_eval_code_compile(m_codeContext.spriteCodeContext, perFrameCode.c_str());
if (!m_codeContext.perFrameCodeHandle)
{
int errorLine{};
int errorColumn{};
auto* errorMessage = projectm_eval_get_error(m_codeContext.spriteCodeContext, &errorLine, &errorColumn);
throw SpriteException("Error compiling sprite per-frame code:" + std::string(errorMessage) + " (Line " + std::to_string(errorLine) + ", column " + std::to_string(errorColumn) + ")");
}
}
auto imageName = Utils::ToLower(parser.GetString("img", ""));
// Store texture as a shared_ptr to make sure TextureManager doesn't delete it.
std::locale const loc;
if (imageName.length() >= 6 &&
imageName.substr(0, 4) == "rand" && std::isdigit(imageName.at(4), loc) && std::isdigit(imageName.at(5), loc))
{
m_texture = renderContext.textureManager->GetRandomTexture(imageName).Texture();
}
else
{
m_texture = renderContext.textureManager->GetTexture(imageName).Texture();
}
}
void MilkdropSprite::Draw(const Audio::FrameAudioData& audioData,
const Renderer::RenderContext& renderContext,
uint32_t outputFramebufferObject,
PresetList presets)
{
auto spriteShader = m_spriteShader.lock();
assert(spriteShader.get());
m_codeContext.RunPerFrameCode(audioData, renderContext);
m_spriteDone = *m_codeContext.done != 0.0;
bool burnIn = *m_codeContext.burn != 0.0;
Quad vertices{};
// Get values from expression code and clamp them where necessary.
float x = std::min(1000.0f, std::max(-1000.0f, static_cast<float>(*m_codeContext.x) * 2.0f - 1.0f));
float y = std::min(1000.0f, std::max(-1000.0f, static_cast<float>(*m_codeContext.y) * 2.0f - 1.0f));
float sx = std::min(1000.0f, std::max(-1000.0f, static_cast<float>(*m_codeContext.sx)));
float sy = std::min(1000.0f, std::max(-1000.0f, static_cast<float>(*m_codeContext.sy)));
float rot = static_cast<float>(*m_codeContext.rot);
int flipx = (*m_codeContext.flipx == 0.0) ? 0 : 1; // Comparing float to 0.0 isn't actually a good idea...
int flipy = (*m_codeContext.flipy == 0.0) ? 0 : 1;
float repeatx = std::min(100.0f, std::max(0.01f, static_cast<float>(*m_codeContext.repeatx)));
float repeaty = std::min(100.0f, std::max(0.01f, static_cast<float>(*m_codeContext.repeaty)));
int blendMode = std::min(4, std::max(0, (static_cast<int>(*m_codeContext.blendmode))));
float r = std::min(1.0f, std::max(0.0f, (static_cast<float>(*m_codeContext.r))));
float g = std::min(1.0f, std::max(0.0f, (static_cast<float>(*m_codeContext.g))));
float b = std::min(1.0f, std::max(0.0f, (static_cast<float>(*m_codeContext.b))));
float a = std::min(1.0f, std::max(0.0f, (static_cast<float>(*m_codeContext.a))));
// ToDo: Move all translations to vertex shader
vertices[0 + flipx].x = -sx;
vertices[1 - flipx].x = sx;
vertices[2 + flipx].x = -sx;
vertices[3 - flipx].x = sx;
vertices[0 + flipy * 2].y = -sy;
vertices[1 + flipy * 2].y = -sy;
vertices[2 - flipy * 2].y = sy;
vertices[3 - flipy * 2].y = sy;
// First aspect ratio: adjust for non-1:1 images
{
auto aspect = m_texture->Height() / static_cast<float>(m_texture->Width());
if (aspect < 1.0f)
{
// Landscape image
for (auto& vertex : vertices)
{
vertex.y *= aspect;
}
}
else
{
// Portrait image
for (auto& vertex : vertices)
{
vertex.x /= aspect;
}
}
}
// 2D rotation
{
auto cos_rot = std::cos(rot);
auto sin_rot = std::sin(rot);
for (auto& vertex : vertices)
{
float rotX = vertex.x * cos_rot - vertex.y * sin_rot;
float rotY = vertex.x * sin_rot + vertex.y * cos_rot;
vertex.x = rotX;
vertex.y = rotY;
}
}
// Translation
for (auto& vertex : vertices)
{
vertex.x += x;
vertex.y += y;
}
// Second aspect ratio: normalize to width of screen
{
float aspect = renderContext.viewportSizeX / static_cast<float>(renderContext.viewportSizeY);
if (aspect > 1.0)
{
for (auto& vertex : vertices)
{
vertex.y *= aspect;
}
}
else
{
for (auto& vertex : vertices)
{
vertex.x /= aspect;
}
}
}
// Third aspect ratio: adjust for burn-in
// -> Not required in projectM, as we always render at viewport size, not a fixed 4:3 ratio
// Set u,v coords
{
float dtu = 0.5f;
float dtv = 0.5f;
vertices[0].u = -dtu;
vertices[1].u = dtu;
vertices[2].u = -dtu;
vertices[3].u = dtu;
vertices[0].v = dtv;
vertices[1].v = dtv;
vertices[2].v = -dtv;
vertices[3].v = -dtv;
for (auto& vertex : vertices)
{
vertex.u = (vertex.u - 0.0f) * repeatx + 0.5f;
vertex.v = (vertex.v - 0.0f) * repeaty + 0.5f;
}
}
spriteShader->Bind();
spriteShader->SetUniformInt("blend_mode", blendMode);
spriteShader->SetUniformInt("texture_sampler", 0);
m_texture->Bind(0);
m_sampler.Bind(0);
glBindVertexArray(m_vaoID);
glBindBuffer(GL_ARRAY_BUFFER, m_vboID);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices.data(), GL_DYNAMIC_DRAW);
glVertexAttrib4f(1, r, g, b, a);
switch (blendMode)
{
case 0:
default:
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
break;
case 1:
glDisable(GL_BLEND);
break;
case 2:
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
break;
case 3:
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);
break;
case 4:
// Milkdrop actually changed color keying to using texture alpha. The color key is ignored.
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
break;
}
// Draw to current output buffer
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
if (burnIn)
{
// Also draw into all active preset main textures for next-frame burn-in effect
for (const auto preset : presets)
{
if (!preset.get())
{
continue;
}
preset.get()->BindFramebuffer();
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
// Reset to original FBO
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, static_cast<GLuint>(outputFramebufferObject));
}
glDisable(GL_BLEND);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
m_texture->Unbind(0);
Renderer::Shader::Unbind();
}
auto MilkdropSprite::Done() const -> bool
{
return m_spriteDone;
}
MilkdropSprite::CodeContext::CodeContext()
: spriteCodeContext(projectm_eval_context_create(nullptr, nullptr))
{
}
MilkdropSprite::CodeContext::~CodeContext()
{
projectm_eval_context_destroy(spriteCodeContext);
spriteCodeContext = nullptr;
perFrameCodeHandle = nullptr;
}
void MilkdropSprite::CodeContext::RegisterBuiltinVariables()
{
projectm_eval_context_reset_variables(spriteCodeContext);
// Input variables
REG_VAR(time);
REG_VAR(frame);
REG_VAR(fps);
REG_VAR(progress);
REG_VAR(bass);
REG_VAR(mid);
REG_VAR(treb);
REG_VAR(bass_att);
REG_VAR(mid_att);
REG_VAR(treb_att);
// Output variables
REG_VAR(done);
REG_VAR(burn);
REG_VAR(x);
REG_VAR(y);
REG_VAR(sx);
REG_VAR(sy);
REG_VAR(rot);
REG_VAR(flipx);
REG_VAR(flipy);
REG_VAR(repeatx);
REG_VAR(repeaty);
REG_VAR(blendmode);
REG_VAR(r);
REG_VAR(g);
REG_VAR(b);
REG_VAR(a);
}
void MilkdropSprite::CodeContext::RunInitCode(const std::string& initCode, const Renderer::RenderContext& renderContext)
{
RegisterBuiltinVariables();
// Set default values of output variables:
// (by not setting these every frame, we allow the values to persist from frame-to-frame.)
*x = 0.5;
*y = 0.5;
*sx = 1.0;
*sy = 1.0;
*repeatx = 1.0;
*repeaty = 1.0;
*rot = 0.0;
*flipx = 0.0;
*flipy = 0.0;
*r = 1.0;
*g = 1.0;
*b = 1.0;
*a = 1.0;
*blendmode = 0.0;
*done = 0.0;
*burn = 1.0;
if (initCode.empty())
{
return;
}
// Only time and frame values are passed to the init code.
*time = renderContext.time;
*frame = renderContext.frame;
auto* initCodeHandle = projectm_eval_code_compile(spriteCodeContext, initCode.c_str());
if (initCodeHandle == nullptr)
{
int errorLine{};
int errorColumn{};
const auto* errorMessage = projectm_eval_get_error(spriteCodeContext, &errorLine, &errorColumn);
throw SpriteException("Error compiling sprite init code:" + std::string(errorMessage) + " (Line " + std::to_string(errorLine) + ", column " + std::to_string(errorColumn) + ")");
}
projectm_eval_code_execute(initCodeHandle);
projectm_eval_code_destroy(initCodeHandle);
}
void MilkdropSprite::CodeContext::RunPerFrameCode(const Audio::FrameAudioData& audioData, const Renderer::RenderContext& renderContext)
{
// If there's no per-frame code, e.g. with static sprites, just skip it.
if (perFrameCodeHandle == nullptr)
{
return;
}
// Fill in input variables
*time = renderContext.time;
*frame = renderContext.frame;
*fps = renderContext.fps;
*progress = renderContext.blendProgress;
*bass = audioData.bass;
*mid = audioData.mid;
*treb = audioData.treb;
*bass_att = audioData.bassAtt;
*mid_att = audioData.midAtt;
*treb_att = audioData.trebAtt;
// Run the code
projectm_eval_code_execute(perFrameCodeHandle);
}
} // namespace UserSprites
} // namespace libprojectM