-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathmodel_shared.c
4784 lines (4500 loc) · 195 KB
/
model_shared.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
/*
Copyright (C) 1996-1997 Id Software, Inc.
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// models.c -- model loading and caching
// models are the only shared resource between a client and server running
// on the same machine.
#include "quakedef.h"
#include "image.h"
#include "r_shadow.h"
#include "polygon.h"
cvar_t r_mipskins = {CF_CLIENT | CF_ARCHIVE, "r_mipskins", "0", "mipmaps model skins so they render faster in the distance and do not display noise artifacts, can cause discoloration of skins if they contain undesirable border colors"};
cvar_t r_mipnormalmaps = {CF_CLIENT | CF_ARCHIVE, "r_mipnormalmaps", "1", "mipmaps normalmaps (turning it off looks sharper but may have aliasing)"};
cvar_t mod_generatelightmaps_unitspersample = {CF_CLIENT | CF_ARCHIVE, "mod_generatelightmaps_unitspersample", "8", "lightmap resolution"};
cvar_t mod_generatelightmaps_borderpixels = {CF_CLIENT | CF_ARCHIVE, "mod_generatelightmaps_borderpixels", "2", "extra space around polygons to prevent sampling artifacts"};
cvar_t mod_generatelightmaps_texturesize = {CF_CLIENT | CF_ARCHIVE, "mod_generatelightmaps_texturesize", "1024", "size of lightmap textures"};
cvar_t mod_generatelightmaps_lightmapsamples = {CF_CLIENT | CF_ARCHIVE, "mod_generatelightmaps_lightmapsamples", "16", "number of shadow tests done per lightmap pixel"};
cvar_t mod_generatelightmaps_vertexsamples = {CF_CLIENT | CF_ARCHIVE, "mod_generatelightmaps_vertexsamples", "16", "number of shadow tests done per vertex"};
cvar_t mod_generatelightmaps_gridsamples = {CF_CLIENT | CF_ARCHIVE, "mod_generatelightmaps_gridsamples", "64", "number of shadow tests done per lightgrid cell"};
cvar_t mod_generatelightmaps_lightmapradius = {CF_CLIENT | CF_ARCHIVE, "mod_generatelightmaps_lightmapradius", "16", "sampling area around each lightmap pixel"};
cvar_t mod_generatelightmaps_vertexradius = {CF_CLIENT | CF_ARCHIVE, "mod_generatelightmaps_vertexradius", "16", "sampling area around each vertex"};
cvar_t mod_generatelightmaps_gridradius = {CF_CLIENT | CF_ARCHIVE, "mod_generatelightmaps_gridradius", "64", "sampling area around each lightgrid cell center"};
model_t *loadmodel;
// Supported model formats
static modloader_t loader[] =
{
{"obj", NULL, 0, Mod_OBJ_Load},
{NULL, "IDPO", 4, Mod_IDP0_Load},
{NULL, "IDP2", 4, Mod_IDP2_Load},
{NULL, "IDP3", 4, Mod_IDP3_Load},
{NULL, "IDSP", 4, Mod_IDSP_Load},
{NULL, "IDS2", 4, Mod_IDS2_Load},
{NULL, "\035", 1, Mod_Q1BSP_Load},
{NULL, "\036", 1, Mod_HLBSP_Load},
{NULL, "BSP2", 4, Mod_BSP2_Load},
{NULL, "2PSB", 4, Mod_2PSB_Load},
{NULL, "IBSP", 4, Mod_IBSP_Load},
{NULL, "VBSP", 4, Mod_VBSP_Load},
{NULL, "ZYMOTICMODEL", 13, Mod_ZYMOTICMODEL_Load},
{NULL, "DARKPLACESMODEL", 16, Mod_DARKPLACESMODEL_Load},
{NULL, "PSKMODEL", 9, Mod_PSKMODEL_Load},
{NULL, "INTERQUAKEMODEL", 16, Mod_INTERQUAKEMODEL_Load},
{"map", NULL, 0, Mod_MAP_Load},
{NULL, NULL, 0, NULL}
};
static mempool_t *mod_mempool;
static memexpandablearray_t models;
static mempool_t* q3shaders_mem;
typedef struct q3shader_hash_entry_s
{
shader_t shader;
struct q3shader_hash_entry_s* chain;
} q3shader_hash_entry_t;
#define Q3SHADER_HASH_SIZE 1021
typedef struct q3shader_data_s
{
memexpandablearray_t hash_entries;
q3shader_hash_entry_t hash[Q3SHADER_HASH_SIZE];
memexpandablearray_t char_ptrs;
} q3shader_data_t;
static q3shader_data_t* q3shader_data;
static void mod_start(void)
{
int i, count;
int nummodels = (int)Mem_ExpandableArray_IndexRange(&models);
model_t *mod;
SCR_PushLoadingScreen("Loading models", 1.0);
count = 0;
for (i = 0;i < nummodels;i++)
if ((mod = (model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
if (mod->used)
++count;
for (i = 0;i < nummodels;i++)
if ((mod = (model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
if (mod->used)
{
SCR_PushLoadingScreen(mod->name, 1.0 / count);
Mod_LoadModel(mod, true, false);
SCR_PopLoadingScreen(false);
}
SCR_PopLoadingScreen(false);
}
static void mod_shutdown(void)
{
int i;
int nummodels = (int)Mem_ExpandableArray_IndexRange(&models);
model_t *mod;
for (i = 0;i < nummodels;i++)
if ((mod = (model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && (mod->loaded || mod->mempool))
Mod_UnloadModel(mod);
Mod_FreeQ3Shaders();
Mod_Skeletal_FreeBuffers();
}
static void mod_newmap(void)
{
msurface_t *surface;
int i, j, k, l, surfacenum, ssize, tsize;
int nummodels = (int)Mem_ExpandableArray_IndexRange(&models);
model_t *mod;
for (i = 0;i < nummodels;i++)
{
if ((mod = (model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool)
{
for (j = 0;j < mod->num_textures && mod->data_textures;j++)
{
// note that materialshaderpass and backgroundshaderpass point to shaderpasses[] and so do the pre/post shader ranges, so this catches all of them...
for (l = 0; l < Q3SHADER_MAXLAYERS; l++)
if (mod->data_textures[j].shaderpasses[l])
for (k = 0; k < mod->data_textures[j].shaderpasses[l]->numframes; k++)
R_SkinFrame_MarkUsed(mod->data_textures[j].shaderpasses[l]->skinframes[k]);
}
if (mod->brush.solidskyskinframe)
R_SkinFrame_MarkUsed(mod->brush.solidskyskinframe);
if (mod->brush.alphaskyskinframe)
R_SkinFrame_MarkUsed(mod->brush.alphaskyskinframe);
}
}
if (!cl_stainmaps_clearonload.integer)
return;
for (i = 0;i < nummodels;i++)
{
if ((mod = (model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool && mod->data_surfaces)
{
for (surfacenum = 0, surface = mod->data_surfaces;surfacenum < mod->num_surfaces;surfacenum++, surface++)
{
if (surface->lightmapinfo && surface->lightmapinfo->stainsamples)
{
ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
memset(surface->lightmapinfo->stainsamples, 255, ssize * tsize * 3);
mod->brushq1.lightmapupdateflags[surfacenum] = true;
}
}
}
}
}
/*
===============
Mod_Init
===============
*/
static void Mod_Print_f(cmd_state_t *cmd);
static void Mod_Precache_f(cmd_state_t *cmd);
static void Mod_Decompile_f(cmd_state_t *cmd);
static void Mod_GenerateLightmaps_f(cmd_state_t *cmd);
void Mod_Init (void)
{
mod_mempool = Mem_AllocPool("modelinfo", 0, NULL);
Mem_ExpandableArray_NewArray(&models, mod_mempool, sizeof(model_t), 16);
Mod_BrushInit();
Mod_AliasInit();
Mod_SpriteInit();
Cvar_RegisterVariable(&r_mipskins);
Cvar_RegisterVariable(&r_mipnormalmaps);
Cvar_RegisterVariable(&mod_generatelightmaps_unitspersample);
Cvar_RegisterVariable(&mod_generatelightmaps_borderpixels);
Cvar_RegisterVariable(&mod_generatelightmaps_texturesize);
Cvar_RegisterVariable(&mod_generatelightmaps_lightmapsamples);
Cvar_RegisterVariable(&mod_generatelightmaps_vertexsamples);
Cvar_RegisterVariable(&mod_generatelightmaps_gridsamples);
Cvar_RegisterVariable(&mod_generatelightmaps_lightmapradius);
Cvar_RegisterVariable(&mod_generatelightmaps_vertexradius);
Cvar_RegisterVariable(&mod_generatelightmaps_gridradius);
Cmd_AddCommand(CF_CLIENT, "modellist", Mod_Print_f, "prints a list of loaded models");
Cmd_AddCommand(CF_CLIENT, "modelprecache", Mod_Precache_f, "load a model");
Cmd_AddCommand(CF_CLIENT, "modeldecompile", Mod_Decompile_f, "exports a model in several formats for editing purposes");
Cmd_AddCommand(CF_CLIENT, "mod_generatelightmaps", Mod_GenerateLightmaps_f, "rebuilds lighting on current worldmodel");
}
void Mod_RenderInit(void)
{
R_RegisterModule("Models", mod_start, mod_shutdown, mod_newmap, NULL, NULL);
}
void Mod_UnloadModel (model_t *mod)
{
char name[MAX_QPATH];
qbool used;
model_t *parentmodel;
if (developer_loading.integer)
Con_Printf("unloading model %s\n", mod->name);
dp_strlcpy(name, mod->name, sizeof(name));
parentmodel = mod->brush.parentmodel;
used = mod->used;
if (mod->mempool)
{
if (mod->surfmesh.data_element3i_indexbuffer && !mod->surfmesh.data_element3i_indexbuffer->isdynamic)
R_Mesh_DestroyMeshBuffer(mod->surfmesh.data_element3i_indexbuffer);
mod->surfmesh.data_element3i_indexbuffer = NULL;
if (mod->surfmesh.data_element3s_indexbuffer && !mod->surfmesh.data_element3s_indexbuffer->isdynamic)
R_Mesh_DestroyMeshBuffer(mod->surfmesh.data_element3s_indexbuffer);
mod->surfmesh.data_element3s_indexbuffer = NULL;
if (mod->surfmesh.data_vertex3f_vertexbuffer && !mod->surfmesh.data_vertex3f_vertexbuffer->isdynamic)
R_Mesh_DestroyMeshBuffer(mod->surfmesh.data_vertex3f_vertexbuffer);
mod->surfmesh.data_vertex3f_vertexbuffer = NULL;
mod->surfmesh.data_svector3f_vertexbuffer = NULL;
mod->surfmesh.data_tvector3f_vertexbuffer = NULL;
mod->surfmesh.data_normal3f_vertexbuffer = NULL;
mod->surfmesh.data_texcoordtexture2f_vertexbuffer = NULL;
mod->surfmesh.data_texcoordlightmap2f_vertexbuffer = NULL;
mod->surfmesh.data_lightmapcolor4f_vertexbuffer = NULL;
mod->surfmesh.data_skeletalindex4ub_vertexbuffer = NULL;
mod->surfmesh.data_skeletalweight4ub_vertexbuffer = NULL;
}
// free textures/memory attached to the model
R_FreeTexturePool(&mod->texturepool);
Mem_FreePool(&mod->mempool);
// clear the struct to make it available
memset(mod, 0, sizeof(model_t));
// restore the fields we want to preserve
dp_strlcpy(mod->name, name, sizeof(mod->name));
mod->brush.parentmodel = parentmodel;
mod->used = used;
mod->loaded = false;
}
static void R_Model_Null_Draw(entity_render_t *ent)
{
return;
}
typedef void (*mod_framegroupify_parsegroups_t) (unsigned int i, int start, int len, float fps, qbool loop, const char *name, void *pass);
static int Mod_FrameGroupify_ParseGroups(const char *buf, mod_framegroupify_parsegroups_t cb, void *pass)
{
const char *bufptr;
int start, len;
float fps;
unsigned int i;
qbool loop;
char name[64];
bufptr = buf;
i = 0;
while(bufptr)
{
// an anim scene!
// REQUIRED: fetch start
COM_ParseToken_Simple(&bufptr, true, false, true);
if (!bufptr)
break; // end of file
if (!strcmp(com_token, "\n"))
continue; // empty line
start = atoi(com_token);
// REQUIRED: fetch length
COM_ParseToken_Simple(&bufptr, true, false, true);
if (!bufptr || !strcmp(com_token, "\n"))
{
Con_Printf("framegroups file: missing number of frames\n");
continue;
}
len = atoi(com_token);
// OPTIONAL args start
COM_ParseToken_Simple(&bufptr, true, false, true);
// OPTIONAL: fetch fps
fps = 20;
if (bufptr && strcmp(com_token, "\n"))
{
fps = atof(com_token);
COM_ParseToken_Simple(&bufptr, true, false, true);
}
// OPTIONAL: fetch loopflag
loop = true;
if (bufptr && strcmp(com_token, "\n"))
{
loop = (atoi(com_token) != 0);
COM_ParseToken_Simple(&bufptr, true, false, true);
}
// OPTIONAL: fetch name
name[0] = 0;
if (bufptr && strcmp(com_token, "\n"))
{
dp_strlcpy(name, com_token, sizeof(name));
COM_ParseToken_Simple(&bufptr, true, false, true);
}
// OPTIONAL: remaining unsupported tokens (eat them)
while (bufptr && strcmp(com_token, "\n"))
COM_ParseToken_Simple(&bufptr, true, false, true);
//Con_Printf("data: %d %d %d %f %d (%s)\n", i, start, len, fps, loop, name);
if(cb)
cb(i, start, len, fps, loop, (name[0] ? name : NULL), pass);
++i;
}
return i;
}
static void Mod_FrameGroupify_ParseGroups_Store (unsigned int i, int start, int len, float fps, qbool loop, const char *name, void *pass)
{
model_t *mod = (model_t *) pass;
animscene_t *anim = &mod->animscenes[i];
if(name)
dp_strlcpy(anim->name, name, sizeof(anim[i].name));
else
dpsnprintf(anim->name, sizeof(anim[i].name), "groupified_%d_anim", i);
anim->firstframe = bound(0, start, mod->num_poses - 1);
anim->framecount = bound(1, len, mod->num_poses - anim->firstframe);
anim->framerate = max(1, fps);
anim->loop = !!loop;
//Con_Printf("frame group %d is %d %d %f %d\n", i, start, len, fps, loop);
}
static void Mod_FrameGroupify(model_t *mod, const char *buf)
{
unsigned int cnt;
// 0. count
cnt = Mod_FrameGroupify_ParseGroups(buf, NULL, NULL);
if(!cnt)
{
Con_Printf("no scene found in framegroups file, aborting\n");
return;
}
mod->numframes = cnt;
// 1. reallocate
// (we do not free the previous animscenes, but model unloading will free the pool owning them, so it's okay)
mod->animscenes = (animscene_t *) Mem_Alloc(mod->mempool, sizeof(animscene_t) * mod->numframes);
// 2. parse
Mod_FrameGroupify_ParseGroups(buf, Mod_FrameGroupify_ParseGroups_Store, mod);
}
static void Mod_FindPotentialDeforms(model_t *mod)
{
int i, j;
texture_t *texture;
mod->wantnormals = false;
mod->wanttangents = false;
for (i = 0;i < mod->num_textures;i++)
{
texture = mod->data_textures + i;
if (texture->materialshaderpass && texture->materialshaderpass->tcgen.tcgen == Q3TCGEN_ENVIRONMENT)
mod->wantnormals = true;
if (texture->materialshaderpass && texture->materialshaderpass->tcgen.tcgen == Q3TCGEN_ENVIRONMENT)
mod->wantnormals = true;
for (j = 0;j < Q3MAXDEFORMS;j++)
{
if (texture->deforms[j].deform == Q3DEFORM_AUTOSPRITE)
{
mod->wanttangents = true;
mod->wantnormals = true;
break;
}
if (texture->deforms[j].deform != Q3DEFORM_NONE)
mod->wantnormals = true;
}
}
}
/*
==================
Mod_LoadModel
Loads a model
==================
*/
model_t *Mod_LoadModel(model_t *mod, qbool crash, qbool checkdisk)
{
unsigned int crc;
void *buf;
fs_offset_t filesize = 0;
char vabuf[1024];
mod->used = true;
if (mod->name[0] == '*') // submodel
return mod;
if (!strcmp(mod->name, "null"))
{
if(mod->loaded)
return mod;
if (mod->loaded || mod->mempool)
Mod_UnloadModel(mod);
if (developer_loading.integer)
Con_Printf("loading model %s\n", mod->name);
mod->used = true;
mod->crc = (unsigned int)-1;
mod->loaded = false;
VectorClear(mod->normalmins);
VectorClear(mod->normalmaxs);
VectorClear(mod->yawmins);
VectorClear(mod->yawmaxs);
VectorClear(mod->rotatedmins);
VectorClear(mod->rotatedmaxs);
mod->modeldatatypestring = "null";
mod->type = mod_null;
mod->Draw = R_Model_Null_Draw;
mod->numframes = 2;
mod->numskins = 1;
// no fatal errors occurred, so this model is ready to use.
mod->loaded = true;
return mod;
}
crc = 0;
buf = NULL;
// even if the model is loaded it still may need reloading...
// if it is not loaded or checkdisk is true we need to calculate the crc
if (!mod->loaded || checkdisk)
{
if (checkdisk && mod->loaded)
Con_DPrintf("checking model %s\n", mod->name);
buf = FS_LoadFile (mod->name, tempmempool, false, &filesize);
if (buf)
{
crc = CRC_Block((unsigned char *)buf, filesize);
// we need to reload the model if the crc does not match
if (mod->crc != crc)
mod->loaded = false;
}
}
// if the model is already loaded and checks passed, just return
if (mod->loaded)
{
if (buf)
Mem_Free(buf);
return mod;
}
if (developer_loading.integer)
Con_Printf("loading model %s\n", mod->name);
SCR_PushLoadingScreen(mod->name, 1);
// LadyHavoc: unload the existing model in this slot (if there is one)
if (mod->loaded || mod->mempool)
Mod_UnloadModel(mod);
// load the model
mod->used = true;
mod->crc = crc;
// errors can prevent the corresponding mod->loaded = true;
mod->loaded = false;
// default lightmap scale
mod->lightmapscale = 1;
// default model radius and bounding box (mainly for missing models)
mod->radius = 16;
VectorSet(mod->normalmins, -mod->radius, -mod->radius, -mod->radius);
VectorSet(mod->normalmaxs, mod->radius, mod->radius, mod->radius);
VectorSet(mod->yawmins, -mod->radius, -mod->radius, -mod->radius);
VectorSet(mod->yawmaxs, mod->radius, mod->radius, mod->radius);
VectorSet(mod->rotatedmins, -mod->radius, -mod->radius, -mod->radius);
VectorSet(mod->rotatedmaxs, mod->radius, mod->radius, mod->radius);
if (!q3shaders_mem)
{
// load q3 shaders for the first time, or after a level change
Mod_LoadQ3Shaders();
}
if (buf)
{
int i;
const char *ext = FS_FileExtension(mod->name);
char *bufend = (char *)buf + filesize;
// all models use memory, so allocate a memory pool
mod->mempool = Mem_AllocPool(mod->name, 0, NULL);
// We need to have a reference to the base model in case we're parsing submodels
loadmodel = mod;
// Call the appropriate loader. Try matching magic bytes.
for (i = 0; loader[i].Load; i++)
{
// Headerless formats can just load based on extension. Otherwise match the magic string.
if((loader[i].extension && !strcasecmp(ext, loader[i].extension) && !loader[i].header) ||
(loader[i].header && !memcmp(buf, loader[i].header, loader[i].headersize)))
{
// Matched. Load it.
loader[i].Load(mod, buf, bufend);
Mem_Free(buf);
Mod_FindPotentialDeforms(mod);
buf = FS_LoadFile(va(vabuf, sizeof(vabuf), "%s.framegroups", mod->name), tempmempool, false, &filesize);
if(buf)
{
Mod_FrameGroupify(mod, (const char *)buf);
Mem_Free(buf);
}
Mod_SetDrawSkyAndWater(mod);
Mod_BuildVBOs();
break;
}
}
if(!loader[i].Load)
Con_Printf(CON_ERROR "Mod_LoadModel: model \"%s\" is of unknown/unsupported type\n", mod->name);
}
else if (crash)
// LadyHavoc: Sys_Error was *ANNOYING*
Con_Printf (CON_ERROR "Mod_LoadModel: %s not found\n", mod->name);
// no fatal errors occurred, so this model is ready to use.
mod->loaded = true;
SCR_PopLoadingScreen(false);
return mod;
}
void Mod_ClearUsed(void)
{
int i;
int nummodels = (int)Mem_ExpandableArray_IndexRange(&models);
model_t *mod;
for (i = 0;i < nummodels;i++)
if ((mod = (model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0])
mod->used = false;
}
void Mod_PurgeUnused(void)
{
int i;
int nummodels = (int)Mem_ExpandableArray_IndexRange(&models);
model_t *mod;
for (i = 0;i < nummodels;i++)
{
if ((mod = (model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !mod->used)
{
Mod_UnloadModel(mod);
Mem_ExpandableArray_FreeRecord(&models, mod);
}
}
}
/*
==================
Mod_FindName
==================
*/
model_t *Mod_FindName(const char *name, const char *parentname)
{
int i;
int nummodels;
model_t *mod;
if (!parentname)
parentname = "";
nummodels = (int)Mem_ExpandableArray_IndexRange(&models);
if (!name[0])
Host_Error ("Mod_ForName: empty name");
// search the currently loaded models
for (i = 0;i < nummodels;i++)
{
if ((mod = (model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !strcmp(mod->name, name) && ((!mod->brush.parentmodel && !parentname[0]) || (mod->brush.parentmodel && parentname[0] && !strcmp(mod->brush.parentmodel->name, parentname))))
{
mod->used = true;
return mod;
}
}
// no match found, create a new one
mod = (model_t *) Mem_ExpandableArray_AllocRecord(&models);
dp_strlcpy(mod->name, name, sizeof(mod->name));
if (parentname[0])
mod->brush.parentmodel = Mod_FindName(parentname, NULL);
else
mod->brush.parentmodel = NULL;
mod->loaded = false;
mod->used = true;
return mod;
}
extern qbool vid_opened;
/*
==================
Mod_ForName
Loads in a model for the given name
==================
*/
model_t *Mod_ForName(const char *name, qbool crash, qbool checkdisk, const char *parentname)
{
model_t *model;
// FIXME: So we don't crash if a server is started early.
if(!vid_opened)
CL_StartVideo();
model = Mod_FindName(name, parentname);
if (!model->loaded || checkdisk)
Mod_LoadModel(model, crash, checkdisk);
return model;
}
/*
==================
Mod_Reload
Reloads all models if they have changed
==================
*/
void Mod_Reload(void)
{
int i, count;
int nummodels = (int)Mem_ExpandableArray_IndexRange(&models);
model_t *mod;
SCR_PushLoadingScreen("Reloading models", 1.0);
count = 0;
for (i = 0;i < nummodels;i++)
if ((mod = (model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
++count;
for (i = 0;i < nummodels;i++)
if ((mod = (model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
{
SCR_PushLoadingScreen(mod->name, 1.0 / count);
Mod_LoadModel(mod, true, true);
SCR_PopLoadingScreen(false);
}
SCR_PopLoadingScreen(false);
}
unsigned char *mod_base;
//=============================================================================
/*
================
Mod_Print
================
*/
static void Mod_Print_f(cmd_state_t *cmd)
{
int i;
int nummodels = (int)Mem_ExpandableArray_IndexRange(&models);
model_t *mod;
Con_Print("Loaded models:\n");
for (i = 0;i < nummodels;i++)
{
if ((mod = (model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
{
if (mod->brush.numsubmodels)
Con_Printf("%4iK %s (%i submodels)\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name, mod->brush.numsubmodels);
else
Con_Printf("%4iK %s\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name);
}
}
}
/*
================
Mod_Precache
================
*/
static void Mod_Precache_f(cmd_state_t *cmd)
{
if (Cmd_Argc(cmd) == 2)
Mod_ForName(Cmd_Argv(cmd, 1), false, true, Cmd_Argv(cmd, 1)[0] == '*' ? cl.model_name[1] : NULL);
else
Con_Print("usage: modelprecache <filename>\n");
}
int Mod_BuildVertexRemapTableFromElements(int numelements, const int *elements, int numvertices, int *remapvertices)
{
int i, count;
unsigned char *used;
used = (unsigned char *)Mem_Alloc(tempmempool, numvertices);
memset(used, 0, numvertices);
for (i = 0;i < numelements;i++)
used[elements[i]] = 1;
for (i = 0, count = 0;i < numvertices;i++)
remapvertices[i] = used[i] ? count++ : -1;
Mem_Free(used);
return count;
}
qbool Mod_ValidateElements(int *element3i, unsigned short *element3s, int numtriangles, int firstvertex, int numvertices, const char *filename, int fileline)
{
int first = firstvertex, last = first + numvertices - 1, numelements = numtriangles * 3;
int i;
int invalidintcount = 0, invalidintexample = 0;
int invalidshortcount = 0, invalidshortexample = 0;
int invalidmismatchcount = 0, invalidmismatchexample = 0;
if (element3i)
{
for (i = 0; i < numelements; i++)
{
if (element3i[i] < first || element3i[i] > last)
{
invalidintcount++;
invalidintexample = i;
}
}
}
if (element3s)
{
for (i = 0; i < numelements; i++)
{
if (element3s[i] < first || element3s[i] > last)
{
invalidintcount++;
invalidintexample = i;
}
}
}
if (element3i && element3s)
{
for (i = 0; i < numelements; i++)
{
if (element3s[i] != element3i[i])
{
invalidmismatchcount++;
invalidmismatchexample = i;
}
}
}
if (invalidintcount || invalidshortcount || invalidmismatchcount)
{
Con_Printf("Mod_ValidateElements(%i, %i, %i, %p, %p) called at %s:%d", numelements, first, last, (void *)element3i, (void *)element3s, filename, fileline);
Con_Printf(", %i elements are invalid in element3i (example: element3i[%i] == %i)", invalidintcount, invalidintexample, element3i ? element3i[invalidintexample] : 0);
Con_Printf(", %i elements are invalid in element3s (example: element3s[%i] == %i)", invalidshortcount, invalidshortexample, element3s ? element3s[invalidshortexample] : 0);
Con_Printf(", %i elements mismatch between element3i and element3s (example: element3s[%i] is %i and element3i[%i] is %i)", invalidmismatchcount, invalidmismatchexample, element3s ? element3s[invalidmismatchexample] : 0, invalidmismatchexample, element3i ? element3i[invalidmismatchexample] : 0);
Con_Print(". Please debug the engine code - these elements have been modified to not crash, but nothing more.\n");
// edit the elements to make them safer, as the driver will crash otherwise
if (element3i)
for (i = 0; i < numelements; i++)
if (element3i[i] < first || element3i[i] > last)
element3i[i] = first;
if (element3s)
for (i = 0; i < numelements; i++)
if (element3s[i] < first || element3s[i] > last)
element3s[i] = first;
if (element3i && element3s)
for (i = 0; i < numelements; i++)
if (element3s[i] != element3i[i])
element3s[i] = element3i[i];
return false;
}
return true;
}
// warning: this is an expensive function!
void Mod_BuildNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const int *elements, float *normal3f, qbool areaweighting)
{
int i, j;
const int *element;
float *vectorNormal;
float areaNormal[3];
// clear the vectors
memset(normal3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
// process each vertex of each triangle and accumulate the results
// use area-averaging, to make triangles with a big area have a bigger
// weighting on the vertex normal than triangles with a small area
// to do so, just add the 'normals' together (the bigger the area
// the greater the length of the normal is
element = elements;
for (i = 0; i < numtriangles; i++, element += 3)
{
TriangleNormal(
vertex3f + element[0] * 3,
vertex3f + element[1] * 3,
vertex3f + element[2] * 3,
areaNormal
);
if (!areaweighting)
VectorNormalize(areaNormal);
for (j = 0;j < 3;j++)
{
vectorNormal = normal3f + element[j] * 3;
vectorNormal[0] += areaNormal[0];
vectorNormal[1] += areaNormal[1];
vectorNormal[2] += areaNormal[2];
}
}
// and just normalize the accumulated vertex normal in the end
vectorNormal = normal3f + 3 * firstvertex;
for (i = 0; i < numvertices; i++, vectorNormal += 3)
VectorNormalize(vectorNormal);
}
#if 0
static void Mod_BuildBumpVectors(const float *v0, const float *v1, const float *v2, const float *tc0, const float *tc1, const float *tc2, float *svector3f, float *tvector3f, float *normal3f)
{
float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
// 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
// 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
// 6 multiply, 9 subtract
VectorSubtract(v1, v0, v10);
VectorSubtract(v2, v0, v20);
normal3f[0] = v20[1] * v10[2] - v20[2] * v10[1];
normal3f[1] = v20[2] * v10[0] - v20[0] * v10[2];
normal3f[2] = v20[0] * v10[1] - v20[1] * v10[0];
// 12 multiply, 10 subtract
tc10[1] = tc1[1] - tc0[1];
tc20[1] = tc2[1] - tc0[1];
svector3f[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
svector3f[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
svector3f[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
tc10[0] = tc1[0] - tc0[0];
tc20[0] = tc2[0] - tc0[0];
tvector3f[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
tvector3f[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
tvector3f[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
// 12 multiply, 4 add, 6 subtract
f = DotProduct(svector3f, normal3f);
svector3f[0] -= f * normal3f[0];
svector3f[1] -= f * normal3f[1];
svector3f[2] -= f * normal3f[2];
f = DotProduct(tvector3f, normal3f);
tvector3f[0] -= f * normal3f[0];
tvector3f[1] -= f * normal3f[1];
tvector3f[2] -= f * normal3f[2];
// if texture is mapped the wrong way (counterclockwise), the tangents
// have to be flipped, this is detected by calculating a normal from the
// two tangents, and seeing if it is opposite the surface normal
// 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
CrossProduct(tvector3f, svector3f, tangentcross);
if (DotProduct(tangentcross, normal3f) < 0)
{
VectorNegate(svector3f, svector3f);
VectorNegate(tvector3f, tvector3f);
}
}
#endif
// warning: this is a very expensive function!
void Mod_BuildTextureVectorsFromNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const float *texcoord2f, const float *normal3f, const int *elements, float *svector3f, float *tvector3f, qbool areaweighting)
{
int i, tnum;
float sdir[3], tdir[3], normal[3], *svec, *tvec;
const float *v0, *v1, *v2, *tc0, *tc1, *tc2, *n;
float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
const int *e;
// clear the vectors
memset(svector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
memset(tvector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
// process each vertex of each triangle and accumulate the results
for (tnum = 0, e = elements;tnum < numtriangles;tnum++, e += 3)
{
v0 = vertex3f + e[0] * 3;
v1 = vertex3f + e[1] * 3;
v2 = vertex3f + e[2] * 3;
tc0 = texcoord2f + e[0] * 2;
tc1 = texcoord2f + e[1] * 2;
tc2 = texcoord2f + e[2] * 2;
// 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
// 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
// calculate the edge directions and surface normal
// 6 multiply, 9 subtract
VectorSubtract(v1, v0, v10);
VectorSubtract(v2, v0, v20);
normal[0] = v20[1] * v10[2] - v20[2] * v10[1];
normal[1] = v20[2] * v10[0] - v20[0] * v10[2];
normal[2] = v20[0] * v10[1] - v20[1] * v10[0];
// calculate the tangents
// 12 multiply, 10 subtract
tc10[1] = tc1[1] - tc0[1];
tc20[1] = tc2[1] - tc0[1];
sdir[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
sdir[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
sdir[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
tc10[0] = tc1[0] - tc0[0];
tc20[0] = tc2[0] - tc0[0];
tdir[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
tdir[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
tdir[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
// if texture is mapped the wrong way (counterclockwise), the tangents
// have to be flipped, this is detected by calculating a normal from the
// two tangents, and seeing if it is opposite the surface normal
// 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
CrossProduct(tdir, sdir, tangentcross);
if (DotProduct(tangentcross, normal) < 0)
{
VectorNegate(sdir, sdir);
VectorNegate(tdir, tdir);
}
if (!areaweighting)
{
VectorNormalize(sdir);
VectorNormalize(tdir);
}
for (i = 0;i < 3;i++)
{
VectorAdd(svector3f + e[i]*3, sdir, svector3f + e[i]*3);
VectorAdd(tvector3f + e[i]*3, tdir, tvector3f + e[i]*3);
}
}
// make the tangents completely perpendicular to the surface normal, and
// then normalize them
// 16 assignments, 2 divide, 2 sqrt, 2 negates, 14 adds, 24 multiplies
for (i = 0, svec = svector3f + 3 * firstvertex, tvec = tvector3f + 3 * firstvertex, n = normal3f + 3 * firstvertex;i < numvertices;i++, svec += 3, tvec += 3, n += 3)
{
f = -DotProduct(svec, n);
VectorMA(svec, f, n, svec);
VectorNormalize(svec);
f = -DotProduct(tvec, n);
VectorMA(tvec, f, n, tvec);
VectorNormalize(tvec);
}
}
void Mod_AllocSurfMesh(mempool_t *mempool, int numvertices, int numtriangles, qbool lightmapoffsets, qbool vertexcolors)
{
unsigned char *data;
data = (unsigned char *)Mem_Alloc(mempool, numvertices * (3 + 3 + 3 + 3 + 2 + 2 + (vertexcolors ? 4 : 0)) * sizeof(float) + numvertices * (lightmapoffsets ? 1 : 0) * sizeof(int) + numtriangles * sizeof(int[3]) + (numvertices <= 65536 ? numtriangles * sizeof(unsigned short[3]) : 0));
loadmodel->surfmesh.num_vertices = numvertices;
loadmodel->surfmesh.num_triangles = numtriangles;
if (loadmodel->surfmesh.num_vertices)
{
loadmodel->surfmesh.data_vertex3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
loadmodel->surfmesh.data_svector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
loadmodel->surfmesh.data_tvector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
loadmodel->surfmesh.data_normal3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
loadmodel->surfmesh.data_texcoordtexture2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
loadmodel->surfmesh.data_texcoordlightmap2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
if (vertexcolors)
loadmodel->surfmesh.data_lightmapcolor4f = (float *)data, data += sizeof(float[4]) * loadmodel->surfmesh.num_vertices;
if (lightmapoffsets)
loadmodel->surfmesh.data_lightmapoffsets = (int *)data, data += sizeof(int) * loadmodel->surfmesh.num_vertices;
}
if (loadmodel->surfmesh.num_triangles)
{
loadmodel->surfmesh.data_element3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
if (loadmodel->surfmesh.num_vertices <= 65536)
loadmodel->surfmesh.data_element3s = (unsigned short *)data, data += sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles;
}
}
shadowmesh_t *Mod_ShadowMesh_Alloc(mempool_t *mempool, int maxverts, int maxtriangles)