-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
2771 lines (2243 loc) · 93.3 KB
/
main.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
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
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include "imgui_internal.h"
#include <stdio.h>
#define GL_SILENCE_DEPRECATION
#if defined(IMGUI_IMPL_OPENGL_ES2)
#include <GLES2/gl2.h>
#endif
#include <GLFW/glfw3.h> // Will drag system OpenGL headers
#include "imfilebrowser.h"
#include "imguitoolbar.h"
#define _CRT_SECURE_NO_WARNINGS
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_resize.h" // Include the resize library
#include "stb_image_write.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include <HTTPRequest.hpp>
#include <base64.h>
#include <json.hpp>
#include "stable-diffusion.h"
#include <algorithm> // For std::max
#include <cmath>
#include <cstdint> // For uint32_t
#include <ctime>
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <stack>
#ifdef SLOP_WINDOWS_BUILD
#include <shlobj.h>
#include <windows.h>
#endif
using json = nlohmann::json;
namespace fs = std::filesystem;
/*
// [Win32] Our example includes a copy of glfw3.lib pre-compiled with VS2010 to
// maximize ease of testing and compatibility with old VS compilers. To link
// with VS2010-era libraries, VS2015+ requires linking with
// legacy_stdio_definitions.lib, which we do using this pragma. Your own project
// should not be affected, as you are likely to link with a newer binary of GLFW
// that is adequate for your version of Visual Studio.
#if defined(_MSC_VER) && (_MSC_VER >= 1900) && \
!defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
#pragma comment(lib, "legacy_stdio_definitions")
#endif
// This example can also compile and run with Emscripten! See
// 'Makefile.emscripten' for details.
#ifdef __EMSCRIPTEN__
#include "../libs/emscripten/emscripten_mainloop_stub.h"
#endif
//todo
const std::string config_dir =
std::getenv("HOME") + std::string("/.config/slop");
*/
// setings location differs by platform
#ifdef SLOP_WINDOWS_BUILD
std::string getAppDataPath() {
// Buffer to store the path
char appDataPath[MAX_PATH];
// Get the AppData path
if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, 0, appDataPath))) {
return std::string(appDataPath); // Convert to std::string
} else {
throw std::runtime_error("Failed to get AppData path.");
}
}
const std::string config_dir = getAppDataPath() + std::string("/slop");
#endif
#ifdef SLOP_LINUX_BUILD
const std::string config_dir =
std::getenv("HOME") + std::string("/.config/slop");
template <typename T> T max(T a, T b) { return std::max(a, b); }
template <typename T> T min(T a, T b) { return std::min(a, b); }
#endif
const std::string settings_file = config_dir + "/settings.json";
struct Layer {
int height;
int width;
bool enabled;
GLuint layerData;
} typedef Layer;
void freeLayer(struct Layer *layer) {
glDeleteTextures(1, &(layer->layerData));
}
struct FlattenedLayerData {
unsigned char *data;
int width;
int height;
};
struct BrushState {
int radius;
float RGBA[4] = {0.0f, 0.0f, 0.0f, 1.0f};
};
struct GenerationState {
int height = 512;
int width = 512;
};
struct SelectionState {
int corner1[2];
int corner2[2];
bool dragging = false;
bool completeSelection = false;
bool selectionDragMode = false;
int selectionXOffset = 0;
int selectionYOffset = 0;
int initialDragX = 0;
int initialDragY = 0;
int selectionZoom = 100;
bool bottomRightScaleMode = false;
bool rightScaleMode = false;
bool bottomScaleMode = false;
bool topLeftScaleMode = false;
bool leftScaleMode = false;
bool topRightScaleMode = false;
bool bottomLeftScaleMode = false;
bool topScaleMode = false;
GLuint selection;
};
struct LayerResizeState {
int targetWidth;
int targetHeight;
};
struct EnvironmentState {
bool stable_diffusion_path_set;
std::string stable_diffusion_path;
};
struct ProgramState {
bool drawMode = false;
bool inpaintMode = false;
bool dragMode = false;
bool selectionMode = false;
bool brushSettingsOpen = false;
bool generationSettingsOpen = false;
bool resizeLayerDialogOpen = false;
bool warningDialogOpen = false;
std::string warningMessage;
int dragInitX;
int dragInitY;
int oldViewOffsetX;
int oldViewOffsetY;
struct BrushState brushState;
struct GenerationState generationState;
struct SelectionState selectionState;
struct LayerResizeState layerResizeState;
struct EnvironmentState tempEnvironmentState;
};
// from stable-diffusion.cpp cli
enum SDMode { TXT2IMG, IMG2IMG, IMG2VID, CONVERT, MODE_COUNT };
struct SDParams {
int n_threads = -1;
SDMode mode = TXT2IMG;
std::string model_path;
std::string vae_path;
std::string taesd_path;
std::string esrgan_path;
std::string controlnet_path;
std::string embeddings_path;
std::string stacked_id_embeddings_path;
std::string input_id_images_path;
sd_type_t wtype = SD_TYPE_COUNT;
std::string lora_model_dir;
std::string output_path = "output.png";
std::string input_path;
std::string control_image_path;
std::string prompt;
std::string negative_prompt;
float min_cfg = 1.0f;
float cfg_scale = 7.0f;
float style_ratio = 20.f;
int clip_skip = -1; // <= 0 represents unspecified
int width = 512;
int height = 512;
int batch_count = 1;
int video_frames = 6;
int motion_bucket_id = 127;
int fps = 6;
float augmentation_level = 0.f;
sample_method_t sample_method = EULER_A;
schedule_t schedule = DEFAULT;
int sample_steps = 20;
float strength = 0.75f;
float control_strength = 0.9f;
rng_type_t rng_type = CUDA_RNG;
int64_t seed = 42;
bool verbose = false;
bool vae_tiling = false;
bool control_net_cpu = false;
bool normalize_input = false;
bool clip_on_cpu = false;
bool vae_on_cpu = false;
bool canny_preprocess = false;
bool color = false;
int upscale_repeats = 1;
};
enum class ActionType {
None = 0,
Import,
Save,
Load,
Export,
Generate,
Inpaint,
Undo,
BrushSettings,
GenerationSettings,
BoxSelect,
ResizeLayer,
MergeActiveLayers,
AddLayer,
RemoveLayer
};
enum class FilePickerActionType { None = 0, Load, Import, Save, Export };
void create_default_settings() {
json default_settings = {{"stable_diffusion_path_set", false},
{"stable_diffusion_path", ""}};
fs::create_directories(config_dir); // Create directory if it doesn't exist
std::ofstream file(settings_file);
if (file.is_open()) {
file << default_settings.dump(4); // Pretty print with 4 spaces indentation
file.close();
} else {
std::cerr << "Failed to create settings file." << std::endl;
}
}
json load_settings() {
json settings;
if (fs::exists(settings_file)) {
std::ifstream file(settings_file);
if (file.is_open()) {
file >> settings;
file.close();
} else {
std::cerr << "Failed to open settings file." << std::endl;
}
} else {
create_default_settings();
settings = json::parse(std::ifstream(settings_file));
}
return settings;
}
void save_settings(const json &settings) {
std::ofstream file(settings_file);
if (file.is_open()) {
file << settings.dump(4); // Pretty print with 4 spaces indentation
file.close();
} else {
std::cerr << "Failed to save settings file." << std::endl;
}
}
void removeLayers(std::vector<Layer> &vec, const std::vector<int> &indices) {
// Create a copy of indices to sort and work with
std::vector<int> sorted_indices(indices);
// Sort indices in descending order to avoid invalidating positions
std::sort(sorted_indices.begin(), sorted_indices.end(),
std::greater<size_t>());
// Remove elements at the specified indices
for (int index : sorted_indices) {
if (index < vec.size()) { // Ensure the index is within range
vec.erase(vec.begin() + index);
}
}
}
std::string encode_file_to_base64(const std::string &path) {
// Open the file in binary mode
std::ifstream file(path, std::ios::binary);
// Check if the file was opened successfully
if (!file) {
throw std::runtime_error("Unable to open file: " + path);
}
// Read the file contents into a stringstream
std::ostringstream oss;
oss << file.rdbuf();
// Get the file contents as a string
std::string file_contents = oss.str();
// Encode the file contents to base64
return base64::to_base64(file_contents);
}
void save_png(const std::string &filename, const unsigned char *image_data,
int width, int height) {
// Write the image to a PNG file
int success =
stbi_write_png(filename.c_str(), width, height, 4, image_data, width * 4);
if (!success) {
std::cout << "Error: Could not write PNG file\n";
} else {
std::cout << "saved" << std::endl;
}
}
// Function to load a vector of Layer structs from a file, including pixel data
bool loadLayersFromFile(std::vector<Layer> &layers,
const std::string &filename) {
std::ifstream inFile(filename, std::ios::binary);
if (!inFile) {
std::cerr << "Error opening file for reading: " << filename << std::endl;
}
uint32_t magicNumber, versionNumber;
inFile.read(reinterpret_cast<char *>(&magicNumber), sizeof(magicNumber));
inFile.read(reinterpret_cast<char *>(&versionNumber), sizeof(versionNumber));
// Read the number of layers
uint32_t layerCount;
inFile.read(reinterpret_cast<char *>(&layerCount), sizeof(layerCount));
layers.resize(layerCount);
for (int i = 0; i < layers.size(); i++) {
uint32_t width, height;
inFile.read(reinterpret_cast<char *>(&width), sizeof(width));
inFile.read(reinterpret_cast<char *>(&height), sizeof(height));
layers[i].width = width;
layers[i].height = height;
inFile.read(reinterpret_cast<char *>(&layers[i].enabled),
sizeof(layers[i].enabled));
// Allocate buffer for pixel data
std::vector<unsigned char> pixels(layers[i].height * layers[i].width *
4); // Assuming RGBA format
// Read pixel data from file
inFile.read(reinterpret_cast<char *>(pixels.data()), pixels.size());
// Create and bind texture
glGenTextures(1, &(layers[i].layerData));
glBindTexture(GL_TEXTURE_2D, layers[i].layerData);
// Upload pixel data to texture
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// Upload pixels into texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layers[i].width, layers[i].height,
0, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());
// Store texture ID in the layer
}
inFile.close();
return true;
}
bool saveLayersToFile(const std::vector<Layer> &layers,
const std::string &filename) {
std::ofstream outFile(filename, std::ios::binary);
if (!outFile) {
std::cerr << "Error opening file for writing: " << filename << std::endl;
return false;
}
// Define magic number and version number as uint32_t
const uint32_t magicNumber = 12312412;
const uint32_t versionNumber = 0;
// Write magic number
outFile.write(reinterpret_cast<const char *>(&magicNumber),
sizeof(magicNumber));
// Write version number
outFile.write(reinterpret_cast<const char *>(&versionNumber),
sizeof(versionNumber));
// Write the number of layers
uint32_t layerCount = layers.size();
outFile.write(reinterpret_cast<const char *>(&layerCount),
sizeof(layerCount));
for (const auto &layer : layers) {
const uint32_t width = layer.width; // we want to ensure ints are always
// saved to file with 4 bytes.
const uint32_t height = layer.height;
outFile.write(reinterpret_cast<const char *>(&width), sizeof(width));
outFile.write(reinterpret_cast<const char *>(&height), sizeof(height));
outFile.write(reinterpret_cast<const char *>(&layer.enabled),
sizeof(layer.enabled));
// Bind the texture and read pixel data
glBindTexture(GL_TEXTURE_2D, layer.layerData);
// Allocate buffer for pixel data
std::vector<unsigned char> pixels(layer.height * layer.width *
4); // Assuming RGBA format
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());
// Write pixel data to file
outFile.write(reinterpret_cast<const char *>(pixels.data()), pixels.size());
}
outFile.close();
return true;
}
// Simple helper function to load an image into a OpenGL texture with common
// settings
bool LoadTextureFromMemory(const void *data, size_t data_size,
GLuint *out_texture, int *out_width,
int *out_height) {
// Load from file
int image_width = 0;
int image_height = 0;
unsigned char *image_data =
stbi_load_from_memory((const unsigned char *)data, (int)data_size,
&image_width, &image_height, NULL, 4);
if (image_data == NULL)
return false;
// Create a OpenGL texture identifier
GLuint image_texture;
glGenTextures(1, &image_texture);
glBindTexture(GL_TEXTURE_2D, image_texture);
// Setup filtering parameters for display
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// Upload pixels into texture
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA,
GL_UNSIGNED_BYTE, image_data);
stbi_image_free(image_data);
*out_texture = image_texture;
*out_width = image_width;
*out_height = image_height;
return true;
}
// Open and read a file, then forward to LoadTextureFromMemory()
bool LoadTextureFromFile(const char *file_name, GLuint *out_texture,
int *out_width, int *out_height) {
FILE *f = fopen(file_name, "rb");
if (f == NULL)
return false;
fseek(f, 0, SEEK_END);
size_t file_size = (size_t)ftell(f);
if (file_size == -1)
return false;
fseek(f, 0, SEEK_SET);
void *file_data = IM_ALLOC(file_size);
fread(file_data, 1, file_size, f);
bool ret = LoadTextureFromMemory(file_data, file_size, out_texture, out_width,
out_height);
IM_FREE(file_data);
return ret;
}
bool SetPixelColor(GLuint texture_id, int x, int y, unsigned char r,
unsigned char g, unsigned char b, unsigned char a, int width,
int height) {
// Check for valid coordinates
if (x < 0 || x >= width || y < 0 || y >= height) {
return false; // Invalid coordinates
}
// Create a buffer to hold the pixel data
unsigned char pixel_data[4] = {r, g, b, a};
// Bind the texture
glBindTexture(GL_TEXTURE_2D, texture_id);
// Update the specific pixel
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE,
pixel_data);
return true;
}
// Helper function to blend a color with an existing pixel
void blendPixel(std::vector<uint8_t> &buffer, int width, int height, int x,
int y, int r, int g, int b, int alpha) {
if (x < 0 || x >= width || y < 0 || y >= height)
return; // Out of bounds check
int index = (y * width + x) * 4; // Assuming RGBA format
// Read the existing color
uint8_t existingR = buffer[index];
uint8_t existingG = buffer[index + 1];
uint8_t existingB = buffer[index + 2];
uint8_t existingA = buffer[index + 3];
// Blend the new color with the existing color
float newAlpha = alpha / 255.0f;
float invAlpha = 1.0f - newAlpha;
buffer[index] =
static_cast<uint8_t>(r); // * newAlpha + existingR * invAlpha); // Red
buffer[index + 1] =
static_cast<uint8_t>(g); //* newAlpha + existingG * invAlpha); // Green
buffer[index + 2] =
static_cast<uint8_t>(b); //* newAlpha + existingB * invAlpha); // Blue
buffer[index + 3] =
static_cast<uint8_t>(alpha); // std::max(static_cast<int>(alpha),
// static_cast<int>(existingA))); // Alpha
// (use the maximum of new and existing)
}
bool drawCircle(GLuint texture_id, int centerX, int centerY, int image_width,
int image_height, int radius, int r, int g, int b, int alpha) {
// Create a buffer for the pixel data (RGBA format)
std::vector<uint8_t> pixel_buffer(image_width * image_height * 4,
0); // Initialize with transparent black
// Bind the texture and read current pixel data into the buffer
glBindTexture(GL_TEXTURE_2D, texture_id);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE,
pixel_buffer.data());
// Compute radius squared once for efficiency
int radius_squared = radius * radius;
// Loop through the bounding box of the circle
for (int x = -radius; x <= radius; ++x) {
int y_max = std::sqrt(radius_squared - x * x);
for (int y = -y_max; y <= y_max; ++y) {
// Compute the pixel position
int pixelX = centerX + x;
int pixelY = centerY + y;
// Check if the pixel is within the image bounds
if (pixelX >= 0 && pixelX < image_width && pixelY >= 0 &&
pixelY < image_height) {
// Blend the pixel color in the buffer
blendPixel(pixel_buffer, image_width, image_height, pixelX, pixelY, r,
g, b, alpha);
}
}
}
// Update the texture from the buffer
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, image_width, image_height, GL_RGBA,
GL_UNSIGNED_BYTE, pixel_buffer.data());
return true;
}
bool drawLine(GLuint texture_id, int start_x, int start_y, int end_x, int end_y,
int image_width, int image_height, int radius, int r, int g,
int b, int alpha) {
// Create a buffer for the pixel data (RGBA format)
std::vector<uint8_t> pixel_buffer(image_width * image_height * 4,
0); // Initialize with transparent black
// Bind the texture and read current pixel data into the buffer
glBindTexture(GL_TEXTURE_2D, texture_id);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE,
pixel_buffer.data());
float pixel_dist = sqrt(pow(end_x - start_x, 2) + pow(end_y - start_y, 2));
int radius_squared = radius * radius;
for (int i = 0; i < (int)pixel_dist; i++) {
float coefficient = (float)i / pixel_dist;
int candidate_x = start_x * (1 - coefficient) + end_x * (coefficient);
int candidate_y = start_y * (1 - coefficient) + end_y * (coefficient);
for (int x = -radius; x <= radius; ++x) {
int y_max = std::sqrt(radius_squared - x * x);
for (int y = -y_max; y <= y_max; ++y) {
// Compute the pixel position
int pixelX = candidate_x + x;
int pixelY = candidate_y + y;
// Check if the pixel is within the image bounds
if (pixelX >= 0 && pixelX < image_width && pixelY >= 0 &&
pixelY < image_height) {
// Blend the pixel color in the buffer
blendPixel(pixel_buffer, image_width, image_height, pixelX, pixelY, r,
g, b, alpha);
}
}
}
}
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, image_width, image_height, GL_RGBA,
GL_UNSIGNED_BYTE, pixel_buffer.data());
return true;
}
bool drawSelectionBox(GLuint texture_id, int x1, int y1, int x2, int y2,
int image_width, int image_height, int radius, int r,
int g, int b, int alpha, bool fill) {
// Create a buffer for the pixel data (RGBA format) and initialize with
// transparent black
std::vector<uint8_t> pixel_buffer(image_width * image_height * 4, 0);
// Ensure x1 <= x2 and y1 <= y2
if (x1 > x2)
std::swap(x1, x2);
if (y1 > y2)
std::swap(y1, y2);
// Draw the box
for (int x = x1; x <= x2; ++x) {
for (int y = y1; y <= y2; ++y) {
// Skip pixels outside the image bounds
if (x < 0 || x >= image_width || y < 0 || y >= image_height)
continue;
// Apply radius effect for rounded corners
int dx1 = min(x - x1, x2 - x);
int dy1 = min(y - y1, y2 - y);
bool is_border = (x == x1 || x == x2 || y == y1 || y == y2 ||
dx1 * dx1 + dy1 * dy1 <= radius * radius);
if (fill || is_border) {
// Overwrite the pixel color in the buffer
int pixel_index = (y * image_width + x) * 4;
pixel_buffer[pixel_index + 0] = r; // Red
pixel_buffer[pixel_index + 1] = g; // Green
pixel_buffer[pixel_index + 2] = b; // Blue
pixel_buffer[pixel_index + 3] = alpha; // Alpha
}
}
}
// Bind the texture
glBindTexture(GL_TEXTURE_2D, texture_id);
// Upload the modified pixel buffer back to the texture
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, image_width, image_height, GL_RGBA,
GL_UNSIGNED_BYTE, pixel_buffer.data());
return true;
}
bool drawBox(GLuint texture_id, int x1, int y1, int x2, int y2, int image_width,
int image_height, int radius, int r, int g, int b, int alpha,
bool fill) {
// Create a buffer for the original pixel data (RGBA format)
std::vector<uint8_t> original_pixel_buffer(image_width * image_height * 4);
// Bind the texture and get the current pixel data
glBindTexture(GL_TEXTURE_2D, texture_id);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE,
original_pixel_buffer.data());
// Create a buffer for the updated pixel data
std::vector<uint8_t> updated_pixel_buffer = original_pixel_buffer;
// Ensure x1 <= x2 and y1 <= y2
if (x1 > x2)
std::swap(x1, x2);
if (y1 > y2)
std::swap(y1, y2);
// Draw the box
for (int x = x1; x <= x2; ++x) {
for (int y = y1; y <= y2; ++y) {
// Skip pixels outside the image bounds
if (x < 0 || x >= image_width || y < 0 || y >= image_height)
continue;
// Apply radius effect for rounded corners
int dx1 = min(x - x1, x2 - x);
int dy1 = min(y - y1, y2 - y);
bool is_border = (x == x1 || x == x2 || y == y1 || y == y2 ||
dx1 * dx1 + dy1 * dy1 <= radius * radius);
if (fill || is_border) {
// Update the pixel color in the buffer
int pixel_index = (y * image_width + x) * 4;
updated_pixel_buffer[pixel_index + 0] = r; // Red
updated_pixel_buffer[pixel_index + 1] = g; // Green
updated_pixel_buffer[pixel_index + 2] = b; // Blue
updated_pixel_buffer[pixel_index + 3] = alpha; // Alpha
}
}
}
// Bind the texture
glBindTexture(GL_TEXTURE_2D, texture_id);
// Upload the modified pixel buffer back to the texture
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, image_width, image_height, GL_RGBA,
GL_UNSIGNED_BYTE, updated_pixel_buffer.data());
return true;
}
bool copyTextureSubset(GLuint *in_texture, GLuint *out_texture, int width,
int height, int x1, int y1, int x2, int y2) {
// Allocate memory for the texture data
unsigned char *image_data = new unsigned char[width * height * 4]; // RGBA
glBindTexture(GL_TEXTURE_2D, *in_texture);
// Read the pixel data from the texture
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);
// Unbind the texture
glBindTexture(GL_TEXTURE_2D, 0);
int dst_width = x2 - x1;
int dst_height = y2 - y1;
unsigned char *cropped_image_data =
new unsigned char[dst_width * dst_height * 4];
// Transfer pixel values to cropped_image_data
for (int y = 0; y < dst_height; ++y) {
for (int x = 0; x < dst_width; ++x) {
int src_index = ((y1 + y) * width + (x1 + x)) * 4;
int dst_index = (y * dst_width + x) * 4;
cropped_image_data[dst_index] = image_data[src_index];
cropped_image_data[dst_index + 1] = image_data[src_index + 1];
cropped_image_data[dst_index + 2] = image_data[src_index + 2];
cropped_image_data[dst_index + 3] = image_data[src_index + 3];
}
}
// Create an OpenGL texture identifier
GLuint texture_id;
glGenTextures(1, &texture_id);
glBindTexture(GL_TEXTURE_2D, texture_id);
// Setup filtering parameters for display
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// Upload pixels into texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, dst_width, dst_height, 0, GL_RGBA,
GL_UNSIGNED_BYTE, cropped_image_data);
// Free the allocated image data
delete[] image_data;
delete[] cropped_image_data;
*out_texture = texture_id;
return true;
}
bool resizeTexture(GLuint *in_texture, int dst_width, int dst_height) {
// Bind the input texture
glBindTexture(GL_TEXTURE_2D, *in_texture);
// Get the original texture dimensions
GLint src_width, src_height;
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &src_width);
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &src_height);
// Allocate memory for the original texture data
unsigned char *image_data =
new unsigned char[src_width * src_height * 4]; // RGBA
// Read the pixel data from the texture
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);
// Allocate memory for the resized texture data
unsigned char *resized_image_data =
new unsigned char[dst_width * dst_height * 4];
// Resize the texture using nearest neighbor interpolation
for (int y = 0; y < dst_height; ++y) {
for (int x = 0; x < dst_width; ++x) {
// Calculate the corresponding pixel in the original texture
int src_x = static_cast<int>(x * src_width / dst_width);
int src_y = static_cast<int>(y * src_height / dst_height);
// Clamp the indices to the original texture dimensions
src_x = std::min(src_x, src_width - 1);
src_y = std::min(src_y, src_height - 1);
// Get the pixel values from the original texture
unsigned char *p = &image_data[(src_y * src_width + src_x) * 4];
// Copy the pixel values to the resized texture
for (int c = 0; c < 4; ++c) {
resized_image_data[(y * dst_width + x) * 4 + c] = p[c];
}
}
}
// Upload pixels into the original texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, dst_width, dst_height, 0, GL_RGBA,
GL_UNSIGNED_BYTE, resized_image_data);
// Free the allocated image data
delete[] image_data;
delete[] resized_image_data;
return true;
}
bool copyTextureToRegion(GLuint *in_texture, GLuint *out_texture, int src_width,
int src_height, int dst_width, int dst_height,
int x_offset, int y_offset, bool overwrite) {
// Allocate memory for the texture data
unsigned char *image_data =
new unsigned char[src_width * src_height * 4]; // RGBA
glBindTexture(GL_TEXTURE_2D, *in_texture);
// Read the pixel data from the texture
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);
// Unbind the texture
glBindTexture(GL_TEXTURE_2D, 0);
unsigned char *result_image_data =
new unsigned char[dst_width * dst_height * 4];
glBindTexture(GL_TEXTURE_2D, *out_texture);
// Read the pixel data from the texture
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, result_image_data);
// Unbind the texture
glBindTexture(GL_TEXTURE_2D, 0);
// Transfer pixel values to cropped_image_data
for (int y = 0; y < src_height; ++y) {
for (int x = 0; x < src_width; ++x) {
int src_index = (y * src_width + x) * 4;
int dst_index = ((y_offset + y) * dst_width + (x_offset + x)) * 4;
if (dst_index >= 0 && dst_index < dst_width * dst_height * 4 &&
y_offset + y < dst_height && x_offset + x < dst_width &&
y_offset + y >= 0 && x_offset + x >= 0) {
// Read alpha values (normalized to [0, 1])
float newAlpha = image_data[src_index + 3] / 255.0f;
float oldAlpha = result_image_data[dst_index + 3] / 255.0f;
// Read color values
float srcRed = image_data[src_index + 0];
float srcGreen = image_data[src_index + 1];
float srcBlue = image_data[src_index + 2];
float dstRed = result_image_data[dst_index + 0];
float dstGreen = result_image_data[dst_index + 1];
float dstBlue = result_image_data[dst_index + 2];
// If newAlpha is 0, copy the source pixel directly
if (oldAlpha == 0 || overwrite) {
result_image_data[dst_index + 0] = srcRed;
result_image_data[dst_index + 1] = srcGreen;
result_image_data[dst_index + 2] = srcBlue;
result_image_data[dst_index + 3] =
static_cast<unsigned char>(newAlpha * 255.0f);
} else {
// Blending using alpha compositing
float blendedAlpha = newAlpha + oldAlpha * (1 - newAlpha);
float blendedRed =
(srcRed * newAlpha + dstRed * oldAlpha * (1 - newAlpha)) /
blendedAlpha;
float blendedGreen =
(srcGreen * newAlpha + dstGreen * oldAlpha * (1 - newAlpha)) /
blendedAlpha;
float blendedBlue =
(srcBlue * newAlpha + dstBlue * oldAlpha * (1 - newAlpha)) /
blendedAlpha;
// Clamp the color values to [0, 255]
result_image_data[dst_index + 0] =
static_cast<unsigned char>(std::clamp(blendedRed, 0.0f, 255.0f));
result_image_data[dst_index + 1] = static_cast<unsigned char>(
std::clamp(blendedGreen, 0.0f, 255.0f));
result_image_data[dst_index + 2] =
static_cast<unsigned char>(std::clamp(blendedBlue, 0.0f, 255.0f));
result_image_data[dst_index + 3] = static_cast<unsigned char>(
std::clamp(blendedAlpha * 255.0f, 0.0f, 255.0f));
}
}
}
}
// Create an OpenGL texture identifier
GLuint texture_id;
glGenTextures(1, &texture_id);
glBindTexture(GL_TEXTURE_2D, texture_id);
// Setup filtering parameters for display
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// Upload pixels into texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, dst_width, dst_height, 0, GL_RGBA,
GL_UNSIGNED_BYTE, result_image_data);
// Free the allocated image data
delete[] image_data;
delete[] result_image_data;
*out_texture = texture_id;
return true;
}
bool GenerateTexture(ProgramState *state, GLuint *out_texture,
std::string prompt_string, int width, int height,
std::string model_path) {
int sd_channels = 3;
SDParams params;
params.model_path = model_path;
params.prompt = prompt_string; //"insidious spiders and octopus";
params.sample_steps = 20;
params.seed = std::rand();
sd_ctx_t *sd_ctx = new_sd_ctx(
params.model_path.c_str(), params.vae_path.c_str(),
params.taesd_path.c_str(), params.controlnet_path.c_str(),
params.lora_model_dir.c_str(), params.embeddings_path.c_str(),
params.stacked_id_embeddings_path.c_str(), true, params.vae_tiling, true,
params.n_threads, params.wtype, params.rng_type, params.schedule,
params.clip_on_cpu, params.control_net_cpu, params.vae_on_cpu);
sd_image_t *results;
sd_image_t *control_image = NULL;
results =
txt2img(sd_ctx, params.prompt.c_str(), params.negative_prompt.c_str(),
params.clip_skip, params.cfg_scale, params.width, params.height,
params.sample_method, params.sample_steps, params.seed,
params.batch_count, control_image, params.control_strength,
params.style_ratio, params.normalize_input,
params.input_id_images_path.c_str());