forked from Aali132/ff7_opengl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.c
2133 lines (1725 loc) · 67.1 KB
/
common.c
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
/*
* ff7_opengl - Complete OpenGL replacement of the Direct3D renderer used in
* the original ports of Final Fantasy VII and Final Fantasy VIII for the PC.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* common.c - common code shared between both games
*/
#include <windows.h>
#include <psapi.h>
#include <stdio.h>
#include <gl/glew.h>
#include <gl/wglew.h>
#include <sys/timeb.h>
#include "types.h"
#include "log.h"
#include "crashdump.h"
#include "macro.h"
#include "common.h"
#include "ff7.h"
#include "ff8.h"
#include "patch.h"
#include "gl.h"
#include "movies.h"
#include "music.h"
#include "saveload.h"
#include "matrix.h"
// global FF7/FF8 flag, available after version check
bool ff8 = false;
// window dimensions requested by the game, normally 640x480
uint width;
uint height;
// offset from screen edge to start of content, for aspect correction
uint x_offset = 0;
uint y_offset = 0;
// output size after aspect correction
uint output_size_x;
uint output_size_y;
// global indirect rendering flag, false if we are rendering directly to the
// output window
bool indirect_rendering = false;
// device context & window handles
HDC hDC = 0;
HWND hwnd = 0;
// game-specific data, see ff7_data.h/ff8_data.h
uint text_colors[NUM_TEXTCOLORS];
unsigned char font_map[256];
struct game_mode modes[64];
uint num_modes;
// memory locations, replaced functions or patching offsets
// some addresses in FF7 are sourced from static tables in the
// externals_102_xx.h files but most of them are computed at runtime,
// see ff7_data.h/ff8_data.h
struct common_externals common_externals;
struct ff7_externals ff7_externals;
struct ff8_externals ff8_externals;
// various statistics, collected for display purposes only EXCEPT for the
// external cache size
struct driver_stats stats;
// on-screen popup messages
char popup_msg[1024];
uint popup_ttl = 0;
uint popup_color;
// scene stack used to save render state when the game calls begin/end scene
struct driver_state scene_stack[8];
uint scene_stack_pointer = 0;
// global frame counter
uint frame_counter = 0;
// default 32-bit BGRA texture format presented to the game
struct texture_format *texture_format;
// install directory for the current game
char basedir[BASEDIR_LENGTH];
// global data used for profiling macros, see compile_cfg.h for more info
#ifdef PROFILE
time_t profile_start;
time_t profile_end;
time_t profile_total;
#endif PROFILE
// support code for the HEAP_DEBUG option, see compile_cfg.h for more info
#ifdef HEAP_DEBUG
uint allocs = 0;
void *driver_malloc(uint size)
{
void *tmp = malloc(size);
trace("%i: malloc(%i) = 0x%x\n", ++allocs, size, tmp);
return tmp;
}
void *driver_calloc(uint size, uint num)
{
void *tmp = calloc(size, num);
trace("%i: calloc(%i, %i) = 0x%x\n", ++allocs, size, num, tmp);
return tmp;
}
void driver_free(void *ptr)
{
if(!ptr) return;
trace("%i: free(0x%x)\n", --allocs, ptr);
free(ptr);
}
void *driver_realloc(void *ptr, uint size)
{
void *tmp = realloc(ptr, size);
trace("%i: realloc(0x%x, %i) = 0x%x\n", allocs, ptr, size, tmp);
return tmp;
}
#endif
// support code for the NO_EXT_HEAP option, see compile_cfg.h for more info
#ifdef NO_EXT_HEAP
void ext_free(void *ptr, const char *file, uint line)
{
driver_free(ptr);
}
void *ext_malloc(uint size, const char *file, uint line)
{
return driver_malloc(size);
}
void *ext_calloc(uint size, uint num, const char *file, uint line)
{
return driver_calloc(size, num);
}
#endif
// figure out which game module is currently running by looking at the game's
// own mode variable and the address of the current main function
struct game_mode *getmode()
{
static uint last_mode = 0;
VOBJ(game_obj, game_object, common_externals.get_game_object());
uint i;
// find exact match, mode and main loop both match
for(i = 0; i < num_modes; i++)
{
struct game_mode *m = &modes[i];
if(m->main_loop == (uint)VREF(game_object, main_obj_A0C).main_loop && m->mode == *common_externals._mode)
{
if(last_mode != m->mode)
{
if(m->trace) trace("%s\n", m->name);
last_mode = m->mode;
}
return m;
}
}
// if there is no exact match, try to find a match by main loop only
for(i = 0; i < num_modes; i++)
{
struct game_mode *m = &modes[i];
if(m->main_loop && m->main_loop == (uint)VREF(game_object, main_obj_A0C).main_loop)
{
if(last_mode != m->mode)
{
#ifndef RELEASE
if(m->mode != *common_externals._mode && m->trace)
{
uint j;
struct game_mode *_m;
for(j = 0; j < num_modes - 1; j++)
{
_m = &modes[j];
if(_m->mode == *common_externals._mode) break;
}
trace("mismatched mode, %s -> %s\n", _m->name, m->name);
}
#endif
if(m->trace) trace("%s\n", m->name);
last_mode = m->mode;
}
return m;
}
}
// finally, ignore main loop and try to match by mode only
for(i = 0; i < num_modes; i++)
{
struct game_mode *m = &modes[i];
if(m->mode == *common_externals._mode)
{
if(last_mode != m->mode)
{
if(m->trace) trace("%s\n", m->name);
last_mode = m->mode;
}
return m;
}
}
if(*common_externals._mode != last_mode)
{
unexpected("unknown mode (%i, 0x%x)\n", *common_externals._mode, (uint)VREF(game_object, main_obj_A0C).main_loop);
last_mode = *common_externals._mode;
}
if(!ff8) return &modes[4];
else return &modes[11];
}
// game mode usually doesn't change in the middle of a frame and even if it
// does we usually don't care until the next frame so we can safely cache it to
// avoid constant lookups
struct game_mode *getmode_cached()
{
static uint last_frame = -1;
static struct game_mode *last_mode;
if(frame_counter != last_frame)
{
last_mode = getmode();
last_frame = frame_counter;
}
return last_mode;
}
// called by the game before rendering starts, after the driver object has been
// created, we use this opportunity to initialize our default OpenGL render
// state
bool common_init(struct game_obj *game_object)
{
if(trace_all) trace("dll_gfx: init\n");
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glDepthFunc(GL_LEQUAL);
glFrontFace(GL_CW);
glEnable(GL_BLEND);
glEnable(GL_TEXTURE_2D);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
if(use_mipmaps) glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
#ifdef SINGLE_STEP
glDrawBuffer(GL_FRONT);
#endif
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, (double)width, (double)height, 0.0, 1.0, -1.0);
gl_set_blend_func(BLEND_NONE);
texture_format = common_externals.create_texture_format();
common_externals.make_pixelformat(32, 0xFF0000, 0xFF00, 0xFF, 0xFF000000, texture_format);
common_externals.add_texture_format(texture_format, game_object);
if(indirect_rendering) gl_prepare_render();
else glViewport(x_offset, y_offset, output_size_x, output_size_y);
return true;
}
// called by the game just before it exits, we need to make sure the game
// doesn't crash after we're gone
void common_cleanup(struct game_obj *game_object)
{
if(trace_all) trace("dll_gfx: cleanup\n");
if(!ff8) ff7_release_movie_objects();
unreplace_functions();
if(strlen(music_plugin) > 0) stop_midi();
}
// unused and unnecessary
bool common_lock(uint surface)
{
if(trace_all) trace("dll_gfx: lock %i\n", surface);
return true;
}
// unused and unnecessary
bool common_unlock(uint surface)
{
if(trace_all) trace("dll_gfx: unlock %i\n", surface);
return true;
}
// called by the game at the end of each frame to swap the front and back
// buffers
void common_flip(struct game_obj *game_object)
{
VOBJ(game_obj, game_object, game_object);
static time_t last_gametime;
static struct timeb last_frame;
static uint fps_counters[3] = {0, 0, 0};
time_t last_seconds = last_frame.time;
struct game_mode *mode = getmode();
if(trace_all) trace("dll_gfx: flip (%i)\n", frame_counter);
// draw any z-sorted content now that we're done drawing everything else
gl_draw_deferred();
if(show_stats)
{
PROCESS_MEMORY_COUNTERS_EX pmc;
SIZE_T ram_size;
pmc.cb = sizeof(pmc);
GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS *)&pmc, sizeof(pmc));
ram_size = pmc.WorkingSetSize;
gl_draw_text(8, 8, text_colors[TEXTCOLOR_PINK], 255,
#ifdef HEAP_DEBUG
"Allocations: %u\n"
#endif
#ifdef PROFILE
"Profiling: %I64u us\n"
#endif
"RAM usage: %uMB\n"
"textures: %u\n"
"external textures: %u\n"
"ext. cache size: %uMB\n"
"texture reloads: %u\n"
"palette writes: %u\n"
"palette changes: %u\n"
"zsort layers: %u\n"
"vertices: %u\n"
"timer: %I64u\n",
#ifdef HEAP_DEBUG
allocs,
#endif
#ifdef PROFILE
(time_t)((profile_total * 1000000.0) / VREF(game_object, countspersecond)),
#endif
ram_size / (1024 * 1024),
stats.texture_count,
stats.external_textures,
stats.ext_cache_size / (1024 * 1024),
stats.texture_reloads,
stats.palette_writes,
stats.palette_changes,
stats.deferred,
stats.vertex_count,
stats.timer
);
}
if(show_fps)
{
// average last two seconds and round up for our FPS counter
gl_draw_text(width - (2 * 16 + 8), 8, text_colors[TEXTCOLOR_YELLOW], 255, "%2i", (fps_counters[1] + fps_counters[2] + 1) / 2);
fps_counters[0]++;
ftime(&last_frame);
if(last_seconds != last_frame.time)
{
fps_counters[2] = fps_counters[1];
fps_counters[1] = fps_counters[0];
fps_counters[0] = 0;
}
}
// if there is an active popup message, display it
if(popup_ttl > 0)
{
if(gl_draw_text(8, height - (8 + 24 * 3), popup_color, (popup_ttl * 255) / POPUP_TTL_MAX, popup_msg))
{
uint diff = (POPUP_TTL_MAX - popup_ttl) / 10;
if(diff == 0) popup_ttl--;
else if(diff > popup_ttl) popup_ttl = 0;
else popup_ttl -= diff;
}
}
#ifdef PRERELEASE
gl_draw_text(8, height - 32, text_colors[TEXTCOLOR_RED], 255, PRERELEASE_WARNING);
#endif
// reset per-frame stats
stats.texture_reloads = 0;
stats.palette_writes = 0;
stats.palette_changes = 0;
stats.vertex_count = 0;
stats.deferred = 0;
if(indirect_rendering) gl_prepare_flip();
#ifndef SINGLE_STEP
if(!SwapBuffers(hDC))
{
error("SwapBuffers failed: ");
windows_error(0);
}
#endif
// new framelimiter, not based on vsync
if(!ff8 && use_new_timer)
{
time_t gametime;
double framerate = mode->framerate;
if(framerate == 0.0) framerate = 60.0;
do qpc_get_time(&gametime); while(gametime > last_gametime && gametime - last_gametime < VREF(game_object, countspersecond * (1.0 / framerate)));
last_gametime = gametime;
}
if(!fullscreen) ShowCursor(true);
// fix unresponsive quit menu
if(!ff8 && VREF(game_object, field_A54))
{
MSG msg;
if(PeekMessageA(&msg, 0, 0, 0, 1))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
if(indirect_rendering) gl_prepare_render();
frame_counter++;
// check for gl errors once per frame
gl_error();
// FF8 does not clear the screen properly in the card game module
if(ff8 && mode->driver_mode == MODE_CARDGAME) common_clear_all(0);
}
// called by the game to clear an aspect of the back buffer, mostly called from
// clear_all below
void common_clear(bool clear_color, bool clear_depth, bool unknown, struct game_obj *game_object)
{
uint mode = getmode()->driver_mode;
GLbitfield mask = 0;
if(trace_all) trace("dll_gfx: clear %i %i %i\n", clear_color, clear_depth, unknown);
glPushAttrib(GL_DEPTH_BUFFER_BIT | GL_SCISSOR_BIT);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glDisable(GL_SCISSOR_TEST);
if(mode == MODE_MENU) mask |= GL_COLOR_BUFFER_BIT;
if(clear_color || mode == MODE_MENU) mask |= GL_COLOR_BUFFER_BIT;
if(clear_depth) mask |= GL_DEPTH_BUFFER_BIT;
glClear(mask);
#ifdef SINGLE_STEP
glFinish();
#endif
glPopAttrib();
}
// called by the game to clear the entire back buffer
void common_clear_all(struct game_obj *game_object)
{
if(trace_all) trace("dll_gfx: clear_all\n");
common_clear(true, true, true, game_object);
}
// called by the game to setup a viewport inside the game window, allowing it
// to clip drawing to the requested area
void common_setviewport(uint _x, uint _y, uint _w, uint _h, struct game_obj *game_object)
{
uint mode = getmode()->driver_mode;
if(trace_all) trace("dll_gfx: setviewport %i %i %i %i\n", _x, _y, _w, _h);
current_state.viewport[0] = _x;
current_state.viewport[1] = _y;
current_state.viewport[2] = _w;
current_state.viewport[3] = _h;
if(indirect_rendering) glScissor(INT_COORD_X(_x), internal_size_y - INT_COORD_Y(_y + _h), INT_COORD_X(_w), INT_COORD_Y(_h));
else glScissor(INT_COORD_X(_x) + x_offset, window_size_y - INT_COORD_Y(_y + _h), INT_COORD_X(_w), INT_COORD_Y(_h));
// emulate the transformation applied by an equivalent Direct3D viewport
d3dviewport_matrix._11 = (float)_w / (float)width;
// no idea why this is necessary
if(!ff8 && mode == MODE_BATTLE) d3dviewport_matrix._22 = 1.0f;
else d3dviewport_matrix._22 = (float)_h / (float)height;
d3dviewport_matrix._41 = (((float)_x + (float)_w / 2.0f) - (float)width / 2.0f) / ((float)width / 2.0f);
d3dviewport_matrix._42 = -(((float)_y + (float)_h / 2.0f) - (float)height / 2.0f) / ((float)height / 2.0f);
}
// called by the game to set the background color which the back buffer will be
// cleared to
void common_setbg(struct bgra_color *color, struct game_obj *game_object)
{
if(trace_all) trace("dll_gfx: setbg\n");
glClearColor(color->r, color->g, color->b, 0.0f);
}
// called by the game to initialize a polygon_set structure
// we don't really need to do anything special here
bool common_prepare_polygon_set(struct polygon_set *polygon_set)
{
VOBJ(polygon_set, polygon_set, polygon_set);
if(VPTR(polygon_set)) VRASS(polygon_set, indexed_primitives, external_calloc(VREF(polygon_set, numgroups), 4));
return true;
}
// called by the game to load a group from a .p file into a renderable format
bool common_load_group(uint group_num, struct matrix_set *matrix_set, struct p_hundred *hundred_data, struct p_group *group_data, struct polygon_data *polygon_data, struct polygon_set *polygon_set, struct game_obj *game_object)
{
if(!ff8) return ff7gl_load_group(group_num, matrix_set, hundred_data, group_data, polygon_data, (struct ff7_polygon_set *)polygon_set, (struct ff7_game_obj *)game_object);
else return common_externals.generic_load_group(group_num, matrix_set, hundred_data, group_data, polygon_data, polygon_set, game_object);
}
// called by the game to update one of the matrices in a matrix_set structure
void common_setmatrix(uint unknown, struct matrix *matrix, struct matrix_set *matrix_set, struct game_obj *game_object)
{
if(trace_all) trace("dll_gfx: setmatrix\n");
switch(unknown)
{
case 0:
if(!matrix_set->matrix_world) matrix_set->matrix_world = matrix;
else memcpy(matrix_set->matrix_world, matrix, sizeof(*matrix));
break;
case 1:
if(!matrix_set->matrix_view) matrix_set->matrix_view = matrix;
else memcpy(matrix_set->matrix_view, matrix, sizeof(*matrix));
break;
case 2:
if(!matrix_set->matrix_projection) matrix_set->matrix_projection = matrix;
else memcpy(matrix_set->matrix_projection, matrix, sizeof(*matrix));
break;
}
}
// called by the game to unload a texture
void common_unload_texture(struct texture_set *texture_set)
{
uint i;
VOBJ(texture_set, texture_set, texture_set);
if(trace_all) trace("dll_gfx: unload_texture 0x%x\n", VPTR(texture_set));
if(!VPTR(texture_set)) return;
if(!VREF(texture_set, texturehandle)) return;
if(!VREF(texture_set, ogl.gl_set)) return;
// do not delete modpath textures directly
if(!VREF(texture_set, ogl.external)) glDeleteTextures(VREF(texture_set, ogl.gl_set->textures), VREF(texture_set, texturehandle));
// remove modpath cache reference
ext_cache_release(VPTR(texture_set));
driver_free(VREF(texture_set, texturehandle));
driver_free(VREF(texture_set, ogl.gl_set));
VRASS(texture_set, texturehandle, 0);
VRASS(texture_set, ogl.gl_set, 0);
stats.texture_count--;
if(VREF(texture_set, ogl.external)) stats.external_textures--;
// remove any other references to this texture
gl_check_deferred(VPTR(texture_set));
for(i = 0; i < scene_stack_pointer; i++)
{
if(scene_stack[i].texture_set == VPTR(texture_set)) scene_stack[i].texture_set = 0;
}
if(current_state.texture_set == VPTR(texture_set)) current_state.texture_set = 0;
if(ff8) ff8_unload_texture(VPTR(texture_set));
}
// create a texture from an area of the framebuffer, source rectangle is encoded into tex header
// with our fictional version FB_TEXT_VERSION
// return true to short-circuit texture loader
bool load_framebuffer_texture(struct texture_set *texture_set, struct tex_header *tex_header)
{
VOBJ(texture_set, texture_set, texture_set);
VOBJ(tex_header, tex_header, tex_header);
GLuint texture;
if(VREF(tex_header, version) != FB_TEX_VERSION) return false;
if(trace_all) trace("load_framebuffer_texture: 0x%x\n", VPTR(texture_set));
glPushAttrib(GL_TEXTURE_BIT);
texture = gl_create_empty_texture();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
if(!indirect_rendering) glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, VREF(tex_header, fb_tex.x) + x_offset, VREF(tex_header, fb_tex.y) + y_offset, VREF(tex_header, fb_tex.w), VREF(tex_header, fb_tex.h), 0);
else glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, VREF(tex_header, fb_tex.x), VREF(tex_header, fb_tex.y), VREF(tex_header, fb_tex.w), VREF(tex_header, fb_tex.h), 0);
VRASS(texture_set, texturehandle[0], texture);
glPopAttrib();
return true;
}
// load modpath texture for tex file, returns true if successful
bool load_external_texture(struct texture_set *texture_set, struct tex_header *tex_header)
{
VOBJ(texture_set, texture_set, texture_set);
VOBJ(tex_header, tex_header, tex_header);
uint texture = 0;
struct gl_texture_set *gl_set = VREF(texture_set, ogl.gl_set);
if(save_textures) return false;
if((uint)VREF(tex_header, file.pc_name) > 32)
{
bool use_compression = true;
if(trace_loaders) trace("texture file name: %s\n", VREF(tex_header, file.pc_name));
if(!_strnicmp(VREF(tex_header, file.pc_name), "field", strlen("field") - 1)) use_compression = false;
texture = load_texture(VREF(tex_header, file.pc_name), VREF(tex_header, palette_index), VREFP(texture_set, ogl.width), VREFP(texture_set, ogl.height), use_compression);
if(!_strnicmp(VREF(tex_header, file.pc_name), "world", strlen("world") - 1)) gl_set->force_filter = true;
if(!_strnicmp(VREF(tex_header, file.pc_name), "menu/usfont", strlen("menu/usfont") - 1))
{
gl_set->force_filter = true;
gl_set->force_zsort = true;
}
if(!_strnicmp(VREF(tex_header, file.pc_name), "menu/btl_win", strlen("menu/btl_win") - 1)) gl_set->force_zsort = true;
if(!_strnicmp(VREF(tex_header, file.pc_name), "flevel/hand_1", strlen("flevel/hand_1") - 1)) gl_set->force_filter = true;
}
if(texture)
{
gl_replace_texture(texture_set, VREF(tex_header, palette_index), texture);
if(!VREF(texture_set, ogl.external)) stats.external_textures++;
VRASS(texture_set, ogl.external, true);
return true;
}
return false;
}
// convert a single 8-bit paletted pixel to 32-bit BGRA format
_inline uint pal2bgra(uint pixel, uint *palette, uint palette_offset, uint color_key, uint reference_alpha)
{
if(color_key && pixel == 0) return 0;
else
{
uint color = palette[palette_offset + pixel];
// FF7 uses a form of alpha keying to emulate PSX blending
if(BGRA_A(color) == 0xFE) color = (color & 0xFFFFFF) | reference_alpha;
return color;
}
}
// convert an entire image from its native format to 32-bit BGRA
void convert_image_data(unsigned char *image_data, uint *converted_image_data, uint w, uint h, struct texture_format *tex_format, bool invert_alpha, bool color_key, uint palette_offset, uint reference_alpha)
{
uint i, j, o = 0, c = 0;
// invalid texture in FF8, do not attempt to convert
if(ff8 && tex_format->bytesperpixel == 0) return;
// paletted source data (4-bit palettes are expanded to 8-bit by the game)
if(tex_format->bytesperpixel == 1)
{
if(!tex_format->use_palette)
{
glitch("unsupported texture format\n");
return;
}
for(i = 0; i < w; i++)
{
for(j = 0; j < h; j++)
{
if(image_data[o] > tex_format->palette_size)
{
glitch("texture conversion error\n");
return;
}
converted_image_data[c++] = pal2bgra(image_data[o++], tex_format->palette_data, palette_offset, color_key, reference_alpha);
}
}
}
// RGB(A) source data
else
{
if(tex_format->use_palette)
{
glitch("unsupported texture format\n");
return;
}
for(i = 0; i < w; i++)
{
for(j = 0; j < h; j++)
{
uint pixel = 0;
uint color = 0;
switch(tex_format->bytesperpixel)
{
// 16-bit RGB(A)
case 2:
pixel = *((word *)(&image_data[o]));
break;
// 24-bit RGB
case 3:
pixel = image_data[o] | image_data[o + 1] << 8 | image_data[o + 2] << 16;
break;
// 32-bit RGBA or RGBX
case 4:
pixel = *((uint *)(&image_data[o]));
break;
default:
glitch("unsupported texture format\n");
return;
}
o += tex_format->bytesperpixel;
// PSX style mask bit
if(color_key && (pixel & ~tex_format->alpha_mask) == 0)
{
converted_image_data[c++] = 0;
continue;
}
// convert source data to 8 bits per channel
color = tex_format->blue_max > 0 ? ((((pixel & tex_format->blue_mask) >> tex_format->blue_shift) * 255) / tex_format->blue_max) : 0;
color |= (tex_format->green_max > 0 ? ((((pixel & tex_format->green_mask) >> tex_format->green_shift) * 255) / tex_format->green_max) : 0) << 8;
color |= (tex_format->red_max > 0 ? ((((pixel & tex_format->red_mask) >> tex_format->red_shift) * 255) / tex_format->red_max) : 0) << 16;
// special case to deal with poorly converted PSX images in FF7
if(invert_alpha && pixel != 0x8000) color |= (tex_format->alpha_max > 0 ? (255 - ((((pixel & tex_format->alpha_mask) >> tex_format->alpha_shift) * 255) / tex_format->alpha_max)) : 255) << 24;
else color |= (tex_format->alpha_max > 0 ? ((((pixel & tex_format->alpha_mask) >> tex_format->alpha_shift) * 255) / tex_format->alpha_max) : 255) << 24;
converted_image_data[c++] = color;
}
}
}
}
// called by the game to load a texture
// can be called under a wide variety of circumstances, we must figure out what the game wants
struct texture_set *common_load_texture(struct texture_set *_texture_set, struct tex_header *_tex_header, struct texture_format *texture_format)
{
VOBJ(game_obj, game_object, common_externals.get_game_object());
VOBJ(texture_set, texture_set, _texture_set);
VOBJ(tex_header, tex_header, _tex_header);
struct palette *palette = 0;
bool color_key = false;
struct texture_format *tex_format = VREFP(tex_header, tex_format);
if(trace_all) trace("dll_gfx: load_texture 0x%x\n", _texture_set);
// no existing texture set, create one
if(!VPTR(texture_set)) VASS(texture_set, common_externals.create_texture_set());
// allocate space for our private data
if(!VREF(texture_set, ogl.gl_set)) VRASS(texture_set, ogl.gl_set, driver_calloc(sizeof(struct gl_texture_set), 1));
// texture handle array may not have been initialized
if(!VREF(texture_set, texturehandle))
{
// allocate some more textures just in case, there could be more palettes we don't know about yet
// FF8 likes to change its mind about just how many palettes a texture has
VRASS(texture_set, ogl.gl_set->textures, VREF(tex_header, palettes) > 0 ? VREF(tex_header, palettes) * 2 : 1);
VRASS(texture_set, texturehandle, driver_calloc(VREF(texture_set, ogl.gl_set->textures), sizeof(GLuint)));
if(ff8 && VREF(tex_header, version) != FB_TEX_VERSION)
{
external_free(VREF(tex_header, old_palette_data));
VRASS(tex_header, old_palette_data, 0);
}
stats.texture_count++;
}
// number of palettes has changed, reload the texture completely
if(VREF(texture_set, ogl.gl_set->textures) != VREF(tex_header, palettes) * 2 && !(VREF(tex_header, palettes) == 0 && VREF(texture_set, ogl.gl_set->textures) == 1))
{
common_unload_texture(VPTR(texture_set));
return common_load_texture(VPTR(texture_set), VPTR(tex_header), texture_format);
}
// make sure the information in the texture set is consistent
VRASS(texture_set, tex_header, VPTR(tex_header));
VRASS(texture_set, texture_format, texture_format);
// check if this is suppposed to be a framebuffer texture, we may not have to do anything
if(load_framebuffer_texture(VPTR(texture_set), VPTR(tex_header))) return VPTR(texture_set);
// initialize palette index to a sane value if it hasn't been set
if(VREF(tex_header, palettes) > 0)
{
if(VREF(texture_set, palette_index) == -1)
{
VRASS(tex_header, palette_index, 0);
}
else
{
VRASS(tex_header, palette_index, VREF(texture_set, palette_index));
}
}
else VRASS(tex_header, palette_index, 0);
if(VREF(tex_header, palette_index) >= VREF(texture_set, ogl.gl_set->textures))
{
unexpected("tried to use non-existent palette (%i, %i)\n", VREF(tex_header, palette_index), VREF(texture_set, ogl.gl_set->textures));
VRASS(tex_header, palette_index, 0);
return VPTR(texture_set);
}
// create palette structure if it doesn't exist already
if(VREF(tex_header, palettes) > 1 && VREF(texture_set, palette) == 0) palette = common_externals.create_palette_for_tex(texture_format->bitsperpixel, VPTR(tex_header), VPTR(texture_set));
if(tex_format->palettes == 0) tex_format->palettes = VREF(tex_header, palette_entries);
// convert texture data from source format and load it
if(texture_format != 0 && VREF(tex_header, image_data) != 0)
{
// detect changes in palette data for FF8, we can't trust it to notify us
if(ff8 && VREF(tex_header, palettes) > 0 && VREF(tex_header, version) != FB_TEX_VERSION)
{
if(!VREF(tex_header, old_palette_data))
{
VRASS(tex_header, old_palette_data, external_malloc(4 * tex_format->palette_size));
}
if(memcmp(VREF(tex_header, old_palette_data), tex_format->palette_data, 4 * tex_format->palette_size))
{
glDeleteTextures(VREF(texture_set, ogl.gl_set->textures), VREF(texture_set, texturehandle));
memset(VREF(texture_set, texturehandle), 0, VREF(texture_set, ogl.gl_set->textures) * sizeof(GLuint));
memcpy(VREF(tex_header, old_palette_data), tex_format->palette_data, 4 * tex_format->palette_size);
}
}
// the texture handle for the current palette is missing, convert & load it
if(!VREF(texture_set, texturehandle[VREF(tex_header, palette_index)]))
{
uint c = 0;
uint w = VREF(tex_header, version) == FB_TEX_VERSION ? VREF(tex_header, fb_tex.w) : tex_format->width;
uint h = VREF(tex_header, version) == FB_TEX_VERSION ? VREF(tex_header, fb_tex.h) : tex_format->height;
bool invert_alpha = false;
uint *image_data;
// pre-calculate some useful data for palette conversion
uint palette_offset = VREF(tex_header, palette_index) * VREF(tex_header, palette_entries);
uint reference_alpha = (VREF(tex_header, reference_alpha) & 0xFF) << 24;
// detect 16-bit PSX 5551 format with mask bit
if(tex_format->bitsperpixel == 16 && tex_format->alpha_mask == 0x8000)
{
// correct incomplete texture format in FF7
if(!ff8)
{
tex_format->blue_mask = 0x001F;
tex_format->green_mask = 0x03E0;
tex_format->red_mask = 0x7C00;
tex_format->blue_shift = 0;
tex_format->green_shift = 5;
tex_format->red_shift = 10;
tex_format->blue_max = 31;
tex_format->green_max = 31;
tex_format->red_max = 31;
}
invert_alpha = true;
}
// check if this texture can be loaded from the modpath, we may not have to do any conversion
if(load_external_texture(VPTR(texture_set), VPTR(tex_header))) return VPTR(texture_set);
// allocate PBO
image_data = gl_get_pixel_buffer(w * h * 4);
if(!ff8)
{
// find out if color keying is enabled for this texture
color_key = VREF(tex_header, color_key);
// find out if color keying is enabled for this particular palette
if(VREF(tex_header, use_palette_colorkey)) color_key = VREF(tex_header, palette_colorkey[VREF(tex_header, palette_index)]);
}
// convert source data
convert_image_data(VREF(tex_header, image_data), image_data, w, h, tex_format, invert_alpha, color_key, palette_offset, reference_alpha);
// save texture to modpath if save_textures is enabled
if(save_textures && (uint)VREF(tex_header, file.pc_name) > 32)
{
if(!save_texture(image_data, w, h, VREF(tex_header, palette_index), VREF(tex_header, file.pc_name))) error("save_texture failed\n");
}
// commit PBO and populate texture set
gl_upload_texture(VPTR(texture_set), VREF(tex_header, palette_index), image_data, GL_BGRA);
}
else return VPTR(texture_set);
}
else unexpected("no texture format specified or no source data\n");
return VPTR(texture_set);
}
// called by the game to indicate when a texture has switched to using another palette
bool common_palette_changed(uint unknown1, uint unknown2, uint unknown3, struct palette *palette, struct texture_set *texture_set)
{
VOBJ(texture_set, texture_set, texture_set);
if(trace_all) trace("dll_gfx: palette_changed 0x%x %i\n", texture_set, VREF(texture_set, palette_index));
if(palette == 0 || texture_set == 0) return false;
// texture loader logic handles missing palettes, just make sure the new palette has been loaded
texture_set = common_load_texture(texture_set, VREF(texture_set, tex_header), VREF(texture_set, texture_format));
// re-bind texture set to make sure the new palette is active
gl_bind_texture_set(texture_set);
stats.palette_changes++;
return true;
}
// called by the game to write new color data to a palette