-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessing.h
More file actions
2350 lines (2052 loc) · 111 KB
/
Processing.h
File metadata and controls
2350 lines (2052 loc) · 111 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
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma once
#ifndef _WIN32
#include <dirent.h>
#endif
#include <functional>
// =============================================================================
// Processing.h -- processing-cpp API
// =============================================================================
// processing-cpp is a C++ creative coding framework inspired by Processing (Java).
// It exposes a familiar draw-loop API backed by OpenGL/GLFW/GLEW.
//
// HOW TO USE:
// 1. Include this header in your sketch file.
// 2. Inside namespace Processing { ... } define:
// void setup() { size(640,360); }
// void draw() { background(0); ellipse(mouseX,mouseY,40,40); }
// 3. Compile with Processing.cpp and link against GLFW + GLEW + OpenGL.
//
// FILE STRUCTURE:
// Processing.h -- This file. API declarations, inline helpers, classes.
// Processing.cpp -- Implementation of all declared functions.
// Platform.h -- OS abstraction (file dialogs, serial, process, sleep).
// IDE.cpp -- The processing-cpp IDE (sketch editor, build, run, terminal).
// =============================================================================
// ---------------------------------------------------------------------------
// Platform shim (must come first; provides termios/glob stubs on Windows)
// ---------------------------------------------------------------------------
#if __has_include("Platform.h")
# include "Platform.h"
#endif
// ---------------------------------------------------------------------------
// M_PI: Windows (MinGW) only defines this when _USE_MATH_DEFINES is set
// before including <cmath>. We also provide a fallback just in case.
// ---------------------------------------------------------------------------
#ifndef _USE_MATH_DEFINES
# define _USE_MATH_DEFINES
#endif
#include <cmath>
#ifndef M_PI
# define M_PI 3.14159265358979323846
#endif
// ---------------------------------------------------------------------------
// Standard library includes
// ---------------------------------------------------------------------------
#include <iostream>
#include <sstream>
#include <fstream>
#include <regex>
#include <cstdlib>
#include <ctime>
#include <chrono>
#include <string>
#include <vector>
#include <thread>
#include <functional>
#include <algorithm>
#include <memory>
#include <map>
#include <set>
#include <random>
#include <stack>
#include <queue>
#include <list>
#include <deque>
#include <tuple>
#include <optional>
#include <variant>
#include <numeric>
#include <iterator>
#include <memory>
#include <regex>
#include <iomanip>
#include <unordered_map>
#include <unordered_set>
// ---------------------------------------------------------------------------
// OpenGL / GLFW
// ---------------------------------------------------------------------------
// Java-style string + number concatenation
inline std::string operator+(const std::string& s, int n) { return s + std::to_string(n); }
inline std::string operator+(const std::string& s, long n) { return s + std::to_string(n); }
inline std::string operator+(const std::string& s, size_t n) { return s + std::to_string(n); }
inline std::string operator+(const std::string& s, float n) { return s + std::to_string(n); }
inline std::string operator+(const std::string& s, double n) { return s + std::to_string(n); }
inline std::string operator+(const std::string& s, char c) { return s + std::string(1, c); }
inline std::string operator+(int n, const std::string& s) { return std::to_string(n) + s; }
inline std::string operator+(long n, const std::string& s) { return std::to_string(n) + s; }
inline std::string operator+(size_t n, const std::string& s) { return std::to_string(n) + s; }
inline std::string operator+(float n, const std::string& s) { return std::to_string(n) + s; }
inline std::string operator+(double n, const std::string& s) { return std::to_string(n) + s; }
inline std::string operator+(char c, const std::string& s) { return std::string(1, c) + s; }
#include <GL/glew.h>
#include <GLFW/glfw3.h>
namespace Processing {
// =============================================================================
// PVECTOR -- 2D/3D vector with all standard Processing operations
// =============================================================================
class PVector {
public:
float x, y, z;
// Constructors
PVector() : x(0), y(0), z(0) {}
PVector(float x, float y) : x(x), y(y), z(0) {}
PVector(float x, float y, float z): x(x), y(y), z(z) {}
// Setters
PVector& set(float _x, float _y, float _z=0) { x=_x; y=_y; z=_z; return *this; }
PVector& set(const PVector& v) { x=v.x; y=v.y; z=v.z; return *this; }
PVector copy() const { return PVector(x, y, z); }
// Magnitude
float mag() const { return std::sqrt(x*x + y*y + z*z); }
float magSq() const { return x*x + y*y + z*z; }
// Arithmetic (in-place)
PVector& add(float _x, float _y, float _z=0) { x+=_x; y+=_y; z+=_z; return *this; }
PVector& add(const PVector& v) { x+=v.x; y+=v.y; z+=v.z; return *this; }
PVector& sub(float _x, float _y, float _z=0) { x-=_x; y-=_y; z-=_z; return *this; }
PVector& sub(const PVector& v) { x-=v.x; y-=v.y; z-=v.z; return *this; }
PVector& mult(float s) { x*=s; y*=s; z*=s; return *this; }
PVector& div(float s) { x/=s; y/=s; z/=s; return *this; }
// Arithmetic (static, returns new vector)
static PVector add(const PVector& a, const PVector& b) { return PVector(a.x+b.x, a.y+b.y, a.z+b.z); }
static PVector sub(const PVector& a, const PVector& b) { return PVector(a.x-b.x, a.y-b.y, a.z-b.z); }
static PVector mult(const PVector& v, float s) { return PVector(v.x*s, v.y*s, v.z*s); }
static PVector div(const PVector& v, float s) { return PVector(v.x/s, v.y/s, v.z/s); }
// Operators
PVector operator+(const PVector& v) const { return PVector(x+v.x, y+v.y, z+v.z); }
PVector operator-(const PVector& v) const { return PVector(x-v.x, y-v.y, z-v.z); }
PVector operator*(float s) const { return PVector(x*s, y*s, z*s); }
PVector operator/(float s) const { return PVector(x/s, y/s, z/s); }
PVector& operator+=(const PVector& v) { return add(v); }
PVector& operator-=(const PVector& v) { return sub(v); }
PVector& operator*=(float s) { return mult(s); }
PVector& operator/=(float s) { return div(s); }
bool operator==(const PVector& v) const { return x==v.x && y==v.y && z==v.z; }
bool operator!=(const PVector& v) const { return !(*this==v); }
// Dot / cross product
float dot(const PVector& v) const { return x*v.x + y*v.y + z*v.z; }
float dot(float _x, float _y, float _z=0) const { return x*_x + y*_y + z*_z; }
static float dot(const PVector& a, const PVector& b) { return a.dot(b); }
PVector cross(const PVector& v) const { return PVector(y*v.z-z*v.y, z*v.x-x*v.z, x*v.y-y*v.x); }
static PVector cross(const PVector& a, const PVector& b) { return a.cross(b); }
// Normalization / limits
PVector& normalize() { float m=mag(); if(m>0) div(m); return *this; }
PVector normalized() const { PVector v(*this); return v.normalize(); }
PVector& limit(float mx) { if(magSq()>mx*mx){ normalize(); mult(mx); } return *this; }
PVector& setMag(float m) { normalize(); mult(m); return *this; }
// Distance / angle
float dist(const PVector& v) const { float dx=x-v.x,dy=y-v.y,dz=z-v.z; return std::sqrt(dx*dx+dy*dy+dz*dz); }
static float dist(const PVector& a, const PVector& b) { return a.dist(b); }
float heading() const { return std::atan2(y, x); }
float angleBetween(const PVector& v) const {
float m = mag() * v.mag();
if (m == 0) return 0;
float c = dot(v) / m;
c = c < -1 ? -1 : (c > 1 ? 1 : c);
return std::acos(c);
}
static float angleBetween(const PVector& a, const PVector& b) { return a.angleBetween(b); }
// Mutation
PVector& rotate(float t) { float c=std::cos(t),s=std::sin(t),nx=x*c-y*s,ny=x*s+y*c; x=nx; y=ny; return *this; }
PVector& lerp(const PVector& v, float t) { x+=(v.x-x)*t; y+=(v.y-y)*t; z+=(v.z-z)*t; return *this; }
PVector& lerp(float _x, float _y, float _z, float t) { x+=(_x-x)*t; y+=(_y-y)*t; z+=(_z-z)*t; return *this; }
static PVector lerp(const PVector& a, const PVector& b, float t) {
return PVector(a.x+(b.x-a.x)*t, a.y+(b.y-a.y)*t, a.z+(b.z-a.z)*t);
}
// Static constructors
static PVector fromAngle(float a, float len=1.0f) { return PVector(std::cos(a)*len, std::sin(a)*len); }
static PVector random2D() {
float a = static_cast<float>(rand()) / RAND_MAX * 6.28318f;
return fromAngle(a);
}
static PVector random3D() {
float t = static_cast<float>(rand()) / RAND_MAX * 6.28318f;
float p = std::acos(2.0f * static_cast<float>(rand()) / RAND_MAX - 1.0f);
return PVector(std::sin(p)*std::cos(t), std::sin(p)*std::sin(t), std::cos(p));
}
std::string toString() const {
std::ostringstream ss;
ss << "[ " << x << ", " << y << ", " << z << " ]";
return ss.str();
}
};
// =============================================================================
// PCOLOR -- RGBA color with HSB conversion and blend operations
// =============================================================================
class PColor {
public:
float r, g, b, a;
PColor() : r(0), g(0), b(0), a(255) {}
PColor(float gray) : r(gray),g(gray),b(gray),a(255) {}
PColor(float gray, float a) : r(gray),g(gray),b(gray),a(a) {}
PColor(float r, float g, float b) : r(r), g(g), b(b), a(255) {}
PColor(float r, float g, float b, float a) : r(r), g(g), b(b), a(a) {}
// Construct from packed ARGB integer (0xAARRGGBB)
explicit PColor(unsigned int argb)
: r((argb>>16)&0xFF), g((argb>>8)&0xFF), b(argb&0xFF), a((argb>>24)&0xFF) {}
// Pack to ARGB integer
unsigned int toARGB() const {
int ri=(int)std::fmax(0,std::fmin(255,r));
int gi=(int)std::fmax(0,std::fmin(255,g));
int bi=(int)std::fmax(0,std::fmin(255,b));
int ai=(int)std::fmax(0,std::fmin(255,a));
return (unsigned int)((ai<<24)|(ri<<16)|(gi<<8)|bi);
}
// Normalised [0..1] accessors
float rf() const { return r/255.0f; }
float gf() const { return g/255.0f; }
float bf() const { return b/255.0f; }
float af() const { return a/255.0f; }
PColor& set(float _r, float _g, float _b, float _a=255) { r=_r; g=_g; b=_b; a=_a; return *this; }
PColor& set(float gray, float _a=255) { r=g=b=gray; a=_a; return *this; }
PColor copy() const { return PColor(r, g, b, a); }
// HSB conversions
float hue() const {
float rf_=r/255.f, gf_=g/255.f, bf_=b/255.f;
float mx=std::fmax(rf_,std::fmax(gf_,bf_));
float mn=std::fmin(rf_,std::fmin(gf_,bf_));
float d=mx-mn;
if (d==0) return 0;
float h = (mx==rf_) ? (gf_-bf_)/d : (mx==gf_) ? 2.f+(bf_-rf_)/d : 4.f+(rf_-gf_)/d;
h *= 60.f;
if (h < 0) h += 360.f;
return h;
}
float saturation() const {
float mx=std::fmax(r,std::fmax(g,b));
float mn=std::fmin(r,std::fmin(g,b));
return mx==0 ? 0 : ((mx-mn)/mx)*100.f;
}
float brightness() const { return std::fmax(r,std::fmax(g,b))/255.f*100.f; }
static PColor fromHSB(float h, float s, float bv, float a=255) {
s /= 100.f; bv /= 100.f;
if (s == 0) { float v=bv*255.f; return PColor(v,v,v,a); }
float hh=std::fmod(h,360.f)/60.f;
int i=(int)hh;
float f=hh-i, p=bv*(1-s), q=bv*(1-s*f), t=bv*(1-s*(1-f));
float rv,gv,blv;
switch(i){
case 0: rv=bv;gv=t; blv=p; break;
case 1: rv=q; gv=bv;blv=p; break;
case 2: rv=p; gv=bv;blv=t; break;
case 3: rv=p; gv=q; blv=bv; break;
case 4: rv=t; gv=p; blv=bv; break;
default:rv=bv;gv=p; blv=q; break;
}
return PColor(rv*255,gv*255,blv*255,a);
}
// Arithmetic operators
PColor operator+(const PColor& o) const { return PColor(r+o.r, g+o.g, b+o.b, a+o.a); }
PColor operator-(const PColor& o) const { return PColor(r-o.r, g-o.g, b-o.b, a-o.a); }
PColor operator*(float s) const { return PColor(r*s, g*s, b*s, a*s); }
PColor operator/(float s) const { return PColor(r/s, g/s, b/s, a/s); }
PColor& operator+=(const PColor& o) { r+=o.r; g+=o.g; b+=o.b; a+=o.a; return *this; }
PColor& operator-=(const PColor& o) { r-=o.r; g-=o.g; b-=o.b; a-=o.a; return *this; }
PColor& operator*=(float s) { r*=s; g*=s; b*=s; a*=s; return *this; }
PColor& operator/=(float s) { r/=s; g/=s; b/=s; a/=s; return *this; }
bool operator==(const PColor& o) const { return r==o.r && g==o.g && b==o.b && a==o.a; }
bool operator!=(const PColor& o) const { return !(*this==o); }
// Utility
static PColor lerp(const PColor& c1, const PColor& c2, float t) {
return PColor(c1.r+(c2.r-c1.r)*t, c1.g+(c2.g-c1.g)*t, c1.b+(c2.b-c1.b)*t, c1.a+(c2.a-c1.a)*t);
}
PColor& clamp() {
r=std::fmax(0,std::fmin(255,r)); g=std::fmax(0,std::fmin(255,g));
b=std::fmax(0,std::fmin(255,b)); a=std::fmax(0,std::fmin(255,a));
return *this;
}
PColor multRGB(float s) const { return PColor(r*s, g*s, b*s, a); }
// Blend modes (return new color)
static PColor blend(const PColor& src, const PColor& dst) {
float sa = src.a/255.f;
return PColor(src.r*sa+dst.r*(1-sa), src.g*sa+dst.g*(1-sa), src.b*sa+dst.b*(1-sa), 255);
}
static PColor add(const PColor& a, const PColor& b) {
return PColor(std::fmin(255,a.r+b.r), std::fmin(255,a.g+b.g), std::fmin(255,a.b+b.b), a.a);
}
static PColor multiply(const PColor& a, const PColor& b) {
return PColor((a.r/255.f)*b.r, (a.g/255.f)*b.g, (a.b/255.f)*b.b, a.a);
}
static PColor screen(const PColor& a, const PColor& b) {
auto sc=[](float x,float y){ return 255-(255-x)*(255-y)/255.f; };
return PColor(sc(a.r,b.r), sc(a.g,b.g), sc(a.b,b.b), a.a);
}
float brightness255() const { return std::fmax(r, std::fmax(g, b)); }
std::string toString() const {
std::ostringstream ss;
ss << "PColor(" << r << ", " << g << ", " << b << ", " << a << ")";
return ss.str();
}
};
// Forward declarations so PColor overloads compile below class definitions
void fill(const PColor& c);
void stroke(const PColor& c);
void background(const PColor& c);
void tint(const PColor& c);
// =============================================================================
// IMAGE FILTER CONSTANTS
// =============================================================================
static constexpr int GRAY = 1;
static constexpr int INVERT = 2;
static constexpr int THRESHOLD = 3;
static constexpr int BLUR_FILTER = 4;
static constexpr int POSTERIZE = 5;
// =============================================================================
// PIMAGE -- Pixel buffer backed by an OpenGL texture
// =============================================================================
class PImage {
public:
int width = 0;
int height = 0;
std::vector<unsigned int> pixels;
GLuint texID = 0;
bool dirty = false;
PImage() = default;
PImage(int w, int h) {
// Guard against bad dimensions from corrupted files or failed loads
if (w > 0 && h > 0 && w < 16384 && h < 16384) {
width = w; height = h;
pixels.assign((size_t)w * h, 0xFF000000);
}
}
// Pixel read/write (bounds-checked)
unsigned int get(int x, int y) const {
if (x<0||x>=width||y<0||y>=height) return 0;
return pixels[y*width+x];
}
void set(int x, int y, unsigned int c) {
if (x<0||x>=width||y<0||y>=height) return;
pixels[y*width+x] = c;
dirty = true;
}
// These mirror the Processing Java API; dirty flag is used by updatePixels()
void loadPixels() {}
void updatePixels() { dirty = true; }
// Upload CPU pixels to the GPU texture
void uploadTexture(); // defined in Processing.cpp
void resize(int w, int h) { width=w; height=h; pixels.assign(w*h, 0xFF000000); dirty=true; }
// Apply an image filter to all pixels
void filter(int mode) {
for (auto& p : pixels) {
int r=(p>>16)&0xFF, g=(p>>8)&0xFF, b=p&0xFF, a=(p>>24)&0xFF;
if (mode == GRAY) { int gr=(r+g+b)/3; p=(a<<24)|(gr<<16)|(gr<<8)|gr; }
else if (mode == INVERT) { p=(a<<24)|((255-r)<<16)|((255-g)<<8)|(255-b); }
else if (mode == THRESHOLD) { int gr=(r+g+b)/3; int t=gr>127?255:0; p=(a<<24)|(t<<16)|(t<<8)|t; }
}
dirty = true;
}
// Extract a sub-image
PImage get(int x, int y, int w, int h) const {
PImage out(w, h);
for (int iy=0; iy<h; iy++)
for (int ix=0; ix<w; ix++)
out.pixels[iy*w+ix] = get(x+ix, y+iy);
return out;
}
// Copy from another image with scaling
void copy(const PImage& src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) {
for (int iy=0; iy<dh; iy++)
for (int ix=0; ix<dw; ix++) {
int srcX = sx+(int)(ix*(float)sw/dw);
int srcY = sy+(int)(iy*(float)sh/dh);
set(dx+ix, dy+iy, src.get(srcX, srcY));
}
dirty = true;
}
// Apply alpha mask from another grayscale image
void mask(const PImage& m) {
for (int i=0; i<width*height && i<(int)m.pixels.size(); i++) {
int a = (m.pixels[i]>>16)&0xFF;
pixels[i] = (pixels[i]&0x00FFFFFF)|(a<<24);
}
dirty = true;
}
void mask(const PImage* m) { if (m) mask(*m); }
// Destructor frees GPU texture
virtual ~PImage() { if (texID) glDeleteTextures(1, &texID); }
// Non-copyable (owns GPU resource -- use PImage* for assignment)
PImage(const PImage&) = delete;
PImage& operator=(const PImage&) = delete;
// Movable
PImage(PImage&& o) noexcept
: width(o.width), height(o.height), pixels(std::move(o.pixels)),
texID(o.texID), dirty(o.dirty) { o.texID=0; }
};
// =============================================================================
// PGRAPHICS -- Off-screen render target (framebuffer object)
// =============================================================================
class PGraphics : public PImage {
public:
GLuint fbo = 0; // framebuffer object
GLuint rbo = 0; // renderbuffer (depth+stencil)
bool active = false;
PGraphics() = default;
PGraphics(int w, int h) : PImage(w, h) {
// Create framebuffer
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
// Colour attachment texture
if (texID == 0) glGenTextures(1, &texID);
glBindTexture(GL_TEXTURE_2D, texID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texID, 0);
// Depth+stencil renderbuffer
glGenRenderbuffers(1, &rbo);
glBindRenderbuffer(GL_RENDERBUFFER, rbo);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, w, h);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
GLint savedViewport[4] = {};
void beginDraw() {
glGetIntegerv(GL_VIEWPORT, savedViewport);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glViewport(0, 0, width, height);
// Y-up (natural OpenGL/FBO) - content stored right-side-up in texture
glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity();
glOrtho(0, width, height, 0, -1, 1);
glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity();
// FBO stores Y flipped vs screen - compensate so Processing Y-down coords work
glScalef(1.0f, -1.0f, 1.0f);
glTranslatef(0.0f, -(float)height, 0.0f);
active = true;
}
void endDraw() {
glMatrixMode(GL_PROJECTION); glPopMatrix();
glMatrixMode(GL_MODELVIEW); glPopMatrix();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
active = false;
// Restore saved main canvas viewport and projection
extern int logicalW, logicalH;
glViewport(savedViewport[0],savedViewport[1],savedViewport[2],savedViewport[3]);
glMatrixMode(GL_PROJECTION);glLoadIdentity();
glOrtho(0,logicalW,logicalH,0,-1,1);
glMatrixMode(GL_MODELVIEW);glLoadIdentity();
}
// Drawing methods forwarded to Processing -- implemented after full decls
void background(float g); void background(float r, float g, float b); void background(float r, float g, float b, float a);
void fill(float g); void fill(float r, float g, float b); void fill(float r, float g, float b, float a);
void noFill(); void stroke(float g); void stroke(float r, float g, float b); void noStroke();
void strokeWeight(float w);
void ellipse(float x, float y, float w, float h);
void rect(float x, float y, float w, float h);
void line(float x1, float y1, float x2, float y2);
void point(float x, float y);
void triangle(float x1,float y1,float x2,float y2,float x3,float y3);
void text(const std::string& s, float x, float y);
void translate(float x, float y); void rotate(float a); void scale(float s);
void pushMatrix(); void popMatrix();
void beginShape(); void endShape(int mode=0); void vertex(float x, float y);
void clear();
~PGraphics() {
if (fbo) glDeleteFramebuffers(1, &fbo);
if (rbo) glDeleteRenderbuffers(1, &rbo);
}
PGraphics(const PGraphics&) = delete;
PGraphics& operator=(const PGraphics&) = delete;
// Allow assignment from pointer (PGraphics pg; pg = createGraphics(w,h))
PGraphics& operator=(PGraphics* p) {
if(p && p!=this){
// Transfer ownership
if(fbo) glDeleteFramebuffers(1,&fbo);
if(rbo) glDeleteRenderbuffers(1,&rbo);
fbo=p->fbo; rbo=p->rbo; texID=p->texID;
width=p->width; height=p->height;
active=p->active;
p->fbo=0; p->rbo=0; p->texID=0;
delete p;
}
return *this;
}
};
// =============================================================================
// ENVIRONMENT STATE -- window / display dimensions
// =============================================================================
extern int winWidth, winHeight; // window client area in screen pixels
extern int displayWidth, displayHeight; // full monitor resolution
extern int pixelWidth, pixelHeight; // framebuffer size (HiDPI may differ)
extern int pixelDensityValue;
extern bool isResizable, focused;
// Aliases: 'width' and 'height' are the canonical Processing names
extern int logicalW, logicalH; // sketch's requested size from size()
// width/height always equal what size() set -- never corrupted by WM tile resize.
static inline int& width = logicalW;
static inline int& height = logicalH;
// =============================================================================
// MOUSE STATE
// =============================================================================
extern float mouseX, mouseY; // current mouse position (screen coords)
extern float pmouseX, pmouseY; // previous frame mouse position
extern bool _mousePressed; // true while any mouse button is held
extern int mouseButton; // LEFT, RIGHT, or CENTER
// =============================================================================
// EVENT CALLBACKS
// =============================================================================
// Define any of these in your sketch; unimplemented ones are safely skipped.
//
// On Linux/macOS: declared __attribute__((weak)) so undefined ones link as nullptr.
// On Windows (MinGW): weak declarations don't work; instead, _wireCallbacksFn is
// set at the bottom of IDE.cpp/sketch to point to a function that wires
// all _on* function pointers. See the Windows Event Wiring section of IDE.cpp.
// ---------------------------------------------------------------------------
// Processing event callbacks -- define whichever ones your sketch needs.
// Processing.cpp uses _on* function pointers; wireCallbacks() in
// Sketch_run.cpp assigns only the ones the sketch defines.
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Internal event function pointers (set by run() via the callbacks above).
// Exposed here so IDE.cpp's wireCallbacks() can assign them.
// ---------------------------------------------------------------------------
#include <functional>
extern std::function<void()> _onKeyPressed;
extern std::function<void()> _onKeyReleased;
extern std::function<void()> _onKeyTyped;
extern std::function<void()> _onMousePressed;
extern std::function<void()> _onMouseReleased;
extern std::function<void()> _onMouseClicked;
extern std::function<void()> _onMouseMoved;
extern std::function<void()> _onMouseDragged;
extern std::function<void(int)> _onMouseWheel;
extern std::function<void()> _onWindowMoved;
extern std::function<void()> _onWindowResized;
// ---------------------------------------------------------------------------
// Windows-only: raw POD function pointer set by IDE.cpp during static init.
// POD is guaranteed zero-initialized before any constructor runs, so writing
// to it from a static initializer in another translation unit is always safe.
// Processing::run() calls it (if non-null) after setup() to wire all _on* ptrs.
// ---------------------------------------------------------------------------
extern void (*_wireCallbacksFn)(); // set before run() to wire event callbacks
extern void (*_staticSketchSetup)(); // set by static sketches for i3/tiling WM redraw
// =============================================================================
// KEYBOARD STATE
// =============================================================================
extern bool _keyPressed; // true while any key is held
extern int keyCode; // special key code (UP, DOWN, LEFT, RIGHT, ALT, CONTROL, SHIFT, etc.)
extern char key; // ASCII character, or CODED (0xFF) for special keys
// =============================================================================
// FRAME / LOOP STATE
// =============================================================================
extern int frameCount;
extern float currentFrameRate;
extern bool looping;
extern float measuredFrameRate;
// =============================================================================
// DRAWING STATE -- internal; exposed so IDE.cpp / PGraphics can inspect
// =============================================================================
extern float fillR, fillG, fillB, fillA;
extern float strokeR, strokeG, strokeB, strokeA;
extern float strokeW;
extern bool doFill, doStroke, smoothing;
extern int currentRectMode, currentEllipseMode, currentImageMode;
extern float tintR, tintG, tintB, tintA;
extern bool doTint;
extern int colorModeVal;
extern float colorMaxH, colorMaxS, colorMaxB, colorMaxA;
extern std::vector<unsigned int> pixels;
// =============================================================================
// CONSTANTS
// =============================================================================
// Mouse buttons
// mouseButton is set to LEFT(37), RIGHT(39), or CENTER(3) when a button is pressed
// ---------------------------------------------------------------------------
// Processing reference constants
// Key codes match Java KeyEvent.VK_* values exactly.
// Mouse button constants match Processing's LEFT/CENTER/RIGHT.
// ---------------------------------------------------------------------------
// key == CODED when a non-ASCII special key is pressed; then check keyCode
static constexpr int CODED = 0xFF;
// Coded keys (keyCode values, Java KeyEvent.VK_*)
static constexpr int UP = 38;
static constexpr int DOWN = 40;
static constexpr int LEFT = 37; // arrow key AND left mouse button
static constexpr int RIGHT = 39; // arrow key AND right mouse button
static constexpr int ALT = 18;
static constexpr int CONTROL = 17;
static constexpr int SHIFT = 16;
static constexpr int HOME_KEY = 36;
static constexpr int END_KEY = 35;
static constexpr int PAGE_UP = 33;
static constexpr int PAGE_DOWN = 34;
static constexpr int F1_KEY = 112; static constexpr int F2_KEY = 113;
static constexpr int F3_KEY = 114; static constexpr int F4_KEY = 115;
static constexpr int F5_KEY = 116; static constexpr int F6_KEY = 117;
static constexpr int F7_KEY = 118; static constexpr int F8_KEY = 119;
static constexpr int F9_KEY = 120; static constexpr int F10_KEY = 121;
static constexpr int F11_KEY = 122; static constexpr int F12_KEY = 123;
// Non-coded keys: use `key` directly (not keyCode) for these
static constexpr char BACKSPACE = 8;
static constexpr char TAB = 9;
static constexpr char ENTER = 10; // PC/Unix enter key
// Undefine any system macros that might conflict
#ifdef RETURN
# undef RETURN
#endif
#ifdef DELETE
# undef DELETE
#endif
static constexpr int RETURN = 13; // Mac return key (same key as ENTER on most systems)
static constexpr int ESC = 27;
static constexpr int DELETE = 127;
// Mouse buttons (mouseButton variable, Java MouseEvent values)
static constexpr int CENTER = 3; // middle mouse button; also rectMode/ellipseMode CENTER
// Color modes
static constexpr int RGB = 1;
static constexpr int HSB = 2;
#define ARGB 3 /* createImage(w,h,ARGB) */
// Shape / rect / ellipse modes
static constexpr int CORNER = 0;
static constexpr int CORNERS = 1;
static constexpr int RADIUS = 2;
// Stroke caps and joins
static constexpr int ROUND = 10;
static constexpr int SQUARE = 11;
static constexpr int PROJECT = 12;
static constexpr int MITER = 13;
static constexpr int BEVEL = 14;
// beginShape() kinds
static constexpr int POINTS = 0;
static constexpr int LINES = 1;
static constexpr int TRIANGLES = 2;
static constexpr int TRIANGLE_FAN = 3;
static constexpr int TRIANGLE_STRIP = 4;
static constexpr int QUADS = 5;
static constexpr int QUAD_STRIP = 6;
static constexpr int CLOSE = 7;
// Text alignment
static constexpr int LEFT_ALIGN = 20;
static constexpr int RIGHT_ALIGN = 21;
static constexpr int TOP_ALIGN = 22;
static constexpr int BOTTOM_ALIGN = 23;
static constexpr int BASELINE = 24;
static constexpr int CENTER_ALIGN = 25;
// Blend modes
static constexpr int BLEND = 30;
static constexpr int ADD = 31;
static constexpr int SUBTRACT = 32;
static constexpr int MULTIPLY = 33;
static constexpr int SCREEN = 34;
static constexpr int DARKEST = 35;
static constexpr int LIGHTEST = 36;
static constexpr int DIFFERENCE = 37;
static constexpr int EXCLUSION = 38;
// Math constants (float precision)
static constexpr float PI = static_cast<float>(M_PI);
static constexpr float TWO_PI = static_cast<float>(M_PI * 2.0);
static constexpr float HALF_PI = static_cast<float>(M_PI / 2.0);
static constexpr float QUARTER_PI = static_cast<float>(M_PI / 4.0);
static constexpr float TAU = TWO_PI; // alias
// Renderer flags for size()
static constexpr int P2D = 2;
static constexpr int P3D = 3;
// Texture / image modes
static constexpr int IMAGE = 100;
static constexpr int NORMAL = 101;
static constexpr int CLAMP = 102;
static constexpr int REPEAT = 103;
// hint() flags
static constexpr int ENABLE_DEPTH_TEST = 1;
static constexpr int DISABLE_DEPTH_TEST = -1;
static constexpr int ENABLE_DEPTH_SORT = 2;
static constexpr int DISABLE_DEPTH_SORT = -2;
static constexpr int ENABLE_OPENGL_ERRORS = 3;
static constexpr int DISABLE_OPENGL_ERRORS = -3;
static constexpr int ENABLE_STROKE_PERSPECTIVE = 4;
static constexpr int DISABLE_STROKE_PERSPECTIVE= -4;
static constexpr int ENABLE_TEXTURE_MIPMAPS = 5;
static constexpr int DISABLE_TEXTURE_MIPMAPS = -5;
// Cursor shapes (map to GLFW)
static constexpr int ARROW = GLFW_ARROW_CURSOR;
static constexpr int CROSS = GLFW_CROSSHAIR_CURSOR;
static constexpr int HAND = GLFW_HAND_CURSOR; // GLFW_POINTING_HAND_CURSOR in 3.4+
static constexpr int MOVE = GLFW_HRESIZE_CURSOR; // GLFW_RESIZE_ALL_CURSOR in 3.4+
static constexpr int TEXT_CURSOR = GLFW_IBEAM_CURSOR;
static constexpr int WAIT = GLFW_VRESIZE_CURSOR; // GLFW_RESIZE_ALL_CURSOR in 3.4+
// =============================================================================
// TIMING -- inline so they compile anywhere without linking Processing.cpp
// =============================================================================
inline unsigned long millis() {
using namespace std::chrono;
static auto start = steady_clock::now();
return static_cast<unsigned long>(duration_cast<milliseconds>(steady_clock::now()-start).count());
}
inline int second() { std::time_t t=std::time(nullptr); return std::localtime(&t)->tm_sec; }
inline int minute() { std::time_t t=std::time(nullptr); return std::localtime(&t)->tm_min; }
inline int hour() { std::time_t t=std::time(nullptr); return std::localtime(&t)->tm_hour; }
inline int day() { std::time_t t=std::time(nullptr); return std::localtime(&t)->tm_mday; }
inline int month() { std::time_t t=std::time(nullptr); return std::localtime(&t)->tm_mon+1; }
inline int year() { std::time_t t=std::time(nullptr); return std::localtime(&t)->tm_year+1900;}
// =============================================================================
// MATH -- float wrappers that match Processing Java's function names
// =============================================================================
inline float sin(float x) { return std::sin(x); }
inline float cos(float x) { return std::cos(x); }
inline float tan(float x) { return std::tan(x); }
inline float asin(float x) { return std::asin(x); }
inline float acos(float x) { return std::acos(x); }
inline float atan(float x) { return std::atan(x); }
inline float atan2(float y, float x) { return std::atan2(y, x); }
inline float sqrt(float x) { return std::sqrt(x); }
inline float sq(float x) { return x * x; }
inline float abs(float x) { return std::fabs(x); }
inline float ceil(float x) { return std::ceil(x); }
inline float floor(float x) { return std::floor(x); }
inline float round(float x) { return std::round(x); }
inline float exp(float x) { return std::exp(x); }
inline float log(float x) { return std::log(x); }
inline float pow(float b, float e) { return std::pow(b, e); }
inline float mag(float x, float y) { return std::sqrt(x*x+y*y); }
inline float mag(float x, float y, float z){ return std::sqrt(x*x+y*y+z*z); }
inline float norm(float v, float lo, float hi) { return (v-lo)/(hi-lo); }
inline float degrees(float r) { return r * 180.f / PI; }
inline float radians(float d) { return d * PI / 180.f; }
inline float lerp(float a, float b, float t){ return a + t*(b-a); }
inline float dist(float x1,float y1,float x2,float y2) {
float dx=x2-x1, dy=y2-y1;
return std::sqrt(dx*dx+dy*dy);
}
inline float dist(float x1,float y1,float z1,float x2,float y2,float z2) {
float dx=x2-x1, dy=y2-y1, dz=z2-z1;
return std::sqrt(dx*dx+dy*dy+dz*dz);
}
inline float map(float v, float i0, float i1, float o0, float o1) {
return o0 + (v-i0)*(o1-o0)/(i1-i0);
}
inline float constrain(float v, float lo, float hi) { return v<lo?lo:(v>hi?hi:v); }
inline float max(float a, float b) { return a>b?a:b; }
inline float min(float a, float b) { return a<b?a:b; }
inline float max(float a, float b, float c) { return max(a,max(b,c)); }
inline float min(float a, float b, float c) { return min(a,min(b,c)); }
inline bool isNaN(float v) { return std::isnan(v); }
inline bool isInfinite(float v) { return std::isinf(v); }
// =============================================================================
// RANDOM / NOISE
// =============================================================================
void randomSeed(long s);
float random(float lo, float hi);
float random(float hi);
float randomGaussian();
void noiseSeed(int seed);
void noiseDetail(int octaves, float falloff=0.5f);
float noise(float x);
float noise(float x, float y);
float noise(float x, float y, float z);
// =============================================================================
// ARRAY UTILITIES -- match Processing Java's array functions
// =============================================================================
template<typename T> inline std::vector<T> append(std::vector<T> arr, T val) { arr.push_back(val); return arr; }
template<typename T> inline std::vector<T> concat(std::vector<T> a, const std::vector<T>& b){ a.insert(a.end(),b.begin(),b.end()); return a; }
template<typename T> inline std::vector<T> expand(std::vector<T> arr, int n=-1) { if(n<0)n=(int)arr.size()*2; arr.resize(n); return arr; }
template<typename T> inline std::vector<T> reverse(std::vector<T> arr) { std::reverse(arr.begin(),arr.end()); return arr; }
template<typename T> inline std::vector<T> shorten(std::vector<T> arr) { if(!arr.empty())arr.pop_back(); return arr; }
template<typename T> inline std::vector<T> sort(std::vector<T> arr) { std::sort(arr.begin(),arr.end()); return arr; }
template<typename T> inline std::vector<T> splice(std::vector<T> arr, T val, int i) { arr.insert(arr.begin()+i,val); return arr; }
template<typename T> inline std::vector<T> splice(std::vector<T> arr, const std::vector<T>& vals, int i){ arr.insert(arr.begin()+i,vals.begin(),vals.end()); return arr; }
template<typename T> inline std::vector<T> subset(const std::vector<T>& arr, int start, int count=-1){
if(count<0) count=(int)arr.size()-start;
return std::vector<T>(arr.begin()+start, arr.begin()+start+count);
}
template<typename T> inline void arrayCopy(const std::vector<T>& src, std::vector<T>& dst) { dst=src; }
template<typename T> inline void arrayCopy(const std::vector<T>& src, int sp, std::vector<T>& dst, int dp, int len){
for(int i=0;i<len;i++) dst[dp+i]=src[sp+i];
}
// =============================================================================
// COLOR TYPE -- matches Processing Java's 'color' (int) type
// =============================================================================
// 'color' is a packed 32-bit ARGB integer, just like in Processing Java.
// Constructors respect the current colorMode setting (see colorMode()).
struct color {
unsigned int value;
color() : value(0xFF000000) {} // default: opaque black
color(unsigned int v) : value(v) {} // allows color pix = img->get(x,y)
// These constructors call makeColor() which applies colorMode.
// Defined in Processing.cpp so the colorMode globals are accessible.
color(int gray);
color(int gray, int a);
color(int r, int g, int b);
color(int r, int g, int b, int a);
// Use explicit cast: color(0,153,204,(int)a) or color(0.f,153.f,204.f,a)
color(float gray);
color(float gray, float a);
color(float r, float g, float b);
color(float r, float g, float b, float a);
explicit operator unsigned int() const { return value; }
unsigned int toInt() const { return value; }
// In Processing Java, color IS int. Allow implicit color<->int conversion
// so sketches can write: int c = color(255); int c = lerpColor(a,b,t);
operator int() const { return (int)value; }
// fromRaw: convert raw int (Java color int) directly to color value
static color fromRaw(int v) { color c; c.value=(unsigned int)v; return c; }
bool operator==(const color& o) const { return value == o.value; }
bool operator!=(const color& o) const { return value != o.value; }
};
// Build a color value from components (respects colorMode)
color makeColor(float a, float b, float c, float d=255);
color makeColor(float gray, float alpha=255);
// Pack raw 0-255 RGBA without colorMode (for internal use)
inline color colorVal(int r, int g, int b, int a=255) {
// Clamp to [0,255] -- don't wrap, which would cause dark artifacts
// when noise()*255 or other values slightly exceed 255
auto clamp8=[](int v){return v<0?0:v>255?255:v;};
return color((unsigned int)(((clamp8(a))<<24)|((clamp8(r))<<16)|((clamp8(g))<<8)|(clamp8(b))));
}
// Color component extractors
float red(color c);
float green(color c);
float blue(color c);
float alpha(color c);
float brightness(color c);
float saturation(color c);
float hue(color c);
color lerpColor(color c1, color c2, float t);
// =============================================================================
// PRINT / OUTPUT
// =============================================================================
template<typename T> inline void print(const T& v) { std::cout << v; std::cout.flush(); }
template<typename T> inline void println(const T& v) { std::cout << v << "\n"; std::cout.flush(); }
inline void println() { std::cout << "\n"; std::cout.flush(); }
template<typename T> inline void printArray(const std::vector<T>& a) {
for (size_t i=0; i<a.size(); i++) std::cout << "[" << i << "] " << a[i] << "\n";
}
// =============================================================================
// STRING UTILITIES
// =============================================================================
inline std::string str(int v) { return std::to_string(v); }
inline std::string str(float v) { return std::to_string(v); }
inline std::string str(bool v) { return v ? "true" : "false"; }
inline std::string str(char v) { return std::string(1, v); }
inline bool toBoolean(const std::string& s) { return s=="true"||s=="1"||s=="yes"; }
inline int toInt(const std::string& s) { return std::stoi(s); }
inline float toFloat(const std::string& s) { return std::stof(s); }
inline char toChar(int v) { return static_cast<char>(v); }
inline std::string trim(const std::string& s) {
size_t a=s.find_first_not_of(" \t\n\r"), b=s.find_last_not_of(" \t\n\r");
return a==std::string::npos ? "" : s.substr(a, b-a+1);
}
inline std::vector<std::string> split(const std::string& s, char d) {
std::vector<std::string> o; std::stringstream ss(s); std::string t;
while (std::getline(ss, t, d)) o.push_back(t);
return o;
}
inline std::vector<std::string> splitTokens(const std::string& s, const std::string& delims) {
std::vector<std::string> o; std::string cur;
for (char c:s) {
if (delims.find(c)!=std::string::npos) { if(!cur.empty()){o.push_back(cur);cur.clear();} }
else cur+=c;
}
if (!cur.empty()) o.push_back(cur);
return o;
}
inline std::string join(const std::vector<std::string>& v, const std::string& sep) {
std::string o;
for (size_t i=0; i<v.size(); i++) { if(i) o+=sep; o+=v[i]; }
return o;
}
// Number formatting
inline std::string nf(float v, int digits) { std::ostringstream ss; ss.precision(digits); ss<<std::fixed<<v; return ss.str(); }
inline std::string nf(int v, int minDigits) { std::ostringstream ss; ss<<std::setw(minDigits)<<std::setfill('0')<<v; return ss.str(); }
inline std::string nf(float v, int left, int right) {
std::ostringstream ss; ss<<std::fixed<<std::setprecision(right)<<v;
std::string s=ss.str(); size_t dot=s.find('.');
size_t intLen=(dot==std::string::npos)?s.size():dot;
while((int)intLen<left){s="0"+s;intLen++;}
return s;
}
inline std::string nfc(float v, int digits) { std::ostringstream ss; ss.precision(digits); ss<<std::fixed<<v; std::string s=ss.str(); int dot=(int)s.find('.'); if(dot<0)dot=(int)s.size(); for(int i=dot-3;i>0;i-=3)s.insert(i,","); return s; }
inline std::string nfp(float v, int digits) { return (v>=0?"+":"") + nf(v,digits); }
inline std::string nfs(float v, int digits) { return (v>=0?" ":"") + nf(v,digits); }
inline std::string hex(int v) { std::ostringstream ss; ss<<std::uppercase<<std::hex<<v; return ss.str(); }
inline std::string hex(int v, int digits) { std::ostringstream ss; ss<<std::uppercase<<std::hex<<std::setw(digits)<<std::setfill('0')<<v; return ss.str(); }
inline std::string binary(int v) { std::string s; for(int i=31;i>=0;i--) s+=((v>>i)&1)?'1':'0'; return s; }
inline int unhex(const std::string& s) { return std::stoi(s,nullptr,16); }
inline int unbinary(const std::string& s){ return std::stoi(s,nullptr,2); }
// Regex helpers
inline std::vector<std::string> match(const std::string& s, const std::string& pat) {
std::vector<std::string> out; std::smatch m; std::regex re(pat);
if (std::regex_search(s,m,re)) for (auto& x:m) out.push_back(x.str());
return out;
}
inline std::vector<std::vector<std::string>> matchAll(const std::string& s, const std::string& pat) {
std::vector<std::vector<std::string>> out; std::regex re(pat);
auto it=std::sregex_iterator(s.begin(),s.end(),re), end=std::sregex_iterator();
for(;it!=end;++it){ std::vector<std::string> row; for(auto& x:*it) row.push_back(x.str()); out.push_back(row); }
return out;
}
// =============================================================================