/
ScriptingGraphics.h
693 lines (475 loc) · 21.4 KB
/
ScriptingGraphics.h
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
/* ===========================================================================
*
* This file is part of HISE.
* Copyright 2016 Christoph Hart
*
* HISE 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 3 of the License, or
* (at your option) any later version.
*
* HISE 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 HISE. If not, see <http://www.gnu.org/licenses/>.
*
* Commercial licenses for using HISE in an closed source project are
* available on request. Please visit the project's website to get more
* information about commercial licensing:
*
* http://www.hise.audio/
*
* HISE is based on the JUCE library,
* which also must be licenced for commercial applications:
*
* http://www.juce.com
*
* ===========================================================================
*/
#pragma once
namespace hise { using namespace juce;
struct ScreenshotListener
{
struct CachedImageBuffer : public ReferenceCountedObject
{
using Ptr = ReferenceCountedObjectPtr<CachedImageBuffer>;
CachedImageBuffer(Rectangle<int> sb) :
data(Image::RGB, sb.getWidth(), sb.getHeight(), true)
{
}
~CachedImageBuffer()
{
int x = 0;
}
Image data;
};
virtual ~ScreenshotListener() {};
virtual void makeScreenshot(const File& targetFile, Rectangle<float> area) {};
/** This will be called on the scripting thread and can be used by listeners to prepare the screenshot. */
virtual void prepareScreenshot() {};
virtual int blockWhileWaiting() { return 0; };
virtual void visualGuidesChanged() {};
private:
JUCE_DECLARE_WEAK_REFERENCEABLE(ScreenshotListener);
};
namespace ScriptingObjects
{
class ScriptShader : public ConstScriptingObject,
public ScreenshotListener
{
public:
struct PreviewComponent;
struct FileParser: public ControlledObject
{
using FileList = ReferenceCountedArray<ExternalScriptFile>;
FileParser(ProcessorWithScriptingContent* p, bool addLineNumbers_, String& fileNameWithoutExtension, FileList& listToUse);
StringArray getLines();
private:
const bool addLineNumbers = false;
String createLinePointer(int i) const;
ProcessorWithScriptingContent* sp;
String loadFileContent();;
ReferenceCountedArray<ExternalScriptFile>& includedFiles;
String s;
String fileNameWithoutExtension;
};
enum class BlendMode
{
_GL_ZERO = GL_ZERO, //< (0, 0, 0, 0)
_GL_ONE = GL_ONE, //< (1, 1, 1, 1)
_GL_SRC_COLOR = GL_SRC_COLOR, //< (Rs / kR, Gs / kG, Bs / kB, As / kA)
_GL_ONE_MINUS_SRC_COLOR = GL_ONE_MINUS_SRC_COLOR, //< (1, 1, 1, 1) - (Rs / kR, Gs / kG, Bs / kB, As / kA)
_GL_DST_COLOR = GL_DST_COLOR, //< (Rd / kR, Gd / kG, Bd / kB, Ad / kA)
_GL_ONE_MINUS_DST_COLOR = GL_ONE_MINUS_DST_COLOR, //< (1, 1, 1, 1) - (Rd / kR, Gd / kG, Bd / kB, Ad / kA)
_GL_SRC_ALPHA = GL_SRC_ALPHA, //< (As / kA, As / kA, As / kA, As / kA)
_GL_ONE_MINUS_SRC_ALPHA = GL_ONE_MINUS_SRC_ALPHA, //< (1, 1, 1, 1) - (As / kA, As / kA, As / kA, As / kA)
_GL_DST_ALPHA = GL_DST_ALPHA, //< (Ad / kA, Ad / kA, Ad / kA, Ad / kA)
_GL_ONE_MINUS_DST_ALPHA = GL_ONE_MINUS_DST_ALPHA, //< (1, 1, 1, 1) - (Ad / kA, Ad / kA, Ad / kA, Ad / kA)
_GL_SRC_ALPHA_SATURATE = GL_SRC_ALPHA_SATURATE,
numBlendModes = 11 // needs to be set manually...
};
ScriptShader(ProcessorWithScriptingContent* sp);;
Identifier getObjectName() const override { RETURN_STATIC_IDENTIFIER("ScriptShader"); }
// =============================================================== API Methods
/** Loads a .glsl file from the script folder. */
void setFragmentShader(String shaderFile);
/** Sets an uniform variable to be used in the shader code. */
void setUniformData(const String& id, var data);
/** Sets the blend mode for the shader. */
void setBlendFunc(bool enabled, int sFactor, int dFactor);
/** Compresses the GLSL code and returns a encoded string snippet. */
String toBase64();
/** Compiles the code from the given base64 string. */
void fromBase64(String b64);
/** Returns a JSON object with the current OpenGL statistics. */
var getOpenGLStatistics();
/** If this is enabled, the shader will create a buffered image of the last rendering result. */
void setEnableCachedBuffer(bool shouldEnableBuffer);
// ===========================================================================
int blockWhileWaiting() override;
void prepareScreenshot() override;
void makeStatistics();
void setEnableLineNumbers(bool shouldUseLineNumbers)
{
useLineNumbers = shouldUseLineNumbers;
}
Component* createPopupComponent(const MouseEvent& e, Component *c) override;
bool compiledOk() const { return r.wasOk(); }
String getErrorMessage(bool verbose) const;
void setCompileResult(Result compileResult)
{
r = processErrorMessage(compileResult);
for (auto f : includedFiles)
f->setRuntimeErrors(r);
}
void setGlobalBounds(Rectangle<int> b, float sf)
{
globalRect = b.toFloat();
scaleFactor = sf;
}
bool shouldWriteToBuffer() const
{
return enableCache || screenshotPending;
}
void renderWasFinished(ScreenshotListener::CachedImageBuffer::Ptr newData)
{
if (screenshotPending)
{
DBG("REPAINT DONE");
screenshotPending = false;
lastScreenshot = newData;
}
else
lastScreenshot = nullptr;
}
ScreenshotListener::CachedImageBuffer::Ptr getScreenshotBuffer()
{
if (isRenderingScreenshot())
return lastScreenshot;
return nullptr;
}
struct Wrapper;
ScreenshotListener::CachedImageBuffer::Ptr lastScreenshot;
float scaleFactor = 1.0f;
String shaderCode;
NamedValueSet uniformData;
var openGLStats;
ScopedPointer<juce::OpenGLGraphicsContextCustomShader> shader;
bool dirty = false;
bool useLineNumbers = false;
double iTime = 0;
Rectangle<float> globalRect;
Rectangle<float> localRect;
ReferenceCountedArray<ExternalScriptFile> includedFiles;
bool enableBlending = false;
bool enableCache = false;
BlendMode src = BlendMode::_GL_SRC_ALPHA;
BlendMode dst = BlendMode::_GL_ONE_MINUS_SRC_ALPHA;
static bool isRenderingScreenshot() { return renderingScreenShot; }
struct ScopedScreenshotRenderer
{
ScopedScreenshotRenderer()
{
renderingScreenShot = true;
}
~ScopedScreenshotRenderer()
{
renderingScreenShot = false;
}
};
private:
bool screenshotPending = false;
static bool renderingScreenShot;
String compiledCode;
String shaderName;
String getHeader();
void compileRawCode(const String& code);
struct Result processErrorMessage(const Result& r);
Result r;
JUCE_DECLARE_WEAK_REFERENCEABLE(ScriptShader);
};
class PathObject : public ConstScriptingObject
{
public:
// ============================================================================================================
PathObject(ProcessorWithScriptingContent* p);
~PathObject();
Identifier getObjectName() const override { RETURN_STATIC_IDENTIFIER("Path"); }
String getDebugValue() const override {
return p.getBounds().toString();
}
String getDebugName() const override { return "Path"; }
Component* createPopupComponent(const MouseEvent& e, Component *c) override;
// ============================================================================================================ API Methods
/** Loads a path from a data array. */
void loadFromData(var data);
/** Clears the Path. */
void clear();
/** Starts a new Path. It does not clear the path, so use 'clear()' if you want to start all over again. */
void startNewSubPath(var x, var y);
/** Closes the Path. */
void closeSubPath();
/** Adds a line to [x,y]. */
void lineTo(var x, var y);
/** Adds a quadratic bezier curve with the control point [cx,cy] and the end point [x,y]. */
void quadraticTo(var cx, var cy, var x, var y);
/** Adds an arc to the path. */
void addArc(var area, var fromRadians, var toRadians);
/** Returns the area ([x, y, width, height]) that the path is occupying with the scale factor applied. */
var getBounds(var scaleFactor);
// ============================================================================================================
struct Wrapper;
Path& getPath() { return p; }
const Path& getPath() const { return p; }
private:
Path p;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(PathObject);
// ============================================================================================================
};
class GraphicsObject : public ConstScriptingObject
{
public:
// ============================================================================================================
GraphicsObject(ProcessorWithScriptingContent *p, ConstScriptingObject* parent);
~GraphicsObject();
// ============================================================================================================
Identifier getObjectName() const override { RETURN_STATIC_IDENTIFIER("Graphics"); }
// ============================================================================================================ API Methods
/** Starts a new Layer. */
void beginLayer(bool drawOnParent);
/** Begins a new layer that will use the given blend effect. */
void beginBlendLayer(String blendMode, float alpha);
/** flushes the current layer. */
void endLayer();
/** Applies gaussian blur to the current layer. */
void gaussianBlur(var blurAmount);
/** Applies a box blur to the current layer. */
void boxBlur(var blurAmount);
/** Adds noise to the current layer. */
void addNoise(var noiseAmount);
/** Removes all colour from the current layer. */
void desaturate();
/** Applies a mask to the current layer. */
void applyMask(var path, var area, bool invert);
/** Fills the whole area with the given colour. */
void fillAll(var colour);
/** Fills a rectangle with the given colour. */
void fillRect(var area);
/** Draws a rectangle. */
void drawRect(var area, float borderSize);
/** Fills a rounded rectangle. */
void fillRoundedRectangle(var area, float cornerSize);
/** Draws a rounded rectangle. */
void drawRoundedRectangle(var area, float cornerSize, float borderSize);
/** Draws a (non interpolated) horizontal line. */
void drawHorizontalLine(int y, float x1, float x2);
/** Sets a global transparency level. */
void setOpacity(float alphaValue);
/** Draws a line. */
void drawLine(float x1, float x2, float y1, float y2, float lineThickness);
/** Sets the current colour. */
void setColour(var colour);
/** Sets the current font. */
void setFont(String fontName, float fontSize);
/** Draws a centered and vertically stretched text. */
void drawText(String text, var area);
/** Draws a text with the given alignment (see the Label alignment property). */
void drawAlignedText(String text, var area, String alignment);
/** Sets the current gradient via an array [Colour1, x1, y1, Colour2, x2, y2] */
void setGradientFill(var gradientData);
/** Draws a ellipse in the given area. */
void drawEllipse(var area, float lineThickness);
/** Applies a HSL grading on the current layer. */
void applyHSL(float hue, float saturation, float lightness);
/** Applies a gamma correction to the current layer. */
void applyGamma(float gamma);
/** Applies a gradient map to the brightness level of the current layer. */
void applyGradientMap(var darkColour, var brightColour);
/** Applies a sharpen / soften filter on the current layer. */
void applySharpness(int delta);
/** Applies an oldschool sepia filter on the current layer. */
void applySepia();
/** Applies a vignette (dark corners on the current layer. */
void applyVignette(float amount, float radius, float falloff);
/** Fills a ellipse in the given area. */
void fillEllipse(var area);
/** Draws a image into the area. */
void drawImage(String imageName, var area, int xOffset, int yOffset);
/** Draws a drop shadow around a rectangle. */
void drawDropShadow(var area, var colour, int radius);
/** Draws a drop shadow from a path. */
void drawDropShadowFromPath(var path, var area, var colour, int radius, var offset);
/** Draws a triangle rotated by the angle in radians. */
void drawTriangle(var area, float angle, float lineThickness);
/** Fills a triangle rotated by the angle in radians. */
void fillTriangle(var area, float angle);
/** Adds a drop shadow based on the alpha values of the current image. */
void addDropShadowFromAlpha(var colour, int radius);
/** Applies an OpenGL shader to the panel. */
void applyShader(var shader, var area);
/** Fills a Path. */
void fillPath(var path, var area);
/** Draws the given path. */
void drawPath(var path, var area, var strokeStyle);
/** Rotates the canvas around center `[x, y]` by the given amount in radian. */
void rotate(var angleInRadian, var center);
// ============================================================================================================
struct Wrapper;
DrawActions::Handler& getDrawHandler() { return drawActionHandler; }
private:
Point<float> getPointFromVar(const var& data);
Rectangle<float> getRectangleFromVar(const var &data);
Rectangle<int> getIntRectangleFromVar(const var &data);
Result rectangleResult;
ConstScriptingObject* parent = nullptr;
DrawActions::Handler drawActionHandler;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(GraphicsObject);
// ============================================================================================================
};
class ScriptedLookAndFeel : public ConstScriptingObject
{
public:
struct Laf : public GlobalHiseLookAndFeel,
public PresetBrowserLookAndFeelMethods,
public TableEditor::LookAndFeelMethods,
public HiseAudioThumbnail::LookAndFeelMethods,
public NumberTag::LookAndFeelMethods,
public MessageWithIcon::LookAndFeelMethods,
public ControlledObject,
public RingBufferComponentBase::LookAndFeelMethods,
public AhdsrGraph::LookAndFeelMethods,
public MidiFileDragAndDropper::LookAndFeelMethods
{
Laf(MainController* mc) :
ControlledObject(mc)
{}
ScriptedLookAndFeel* get()
{
return dynamic_cast<ScriptedLookAndFeel*>(getMainController()->getCurrentScriptLookAndFeel());
}
Font getFont()
{
if (auto l = get())
return l->f;
else
return GLOBAL_BOLD_FONT();
}
void drawAlertBox(Graphics&, AlertWindow&, const Rectangle<int>& textArea, TextLayout&) override;
Font getAlertWindowMessageFont() override { return getFont(); }
Font getAlertWindowTitleFont() override { return getFont(); }
Font getTextButtonFont(TextButton &, int) override { return getFont(); }
Font getComboBoxFont(ComboBox&) override { return getFont(); }
Font getPopupMenuFont() override { return getFont(); };
Font getAlertWindowFont() override { return getFont(); };
MarkdownLayout::StyleData getAlertWindowMarkdownStyleData() override;
void drawPopupMenuBackground(Graphics& g_, int width, int height) override;
void drawPopupMenuItem(Graphics& g, const Rectangle<int>& area,
bool isSeparator, bool isActive,
bool isHighlighted, bool isTicked,
bool hasSubMenu, const String& text,
const String& shortcutKeyText,
const Drawable* icon, const Colour* textColourToUse);
void drawToggleButton(Graphics &g, ToggleButton &b, bool isMouseOverButton, bool /*isButtonDown*/) override;
void drawRotarySlider(Graphics &g, int /*x*/, int /*y*/, int width, int height, float /*sliderPosProportional*/, float /*rotaryStartAngle*/, float /*rotaryEndAngle*/, Slider &s) override;
void drawLinearSlider(Graphics &g, int x, int y, int width, int height, float sliderPos, float minSliderPos, float maxSliderPos, const Slider::SliderStyle style, Slider &slider) override;
void drawButtonText(Graphics &g_, TextButton &button, bool isMouseOverButton, bool isButtonDown) override;
void drawComboBox(Graphics&, int width, int height, bool isButtonDown, int buttonX, int buttonY, int buttonW, int buttonH, ComboBox& cb);
void positionComboBoxText(ComboBox &c, Label &labelToPosition) override;
void drawComboBoxTextWhenNothingSelected(Graphics& g, ComboBox& box, Label& label);
void drawButtonBackground(Graphics& g, Button& button, const Colour& /*backgroundColour*/,
bool isMouseOverButton, bool isButtonDown) override;
void drawNumberTag(Graphics& g, Colour& c, Rectangle<int> area, int offset, int size, int number) override;
void drawPresetBrowserBackground(Graphics& g, PresetBrowser* p) override;
void drawColumnBackground(Graphics& g, Rectangle<int> listArea, const String& emptyText) override;
void drawTag(Graphics& g, bool blinking, bool active, bool selected, const String& name, Rectangle<int> position) override;
void drawModalOverlay(Graphics& g, Rectangle<int> area, Rectangle<int> labelArea, const String& title, const String& command) override;
void drawListItem(Graphics& g, int columnIndex, int, const String& itemName, Rectangle<int> position, bool rowIsSelected, bool deleteMode) override;
void drawSearchBar(Graphics& g, Rectangle<int> area) override;
void drawTablePath(Graphics& g, TableEditor& te, Path& p, Rectangle<float> area, float lineThickness) override;
void drawTablePoint(Graphics& g, TableEditor& te, Rectangle<float> tablePoint, bool isEdge, bool isHover, bool isDragged) override;
void drawTableRuler(Graphics& g, TableEditor& te, Rectangle<float> area, float lineThickness, double rulerPosition) override;
void drawScrollbar(Graphics& g, ScrollBar& scrollbar, int x, int y, int width, int height, bool isScrollbarVertical, int thumbStartPosition, int thumbSize, bool isMouseOver, bool isMouseDown) override;
void drawAhdsrPathSection(Graphics& g, AhdsrGraph& graph, const Path& s, bool isActive) override;
void drawAhdsrBallPosition(Graphics& g, AhdsrGraph& graph, Point<float> p) override;
void drawMidiDropper(Graphics& g, Rectangle<float> area, const String& text, MidiFileDragAndDropper& d) override;
void drawThumbnailRange(Graphics& g, HiseAudioThumbnail& te, Rectangle<float> area, int areaIndex, Colour c, bool areaEnabled);
void drawHiseThumbnailBackground(Graphics& g, HiseAudioThumbnail& th, bool areaIsEnabled, Rectangle<int> area) override;
void drawHiseThumbnailPath(Graphics& g, HiseAudioThumbnail& th, bool areaIsEnabled, const Path& path) override;
void drawHiseThumbnailRectList(Graphics& g, HiseAudioThumbnail& th, bool areaIsEnabled, const HiseAudioThumbnail::RectangleListType& rectList) override;
void drawTextOverlay(Graphics& g, HiseAudioThumbnail& th, const String& text, Rectangle<float> area) override;
Image createIcon(PresetHandler::IconType type) override;
bool functionDefined(const String& s);
static Identifier getIdOfParentFloatingTile(Component& c);
static bool addParentFloatingTile(Component& c, DynamicObject* obj);
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(Laf);
};
struct Wrapper;
ScriptedLookAndFeel(ProcessorWithScriptingContent* sp);
~ScriptedLookAndFeel();
Identifier getObjectName() const override { return "ScriptLookAndFeel"; }
// ========================================================================================
/** Registers a function that will be used for the custom look and feel. */
void registerFunction(var functionName, var function);
/** Set a global font. */
void setGlobalFont(const String& fontName, float fontSize);
/** Loads an image that can be used by the look and feel functions. */
void loadImage(String imageFile, String prettyName);
// ========================================================================================
bool callWithGraphics(Graphics& g_, const Identifier& functionname, var argsObject);
var callDefinedFunction(const Identifier& name, var* args, int numArgs);
int getNumChildElements() const override
{
if (auto dyn = functions.getDynamicObject())
return dyn->getProperties().size();
return 0;
}
DebugInformationBase* getChildElement(int index) override
{
WeakReference<ScriptedLookAndFeel> safeThis(this);
auto vf = [safeThis, index]()
{
if (safeThis != nullptr)
{
if (auto dyn = safeThis->functions.getDynamicObject())
{
if(isPositiveAndBelow(index, dyn->getProperties().size()))
return dyn->getProperties().getValueAt(index);
}
}
return var();
};
String id = "%PARENT%.";
auto mid = functions.getDynamicObject()->getProperties().getName(index);
id << mid;
Location l = getLocation();
return new LambdaValueInformation(vf, id, {}, (DebugInformation::Type)getTypeNumber(), l);
}
static Array<Identifier> getAllFunctionNames();
Font f = GLOBAL_BOLD_FONT();
ReferenceCountedObjectPtr<GraphicsObject> g;
var functions;
Image getLoadedImage(const String& prettyName)
{
for (auto& img : loadedImages)
{
if (img.prettyName == prettyName)
{
return img.image ? *img.image.getData() : Image();
}
}
return Image();
}
struct NamedImage
{
PooledImage image;
String prettyName;
};
Array<NamedImage> loadedImages;
JUCE_DECLARE_WEAK_REFERENCEABLE(ScriptedLookAndFeel);
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ScriptedLookAndFeel);
};
}
} // namespace hise