-
Notifications
You must be signed in to change notification settings - Fork 13
/
source.cpp
3602 lines (3231 loc) · 134 KB
/
source.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
#pragma once
#include "main.h"
#include "ui_core.h"
#include "structs.h"
#include "shaders.hlsl"
#include "events.cpp"
#include "ui_platform_win32.cpp"
#include "ui_d3d11.cpp"
#include "ui_core.cpp"
#include "web_anim.cpp"
#include "gui.cpp"
void d3d11_get_last_error(bool message = false) {
DWORD errorCode = GetLastError();
if (errorCode == 0) return;
LPSTR errorString = NULL;
FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
errorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)&errorString,
0,
NULL
);
if (errorString != NULL) {
if (message)
{
char errorMessage[256];
sprintf(errorMessage, "Error: [%d] %s", errorCode, errorString);
MessageBoxA(NULL, errorMessage, "Error", MB_OK | MB_ICONERROR);
}
else printf("Error: [%d] %s\n", errorCode, errorString);
LocalFree(errorString);
} else {
if (message)
{
char errorMessage[256];
sprintf(errorMessage, "Error code: [%d]", errorCode);
MessageBoxA(NULL, errorMessage, "Error", MB_OK | MB_ICONERROR);
}
else printf("Error code: [%d]\n", errorCode);
}
}
bool win32_get_error(HRESULT hresult, bool message = false) {
if (FAILED(hresult)) {
LPWSTR buffer = NULL;
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, hresult, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&buffer, 0, NULL);
if (buffer) {
if (message)
MessageBoxW(NULL, buffer, L"ERROR", MB_OK | MB_ICONERROR);
else
fwprintf(stderr, L"Error: %s\n", buffer);
LocalFree(buffer);
}
return false;
}
return true;
}
#define err(x) win32_get_error(x)
static ID3DBlob *compile_shader_memory(
char *shader_code,
size_t shader_code_size,
const char *entry_point,
const char *target) {
ID3DBlob* blob;
ID3DBlob* errors;
HRESULT result = D3DCompile(
shader_code, shader_code_size,
nullptr,
nullptr, // defines
nullptr, // includes
entry_point,
target,
0, 0,
&blob,
&errors
);
int error_count = 0;
if (errors) {
error_count = int(errors->GetBufferSize());
printf("%*s\n", error_count, (char *)errors->GetBufferPointer());
fflush(stdout);
}
if (FAILED(result)) {
blob = nullptr;
}
return blob;
}
static ID3D11Buffer * create_constants_buffer(Graphics *ctx, size_t bytes) {
D3D11_BUFFER_DESC desc = {};
// round constant buffer size to 16 byte boundary
desc.ByteWidth = (bytes + 0xf) & 0xfffffff0;
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
ID3D11Buffer *buffer;
ctx->device->CreateBuffer(&desc, nullptr, &buffer);
return buffer;
}
static Shader_Program create_shader_program(
Graphics *ctx, char *shader_string, size_t shader_string_size,
char * vs_entry_point, char * ps_entry_point, size_t constants_size,
int input_elements, D3D11_INPUT_ELEMENT_DESC *input_desc) {
Shader_Program shader = { 0 };
ID3DBlob *vs_blob = compile_shader_memory(shader_string, shader_string_size, vs_entry_point, "vs_5_0");
ctx->device->CreateVertexShader(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), nullptr, &shader.vertex_shader);
ID3DBlob *ps_blob = compile_shader_memory(shader_string, shader_string_size, ps_entry_point, "ps_5_0");
ctx->device->CreatePixelShader(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), nullptr, &shader.pixel_shader);
if (input_desc) {
ctx->device->CreateInputLayout(
input_desc, input_elements,
vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(),
&shader.input_layout);
}
if (constants_size) {
shader.constants_buffer = create_constants_buffer(ctx, constants_size);
}
shader.constants_buffer_size = constants_size;
return shader;
}
static void upload_constants(Shader_Program* program, void* data) {
D3D11_MAPPED_SUBRESOURCE mapped;
G->graphics.device_ctx->Map(program->constants_buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped);
assert(program->constants_buffer_size > 0);
memcpy(mapped.pData, data, program->constants_buffer_size);
G->graphics.device_ctx->Unmap(program->constants_buffer, 0);
}
static void upload_texture(Texture* texture, void* data, u64 size) {
D3D11_MAPPED_SUBRESOURCE mapped;
ZeroMemory(&mapped, sizeof(D3D11_MAPPED_SUBRESOURCE));
HRESULT hr = G->graphics.device_ctx->Map(texture->d3d_texture, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped);
BYTE* dest = static_cast<BYTE*>(mapped.pData);
BYTE* src = G->anim_buffer + G->anim_index * G->graphics.main_image.w * G->graphics.main_image.h * 4;
int row_pitch = mapped.RowPitch;
int row_size = G->graphics.main_image.w * 4; // 4 bytes per pixel as it's RGBA
for (int y = 0; y < G->graphics.main_image.h; ++y) {
memcpy(dest, src, row_size);
dest += row_pitch;
src += row_size;
}
G->graphics.device_ctx->Unmap(texture->d3d_texture, 0);
}
static void set_framebuffer_size(Graphics *ctx, iv2 size, bool set_dpi) {
if (ctx == nullptr) return;
if (ctx->viewport_size == size) return;
if (ctx->frame_buffer == nullptr) return;
if (size.x <= 0 || size.y <= 0) return;
// resize swapchain
float dpi_scale_factor = 1;
if (set_dpi) {
UINT dpi = GetDpiForWindow(hwnd);
dpi_scale_factor = dpi / 96.0f;
}
ctx->frame_buffer_view->Release();
ctx->frame_buffer->Release();
ctx->swap_chain->ResizeBuffers(0, size.x / dpi_scale_factor, size.y / dpi_scale_factor, DXGI_FORMAT_UNKNOWN, 0);
ctx->swap_chain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&ctx->frame_buffer);
ctx->device->CreateRenderTargetView(ctx->frame_buffer, nullptr, &ctx->frame_buffer_view);
//resize depthbuffer
D3D11_TEXTURE2D_DESC depth_buffer_desc;
ctx->depth_buffer->GetDesc(&depth_buffer_desc);
ctx->depth_buffer_view->Release();
ctx->depth_buffer->Release();
depth_buffer_desc.Width = size.x;
depth_buffer_desc.Height = size.y;
ctx->device->CreateTexture2D(&depth_buffer_desc, nullptr, &ctx->depth_buffer);
ctx->device->CreateDepthStencilView(ctx->depth_buffer, nullptr, &ctx->depth_buffer_view);
ctx->viewport_size = size;
}
static void init_d3d11(HWND window_handle, int ww, int wh) {
Graphics *ctx = &G->graphics;
RECT rect;
GetClientRect(hwnd, &rect);
ww = rect.right - rect.left;
wh = rect.bottom - rect.top;
D3D_FEATURE_LEVEL feature_levels[] = {
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
};
ID3D11Device* base_device;
ID3D11DeviceContext* base_device_ctx;
UINT createDeviceFlags = 0;
#if DEBUG_MODE
//createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D11CreateDevice(
nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags,
feature_levels, array_size(feature_levels),
D3D11_SDK_VERSION, &base_device,
nullptr, &base_device_ctx
);
base_device->QueryInterface(__uuidof(ID3D11Device1), (void**)&ctx->device);
base_device_ctx->QueryInterface(__uuidof(ID3D11DeviceContext1), (void**)&ctx->device_ctx);
IDXGIDevice1* dxgi_device;
(ctx->device)->QueryInterface(__uuidof(IDXGIDevice1), (void**)&dxgi_device);
IDXGIAdapter* dxgi_adapter;
dxgi_device->GetAdapter(&dxgi_adapter);
IDXGIFactory2* dxgi_factory;
dxgi_adapter->GetParent(__uuidof(IDXGIFactory2), (void**)&dxgi_factory);
DXGI_SWAP_CHAIN_DESC1 swap_chain_desc = { 0 };
swap_chain_desc.Width = 0;
swap_chain_desc.Height = 0;
swap_chain_desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
swap_chain_desc.Stereo = FALSE;
swap_chain_desc.SampleDesc.Count = 1;
swap_chain_desc.SampleDesc.Quality = 0;
swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swap_chain_desc.BufferCount = 2;
swap_chain_desc.Scaling = DXGI_SCALING_STRETCH;
swap_chain_desc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swap_chain_desc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
swap_chain_desc.Flags = 0;
dxgi_factory->CreateSwapChainForHwnd(ctx->device, window_handle, &swap_chain_desc, nullptr, nullptr, &ctx->swap_chain);
ctx->swap_chain->GetDesc1(&swap_chain_desc);
D3D11_TEXTURE2D_DESC frame_buffer_desc = { 0 };;
frame_buffer_desc.Width = ww ;
frame_buffer_desc.Height = wh ;
frame_buffer_desc.SampleDesc.Count = 1;
frame_buffer_desc.MipLevels = 1;
frame_buffer_desc.ArraySize = 1;
frame_buffer_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
frame_buffer_desc.Usage = D3D11_USAGE_DEFAULT;
frame_buffer_desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
D3D11_TEXTURE2D_DESC depth_buffer_desc = frame_buffer_desc;
depth_buffer_desc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depth_buffer_desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
err(ctx->swap_chain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&ctx->frame_buffer)); // substitutes needing to call createtexture since we're using the swap chain's texture
err(ctx->device->CreateRenderTargetView(ctx->frame_buffer, nullptr, &ctx->frame_buffer_view));
err(ctx->device->CreateTexture2D(&depth_buffer_desc, nullptr, &ctx->depth_buffer));
err(ctx->device->CreateDepthStencilView(ctx->depth_buffer, nullptr, &ctx->depth_buffer_view));
ctx->main_program = create_shader_program(ctx, shader_text_main, strlen(shader_text_main),
"vs_main", "ps_main", sizeof(Shader_Constants_Main), 0, 0);
ctx->bg_program = create_shader_program(ctx, shader_text_bg, strlen(shader_text_bg),
"vs_bg", "ps_bg", sizeof(Shader_Constants_BG), 0, 0);
ctx->crop_program = create_shader_program(ctx, shader_text_crop, strlen(shader_text_crop),
"vs_crop", "ps_crop", sizeof(Shader_Constants_Crop), 0, 0);
D3D11_INPUT_ELEMENT_DESC lines_layout[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
ctx->lines_program= create_shader_program(ctx, shader_text_lines, strlen(shader_text_lines),
"vs_lines", "ps_lines", sizeof(Shader_Constants_Lines),
1, lines_layout);
D3D11_BUFFER_DESC lines_vertex_desc = {};
lines_vertex_desc.Usage = D3D11_USAGE_DYNAMIC;
lines_vertex_desc.ByteWidth = sizeof(v2) * 256;
lines_vertex_desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
lines_vertex_desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
ctx->device->CreateBuffer(&lines_vertex_desc, 0, &G->graphics.lines_vertex_buffer);
D3D11_BLEND_DESC blend_desc = { 0 };
blend_desc.AlphaToCoverageEnable = false;
blend_desc.RenderTarget[0].BlendEnable = true;
blend_desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
blend_desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
blend_desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blend_desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
blend_desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
blend_desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blend_desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
err(ctx->device->CreateBlendState(&blend_desc, &ctx->blend_state));
D3D11_RASTERIZER_DESC rast_desc = { 0 };
rast_desc.CullMode = D3D11_CULL_NONE;
rast_desc.FillMode = D3D11_FILL_SOLID;
rast_desc.ScissorEnable = false;
rast_desc.DepthClipEnable = false;
rast_desc.FrontCounterClockwise = true;
err(ctx->device->CreateRasterizerState(&rast_desc, &ctx->raster_state));
D3D11_DEPTH_STENCIL_DESC depth_desc = { 0 };
depth_desc.DepthEnable = false;
depth_desc.StencilEnable = false;
depth_desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depth_desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
depth_desc.FrontFace.StencilFailOp = depth_desc.FrontFace.StencilDepthFailOp = depth_desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depth_desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depth_desc.BackFace = depth_desc.FrontFace;
err(ctx->device->CreateDepthStencilState(&depth_desc, &ctx->depth_stencil_state));
D3D11_SAMPLER_DESC sampler_desc = { 0 };
sampler_desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sampler_desc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
sampler_desc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
sampler_desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
sampler_desc.ComparisonFunc = D3D11_COMPARISON_NEVER;
sampler_desc.MinLOD = 0;
sampler_desc.MaxLOD = D3D11_FLOAT32_MAX;
err(ctx->device->CreateSamplerState(&sampler_desc, &ctx->sampler_linear));
sampler_desc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
err(ctx->device->CreateSamplerState(&sampler_desc, &ctx->sampler_nearest));
set_framebuffer_size(ctx, iv2(ww, wh));
G->graphics.MAX_GPU = D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION;
}
static Shader_Constants_Main set_main_shader_constants() {
Shader_Constants_Main result = { 0 };
result.aspect_img = G->graphics.aspect_img;
result.aspect_wnd = G->graphics.aspect_wnd;
result.scale = G->scale;
result.position = G->position / v2(WW, -WH) * 2;
result.pixel_grid = (G->nearest_filtering && (G->truescale > 5) && G->pixel_grid) ? 1 : 0;
result.true_scale = G->truescale;
result.image_dim = v2(G->graphics.main_image.w, G->graphics.main_image.h);
result.window = v2(WW, WH);
result.rgba_flags = v4((float)RGBAflags[0], (float)RGBAflags[1], (float)RGBAflags[2], (float)RGBAflags[3]);
result.rotation = G->graphics.main_image.orientation;
result.hue = G->hue;
result.saturation = G->saturation;
result.contrast = G->contrast;
result.brightness = G->brightness;
result.srgb = G->srgb;
result.gamma = G->gamma;
result.render_mode = RENDER_MODE_VEIWER;
result.do_blur = G->do_blur;
result.blur_lod = G->blur_lod;
result.blur_samples = G->blur_samples;
result.blur_scale = G->blur_scale;
result.crop_a = _v2(G->crop_a);
result.crop_b = _v2(G->crop_b);
result.crop_mode = G->crop_mode;
return result;
}
static Texture create_texture(u8 *data, int w, int h, bool dynamic) {
Graphics *d3d_ctx = &G->graphics;
D3D11_TEXTURE2D_DESC texture_desc = {};
texture_desc.Width = w;
texture_desc.Height = h;
texture_desc.MipLevels = dynamic ? 1 : 0;
texture_desc.ArraySize = 1;
texture_desc.SampleDesc.Count = 1;
texture_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
texture_desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
texture_desc.Usage = dynamic ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
if (!dynamic) texture_desc.BindFlags |= D3D11_BIND_RENDER_TARGET;
if (!dynamic) texture_desc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
if (dynamic) texture_desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
D3D11_SUBRESOURCE_DATA texture_SRD = {};
texture_SRD.pSysMem = data;
texture_SRD.SysMemPitch = w * 4;
D3D11_SHADER_RESOURCE_VIEW_DESC srv_desc = {};
srv_desc.Format = texture_desc.Format;
srv_desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srv_desc.Texture2D.MipLevels = UINT_MAX;
Texture result;
result.size = v2(w, h);
err(d3d_ctx->device->CreateTexture2D(&texture_desc, 0, &result.d3d_texture));
err(d3d_ctx->device->CreateShaderResourceView(result.d3d_texture, &srv_desc, &result.srv));
if (!dynamic) {
d3d_ctx->device_ctx->UpdateSubresource(result.d3d_texture, 0, NULL, data, w * 4, w * h * 4);
d3d_ctx->device_ctx->GenerateMips(result.srv);
}
return result;
}
#include <windows.h>
RECT g_original_window_rect;
LONG g_original_window_style;
void enter_fullscreen(HWND hwnd) {
GetWindowRect(hwnd, &g_original_window_rect);
g_original_window_style = GetWindowLong(hwnd, GWL_STYLE);
LONG newWindowStyle = g_original_window_style & ~(WS_CAPTION | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SYSMENU | WS_THICKFRAME);
SetWindowLong(hwnd, GWL_STYLE, newWindowStyle);
int screenWidth = GetSystemMetrics(SM_CXSCREEN);
int screenHeight = GetSystemMetrics(SM_CYSCREEN);
SetWindowPos(hwnd, HWND_TOP, 0, 0, screenWidth, screenHeight, SWP_FRAMECHANGED);
}
void exit_fullscreen(HWND hwnd) {
SetWindowLong(hwnd, GWL_STYLE, g_original_window_style);
SetWindowPos(hwnd, HWND_NOTOPMOST,
g_original_window_rect.left, g_original_window_rect.top,
g_original_window_rect.right - g_original_window_rect.left,
g_original_window_rect.bottom - g_original_window_rect.top,
SWP_FRAMECHANGED);
}
bool is_fullscreen(HWND hwnd) {
return !(GetWindowLong(hwnd, GWL_STYLE) & WS_CAPTION);
}
void toggle_fullscreen(HWND hwnd){
if (!is_fullscreen(hwnd))
enter_fullscreen(hwnd);
else
exit_fullscreen(hwnd);
}
static void init_logo_image() {
G->graphics.logo_image = create_texture(minilogo, 50, 53, false);
}
static void save_settings() {
char buffer[0x400];
snprintf(buffer, sizeof(buffer), "%s\\config.json", APPDATA_FOLDER);
FILE *F = fopen(buffer, "w");
cJSON *config_file = cJSON_CreateObject();
if (F) {
cJSON *j_checkboard_color_1 = cJSON_CreateArray();
cJSON_AddItemToArray(j_checkboard_color_1, cJSON_CreateNumber(checkerboard_color_1[0]));
cJSON_AddItemToArray(j_checkboard_color_1, cJSON_CreateNumber(checkerboard_color_1[1]));
cJSON_AddItemToArray(j_checkboard_color_1, cJSON_CreateNumber(checkerboard_color_1[2]));
cJSON *j_checkboard_color_2 = cJSON_CreateArray();
cJSON_AddItemToArray(j_checkboard_color_2, cJSON_CreateNumber(checkerboard_color_2[0]));
cJSON_AddItemToArray(j_checkboard_color_2, cJSON_CreateNumber(checkerboard_color_2[1]));
cJSON_AddItemToArray(j_checkboard_color_2, cJSON_CreateNumber(checkerboard_color_2[2]));
cJSON *j_bg_color = cJSON_CreateArray();
cJSON_AddItemToArray(j_bg_color, cJSON_CreateNumber(bg_color[0]));
cJSON_AddItemToArray(j_bg_color, cJSON_CreateNumber(bg_color[1]));
cJSON_AddItemToArray(j_bg_color, cJSON_CreateNumber(bg_color[2]));
cJSON_AddItemToArray(j_bg_color, cJSON_CreateNumber(bg_color[3]));
cJSON_AddItemToObject(config_file, "settings_resetpos", cJSON_CreateNumber(G->settings_resetpos));
cJSON_AddItemToObject(config_file, "settings_resetzoom", cJSON_CreateNumber(G->settings_resetzoom));
cJSON_AddItemToObject(config_file, "checkerboard_color_1", j_checkboard_color_1);
cJSON_AddItemToObject(config_file, "checkerboard_color_2", j_checkboard_color_2);
cJSON_AddItemToObject(config_file, "bg_color", j_bg_color);
cJSON_AddItemToObject(config_file, "settings_autoplayGIFs", cJSON_CreateBool(G->settings_autoplayGIFs));
cJSON_AddItemToObject(config_file, "settings_movementmag", cJSON_CreateNumber(G->settings_movementmag));
cJSON_AddItemToObject(config_file, "settings_shiftslowmag", cJSON_CreateNumber(G->settings_shiftslowmag));
cJSON_AddItemToObject(config_file, "settings_movementinvert", cJSON_CreateBool(G->settings_movementinvert));
cJSON_AddItemToObject(config_file, "nearest_filtering", cJSON_CreateBool(G->nearest_filtering));
cJSON_AddItemToObject(config_file, "pixel_grid", cJSON_CreateBool(G->pixel_grid));
cJSON_AddItemToObject(config_file, "settings_sort", cJSON_CreateBool(G->settings_sort));
cJSON_AddItemToObject(config_file, "settings_exif", cJSON_CreateBool(G->settings_exif));
cJSON_AddItemToObject(config_file, "settings_hide_status_fullscreen", cJSON_CreateBool(G->settings_hide_status_fullscreen));
cJSON_AddItemToObject(config_file, "settings_dont_resize", cJSON_CreateBool(G->settings_dont_resize));
cJSON_AddItemToObject(config_file, "settings_selected_theme", cJSON_CreateNumber(G->settings_selected_theme));
cJSON_AddItemToObject(config_file, "settings_calculate_histograms", cJSON_CreateBool(G->settings_calculate_histograms));
cJSON_AddItemToObject(config_file, "settings_hide_status_with_gui", cJSON_CreateBool(G->settings_hide_status_with_gui));
cJSON_AddItemToObject(config_file, "settings_newfilezoom", cJSON_CreateNumber(G->settings_newfilezoom));
cJSON_AddItemToObject(config_file, "settings_copy_color_format", cJSON_CreateNumber(G->settings_copy_color_format));
cJSON_AddItemToObject(config_file, "settings_copy_color_enclose_type", cJSON_CreateNumber(G->settings_copy_color_enclose_type));
cJSON_AddItemToObject(config_file, "settings_copy_color_include_alpha", cJSON_CreateBool(G->settings_copy_color_include_alpha));
cJSON_AddItemToObject(config_file, "settings_copy_color_normalize_rgb", cJSON_CreateBool(G->settings_copy_color_normalize_rgb));
fprintf(F, cJSON_Print(config_file));
fclose(F);
}
}
static void load_settings() {
char buffer[0x400];
snprintf(buffer, sizeof(buffer), "%s\\config.json", APPDATA_FOLDER);
FILE *F = fopen(buffer, "r");
if (F) {
fseek(F, 0, SEEK_END);
size_t size = ftell(F);
fseek(F, 0, SEEK_SET);
char *data = (char *)malloc(size);
fread(data, 1, size, F);
fclose(F);
cJSON *config_file = cJSON_ParseWithLength(data, size);
cJSON *j_checkboard_color_1 = cJSON_GetObjectItemCaseSensitive(config_file, "checkerboard_color_1");
checkerboard_color_1[0] = cJSON_GetArrayItem(j_checkboard_color_1, 0)->valuedouble;
checkerboard_color_1[1] = cJSON_GetArrayItem(j_checkboard_color_1, 1)->valuedouble;
checkerboard_color_1[2] = cJSON_GetArrayItem(j_checkboard_color_1, 2)->valuedouble;
cJSON *j_checkboard_color_2 = cJSON_GetObjectItemCaseSensitive(config_file, "checkerboard_color_2");
checkerboard_color_2[0] = cJSON_GetArrayItem(j_checkboard_color_2, 0)->valuedouble;
checkerboard_color_2[1] = cJSON_GetArrayItem(j_checkboard_color_2, 1)->valuedouble;
checkerboard_color_2[2] = cJSON_GetArrayItem(j_checkboard_color_2, 2)->valuedouble;
cJSON *j_bg_color = cJSON_GetObjectItemCaseSensitive(config_file, "bg_color");
bg_color[0] = cJSON_GetArrayItem(j_bg_color, 0)->valuedouble;
bg_color[1] = cJSON_GetArrayItem(j_bg_color, 1)->valuedouble;
bg_color[2] = cJSON_GetArrayItem(j_bg_color, 2)->valuedouble;
bg_color[3] = cJSON_GetArrayItem(j_bg_color, 3)->valuedouble;
G->settings_resetpos = cJSON_GetObjectItemCaseSensitive(config_file, "settings_resetpos")->valueint;
G->settings_resetzoom = cJSON_GetObjectItemCaseSensitive(config_file, "settings_resetzoom")->valueint;
G->settings_autoplayGIFs = cJSON_GetObjectItemCaseSensitive(config_file, "settings_autoplayGIFs")->valueint;
G->settings_movementmag = cJSON_GetObjectItemCaseSensitive(config_file, "settings_movementmag")->valuedouble;
G->settings_shiftslowmag = cJSON_GetObjectItemCaseSensitive(config_file, "settings_shiftslowmag")->valuedouble;
G->settings_movementinvert = cJSON_GetObjectItemCaseSensitive(config_file, "settings_movementinvert")->valueint;
G->nearest_filtering = cJSON_GetObjectItemCaseSensitive(config_file, "nearest_filtering")->valueint;
G->pixel_grid = cJSON_GetObjectItemCaseSensitive(config_file, "pixel_grid")->valueint;
G->settings_sort = cJSON_GetObjectItemCaseSensitive(config_file, "settings_sort")->valueint;
G->settings_exif = cJSON_GetObjectItemCaseSensitive(config_file, "settings_exif")->valueint;
G->settings_hide_status_fullscreen = cJSON_GetObjectItemCaseSensitive(config_file, "settings_hide_status_fullscreen")->valueint;
G->settings_dont_resize = cJSON_GetObjectItemCaseSensitive(config_file, "settings_dont_resize")->valueint;
G->settings_selected_theme = cJSON_GetObjectItemCaseSensitive(config_file, "settings_selected_theme")->valueint;
G->settings_calculate_histograms = cJSON_GetObjectItemCaseSensitive(config_file, "settings_calculate_histograms")->valueint;
G->settings_hide_status_with_gui = cJSON_GetObjectItemCaseSensitive(config_file, "settings_hide_status_with_gui")->valueint;
G->settings_newfilezoom = cJSON_GetObjectItemCaseSensitive(config_file, "settings_newfilezoom")->valueint;
G->settings_copy_color_format = cJSON_GetObjectItemCaseSensitive(config_file, "settings_copy_color_format")->valueint;
G->settings_copy_color_enclose_type = cJSON_GetObjectItemCaseSensitive(config_file, "settings_copy_color_enclose_type")->valueint;
G->settings_copy_color_include_alpha = cJSON_GetObjectItemCaseSensitive(config_file, "settings_copy_color_include_alpha")->valueint;
G->settings_copy_color_normalize_rgb = cJSON_GetObjectItemCaseSensitive(config_file, "settings_copy_color_normalize_rgb")->valueint;
fclose(F);
free(data);
}
}
static uint32_t get_ticks() {
static LARGE_INTEGER frequency;
static bool n = QueryPerformanceFrequency(&frequency);
LARGE_INTEGER result;
QueryPerformanceCounter(&result);
return 1000 * result.QuadPart / frequency.QuadPart;
}
static void center_window() {
v2 display_size = v2(GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
RECT rect;
GetClientRect (hwnd, &rect);
int w = rect.right - rect.left;
int h = rect.bottom - rect.top;
int x = (display_size.x - w) / 2;
int y = (display_size.y - h) / 2;
SetWindowPos(hwnd, NULL, x, y, w, h, SWP_NOZORDER | SWP_NOACTIVATE);
}
bool get_font_file_from_system(char* output, int output_size, char* font)
{
HKEY hkey;
CHAR value[2048];
DWORD value_length = sizeof(value);
const CHAR* sub_key = "Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts";
CHAR windows_dir[MAX_PATH];
bool windows_path_found = false;
bool result = false;
if (GetWindowsDirectoryA(windows_dir, MAX_PATH))
windows_path_found = true;
if (windows_path_found && RegOpenKeyExA(HKEY_LOCAL_MACHINE, sub_key, 0, KEY_READ, &hkey) == ERROR_SUCCESS)
{
if (RegQueryValueExA(hkey, font, NULL, NULL, (LPBYTE)value, &value_length) == ERROR_SUCCESS)
{
snprintf(output, output_size, "%s\\Fonts\\%.*s", windows_dir, value_length, value);
result = true;
}
RegCloseKey(hkey);
}
return result;
}
static void init_all() {
WW = 700;
WH = 800;
HINSTANCE hInstance = GetModuleHandle(NULL);
const char* szTitle = "CactusViewer";
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS ;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hbrBackground = NULL;
wcex.lpszMenuName = nullptr;
wcex.lpszClassName = L"CactusViewer" ;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(1));
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(1));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
RegisterClassEx(&wcex);
RECT rc { 0, 0, WW, WH };
AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, 0);
hwnd = CreateWindowEx(WS_EX_APPWINDOW, L"CactusViewer", L"CactusViewer", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, nullptr, nullptr, hInstance, nullptr);
hdc = GetDC(hwnd);
center_window();
PIXELFORMATDESCRIPTOR pfd;
ZeroMemory(&pfd, sizeof(PIXELFORMATDESCRIPTOR));
pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 24;
pfd.cStencilBits = 8;
SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE);
Gdiplus::GdiplusStartupInput gdipsi;
ULONG_PTR gdipt;
Gdiplus::GdiplusStartup(&gdipt, &gdipsi, NULL);
init_d3d11(hwnd, WW, WH);
init_logo_image();
bg_color[0] = 0.15;
bg_color[1] = 0.15;
bg_color[2] = 0.15;
bg_color[3] = 0;
float c1 = 0.16;
float c2 = 0.1;
checkerboard_color_1[0] = c1;
checkerboard_color_1[1] = c1;
checkerboard_color_1[2] = c1;
checkerboard_color_2[0] = c2;
checkerboard_color_2[1] = c2;
checkerboard_color_2[2] = c2;
Checkerboard_size = 250;
RGBAflags[0] = 1;
RGBAflags[1] = 1;
RGBAflags[2] = 1;
RGBAflags[3] = 1;
G->alert.timer = 0;
G->settings_autoplayGIFs = true;
G->settings_movementmag = 2;
G->settings_shiftslowmag = 9;
G->hue = 0;
G->saturation = 1;
G->contrast = 1;
G->brightness = 0;
G->gamma = 1;
G->do_blur = false;
G->blur_lod = 1;
G->blur_samples = 32;
G->blur_scale = 0.001;
G->graphics.main_image.has_exif = false;
G->graphics.main_image.orientation = 0;
load_settings();
// BOOL USE_DARK_MODE = G->settings_selected_theme != UI_Theme_Light;
// BOOL SET_IMMERSIVE_DARK_MODE_SUCCESS = SUCCEEDED(DwmSetWindowAttribute(
// hwnd, DWMWINDOWATTRIBUTE::DWMWA_USE_IMMERSIVE_DARK_MODE,
// &USE_DARK_MODE, sizeof(USE_DARK_MODE)));
DragAcceptFiles(hwnd, TRUE);
ShowWindow(hwnd, SW_SHOW);
UpdateWindow(hwnd);
SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)wcex.hIcon);
SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)wcex.hIcon);
G->hcursor[(int)Cursor_Type_arrow] = LoadCursor(nullptr, IDC_ARROW);
G->hcursor[(int)Cursor_Type_text] = LoadCursor(nullptr, IDC_IBEAM);
G->hcursor[(int)Cursor_Type_resize_h] = LoadCursor(nullptr, IDC_SIZEWE);
G->hcursor[(int)Cursor_Type_resize_v] = LoadCursor(nullptr, IDC_SIZENS);
G->hcursor[(int)Cursor_Type_resize_dr] = LoadCursor(nullptr, IDC_SIZENWSE);
G->hcursor[(int)Cursor_Type_resize_dl] = LoadCursor(nullptr, IDC_SIZENESW);
G->graphics.main_image.texture.d3d_texture = 0;
InitializeCriticalSection(&G->mutex);
InitializeCriticalSection(&G->sort_mutex);
InitializeCriticalSection(&G->id_mutex);
G->ui = UI_init_context();
UI_d3d11_init(G->ui, G->graphics.device, G->graphics.device_ctx);
UI_init_platform_win32(G->ui);
int sizes[] = { 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20 };
int ascii_start = 32;
int ascii_end = 126;
//#if DEBUG_MODE
// G->ui_font = UI_load_font_file(G->ui, "../src/FiraSans-Regular.ttf",
// ascii_start, ascii_end, sizes, array_size(sizes));
//#else
// u8 font_file[] = {
// #include "FiraSans-Regular.ttf.cpp"
// };
// G->ui_font = UI_load_font_memory(G->ui, font_file, array_size(font_file),
// ascii_start, ascii_end, sizes, array_size(sizes));
// #endif
// just getting the font from the system now:
char system_font[512] = {};
if (!get_font_file_from_system(system_font, 512, "Segoe UI (TrueType)"))
get_font_file_from_system(system_font, 512, "Arial (TrueType)");
G->ui_font = UI_load_font_file(G->ui, system_font,
ascii_start, ascii_end, sizes, array_size(sizes));
// G->shapes_texture_id = UI_create_texture(G->ui,
// (u8*)UI_asset_shape_arrow,
// UI_ASSET_SHAPE_ARROW_WIDTH,
// UI_ASSET_SHAPE_ARROW_HEIGHT);
// CreateThread(NULL, 0, FontLoadThread, NULL, 0, NULL);
G->force_loop_frames = 2;
G->loader_event = CreateEvent(
NULL, // default security attributes
TRUE, // manual-reset event; false = auto-reset
FALSE, // initial state is nonsignaled
TEXT("loader event")
);
}
static void push_alert(char *string, Alert_Type type = Alert_Error) {
int l = strlen(string) + 1;
memcpy(G->alert.string, string, min(l, 256));
G->alert.timer = 1;
G->alert.type = type;
G->force_loop_frames += 310;
#if DEBUG_MODE
printf("%s\n",string);
#endif
};
struct Loader_Thread_Inputs {
wchar_t *path;
u32 id;
File_Data* file_data;
bool dropped;
};
static void reset_to_no_folder() {
if (G->loading_dropped_file)
G->loading_dropped_file = false;
G->files.reset_count();
}
static void set_to_no_file() {
G->graphics.main_image.w = 50;
G->graphics.main_image.h = 53;
G->req_truescale = 4;
G->position.x = 0;
G->position.y = 0;
send_signal(G->signals.update_truescale);
}
void calculate_histogram(unsigned char* data, u64 size) {
G->graphics.main_image.has_histo = false;
if (!G->settings_calculate_histograms) return;
assert(size % 4 == 0);
memset(G->histo_r, 0, 256 * sizeof(u64));
memset(G->histo_g, 0, 256 * sizeof(u64));
memset(G->histo_b, 0, 256 * sizeof(u64));
memset(G->histo_t, 0, 256 * sizeof(u64));
G->histo_max = 0;
for (int i = 0; i < size - 4; i+=4) {
G->histo_r[data[i + 0]]++; G->histo_t[data[i + 0]]++;
G->histo_g[data[i + 1]]++; G->histo_t[data[i + 1]]++;
G->histo_b[data[i + 2]]++; G->histo_t[data[i + 2]]++;
}
for (int i = 0; i < 256; i++) {
G->histo_max = max(G->histo_max, G->histo_t[i]);
}
G->histo_max_edit = G->histo_max;
G->graphics.main_image.has_histo = true;
}
static int load_image_pre(wchar_t *path, u32 id, bool dropped) {
int w, h, n;
int result = 0;
G->files[id].loading = true;
int size = stbi_convert_wchar_to_utf8(0, 0, path);
char *filename_utf8 = (char *)malloc(size);
stbi_convert_wchar_to_utf8(filename_utf8, size, path);
unsigned char *data = stbi_load(filename_utf8, &w, &h, &n, 4);
G->files[id].loading = false;
if (data == nullptr) {
push_alert("Loading the file failed");
G->files[G->current_file_index].failed = true;
G->loaded = true;
//if (dropped)
// reset_to_no_folder();
set_to_no_file();
} else {
if (G->graphics.MAX_GPU < w || G->graphics.MAX_GPU < h) {
push_alert("Image is too large.");
}
else {
EnterCriticalSection(&G->mutex);
if (id == G->current_file_index) {
G->graphics.main_image.w = w;
G->graphics.main_image.h = h;
G->graphics.main_image.n = n;
if (G->graphics.main_image.data) {
wfree(G->graphics.main_image.data);
G->graphics.main_image.data = 0;
}
G->graphics.main_image.data = data;
send_signal(G->signals.init_step_2);
}
else {
free(data);
}
LeaveCriticalSection(&G->mutex);
result = 1;
}
}
return result;
}
static int load_image_wic_pre(wchar_t *path, u32 id, bool dropped, File_Data* file_data) {
u32 w, h;
int result = 0;
G->files[id].loading = true;
IWICBitmapDecoder* decoder = NULL;
IWICBitmapFrameDecode* frame = NULL;
IWICFormatConverter* converter = NULL;
// Initialize the COM library
CoInitialize(NULL);
// Create WIC factory
err(CoCreateInstance(CLSID_WICImagingFactory,
NULL,
CLSCTX_INPROC_SERVER,
IID_IWICImagingFactory,
(LPVOID*) & G->wic_factory));
HRESULT hr = G->wic_factory->CreateDecoderFromFilename(path,
NULL,
GENERIC_READ,
WICDecodeMetadataCacheOnDemand,
&decoder);
if(SUCCEEDED(hr))
hr = decoder->GetFrame(0, &frame);
if(SUCCEEDED(hr))
hr =G->wic_factory->CreateFormatConverter(&converter);
if(SUCCEEDED(hr))
hr = converter->Initialize(frame,
GUID_WICPixelFormat32bppRGBA,
WICBitmapDitherTypeNone,
NULL,
0.0,
WICBitmapPaletteTypeCustom);
unsigned char *data = 0;
if (SUCCEEDED(hr)) {
converter->GetSize(&w, &h);
data = (unsigned char *)walloc(w * h * 4);
converter->CopyPixels(NULL, w * 4, w * h * 4, data);
// expensive, but requested:
if (G->settings_exif) {
FILE* temp_file = _wfopen(path, L"rb");
if (temp_file) {
fseek(temp_file, 0, SEEK_END);
size_t file_size = ftell(temp_file);
fseek(temp_file, 0, SEEK_SET);
uint8_t* file_data = (uint8_t*) malloc(file_size);
fread(file_data, 1, file_size, temp_file);
fclose(temp_file);
int exif_result = G->graphics.main_image.exif_info.parseFrom(file_data, file_size);
free(file_data);
G->graphics.main_image.has_exif = exif_result == PARSE_EXIF_SUCCESS;
if (G->graphics.main_image.has_exif) {
switch (G->graphics.main_image.exif_info.Orientation) {
case 3:
G->graphics.main_image.orientation = 2; break;
case 6:
G->graphics.main_image.orientation = 3; break;
case 8:
G->graphics.main_image.orientation = 1; break;
}
send_signal(G->signals.update_orientation_step_2);
}
}
}
}
G->files[id].loading = false;
if (FAILED(hr) || data == 0) {
if (hr == WINCODEC_ERR_COMPONENTNOTFOUND) {
push_alert(UI_sprintf(&G->ui->strings, "Component not found: File type '%s' not supported.", UI_sprintf(&G->ui->strings, "%S", file_data->file.ext)));
} else if (hr == WINCODEC_ERR_COMPONENTINITIALIZEFAILURE) {
push_alert(UI_sprintf(&G->ui->strings, "Component initialization failed: Codec of '%s' is likely not installed.", UI_sprintf(&G->ui->strings, "%S", file_data->file.ext)));
} else {
LPVOID lpMsgBuf;
DWORD bufLen = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
hr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR) & lpMsgBuf,
0, NULL);
push_alert((char*)lpMsgBuf);
LocalFree(lpMsgBuf);
}
G->files[G->current_file_index].failed = true;
G->loaded = true;
//if (dropped)
//reset_to_no_folder();
set_to_no_file();
} else {
if (G->graphics.MAX_GPU < w || G->graphics.MAX_GPU < h) {
push_alert("Image is too large.");
} else {
EnterCriticalSection(&G->mutex);
if (id == G->current_file_index) {
G->graphics.main_image.w = w;
G->graphics.main_image.h = h;
G->graphics.main_image.n = 0;
// if (G->graphics.main_image.data) {
// wfree(G->graphics.main_image.data);
// G->graphics.main_image.data = 0;
// }
G->graphics.main_image.data = data;
calculate_histogram(data, w * h * 4);
send_signal(G->signals.init_step_2);
} else {
wfree(data);
}
LeaveCriticalSection(&G->mutex);
result = 1;
}
}
cleanup:
if (frame) frame->Release();
if (decoder) decoder->Release();
if (converter) converter->Release();
CoUninitialize();
return result;
}
static void unload_anim_image() {
G->anim_frames = 0;
free(G->anim_buffer);
G->anim_buffer = nullptr;
free(G->anim_frame_delays);
G->anim_frame_delays = nullptr;
}
static int load_webp_pre(wchar_t *path, u32 id, bool dropped, int* type) {
int w, h;
int result = 0;
int size = stbi_convert_wchar_to_utf8(0, 0, path);
char *filename_utf8 = (char *)malloc(size);